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: add SARIF reporter for GitHub Code Scanning (#117)
Mohammed Imran Khanea9b23971f53
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9a415f25..57deee3a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,12 @@ All notable changes to SkillEvaluator are documented in this file.## Unreleased+### Added++- SARIF 2.1.0 reporter (`-r sarif`) for GitHub Code Scanning and other SARIF+ consumers. Findings map to rule IDs, severity levels, and file locations from+ Tier 1 validation results.+### Fixed- `--llm-verify` now refuses to send file context from paths outside thediff --git a/docs/ci-integration.mdx b/docs/ci-integration.mdxindex 229074ac..99ca3d16 100644--- a/docs/ci-integration.mdx+++ b/docs/ci-integration.mdx@@ -28,7 +28,7 @@ Each flag earns its place:- **`--external`** pins the public-publication profile explicitly instead of relying on the environment, so the gate behaves identically on every runner. The active profile name is stamped into the HTML report and `BENCHMARK.md` (and printed in the run banner with `--verbose`), so a run always records which gate was applied.- **`--no-dedup`** skips Tier 2, which needs an embedding-capable provider key (`--no-tier2` is an equivalent alias). Without it the run is fully keyless and hermetic. Drop this flag once you add a provider secret.-- **`-r json,markdown`** writes a machine-readable report for your pipeline and a Markdown report you can post as a PR comment.+- **`-r json,markdown,sarif`** writes machine-readable JSON, a Markdown PR comment, and a SARIF file for GitHub Code Scanning.- **`-o reports`** collects everything in one directory for artifact upload.- **`--min-score 70`** is the default quality bar, written out explicitly so raising it later is a visible one-line diff.@@ -52,6 +52,7 @@ jobs:permissions:contents: readpull-requests: write+ security-events: writesteps:- uses: actions/checkout@v7@@ -78,7 +79,7 @@ jobs:- name: Validate skillsrun: |skillevaluator validate ./skills --external --no-dedup \- -r json,markdown -o reports --min-score 70+ -r json,markdown,sarif -o reports --min-score 70- name: Upload reportsif: always()@@ -87,6 +88,44 @@ jobs:name: skillevaluator-reportspath: reports/+ - name: Find SARIF reports+ if: always()+ id: sarif+ run: |+ mapfile -t files < <(find reports -name '*.sarif.json' -type f 2>/dev/null | sort)+ if [ "${#files[@]}" -eq 0 ]; then+ echo "count=0" >> "$GITHUB_OUTPUT"+ exit 0+ fi+ skillevaluator_python="$(dirname "$(readlink -f "$(command -v skillevaluator)")")/python"+ "$skillevaluator_python" - <<'PY'+ import json+ import pathlib++ from skillevaluator.reporting.sarif_reporter import merge_catalog_sarif_documents++ documents = []+ for raw in sorted(pathlib.Path("reports").rglob("*.sarif.json")):+ if raw.name == "catalog-sarif.json":+ continue+ documents.append(json.loads(raw.read_text(encoding="utf-8")))+ if not documents:+ raise SystemExit(0)+ merged = merge_catalog_sarif_documents(documents)+ out = pathlib.Path("reports/catalog-sarif.json")+ out.write_text(json.dumps(merged, indent=2), encoding="utf-8")+ print(f"merged {len(documents)} child report(s) into one run at {out}")+ PY+ echo "count=${#files[@]}" >> "$GITHUB_OUTPUT"+ echo "path=reports/catalog-sarif.json" >> "$GITHUB_OUTPUT"++ - name: Upload SARIF to GitHub Code Scanning+ if: always() && steps.sarif.outputs.count != '0'+ uses: github/codeql-action/upload-sarif@v4+ with:+ sarif_file: ${{ steps.sarif.outputs.path }}+ category: skillevaluator+- name: Post the Markdown report as a PR commentif: always() && github.event_name == 'pull_request'uses: actions/github-script@v9diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex e745de0b..d3cc8a46 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -44,10 +44,10 @@ commands referenced below.| Flag | Default | Effect || --- | --- | --- |-| `-r, --report [cli\|json\|html\|markdown]` | `cli` | Report format(s). Accepts comma- or space-separated values (`-r cli,json,html` or `-r cli json html`) and may be repeated. The compact default view writes html+json unless `-r` is passed explicitly, which is honored exactly (including `cli`). |+| `-r, --report [cli\|json\|html\|markdown\|sarif]` | `cli` | Report format(s). Accepts comma- or space-separated values (`-r cli,json,html` or `-r cli json html`) and may be repeated. The compact default view writes html+json unless `-r` is passed explicitly, which is honored exactly (including `cli`). || `-o, --output-dir DIRECTORY` | `reports` | Directory for generated reports. |-In practice: a default `validate` run (no `-r`) shows the compact pipeline view **and** writes `json` + `html` report files; passing `-r` takes over completely — `-r cli` really means terminal output only, no files. The standalone commands take the `cli` default literally: they print the full terminal report and write files only for the formats you request with `-r`. A `validate` run writes `skillevaluator-output-<timestamp>.json` / `.html` (plus `.md` with `-r markdown`); standalone commands write a fixed `skillevaluator-<kind>` basename (for example `skillevaluator-quality.json`), so a re-run overwrites the previous report. Filename conventions and report anatomy live in [Reports & Results](reports.mdx).+In practice: a default `validate` run (no `-r`) shows the compact pipeline view **and** writes `json` + `html` report files; passing `-r` takes over completely — `-r cli` really means terminal output only, no files. The standalone commands take the `cli` default literally: they print the full terminal report and write files only for the formats you request with `-r`. A `validate` run writes `skillevaluator-output-<timestamp>.json` / `.html` (plus `.md` with `-r markdown` or `.sarif.json` with `-r sarif`); standalone commands write a fixed `skillevaluator-<kind>` basename (for example `skillevaluator-quality.json`), so a re-run overwrites the previous report. Filename conventions and report anatomy live in [Reports & Results](reports.mdx).**Exit codes.** Commands communicate through a small exit-code contract — this is what your CI gates on (see [Gate Your CI](ci-integration.mdx)):diff --git a/docs/reports.mdx b/docs/reports.mdxindex e6466eb6..c1d3993a 100644--- a/docs/reports.mdx+++ b/docs/reports.mdx@@ -36,9 +36,10 @@ the terminal instead.| `json` | Machine-readable JSON (default) | CI needs to parse scores and findings || `html` | Standalone HTML report (default) | A human needs to review or archive a run || `markdown` | Markdown for PR comments | You want the result posted on a pull request |+| `sarif` | SARIF 2.1.0 JSON | GitHub Code Scanning or other SARIF consumers need inline annotations |-```bash title="One run, three report files"-skillevaluator validate ./my-skill -r json,html,markdown -o reports+```bash title="One run, four report files"+skillevaluator validate ./my-skill -r json,html,markdown,sarif -o reports```For gating a pipeline on the JSON output, see [Gate Your CI](ci-integration.mdx).@@ -59,7 +60,7 @@ Report filenames follow two patterns, both under the output directory:| `context-optimization-check` | `skillevaluator-context` | Yes || `dedup-scan` | `skillevaluator-dedup` | Yes |-The extension matches the format (`.json`, `.html`, `.md`); the `cli` format+The extension matches the format (`.json`, `.html`, `.md`, `.sarif.json`); the `cli` formatprints to the terminal and never writes a file. A full `validate` run'stimestamp is `YYYYMMDDHHMMSS`, so`-r json` produces something like `skillevaluator-output-20260709141530.json`diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex 0ed29141..8aa423ab 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -223,6 +223,7 @@ _FILE_REPORT_EXTENSIONS = {"json": ".json","html": ".html","markdown": ".md",+ "sarif": ".sarif.json",}@@ -314,7 +315,7 @@ def _report_options(func):"report_formats",cls=_MultiValueOption,multiple=True,- type=click.Choice(["cli", "json", "html", "markdown"]),+ type=click.Choice(["cli", "json", "html", "markdown", "sarif"]),default=("cli",),show_default=True,help="Report format(s). Accepts comma- or space-separated values "@@ -765,7 +766,7 @@ def _finish_pipeline_view("""Render the quiet-mode verdict panel and report footer."""from skillevaluator.reporting.console_ui import Verdict, _is_skipped, first_fix- ext = {"html": ".html", "json": ".json", "markdown": ".md"}+ ext = {"html": ".html", "json": ".json", "markdown": ".md", "sarif": ".sarif.json"}links: list[tuple[str, str]] = [("report" if fmt == "html" else fmt, str(output_dir / f"{basename}{ext[fmt]}"))for fmt in report_formats@@ -1177,7 +1178,7 @@ def validate()from skillevaluator.reporting import CLIReporterfrom skillevaluator.reporting.naming import REPORT_PREFIX- from skillevaluator.utils.helpers import make_timestamped_basename, resolve_git_remote_url+ from skillevaluator.utils.helpers import make_timestamped_basename, resolve_git_remote_url, resolve_git_rootfrom skillevaluator.validators.policy import apply_policy, resolve_policyif external and profile and profile != "external":@@ -1443,6 +1444,9 @@ def validate(CONTENT_TYPE_PLUGIN: "Plugin",}.get(resolved_type, "Skill")target_display = resolve_git_remote_url(target_path) or str(target_path)+ sarif_repository_root = resolve_git_root(target_path)+ if sarif_repository_root is None:+ sarif_repository_root = target_path if target_path.is_dir() else target_path.parent# Quiet mode defaults the reports to html+json (the terminal shows only# the summary; the files carry the findings) and points at them from the@@ -1462,6 +1466,8 @@ def validate(target_path=target_display,content_label=content_label,announce_paths=not quiet,+ sarif_scan_root=target_path,+ sarif_repository_root=sarif_repository_root,)# BENCHMARK.md is generated compulsorily for skills (matches SkillEvaluator), even ondiff --git a/src/skillevaluator/reporting/__init__.py b/src/skillevaluator/reporting/__init__.pyindex 80e31100..eac1d630 100644--- a/src/skillevaluator/reporting/__init__.py+++ b/src/skillevaluator/reporting/__init__.py@@ -10,6 +10,7 @@ in various formats for different use cases:- JSONReporter: Machine-readable JSON for CI/CD pipelines- HTMLReporter: Standalone HTML reports for archiving/sharing- MarkdownReporter: Markdown for PR comments and documentation+- SARIFReporter: SARIF 2.1.0 for GitHub Code ScanningAll reporters consume the same ValidationResult data structure fromskillevaluator.models, ensuring consistent information across all output formats.@@ -36,6 +37,7 @@ from skillevaluator.reporting.cli import CLIReporterfrom skillevaluator.reporting.html import HTMLReporterfrom skillevaluator.reporting.json_reporter import JSONReporterfrom skillevaluator.reporting.markdown import MarkdownReporter+from skillevaluator.reporting.sarif_reporter import SARIFReporter__all__ = ["BenchmarkReporter",@@ -44,4 +46,5 @@ __all__ = ["JSONReporter","MarkdownReporter","ReporterBase",+ "SARIFReporter",]diff --git a/src/skillevaluator/reporting/base.py b/src/skillevaluator/reporting/base.pyindex c199274b..1789e6c9 100644--- a/src/skillevaluator/reporting/base.py+++ b/src/skillevaluator/reporting/base.py@@ -438,5 +438,6 @@ class ReporterBase(ABC):"json": ".json","html": ".html","markdown": ".md",+ "sarif": ".sarif.json",}return extensions.get(self.name, ".txt")diff --git a/src/skillevaluator/reporting/sarif_reporter.py b/src/skillevaluator/reporting/sarif_reporter.pynew file mode 100644index 00000000..ffafef2e--- /dev/null+++ b/src/skillevaluator/reporting/sarif_reporter.py@@ -0,0 +1,313 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""SARIF reporter for CI security integrations.++Produces SARIF 2.1.0 output suitable for GitHub Code Scanning and other SARIF+consumers. Tier 1 findings with file locations are mapped to ``results``;+validators without structured findings are omitted.+"""++from __future__ import annotations++import json+import re+from datetime import UTC, datetime+from pathlib import Path+from typing import TYPE_CHECKING, Any+from urllib.parse import quote++from skillevaluator import __version__+from skillevaluator.reporting.base import ReporterBase++if TYPE_CHECKING:+ from skillevaluator.models import Finding, ValidationResult++_SARIF_SCHEMA = "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json"+_TOOL_URI = "https://github.com/NVIDIA/SkillEvaluator"+_RULE_ID_PATTERN = re.compile(r"[^A-Za-z0-9._/-]+")+++def _sanitize_rule_component(value: str) -> str:+ """Return a SARIF-safe rule identifier fragment."""+ cleaned = _RULE_ID_PATTERN.sub("-", value.strip())+ return cleaned.strip("-") or "finding"+++def _rule_id(validator_name: str, check_name: str) -> str:+ validator = _sanitize_rule_component(validator_name)+ check = _sanitize_rule_component(check_name)+ if check and check != validator:+ return f"{validator}/{check}"+ return validator+++def _severity_to_level(severity: str) -> str:+ if severity in {"critical", "high"}:+ return "error"+ if severity == "medium":+ return "warning"+ return "note"+++def _finding_severity_value(finding: Finding) -> str:+ severity = finding.severity+ if hasattr(severity, "value"):+ return str(severity.value).lower()+ return str(severity).lower()+++def _rule_descriptor(finding: Finding, validator_name: str) -> dict[str, Any]:+ rule_id = _rule_id(validator_name, finding.check_name)+ severity = _finding_severity_value(finding)+ descriptor: dict[str, Any] = {+ "id": rule_id,+ "name": finding.check_name,+ "shortDescription": {"text": finding.check_name},+ "defaultConfiguration": {"level": _severity_to_level(severity)},+ }+ if finding.message:+ descriptor["fullDescription"] = {"text": finding.message}+ return descriptor+++def _positive_start_line(line_number: Any) -> int | None:+ """Return a SARIF-valid positive integer line number, else ``None``."""+ if isinstance(line_number, bool):+ return None+ if isinstance(line_number, str):+ stripped = line_number.strip()+ if not stripped:+ return None+ try:+ line_number = int(stripped)+ except ValueError:+ return None+ if isinstance(line_number, int) and line_number > 0:+ return line_number+ return None+++def _resolve_artifact_path(file_path: str, scan_root: Path | None) -> Path:+ """Resolve a validator file path against the scanned skill directory."""+ normalized = file_path.replace("\\", "/")+ path = Path(normalized)+ if scan_root is not None and not path.is_absolute():+ return (scan_root / path).resolve()+ if path.is_absolute():+ return path.resolve()+ return path+++def _normalize_artifact_uri(+ file_path: str,+ workspace_root: Path | None,+ scan_root: Path | None = None,+) -> str:+ """Return a repository-relative, URI-encoded artifact path for SARIF."""+ path = _resolve_artifact_path(file_path, scan_root)+ if workspace_root is not None:+ try:+ # Windows paths can be rooted (``\\workspace\\...``) without a+ # drive, in which case ``is_absolute()`` is false until resolved.+ if path.is_absolute() or path.root:+ relative = path.resolve().relative_to(workspace_root.resolve())+ normalized = relative.as_posix()+ else:+ normalized = path.as_posix()+ except ValueError:+ normalized = path.as_posix()+ elif path.is_absolute():+ normalized = path.as_posix()+ else:+ normalized = path.as_posix()+ return quote(normalized, safe="/:@%")+++def _physical_location(+ finding: Finding,+ workspace_root: Path | None,+ scan_root: Path | None = None,+) -> dict[str, Any] | None:+ if not finding.file_path:+ return None+ location: dict[str, Any] = {+ "artifactLocation": {+ "uri": _normalize_artifact_uri(finding.file_path, workspace_root, scan_root),+ },+ }+ start_line = _positive_start_line(finding.line_number)+ if start_line is not None:+ region: dict[str, Any] = {"startLine": start_line}+ if finding.line_content:+ region["snippet"] = {"text": finding.line_content}+ location["region"] = region+ return {"physicalLocation": location}+++def _result_from_finding(+ finding: Finding,+ validator_name: str,+ workspace_root: Path | None,+ scan_root: Path | None = None,+) -> dict[str, Any]:+ severity = _finding_severity_value(finding)+ result: dict[str, Any] = {+ "ruleId": _rule_id(validator_name, finding.check_name),+ "level": _severity_to_level(severity),+ "message": {"text": finding.message},+ }+ if finding.suggestion:+ result["message"]["markdown"] = f"{finding.message}\n\n**Suggestion:** {finding.suggestion}"+ location = _physical_location(finding, workspace_root, scan_root)+ if location is not None:+ result["locations"] = [location]+ properties: dict[str, Any] = {+ "category": finding.category,+ "validator": validator_name,+ "checkName": finding.check_name,+ "severity": severity,+ }+ if finding.metadata:+ properties["metadata"] = finding.metadata+ result["properties"] = properties+ return result+++def _collect_incomplete_scans(results: list[ValidationResult]) -> list[str]:+ scans: list[str] = []+ for result in results:+ for tool in result.incomplete_scans:+ if tool not in scans:+ scans.append(tool)+ return scans+++def _build_invocation(results: list[ValidationResult]) -> dict[str, Any]:+ incomplete_scans = _collect_incomplete_scans(results)+ invocation: dict[str, Any] = {+ "executionSuccessful": not incomplete_scans,+ "endTimeUtc": datetime.now(tz=UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z"),+ }+ if incomplete_scans:+ invocation["toolExecutionNotifications"] = [+ {+ "descriptor": {"id": f"incomplete/{tool}"},+ "level": "error",+ "message": {"text": f"{tool} scan did not complete"},+ }+ for tool in incomplete_scans+ ]+ return invocation+++def merge_catalog_sarif_documents(documents: list[dict[str, Any]]) -> dict[str, Any]:+ """Merge per-skill SARIF payloads into one upload-ready document.++ GitHub Code Scanning rejects SARIF with more than 20 runs, so child reports+ are folded into a single run with combined rules and results.+ """+ rules: dict[str, dict[str, Any]] = {}+ results: list[dict[str, Any]] = []+ invocations: list[dict[str, Any]] = []+ driver: dict[str, Any] = {+ "name": "SkillEvaluator",+ "informationUri": _TOOL_URI,+ }++ for payload in documents:+ for run in payload.get("runs", []):+ run_driver = run.get("tool", {}).get("driver", {})+ if run_driver.get("name"):+ driver["name"] = run_driver["name"]+ if run_driver.get("informationUri"):+ driver["informationUri"] = run_driver["informationUri"]+ if run_driver.get("version"):+ driver["version"] = run_driver["version"]+ for rule in run_driver.get("rules", []):+ rules[rule["id"]] = rule+ results.extend(run.get("results", []))+ invocations.extend(run.get("invocations", []))++ merged_run: dict[str, Any] = {+ "tool": {+ "driver": {+ **driver,+ "rules": sorted(rules.values(), key=lambda item: item["id"]),+ }+ },+ "results": results,+ "automationDetails": {"id": "/skillevaluator/catalog"},+ }+ if invocations:+ merged_run["invocations"] = invocations+ return {+ "$schema": _SARIF_SCHEMA,+ "version": "2.1.0",+ "runs": [merged_run],+ }+++class SARIFReporter(ReporterBase):+ """SARIF 2.1.0 export for security scanning integrations."""++ def __init__(+ self,+ *,+ indent: int | None = 2,+ include_timestamp: bool = True,+ workspace_root: Path | None = None,+ scan_root: Path | None = None,+ ) -> None:+ self.indent = indent+ self.include_timestamp = include_timestamp+ self.workspace_root = workspace_root+ self.scan_root = scan_root++ @property+ def name(self) -> str:+ return "sarif"++ @property+ def description(self) -> str:+ return "SARIF 2.1.0 for GitHub Code Scanning and SARIF consumers"++ def render(self, result: ValidationResult) -> str:+ return self.render_all([result])++ def render_all(self, results: list[ValidationResult]) -> str:+ rules: dict[str, dict[str, Any]] = {}+ sarif_results: list[dict[str, Any]] = []+ workspace_root = self.workspace_root+ scan_root = self.scan_root++ for result in results:+ validator_name = result.validator_name or "UNKNOWN"+ for finding in result.findings:+ rule = _rule_descriptor(finding, validator_name)+ rules[rule["id"]] = rule+ sarif_results.append(_result_from_finding(finding, validator_name, workspace_root, scan_root))++ run: dict[str, Any] = {+ "tool": {+ "driver": {+ "name": "SkillEvaluator",+ "informationUri": _TOOL_URI,+ "version": __version__,+ "rules": sorted(rules.values(), key=lambda item: item["id"]),+ }+ },+ "results": sarif_results,+ }+ if self.include_timestamp or _collect_incomplete_scans(results):+ run["invocations"] = [_build_invocation(results)]++ document: dict[str, Any] = {+ "$schema": _SARIF_SCHEMA,+ "version": "2.1.0",+ "runs": [run],+ }+ return json.dumps(document, indent=self.indent, default=str, allow_nan=False)++ def get_file_extension(self) -> str:+ return ".sarif.json"diff --git a/src/skillevaluator/tier1/commands.py b/src/skillevaluator/tier1/commands.pyindex b3e00879..d0822fa0 100644--- a/src/skillevaluator/tier1/commands.py+++ b/src/skillevaluator/tier1/commands.py@@ -19,7 +19,7 @@ from skillevaluator.constants import (CONTENT_TYPE_WORKFLOWS,)from skillevaluator.models.result import ValidationResult-from skillevaluator.reporting import CLIReporter, HTMLReporter, JSONReporter, MarkdownReporter+from skillevaluator.reporting import CLIReporter, HTMLReporter, JSONReporter, MarkdownReporter, SARIFReporterfrom skillevaluator.reporting.html import is_tier2_validator_namefrom skillevaluator.reporting.naming import DEFAULT_REPORT_BASENAMEfrom skillevaluator.validators.base import continue_on_failure_scope@@ -70,6 +70,7 @@ REPORTERS = {"json": JSONReporter,"html": HTMLReporter,"markdown": MarkdownReporter,+ "sarif": SARIFReporter,}@@ -332,6 +333,8 @@ def emit_reports(target_path: str | None = None,content_label: str = "Skill",announce_paths: bool = True,+ sarif_scan_root: Path | None = None,+ sarif_repository_root: Path | None = None,) -> bool:"""Render reports and return whether every result passed.@@ -356,6 +359,11 @@ def emit_reports(reporter_cls = REPORTERS[fmt]if fmt == "html":reporter = reporter_cls(target_path=target_path, content_label=content_label, tabs=html_tabs)+ elif fmt == "sarif":+ reporter = reporter_cls(+ workspace_root=sarif_repository_root,+ scan_root=sarif_scan_root,+ )else:reporter = reporter_cls()output_path = output_dir / f"{basename}{reporter.get_file_extension()}"diff --git a/src/skillevaluator/utils/helpers.py b/src/skillevaluator/utils/helpers.pyindex 3eb82cff..cd5d474c 100644--- a/src/skillevaluator/utils/helpers.py+++ b/src/skillevaluator/utils/helpers.py@@ -62,6 +62,22 @@ def find_bundled_plugin_skills(plugin_root: Path) -> list[Path]:]+def resolve_git_root(local_path: Path) -> Path | None:+ """Return the containing Git repository root without importing optional tiers."""+ resolved = local_path.resolve()+ working_dir = resolved if resolved.is_dir() else resolved.parent+ try:+ root = subprocess.check_output(+ ["git", "rev-parse", "--show-toplevel"],+ cwd=str(working_dir),+ stderr=subprocess.DEVNULL,+ text=True,+ ).strip()+ except (subprocess.CalledProcessError, FileNotFoundError, OSError):+ return None+ return Path(root).resolve() if root else None++def resolve_git_remote_url(local_path: Path) -> str | None:"""Resolve a local path to a browsable HTTPS URL if inside a git repo.@@ -79,20 +95,15 @@ def resolve_git_remote_url(local_path: Path) -> str | None:HTTPS URL string, or None if not inside a git repo"""resolved = local_path.resolve()+ repo_root = resolve_git_root(resolved)+ if repo_root is None:+ return Nonetry:- # Find the git repo root- repo_root = subprocess.check_output(- ["git", "rev-parse", "--show-toplevel"],- cwd=str(resolved if resolved.is_dir() else resolved.parent),- stderr=subprocess.DEVNULL,- text=True,- ).strip()-# Get the remote origin URLremote_url = subprocess.check_output(["git", "remote", "get-url", "origin"],- cwd=repo_root,+ cwd=str(repo_root),stderr=subprocess.DEVNULL,text=True,).strip()@@ -108,7 +119,7 @@ def resolve_git_remote_url(local_path: Path) -> str | None:try:branch = subprocess.check_output(["git", "rev-parse", "HEAD"],- cwd=repo_root,+ cwd=str(repo_root),stderr=subprocess.DEVNULL,text=True,).strip()@@ -118,7 +129,7 @@ def resolve_git_remote_url(local_path: Path) -> str | None:try:branch = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"],- cwd=repo_root,+ cwd=str(repo_root),stderr=subprocess.DEVNULL,text=True,).strip()diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex bc1aa820..a912b9ac 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -62,7 +62,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -213,7 +214,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -747,7 +749,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -819,7 +822,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -867,7 +871,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -915,7 +920,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -977,7 +983,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -1089,7 +1096,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -1130,7 +1138,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -1179,7 +1188,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -1227,7 +1237,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -1275,7 +1286,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -1337,7 +1349,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -1741,7 +1754,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -1810,7 +1824,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -1874,7 +1889,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -1986,7 +2002,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,@@ -3025,7 +3042,8 @@"cli","json","html",- "markdown"+ "markdown",+ "sarif"],"default": "('cli',)","multiple": true,diff --git a/tests/reporting/test_reporters.py b/tests/reporting/test_reporters.pyindex a5fbbb0a..645b2924 100644--- a/tests/reporting/test_reporters.py+++ b/tests/reporting/test_reporters.py@@ -17,7 +17,14 @@ from skillevaluator.evaluation.tier3_report import (render_agent_eval_html_report,)from skillevaluator.models import Finding, Severity, ValidationResult-from skillevaluator.reporting import BenchmarkReporter, CLIReporter, HTMLReporter, JSONReporter, MarkdownReporter+from skillevaluator.reporting import (+ BenchmarkReporter,+ CLIReporter,+ HTMLReporter,+ JSONReporter,+ MarkdownReporter,+ SARIFReporter,+)from skillevaluator.tier1.commands import emit_reports@@ -422,6 +429,186 @@ class TestJSONReporter:assert reporter.name == "json"+class TestSARIFReporter:+ """Tests for SARIFReporter."""++ def test_render_failure_produces_valid_sarif(self, failure_result: ValidationResult) -> None:+ reporter = SARIFReporter(include_timestamp=False)+ document = json.loads(reporter.render_all([failure_result]))++ assert document["version"] == "2.1.0"+ assert document["$schema"] == (+ "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json"+ )+ run = document["runs"][0]+ driver = run["tool"]["driver"]+ assert driver["name"] == "SkillEvaluator"+ assert driver["informationUri"] == "https://github.com/NVIDIA/SkillEvaluator"+ assert len(driver["rules"]) == 2+ assert len(run["results"]) == 2++ critical = next(item for item in run["results"] if item["level"] == "error")+ assert critical["ruleId"] == "SECRETS/aws-access-key-id"+ assert critical["message"]["text"] == "AWS Access Key ID detected"+ location = critical["locations"][0]["physicalLocation"]+ assert location["artifactLocation"]["uri"] == "config/settings.py"+ assert location["region"]["startLine"] == 15++ def test_severity_mapping(self) -> None:+ result = ValidationResult(validator_name="TEST", validator_description="test")+ result.add_finding(+ Finding(+ category="TEST",+ severity=Severity.MEDIUM,+ check_name="medium-check",+ message="medium issue",+ file_path="SKILL.md",+ line_number=3,+ )+ )+ result.add_finding(+ Finding(+ category="TEST",+ severity=Severity.LOW,+ check_name="low-check",+ message="low issue",+ file_path="SKILL.md",+ )+ )++ run = json.loads(SARIFReporter(include_timestamp=False).render_all([result]))["runs"][0]+ levels = {item["ruleId"]: item["level"] for item in run["results"]}+ assert levels["TEST/medium-check"] == "warning"+ assert levels["TEST/low-check"] == "note"++ def test_emit_reports_writes_sarif_file(self, failure_result: ValidationResult) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ output_dir = Path(tmp)+ emit_reports(+ [failure_result],+ report_formats=("sarif",),+ output_dir=output_dir,+ basename="skillevaluator-security",+ announce_paths=False,+ )+ sarif_path = output_dir / "skillevaluator-security.sarif.json"+ assert sarif_path.is_file()+ document = json.loads(sarif_path.read_text(encoding="utf-8"))+ assert document["runs"][0]["results"]++ def test_name_and_extension(self) -> None:+ reporter = SARIFReporter()+ assert reporter.name == "sarif"+ assert reporter.get_file_extension() == ".sarif.json"++ def test_incomplete_scan_marks_execution_unsuccessful(self) -> None:+ result = ValidationResult(validator_name="BANDIT", validator_description="Bandit")+ result.add_error("Bandit did not return valid JSON; scan did not complete")+ result.mark_scan_incomplete("bandit")++ invocation = json.loads(SARIFReporter(include_timestamp=False).render_all([result]))["runs"][0]["invocations"][+ 0+ ]+ assert invocation["executionSuccessful"] is False+ assert invocation["toolExecutionNotifications"][0]["message"]["text"] == "bandit scan did not complete"++ def test_physical_location_uri_encodes_spaces_and_skips_invalid_lines(self) -> None:+ root = Path("/workspace/my skill")+ result = ValidationResult(validator_name="QUALITY", validator_description="quality")+ result.add_finding(+ Finding(+ category="QUALITY",+ severity=Severity.MEDIUM,+ check_name="spacing",+ message="issue",+ file_path=str(root / "SKILL.md"),+ line_number=0,+ )+ )+ result.add_finding(+ Finding(+ category="QUALITY",+ severity=Severity.LOW,+ check_name="spacing",+ message="issue",+ file_path=str(root / "notes/readme.md"),+ line_number=3,+ )+ )++ run = json.loads(SARIFReporter(include_timestamp=False, workspace_root=root).render_all([result]))["runs"][0]+ locations = [item["locations"][0]["physicalLocation"] for item in run["results"]]+ assert locations[0]["artifactLocation"]["uri"] == "SKILL.md"+ assert "region" not in locations[0]+ assert locations[1]["artifactLocation"]["uri"] == "notes/readme.md"+ assert locations[1]["region"]["startLine"] == 3++ def test_nested_skill_path_relativized_to_repository_root(self, tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ skill = repo / "skills" / "demo"+ skill.mkdir(parents=True)+ result = ValidationResult(validator_name="QUALITY", validator_description="quality")+ result.add_finding(+ Finding(+ category="QUALITY",+ severity=Severity.MEDIUM,+ check_name="spacing",+ message="issue",+ file_path="SKILL.md",+ line_number=2,+ )+ )++ run = json.loads(+ SARIFReporter(+ include_timestamp=False,+ workspace_root=repo,+ scan_root=skill,+ ).render_all([result])+ )["runs"][0]+ uri = run["results"][0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]+ assert uri == "skills/demo/SKILL.md"++ def test_merge_catalog_sarif_combines_into_single_run(self) -> None:+ child = SARIFReporter(include_timestamp=False)+ documents = []+ for index in range(21):+ result = ValidationResult(validator_name="TEST", validator_description="test")+ result.add_finding(+ Finding(+ category="TEST",+ severity=Severity.LOW,+ check_name=f"check-{index}",+ message="issue",+ file_path=f"skills/s{index}/SKILL.md",+ )+ )+ documents.append(json.loads(child.render_all([result])))++ from skillevaluator.reporting.sarif_reporter import merge_catalog_sarif_documents++ merged = merge_catalog_sarif_documents(documents)+ assert len(merged["runs"]) == 1+ assert len(merged["runs"][0]["results"]) == 21+ automation = merged["runs"][0]["automationDetails"]+ assert automation == {"id": "/skillevaluator/catalog"}+ assert "name" not in automation++ def test_merge_catalog_sarif_preserves_incomplete_invocation(self) -> None:+ result = ValidationResult(validator_name="BANDIT", validator_description="Bandit")+ result.add_error("Bandit scan did not complete")+ result.mark_scan_incomplete("bandit")+ child = json.loads(SARIFReporter(include_timestamp=False).render_all([result]))++ from skillevaluator.reporting.sarif_reporter import merge_catalog_sarif_documents++ merged = merge_catalog_sarif_documents([child])+ invocations = merged["runs"][0]["invocations"]+ assert invocations == child["runs"][0]["invocations"]+ assert invocations[0]["executionSuccessful"] is False+ assert invocations[0]["toolExecutionNotifications"][0]["descriptor"]["id"] == "incomplete/bandit"++def _blocking_result() -> ValidationResult:"""Tier 1 validator result with one critical + one high finding."""r = ValidationResult(validator_name="SECRETS", validator_description="Secrets")diff --git a/tests/test_cli.py b/tests/test_cli.pyindex 5a55cb58..1e1cf343 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -263,11 +263,20 @@ def test_validate_preserves_linked_root_support_when_tier2_is_disabled(tmp_path:assert observed_targets == [target.resolve()][email protected]("extension", [".json", ".html", ".md"])+ ("extension", "report_formats"),+ [+ (".json", "json,html,markdown"),+ (".html", "json,html,markdown"),+ (".md", "json,html,markdown"),+ (".sarif.json", "sarif"),+ ],+)def test_similarity_cli_rejects_catalog_collision_with_every_selected_report(tmp_path: Path,monkeypatch,extension: str,+ report_formats: str,) -> None:skill = tmp_path / "skill"skill.mkdir()@@ -289,7 +298,7 @@ def test_similarity_cli_rejects_catalog_collision_with_every_selected_report("--save-catalog",str(catalog),"-r",- "json,html,markdown",+ report_formats,"-o",str(reports),],diff --git a/tests/test_oss_packaging.py b/tests/test_oss_packaging.pyindex 5d80f381..5a955733 100644--- a/tests/test_oss_packaging.py+++ b/tests/test_oss_packaging.py@@ -597,6 +597,14 @@ def test_launch_docs_address_scanner_and_naming_ambiguities() -> None:assert "are not interchangeable" in environment+def test_ci_sarif_merge_uses_uv_tool_python() -> None:+ ci = (REPO_ROOT / "docs" / "ci-integration.mdx").read_text(encoding="utf-8")++ assert 'skillevaluator_python="$(dirname "$(readlink -f "$(command -v skillevaluator)")")/python"' in ci+ assert "\"$skillevaluator_python\" - <<'PY'" in ci+ assert "python3 - <<'PY'" not in ci++def test_harbor_atif_and_agent_eval_alias_are_defined() -> None:harbor_url = "https://github.com/harbor-framework/harbor"harbor_pages = [diff --git a/tests/utils/test_helpers.py b/tests/utils/test_helpers.pyindex 4a197692..20854949 100644--- a/tests/utils/test_helpers.py+++ b/tests/utils/test_helpers.py@@ -11,6 +11,7 @@ from skillevaluator.utils import find_skills_in_directory, get_skill_name_from_pfrom skillevaluator.utils.helpers import (_ssh_to_https,resolve_git_remote_url,+ resolve_git_root,)@@ -178,6 +179,24 @@ def _init_git_repo(path: Path, remote_url: str) -> str:return subprocess.check_output(["git", "-C", str(path), "rev-parse", "HEAD"], text=True).strip()+class TestResolveGitRoot:+ """Tests for lightweight repository-root discovery used by base reports."""++ def test_resolves_nested_directory_and_file(self, tmp_path: Path) -> None:+ repo_root = tmp_path / "repo"+ _init_git_repo(repo_root, "[email protected]:example/project.git")+ nested = repo_root / "skills" / "demo"+ nested.mkdir(parents=True)+ manifest = nested / "SKILL.md"+ manifest.write_text("---\nname: demo\n---\n", encoding="utf-8")++ assert resolve_git_root(nested) == repo_root.resolve()+ assert resolve_git_root(manifest) == repo_root.resolve()++ def test_returns_none_outside_git_repository(self, tmp_path: Path) -> None:+ assert resolve_git_root(tmp_path) is None++class TestResolveGitRemoteUrl:"""Tests for the Git remote URL resolver used in HTML report links."""