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(reporting): add a JUnit XML report format (#691)

Matt Van Hornde50c8acd6c4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f3a4fafc..41f49726 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,11 @@ All notable changes to SkillEvaluator are documented in this file.
`skillevaluator-lint-scripts`. A hidden `skillevaluator precommit-run` entry
maps changed files to skill roots and runs each check without an API key,
network, Docker, or scanner download.
+- JUnit XML report format (`-r junit`, `.junit.xml`) for CI test-report
+ artifacts. One testsuite is emitted per check group, failures include
+ file:line when recorded and follow the same gate as the exit code, incomplete
+ scanners are reported as errors, and checks that did not run are skipped
+ rather than reported as passed.
- The Tier 3 report data and JSON report record which execution backend ran the
evaluation, as `execution_backend` (`harbor` or `nemo-gym`), next to the sandbox
`environment`.
diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdx
index 64e59fe4..8077cd35 100644
--- a/docs/cli-reference.mdx
+++ b/docs/cli-reference.mdx
@@ -72,10 +72,10 @@ Direct `tier1 PATH`, `tier1 validate PATH`, and `tier2 PATH` default to
| Flag | Default | Effect |
| --- | --- | --- |
-| `-r, --report [cli\|json\|html\|markdown\|sarif]` | `cli,json,html` for direct workflows; `cli` for focused commands | 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\|junit]` | `cli,json,html` for direct workflows; `cli` for focused commands | 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 focused expert 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. Direct workflows write `skillevaluator-tier1` or `skillevaluator-tier2` reports in the selected formats and also overwrite previous files with that basename. Filename conventions and report anatomy live in [Reports & Results](/skills/skillevaluator/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 focused expert 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`, `.sarif.json` with `-r sarif`, or `.junit.xml` with `-r junit`); standalone commands write a fixed `skillevaluator-<kind>` basename (for example `skillevaluator-quality.json`), so a re-run overwrites the previous report. Direct workflows write `skillevaluator-tier1` or `skillevaluator-tier2` reports in the selected formats and also overwrite previous files with that basename. Filename conventions and report anatomy live in [Reports & Results](/skills/skillevaluator/reports).
**Exit codes.** Commands communicate through a small exit-code contract — this is what your CI gates on (see [Gate Your CI](/skills/skillevaluator/ci-integration)):
diff --git a/docs/gitlab-ci.mdx b/docs/gitlab-ci.mdx
index ce3745ac..39c9ddf4 100644
--- a/docs/gitlab-ci.mdx
+++ b/docs/gitlab-ci.mdx
@@ -77,6 +77,26 @@ its detailed HTML report. JSON, Markdown and SARIF are included.
<img src="./assets/repository-ci-results-example.png" alt="Example report table showing a failed skill with a quality score of 98.2 and a link to its report" />
</Frame>
+The shared `skill-evaluation` job writes JSON, Markdown and SARIF reports; it
+does not produce JUnit XML yet. To show findings as a native GitLab
+merge-request test report, run SkillEvaluator in your own job with `-r junit`
+and attach the file it writes. `tier1` writes
+`reports/skillevaluator-tier1.junit.xml`:
+
+```yaml title="Run it yourself: JUnit test report"
+skill-junit:
+ script:
+ - skillevaluator tier1 skills/foo -r junit -o reports
+ artifacts:
+ when: always
+ reports:
+ junit: reports/skillevaluator-tier1.junit.xml
+```
+
+`skillevaluator validate` on a folder of skills writes one file per skill
+instead, as `reports/<skill>/skillevaluator-output-<timestamp>.junit.xml`;
+point `junit:` at `reports/*/*.junit.xml` for that layout.
+
The [public examples](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/examples/README.md)
include this report preview and a log excerpt without requiring access to a
separate demo project.
diff --git a/docs/reports.mdx b/docs/reports.mdx
index 34d38d48..b4f0bd0f 100644
--- a/docs/reports.mdx
+++ b/docs/reports.mdx
@@ -85,6 +85,7 @@ no-color, redirected, and string-rendered output retains readable paths.
| `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 |
+| `junit` | JUnit XML | CI systems that show native test reports need a JUnit artifact |
HTML reports use a shared NVIDIA presentation across all three tiers, with
numbered Insights cards, expandable findings, and tables alongside charts.
@@ -94,8 +95,8 @@ Saved Light, Dark and System choices take precedence when browser storage is
available; System follows changes to the device preference.
Reports, including charts, work without a network connection.
-```bash title="One run, four report files"
-skillevaluator validate ./my-skill -r json,html,markdown,sarif -o reports
+```bash title="One run, five report files"
+skillevaluator validate ./my-skill -r json,html,markdown,sarif,junit -o reports
```
For gating a pipeline on the JSON output, see [Gate Your CI](/skills/skillevaluator/ci-integration).
@@ -332,12 +333,50 @@ 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`, `.sarif.json`); the `cli` format
+The extension matches the format (`.json`, `.html`, `.md`, `.sarif.json`, `.junit.xml`); the `cli` format
prints to the terminal and never writes a file. A full `validate` run's
timestamp is `YYYYMMDDHHMMSS`, so
`-r json` produces something like `skillevaluator-output-20260709141530.json`
and never clobbers the previous run.
+## JUnit report
+
+`-r junit` writes one XML file for CI test-report consumers such as GitLab
+merge-request test reports, Jenkins, Azure Pipelines, CircleCI, and Buildkite.
+
+| JUnit element | SkillEvaluator source |
+| --- | --- |
+| `testsuites` | One document per run |
+| `testsuite` | One check group (`ValidationResult`) |
+| `testcase` | One check, finding, gate failure, or incomplete scanner |
+| `failure` | A blocking finding, with `file:line` when recorded; an independent error on a group whose scanners all completed (schema errors, `No SKILL.md found`) as a case named `error`; or a gate failure, such as a minimum score, as a case named `gate_failure` |
+| `error` | An `incomplete/<tool>` case for a scanner that did not complete, with `type="incomplete"` and the scanner's own reason when one was recorded (for example `skillspector not installed`); and, on a group with an incomplete scanner, each independent error that is not a gate failure (a crash or unusable scanner output, such as `Bandit did not return valid JSON; scan did not complete`) as a case named `error` with `type="execution"`. Other checks and findings in that group keep their real passed or failed status |
+| `skipped` | A check group that did not run and does not fail the gate, as one case with its skip reason. A blocking group that was skipped is a `gate_failure` instead |
+| `system-out` | Score and threshold when recorded, and non-failing finding text |
+
+Counts on `testsuites` and each `testsuite` (`tests`, `failures`, `errors`,
+`skipped`, `time`) match the cases they contain. A finding case is named
+after its check and location, `check_name (path:line)` (or `check_name (path)`
+when no line was recorded), so adding or reordering findings does not rename
+the others in CI test history. File paths are relative to the Git repository
+root that contains the target (the target folder when it is not in a Git
+repository), from `validate` and from single-check commands alike. SARIF uses the
+same base, resolution rules, and percent-encoding, so a file
+name that is not valid UTF-8 stays distinct (`caf%E9.md`). In other text such a
+name is backslash-escaped (`caf\xe9.md`), then characters XML 1.0 forbids are
+stripped. An incomplete scan is never emitted as an all-passed suite, and a
+run that failed on one never reports `failures` and `errors` both zero.
+
+Failures follow the same gate as the exit code. When `validate` marks a group
+as blocking and it fails the gate with no failing case of its own, for example
+a scored Tier 3 verdict of FAIL or NEUTRAL under `--block-on-agent-eval`, the
+suite gets a `gate_failure` case whose message is the cause: the first error,
+the Tier 3 verdict, or the skip reason. An advisory group (Tier 3 without
+`--block-on-agent-eval`, Tier 2 with `--no-block-on-dedup`) never adds a
+`failure` or `error`; its findings, errors, and execution errors are kept in
+`system-out` with an `Advisory, does not gate:` prefix, and its incomplete
+scanners are `skipped`.
+
## HTML report
The HTML report is one self-contained file. It opens on the answer and puts
diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx
index 26acd8cf..653c639a 100644
--- a/docs/tier1-validation.mdx
+++ b/docs/tier1-validation.mdx
@@ -108,7 +108,7 @@ for skills. Its Tier 1 LLM checks still run only when requested.
Direct `tier1 PATH` and `tier1 validate PATH` print the terminal report and
write JSON and HTML reports by default. Use `-r cli` for terminal-only output.
-Reports for any of these runs are selected with `-r`/`--report` (`cli`, `json`, `html`, `markdown`, `sarif`) and written to `-o`/`--output-dir` (default `reports/`). File naming, `BENCHMARK.md`, and the JSON contract are covered in [Reports & Results](/skills/skillevaluator/reports).
+Reports for any of these runs are selected with `-r`/`--report` (`cli`, `json`, `html`, `markdown`, `sarif`, `junit`) and written to `-o`/`--output-dir` (default `reports/`). File naming, `BENCHMARK.md`, and the JSON contract are covered in [Reports & Results](/skills/skillevaluator/reports).
## Content types
diff --git a/skills/skillevaluator/SKILL.md b/skills/skillevaluator/SKILL.md
index 6da7fd72..ddb9faf3 100644
--- a/skills/skillevaluator/SKILL.md
+++ b/skills/skillevaluator/SKILL.md
@@ -86,6 +86,7 @@ Never print, echo, or commit API keys; keep them in the host environment.
| Same, without Docker | `skillevaluator tier3 evaluate <skill-dir> -a opencode --env-mode local` | provider, agent CLI on host |
| Everything, with one exit code | `skillevaluator validate <skill-dir>` | all of the above |
| CI-safe keyless gate | `skillevaluator validate <skills-dir> --profile default --tiers 1 -r json,markdown,sarif -o reports` | scanners |
+| CI test report (JUnit XML) | add `junit` to `-r`, for example `-r json,sarif,junit` | same as the gate |
| Set up repo CI | `skillevaluator ci init` | GitHub checkout |
Full flag tables: [Tier 1](references/commands-tier1.md),
diff --git a/skills/skillevaluator/references/commands-tier1.md b/skills/skillevaluator/references/commands-tier1.md
index 5ba21f55..3ab4c0ba 100644
--- a/skills/skillevaluator/references/commands-tier1.md
+++ b/skills/skillevaluator/references/commands-tier1.md
@@ -8,7 +8,7 @@ Global options go before the command: `skillevaluator -v validate <skill-dir>`.
| Flag | Default | Effect |
| --- | --- | --- |
-| `-r, --report` | `cli,json,html` for `tier1 PATH`, `tier2 PATH`, `validate`; `cli` for focused commands | `cli`, `json`, `html`, `markdown`, `sarif`; comma-separated or repeated |
+| `-r, --report` | `cli,json,html` for `tier1 PATH`, `tier2 PATH`, `validate`; `cli` for focused commands | `cli`, `json`, `html`, `markdown`, `sarif`, `junit`; comma-separated or repeated |
| `-o, --output-dir` | `reports` | Report directory |
Passing `-r` is honored exactly: `-r cli` writes no files. Basenames:
diff --git a/skills/skillevaluator/references/reports-and-ci.md b/skills/skillevaluator/references/reports-and-ci.md
index d46dfe05..8c903ec8 100644
--- a/skills/skillevaluator/references/reports-and-ci.md
+++ b/skills/skillevaluator/references/reports-and-ci.md
@@ -39,6 +39,12 @@ skillevaluator validate <skills-dir> --profile default --tiers 1 -c \
-r json,markdown,sarif -o reports --min-score 70
```
+Add `junit` to `-r` when the CI system shows native test reports (GitLab
+`artifacts:reports:junit`, Jenkins, Azure Pipelines). `tier1` writes
+`skillevaluator-tier1.junit.xml`; `validate` on a skills folder writes
+`<skill>/skillevaluator-output-<timestamp>.junit.xml` per skill. JUnit
+failures follow the same gate as the exit code.
+
Adopt progressively: run with `|| true` (advisory), then gate on Tier 1,
raise `--min-score`, add `--llm --tiers 1,2` with a masked provider secret,
and finally an advisory Tier 3 job (`--block-on-agent-eval` when ready).
diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.py
index 131af78a..d606446d 100644
--- a/src/skillevaluator/cli.py
+++ b/src/skillevaluator/cli.py
@@ -68,6 +68,7 @@ from skillevaluator.tier1.commands import (
)
from skillevaluator.tier3_environments import all_env_modes
from skillevaluator.tier_group import TierGroup
+from skillevaluator.utils.helpers import resolve_git_root
from skillevaluator.utils.json_output import json_needs_ascii
from skillevaluator.utils.path_security import resolve_repo_context_root
from skillevaluator.utils.rich_markup import escape_markup, strip_terminal_controls
@@ -407,6 +408,7 @@ _FILE_REPORT_EXTENSIONS = {
"html": ".html",
"markdown": ".md",
"sarif": ".sarif.json",
+ "junit": ".junit.xml",
}
@@ -498,7 +500,7 @@ def _report_options(func):
"report_formats",
cls=_MultiValueOption,
multiple=True,
- type=click.Choice(["cli", "json", "html", "markdown", "sarif"]),
+ type=click.Choice(["cli", "json", "html", "markdown", "sarif", "junit"]),
default=("cli",),
show_default=True,
help="Report format(s). Accepts comma- or space-separated values "
@@ -619,6 +621,19 @@ def _resolve_report_output_location(target_path: Path, output_dir: Path) -> Path
)
+def _report_roots(target_path: Path) -> dict[str, Path]:
+ """Return the scan and repository roots SARIF and JUnit paths are made relative to.
+
+ The repository root is the Git root containing *target_path*, so a finding
+ reads the same repository-relative ``file`` from every command; outside Git
+ it falls back to the target folder.
+ """
+ repository_root = resolve_git_root(target_path)
+ if repository_root is None:
+ repository_root = target_path if target_path.is_dir() else target_path.parent
+ return {"scan_root": target_path, "repository_root": repository_root}
+
+
def _resolve_file_report_output_location(
target_path: Path,
output_dir: Path,
@@ -1984,7 +1999,7 @@ def _finish_pipeline_view(
details += (context.coverage.text, *context.coverage.details)
details += (f"Publication eligibility: {context.publication_label}",)
- ext = {"html": ".html", "json": ".json", "markdown": ".md", "sarif": ".sarif.json"}
+ ext = {"html": ".html", "json": ".json", "markdown": ".md", "sarif": ".sarif.json", "junit": ".junit.xml"}
links: list[tuple[str, str]] = [
("report" if fmt == "html" else fmt, str(output_dir / f"{basename}{ext[fmt]}"))
for fmt in report_formats
@@ -2617,7 +2632,7 @@ def validate(
)
from skillevaluator.reporting import CLIReporter
from skillevaluator.reporting.naming import REPORT_PREFIX
- from skillevaluator.utils.helpers import make_timestamped_basename, resolve_git_remote_url, resolve_git_root
+ from skillevaluator.utils.helpers import make_timestamped_basename, resolve_git_remote_url
from skillevaluator.validators.policy import apply_policy, resolve_policy
if external and profile and profile not in {"default", "external"}:
@@ -3024,9 +3039,6 @@ 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
@@ -3056,8 +3068,8 @@ def validate(
explicit_skill_name=publication_name if resolved_type == CONTENT_TYPE_SKILL and target_path.is_dir() else None,
content_label=content_label,
announce_paths=not quiet,
- sarif_scan_root=target_path,
- sarif_repository_root=sarif_repository_root,
+ **_report_roots(target_path),
+ catalog_root=catalog_root,
)
_record_validate_json_report(f"{report_basename_value}.json" if "json" in effective_formats else None)
if harness_rows and "json" in effective_formats:
@@ -3258,6 +3270,7 @@ def quality_check(
report_formats=report_formats,
output_dir=output_dir,
basename=report_basename("quality"),
+ **_report_roots(target_path),
):
raise click.ClickException("quality check failed")
@@ -3274,6 +3287,7 @@ def rubric_eval(target_path: Path, min_score: int, report_formats: tuple[str, ..
report_formats=report_formats,
output_dir=output_dir,
basename=report_basename("rubric"),
+ **_report_roots(target_path),
):
raise click.ClickException("rubric evaluation failed")
@@ -3301,6 +3315,7 @@ def security_scan(
report_formats=report_formats,
output_dir=output_dir,
basename=report_basename("security"),
+ **_report_roots(target_path),
):
raise click.ClickException("security scan failed")
@@ -3324,6 +3339,7 @@ def pii_scan(
report_formats=report_formats,
output_dir=output_dir,
basename=report_basename("pii"),
+ **_report_roots(target_path),
):
raise click.ClickException("PII scan failed")
@@ -3339,6 +3355,7 @@ def lint_scripts(target_path: Path, report_formats: tuple[str, ...], output_dir:
report_formats=report_formats,
output_dir=output_dir,
basename=report_basename("script-lint"),
+ **_report_roots(target_path),
):
raise click.ClickException("script lint failed")
@@ -3465,6 +3482,7 @@ def similarity_check(
report_formats=report_formats,
output_dir=output_dir,
basename=similarity_basename,
+ **_report_roots(content_path),
):
raise click.ClickException("similarity check failed")
@@ -3495,6 +3513,7 @@ def context_optimization_check(
report_formats=report_formats,
output_dir=output_dir,
basename=report_basename("context"),
+ **_report_roots(skill_path),
):
raise click.ClickException("context optimization check failed")
@@ -3530,6 +3549,7 @@ def dedup_scan(
report_formats=report_formats,
output_dir=output_dir,
basename=report_basename("dedup"),
+ **_report_roots(skill_path),
):
raise click.ClickException("dedup scan failed")
@@ -3618,6 +3638,11 @@ def _tier1_workflow(
policy = resolve_policy(profile=profile, policy_path=policy_path)
except (FileNotFoundError, ValueError) as exc:
raise click.ClickException(str(exc)) from exc
+ # Validators build finding paths from this root, so it is made absolute, as
+ # validate does: a relative root leaves finding paths relative to the working
+ # directory, and the report roots would then prefix the skill folder twice.
+ target_label = str(skill_path)
+ skill_path = skill_path.resolve()
results = run_tier1_workflow(
skill_path,
checks=checks,
@@ -3632,14 +3657,15 @@ def _tier1_workflow(
prepare_scanners=lambda: _offer_scanner_install(checks, skip),
)
# Resolved after the run so configuration errors still leave no output.
- output_dir = _resolve_file_report_output_location(skill_path.resolve(), output_dir, report_formats)
+ output_dir = _resolve_file_report_output_location(skill_path, output_dir, report_formats)
if not emit_reports(
results,
report_formats=report_formats,
output_dir=output_dir,
basename=report_basename("tier1"),
policy=policy,
- target_path=str(skill_path),
+ target_path=target_label,
+ **_report_roots(skill_path),
):
raise click.ClickException("Tier 1 checks failed or were incomplete")
@@ -3709,6 +3735,7 @@ def _tier2_workflow(
output_dir=resolved_output_dir,
basename=basename,
target_path=str(skill_path),
+ **_report_roots(skill_path),
):
raise click.ClickException("Tier 2 checks failed or were incomplete")
diff --git a/src/skillevaluator/reporting/__init__.py b/src/skillevaluator/reporting/__init__.py
index eac1d630..292e4b85 100644
--- a/src/skillevaluator/reporting/__init__.py
+++ b/src/skillevaluator/reporting/__init__.py
@@ -11,6 +11,7 @@ in various formats for different use cases:
- HTMLReporter: Standalone HTML reports for archiving/sharing
- MarkdownReporter: Markdown for PR comments and documentation
- SARIFReporter: SARIF 2.1.0 for GitHub Code Scanning
+- JUnitReporter: JUnit XML for CI test-report consumers
All reporters consume the same ValidationResult data structure from
skillevaluator.models, ensuring consistent information across all output formats.
@@ -36,6 +37,7 @@ from skillevaluator.reporting.benchmark import BenchmarkReporter
from skillevaluator.reporting.cli import CLIReporter
from skillevaluator.reporting.html import HTMLReporter
from skillevaluator.reporting.json_reporter import JSONReporter
+from skillevaluator.reporting.junit_reporter import JUnitReporter
from skillevaluator.reporting.markdown import MarkdownReporter
from skillevaluator.reporting.sarif_reporter import SARIFReporter
@@ -44,6 +46,7 @@ __all__ = [
"CLIReporter",
"HTMLReporter",
"JSONReporter",
+ "JUnitReporter",
"MarkdownReporter",
"ReporterBase",
"SARIFReporter",
diff --git a/src/skillevaluator/reporting/base.py b/src/skillevaluator/reporting/base.py
index ac687f47..a8b64b7d 100644
--- a/src/skillevaluator/reporting/base.py
+++ b/src/skillevaluator/reporting/base.py
@@ -2725,5 +2725,6 @@ class ReporterBase(ABC):
"html": ".html",
"markdown": ".md",
"sarif": ".sarif.json",
+ "junit": ".junit.xml",
}
return extensions.get(self.name, ".txt")
diff --git a/src/skillevaluator/reporting/junit_reporter.py b/src/skillevaluator/reporting/junit_reporter.py
new file mode 100644
index 00000000..38cefc27
--- /dev/null
+++ b/src/skillevaluator/reporting/junit_reporter.py
@@ -0,0 +1,483 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""JUnit XML reporter for CI test-report consumers.
+
+Produces a JUnit XML document with one ``testsuite`` per check group
+(``ValidationResult``) and one ``testcase`` per check, finding, gate failure, or
+incomplete scanner. CI systems that ingest JUnit reports (GitLab merge-request
+test reports, Jenkins, Azure Pipelines, CircleCI, Buildkite) read this format.
+
+File paths are stored as repository- or scan-root-relative POSIX paths using the
+same resolution rules as the SARIF reporter, percent-encoded as SARIF does so a
+file name that is not valid UTF-8 stays distinct (``caf\\udce9.md`` becomes
+``caf%E9.md``). In other text, lone surrogates are written as backslash escapes,
+then characters XML 1.0 forbids are stripped before serialization.
+
+When the reporter knows the evaluated target, suite names and testcase
+classnames are qualified with its repository-relative path (for example
+``group-a/demo::Schema & Repository Governance``), so reports from several
+targets collected into one CI test report keep distinct test identities.
+A finding case is named after its check and location (``check (path:line)``), so
+its identity does not shift when other findings are added or reordered.
+"""
+
+from __future__ import annotations
+
+import xml.etree.ElementTree as ET
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from skillevaluator.reporting.base import (
+ ReporterBase,
+ get_skip_reason,
+ is_cleanly_skipped,
+ passes_required_gate,
+)
+from skillevaluator.reporting.run_status import Status, finding_blocks, result_status
+from skillevaluator.reporting.sarif_reporter import (
+ _positive_start_line,
+ _quote_uri_path,
+ _resolve_artifact_path,
+ _workspace_relative_path,
+)
+
+if TYPE_CHECKING:
+ from skillevaluator.models import Finding, ValidationResult
+
+_XML_DECLARATION = '<?xml version="1.0" encoding="UTF-8"?>\n'
+
+
+def _xml_char_allowed(character: str) -> bool:
+ """Return whether *character* is legal in XML 1.0 text."""
+ code = ord(character)
+ if code in {0x9, 0xA, 0xD}:
+ return True
+ if 0x20 <= code <= 0xD7FF:
+ return True
+ if 0xE000 <= code <= 0xFFFD:
+ return True
+ return 0x10000 <= code <= 0x10FFFF
+
+
+def _escape_surrogates(text: str) -> str:
+ """Return *text* with lone surrogates written as backslash escapes.
+
+ A file name that is not valid UTF-8 arrives with surrogate escapes, which
+ XML cannot hold; escaping them keeps ``caf\\udce9.md`` distinct from
+ ``caf.md`` (it becomes ``caf\\xe9.md``).
+ """
+ try:
+ return text.encode("utf-8", "surrogateescape").decode("utf-8", "backslashreplace")
+ except UnicodeEncodeError:
+ return text.encode("utf-8", "backslashreplace").decode("utf-8")
+
+
+def _xml_text(value: object) -> str:
+ """Return *value* as XML 1.0 text, dropping characters the spec forbids."""
+ if value is None:
+ text = ""
+ elif isinstance(value, str):
+ text = value
+ else:
+ text = str(value)
+ text = _escape_surrogates(text).replace("\r\n", "\n").replace("\r", "\n")
+ return "".join(character for character in text if _xml_char_allowed(character))
+
+
+def _junit_file_path(
+ file_path: object,
+ workspace_root: Path | None,
+ scan_root: Path | None,
+) -> str:
+ """Return a percent-encoded POSIX path relative to the scanned workspace, matching SARIF."""
+ if not isinstance(file_path, str) or not file_path.strip():
+ return ""
+ raw = file_path.strip()
+ path = _resolve_artifact_path(raw, scan_root)
+ if workspace_root is not None and (path.is_absolute() or path.root):
+ relative = _workspace_relative_path(path, raw, workspace_root, scan_root)
+ if relative is not None:
+ return _quote_uri_path(relative.as_posix())
+ if scan_root is not None:
+ try:
+ return _quote_uri_path(path.resolve().relative_to(scan_root.resolve()).as_posix())
+ except ValueError:
+ pass
+ if path.is_absolute() or path.root:
+ return _quote_uri_path(path.as_posix())
+ return _quote_uri_path(raw.replace("\\", "/"))
+
+
+def _relative_posix(path: Path, root: Path | None) -> str | None:
+ """Return *path* relative to *root* as POSIX text, or None when outside it."""
+ if root is None:
+ return None
+ try:
+ relative = path.relative_to(root.resolve())
+ except (OSError, ValueError):
+ return None
+ text = relative.as_posix()
+ return None if text in {"", "."} else text
+
+
+def junit_target_identity(
+ scan_root: Path | None,
+ repository_root: Path | None = None,
+ catalog_root: Path | None = None,
+) -> str:
+ """Return a stable identity for the evaluated target.
+
+ The target's path relative to the repository root comes first, then its path
+ relative to the catalog folder it was found in, then its own name. The same
+ leaf name under two catalog groups (``group-a/demo`` and ``group-b/demo``)
+ therefore yields two identities.
+ """
+ if scan_root is None:
+ return ""
+ try:
+ target = scan_root.resolve()
+ except OSError:
+ target = scan_root
+ for root in (repository_root, catalog_root):
+ relative = _relative_posix(target, root)
+ if relative is not None:
+ return _xml_text(relative)
+ return _xml_text(target.name)
+
+
+def _qualified(target: str, name: str) -> str:
+ return f"{target}::{name}" if target else name
+
+
+def _failure_body(finding: Finding, file_path: str) -> str:
+ """Return failure text with file:line when the finding records a location."""
+ line = _positive_start_line(finding.line_number)
+ if file_path and line is not None:
+ location = f"{file_path}:{line}"
+ elif file_path:
+ location = file_path
+ else:
+ location = ""
+ message = _xml_text(finding.message)
+ body = f"{location}: {message}" if location else message
+ suggestion = _xml_text(finding.suggestion) if finding.suggestion else ""
+ if suggestion:
+ return f"{body}\nSuggestion: {suggestion}"
+ return body
+
+
+def _finding_case_name(check_name: str, file_path: str, line: int | None) -> str:
+ """Return a finding case name keyed on its location, not its position in the list.
+
+ ``quality_correctness (SKILL.md:12)`` stays the same when other findings are
+ added or reordered, so CI test history keyed on suite, class and name holds.
+ """
+ stem = check_name or "finding"
+ if not file_path:
+ return stem
+ location = f"{file_path}:{line}" if line is not None else file_path
+ return f"{stem} ({location})"
+
+
+def _unique_name(base: str, used: set[str]) -> str:
+ stem = base or "check"
+ name = stem
+ index = 2
+ while name in used:
+ name = f"{stem}-{index}"
+ index += 1
+ used.add(name)
+ return name
+
+
+def _suite_system_out(result: ValidationResult) -> str:
+ """Return score and threshold text when the result records them."""
+ metadata = result.metadata if isinstance(result.metadata, dict) else {}
+ lines: list[str] = []
+ quality = metadata.get("quality_scores")
+ if isinstance(quality, dict) and quality.get("overall_score") is not None:
+ score = quality["overall_score"]
+ grade = quality.get("grade")
+ if grade:
+ lines.append(f"Score: {score}/100 (Grade: {grade})")
+ else:
+ lines.append(f"Score: {score}/100")
+ config = metadata.get("quality_config")
+ if isinstance(config, dict) and config.get("min_score") is not None:
+ lines.append(f"Threshold: {config['min_score']}/100")
+ rubric = metadata.get("rubric_eval")
+ if isinstance(rubric, dict) and rubric.get("overall_score") is not None:
+ lines.append(f"Rubric score: {rubric['overall_score']}/100")
+ if rubric.get("min_score") is not None:
+ lines.append(f"Rubric threshold: {rubric['min_score']}/100")
+ return _xml_text("\n".join(lines))
+
+
+def _set_counts(element: ET.Element, *, tests: int, failures: int, errors: int, skipped: int) -> None:
+ element.set("tests", str(tests))
+ element.set("failures", str(failures))
+ element.set("errors", str(errors))
+ element.set("skipped", str(skipped))
+ element.set("time", "0")
+
+
+@dataclass(slots=True, frozen=True)
+class _Case:
+ name: str
+ classname: str
+ failed: bool = False
+ errored: bool = False
+ error_type: str = ""
+ skipped: bool = False
+ message: str = ""
+ body: str = ""
+ file_path: str = ""
+ line: int | None = None
+ system_out: str = ""
+
+
+def _gating(result: ValidationResult) -> dict | None:
+ """Return the gate ``validate`` stamped on *result*, or None when it has none."""
+ metadata = result.metadata if isinstance(result.metadata, dict) else {}
+ gating = metadata.get("gating")
+ return gating if isinstance(gating, dict) else None
+
+
+def _failure_reason(result: ValidationResult) -> str:
+ """Return the real cause of a failed result for a synthetic failure case."""
+ if result.errors:
+ return _xml_text(result.errors[0])
+ metadata = result.metadata if isinstance(result.metadata, dict) else {}
+ payload = metadata.get("agent_eval")
+ if isinstance(payload, dict) and payload.get("execution_status") == "succeeded" and payload.get("verdict"):
+ return _xml_text(f"Tier 3 verdict {str(payload['verdict']).upper()} does not pass the required gate")
+ provenance = payload.get("provenance") if isinstance(payload, dict) else None
+ if metadata.get("skip_reason") or result.warnings or (isinstance(provenance, dict) and provenance.get("message")):
+ return _xml_text(get_skip_reason(result))
+ return "failed"
+
+
+def _incomplete_reason(result: ValidationResult, tool: str) -> str:
+ """Return the first warning or error that names *tool*, else a generic incomplete-scan reason."""
+ needle = tool.casefold()
+ for text in (*result.warnings, *result.errors):
+ if isinstance(text, str) and needle in text.casefold():
+ return _xml_text(text)
+ return _xml_text(f"{tool} scan did not complete")
+
+
+def _cases_for_result(
+ result: ValidationResult,
+ workspace_root: Path | None,
+ scan_root: Path | None,
+ target: str = "",
+) -> list[_Case]:
+ validator = _xml_text(result.validator_name) or "check"
+ classname = _qualified(target, validator)
+ used: set[str] = set()
+ # A skip that run status reports as failed (a blocking gate that did not run)
+ # falls through to the gate_failure case below rather than a <skipped> case.
+ if is_cleanly_skipped(result) and result_status(result) == Status.SKIPPED:
+ return [
+ _Case(
+ name=_unique_name(validator, used),
+ classname=classname,
+ skipped=True,
+ message=_xml_text(get_skip_reason(result)),
+ body=_xml_text(get_skip_reason(result)),
+ )
+ ]
+
+ cases: list[_Case] = []
+ for finding in result.findings:
+ file_path = _junit_file_path(finding.file_path, workspace_root, scan_root)
+ line = _positive_start_line(finding.line_number)
+ failed = finding_blocks(result, finding)
+ name = _unique_name(_finding_case_name(_xml_text(finding.check_name), file_path, line), used)
+ detail = _failure_body(finding, file_path)
+ cases.append(
+ _Case(
+ name=name,
+ classname=classname,
+ failed=failed,
+ message=_xml_text(finding.message),
+ body=detail if failed else "",
+ file_path=file_path,
+ line=line,
+ system_out="" if failed else detail,
+ )
+ )
+ for success in result.success_details:
+ cases.append(
+ _Case(
+ name=_unique_name(_xml_text(success.check_name) or "check", used),
+ classname=classname,
+ system_out=_xml_text(success.message),
+ )
+ )
+ gate_failures = set(result.gate_failures)
+ # A group with an incomplete scan recorded that a scanner could not run or crashed,
+ # so its independent errors are execution diagnostics: JUnit <error>, not <failure>.
+ # Gate failures (a minimum score, for example) stay <failure> either way.
+ scan_incomplete = bool(result.incomplete_scans)
+ for error in result.independent_errors():
+ is_gate = error in gate_failures
+ execution = scan_incomplete and not is_gate
+ cases.append(
+ _Case(
+ name=_unique_name("gate_failure" if is_gate else "error", used),
+ classname=classname,
+ failed=not execution,
+ errored=execution,
+ error_type="execution" if execution else "",
+ message=_xml_text(error),
+ body=_xml_text(error),
+ )
+ )
+ for tool in result.incomplete_scans:
+ # An incomplete scan fails the run, so it is an <error>, never a <skipped> case.
+ reason = _incomplete_reason(result, tool)
+ cases.append(
+ _Case(
+ name=_unique_name(_xml_text(f"incomplete/{tool}"), used),
+ classname=classname,
+ errored=True,
+ error_type="incomplete",
+ message=reason,
+ body=reason,
+ )
+ )
+ gating = _gating(result)
+ if gating is not None and not gating.get("blocking", True):
+ # An advisory result never fails the exit gate, so it fails or errors no case here:
+ # incomplete scanners are skipped, and failures and execution errors move to system-out.
+ cases = [
+ _Case(
+ name=case.name,
+ classname=case.classname,
+ skipped=case.skipped or case.error_type == "incomplete",
+ message=case.message if case.skipped or case.error_type == "incomplete" else "",
+ body=case.body if case.skipped or case.error_type == "incomplete" else "",
+ file_path=case.file_path,
+ line=case.line,
+ system_out=(
+ f"Advisory, does not gate: {case.body}"
+ if case.failed or case.error_type == "execution"
+ else case.system_out
+ ),
+ )
+ for case in cases
+ ]
+ needs_failure = not passes_required_gate(result) and not any(case.failed or case.errored for case in cases)
+ if needs_failure:
+ message = _failure_reason(result)
+ cases.append(
+ _Case(
+ name=_unique_name("gate_failure" if gating is not None else "error", used),
+ classname=classname,
+ failed=True,
+ message=message,
+ body=message,
+ )
+ )
+ elif not cases:
+ note = _failure_reason(result) if not result.passed else "passed"
+ cases.append(_Case(name=validator, classname=classname, system_out=note))
+ return cases
+
+
+def _append_case(suite: ET.Element, case: _Case) -> None:
+ testcase = ET.SubElement(suite, "testcase")
+ testcase.set("name", case.name)
+ testcase.set("classname", case.classname)
+ testcase.set("time", "0")
+ if case.file_path:
+ testcase.set("file", case.file_path)
+ if case.line is not None:
+ testcase.set("line", str(case.line))
+ if case.skipped:
+ skipped = ET.SubElement(testcase, "skipped")
+ if case.message:
+ skipped.set("message", case.message)
+ if case.body:
+ skipped.text = case.body
+ elif case.errored:
+ error = ET.SubElement(testcase, "error")
+ if case.message:
+ error.set("message", case.message)
+ error.set("type", case.error_type or "error")
+ if case.body:
+ error.text = case.body
+ elif case.failed:
+ failure = ET.SubElement(testcase, "failure")
+ if case.message:
+ failure.set("message", case.message)
+ failure.set("type", "failure")
+ if case.body:
+ failure.text = case.body
+ if case.system_out:
+ system_out = ET.SubElement(testcase, "system-out")
+ system_out.text = case.system_out
+
+
+class JUnitReporter(ReporterBase):
+ """JUnit XML export for CI test-report integrations."""
+
+ def __init__(
+ self,
+ *,
+ workspace_root: Path | None = None,
+ scan_root: Path | None = None,
+ target_identity: str | None = None,
+ ) -> None:
+ self.workspace_root = workspace_root
+ self.scan_root = scan_root
+ self.target_identity = _xml_text(target_identity) if target_identity else ""
+
+ @property
+ def name(self) -> str:
+ return "junit"
+
+ @property
+ def description(self) -> str:
+ return "JUnit XML for GitLab, Jenkins, and other CI test-report consumers"
+
+ def render(self, result: ValidationResult) -> str:
+ return self.render_all([result])
+
+ def render_all(self, results: list[ValidationResult]) -> str:
+ testsuites = ET.Element("testsuites")
+ testsuites.set("name", "SkillEvaluator")
+ total_tests = 0
+ total_failures = 0
+ total_errors = 0
+ total_skipped = 0
+ for result in results:
+ cases = _cases_for_result(result, self.workspace_root, self.scan_root, self.target_identity)
+ suite = ET.SubElement(testsuites, "testsuite")
+ suite.set("name", _qualified(self.target_identity, _xml_text(result.validator_name) or "check"))
+ failures = sum(1 for case in cases if case.failed)
+ errors = sum(1 for case in cases if case.errored)
+ skipped = sum(1 for case in cases if case.skipped)
+ _set_counts(suite, tests=len(cases), failures=failures, errors=errors, skipped=skipped)
+ for case in cases:
+ _append_case(suite, case)
+ system_out_text = _suite_system_out(result)
+ if system_out_text:
+ system_out = ET.SubElement(suite, "system-out")
+ system_out.text = system_out_text
+ total_tests += len(cases)
+ total_failures += failures
+ total_errors += errors
+ total_skipped += skipped
+ _set_counts(testsuites, tests=total_tests, failures=total_failures, errors=total_errors, skipped=total_skipped)
+ ET.indent(testsuites, space=" ")
+ body = ET.tostring(testsuites, encoding="unicode")
+ if not body.endswith("\n"):
+ body += "\n"
+ return _XML_DECLARATION + body
+
+ def get_file_extension(self) -> str:
+ return ".junit.xml"
diff --git a/src/skillevaluator/reporting/plugin_runtime_render.py b/src/skillevaluator/reporting/plugin_runtime_render.py
index 4fef6ef7..08b5b678 100644
--- a/src/skillevaluator/reporting/plugin_runtime_render.py
+++ b/src/skillevaluator/reporting/plugin_runtime_render.py
@@ -37,6 +37,8 @@ def _augment(reporter: ReporterBase, document: str, payload: dict) -> str:
data = json.loads(document)
data["runs"][0].setdefault("properties", {})["pluginRuntime"] = payload
return json.dumps(data, indent=reporter.indent, ensure_ascii=True, allow_nan=False)
+ if reporter.name == "junit":
+ return document
if reporter.name == "html":
raise ValueError("HTML runtime evidence must be supplied to render_all before rendering")
options = {
diff --git a/src/skillevaluator/reporting/plugin_static_render.py b/src/skillevaluator/reporting/plugin_static_render.py
index a729fb37..96f39b41 100644
--- a/src/skillevaluator/reporting/plugin_static_render.py
+++ b/src/skillevaluator/reporting/plugin_static_render.py
@@ -125,6 +125,8 @@ def _augment(
if component is not None:
row.setdefault("properties", {})["pluginComponent"] = component
return json.dumps(data, indent=reporter.indent, ensure_ascii=True, allow_nan=False)
+ if reporter.name == "junit":
+ return document
if reporter.name == "html":
return reporter.render_all(results, plugin_static=payload)
if reporter.name in {"markdown", "benchmark"}:
diff --git a/src/skillevaluator/reporting/run_status.py b/src/skillevaluator/reporting/run_status.py
index 6cb96a7e..192d16bf 100644
--- a/src/skillevaluator/reporting/run_status.py
+++ b/src/skillevaluator/reporting/run_status.py
@@ -17,8 +17,10 @@ from functools import cached_property
from types import MappingProxyType
from typing import TYPE_CHECKING
+from skillevaluator.models.result import Severity
+
if TYPE_CHECKING:
- from skillevaluator.models.result import ValidationResult
+ from skillevaluator.models.result import Finding, ValidationResult
from skillevaluator.reporting.base import PublicationAssessment
from skillevaluator.reporting.base import (
assess_publication,
@@ -79,21 +81,31 @@ class RunStatus:
return outcome if outcome is not None else result_status(result)
-def _blocking_finding(result: ValidationResult) -> bool:
- for finding in result.findings:
- if finding.severity.is_error() or finding.to_legacy_string() in result.errors:
+def finding_blocks(result: ValidationResult, finding: Finding) -> bool:
+ """Return whether *finding* blocks *result*.
+
+ A finding blocks when its severity is an error or when the validator recorded
+ its legacy line in ``result.errors`` (for example a MEDIUM finding added with
+ ``is_error=True``, or one under a fail-on-medium policy).
+ """
+ severity = finding.severity
+ if (isinstance(severity, Severity) and severity.is_error()) or finding.to_legacy_string() in result.errors:
+ return True
+ # Folder merges prefix legacy errors and place those same labels inside
+ # finding paths. Respect fail-on-medium/low in either representation.
+ location, prefix = finding.location or "", ""
+ while location.startswith("[") and "] " in location:
+ label, _, location = location.partition("] ")
+ prefix += label + "] "
+ if f"{prefix}{finding.tag} {finding.message} in {location}" in result.errors:
return True
- # Folder merges prefix legacy errors and place those same labels inside
- # finding paths. Respect fail-on-medium/low in either representation.
- location, prefix = finding.location or "", ""
- while location.startswith("[") and "] " in location:
- label, _, location = location.partition("] ")
- prefix += label + "] "
- if f"{prefix}{finding.tag} {finding.message} in {location}" in result.errors:
- return True
return False
+def _blocking_finding(result: ValidationResult) -> bool:
+ return any(finding_blocks(result, finding) for finding in result.findings)
+
+
def result_status(result: ValidationResult) -> Status:
metadata = result.metadata if isinstance(result.metadata, dict) else {}
if _blocking_finding(result) or metadata.get("confirmed_failure") is True:
diff --git a/src/skillevaluator/tier1/commands.py b/src/skillevaluator/tier1/commands.py
index 374843fc..8c4b634b 100644
--- a/src/skillevaluator/tier1/commands.py
+++ b/src/skillevaluator/tier1/commands.py
@@ -39,7 +39,15 @@ from skillevaluator.publication_identity import (
publication_paths_skipped_by_scan,
publication_target_from_path,
)
-from skillevaluator.reporting import CLIReporter, HTMLReporter, JSONReporter, MarkdownReporter, SARIFReporter
+from skillevaluator.reporting import (
+ CLIReporter,
+ HTMLReporter,
+ JSONReporter,
+ JUnitReporter,
+ MarkdownReporter,
+ SARIFReporter,
+)
+from skillevaluator.reporting.junit_reporter import junit_target_identity
from skillevaluator.reporting.naming import DEFAULT_REPORT_BASENAME
from skillevaluator.reporting.presentation import FinalRenderContext, build_final_render_context
from skillevaluator.reporting.run_status import result_tier
@@ -153,6 +161,7 @@ REPORTERS = {
"html": HTMLReporter,
"markdown": MarkdownReporter,
"sarif": SARIFReporter,
+ "junit": JUnitReporter,
}
@@ -643,8 +652,9 @@ def emit_reports(
explicit_skill_name: str | None = None,
content_label: str = "Skill",
announce_paths: bool = True,
- sarif_scan_root: Path | None = None,
- sarif_repository_root: Path | None = None,
+ scan_root: Path | None = None,
+ repository_root: Path | None = None,
+ catalog_root: Path | None = None,
requested_tiers: tuple[int, ...] | None = None,
displayed_tiers: tuple[int, ...] | None = None,
presentation_context: FinalRenderContext | None = None,
@@ -663,6 +673,10 @@ def emit_reports(
The JSON report records *target_path* too. *explicit_skill_name* names
the one skill a single-skill run validated, so the JSON ``skills`` list
names it even when no finding path or quality score does.
+
+ *scan_root* is the evaluated target and *repository_root* the base that
+ SARIF and JUnit file paths are made relative to (the Git root when the
+ target is inside a repository); both formats get the same pair.
"""
if policy is not None:
apply_policy(results, policy)
@@ -692,9 +706,12 @@ def emit_reports(
expected_skill_name=expected_skill_name,
)
elif fmt == "sarif":
+ reporter = reporter_cls(workspace_root=repository_root, scan_root=scan_root)
+ elif fmt == "junit":
reporter = reporter_cls(
- workspace_root=sarif_repository_root,
- scan_root=sarif_scan_root,
+ workspace_root=repository_root,
+ scan_root=scan_root,
+ target_identity=junit_target_identity(scan_root, repository_root, catalog_root),
)
elif fmt == "json":
reporter = reporter_cls(
diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.json
index d18d7ad8..682827d0 100644
--- a/tests/golden/cli_surface.json
+++ b/tests/golden/cli_surface.json
@@ -508,7 +508,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -704,7 +705,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -1610,7 +1612,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -1691,7 +1694,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -1790,7 +1794,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -1839,7 +1844,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -1910,7 +1916,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -2041,7 +2048,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -2083,7 +2091,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -2141,7 +2150,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -2198,7 +2208,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -2247,7 +2258,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -2318,7 +2330,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -2443,7 +2456,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli', 'json', 'html')",
"multiple": true,
@@ -2570,7 +2584,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli', 'json', 'html')",
"multiple": true,
@@ -2638,7 +2653,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -2703,7 +2719,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -2834,7 +2851,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
@@ -2912,7 +2930,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli', 'json', 'html')",
"multiple": true,
@@ -5357,7 +5376,8 @@
"json",
"html",
"markdown",
- "sarif"
+ "sarif",
+ "junit"
],
"default": "('cli',)",
"multiple": true,
diff --git a/tests/reporting/test_incomplete_scans.py b/tests/reporting/test_incomplete_scans.py
index e2a75d1a..5fc6a003 100644
--- a/tests/reporting/test_incomplete_scans.py
+++ b/tests/reporting/test_incomplete_scans.py
@@ -5,6 +5,7 @@
import json
import re
+import xml.etree.ElementTree as ET
from skillevaluator.models import ValidationResult
from skillevaluator.reporting import (
@@ -12,6 +13,7 @@ from skillevaluator.reporting import (
CLIReporter,
HTMLReporter,
JSONReporter,
+ JUnitReporter,
MarkdownReporter,
)
@@ -122,6 +124,18 @@ class TestIncompleteScanReporting:
assert "did not complete" not in output
assert "INCOMPLETE" not in output
+ def test_junit_marks_incomplete_as_error_not_passed(self):
+ root = ET.fromstring(JUnitReporter().render_all([_incomplete_result()]))
+ cases = list(root.iter("testcase"))
+ assert cases
+ assert all(case.find("skipped") is None for case in cases)
+ errors = [case.find("error") for case in cases if case.find("error") is not None]
+ assert len(errors) == 1
+ assert errors[0].attrib["type"] == "incomplete"
+ assert errors[0].attrib["message"] == "skillspector timed out after 300 seconds"
+ assert int(root.attrib["errors"]) == 1
+ assert int(root.attrib["skipped"]) == 0
+
def test_status_handles_sanitized_finding_without_location():
from skillevaluator.models import Finding, Severity
diff --git a/tests/reporting/test_junit_reporter.py b/tests/reporting/test_junit_reporter.py
new file mode 100644
index 00000000..6f997425
--- /dev/null
+++ b/tests/reporting/test_junit_reporter.py
@@ -0,0 +1,790 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Tests for the JUnit XML reporter."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+from click.testing import CliRunner
+
+from skillevaluator.cli import cli
+from skillevaluator.models import Finding, Severity, ValidationResult
+from skillevaluator.reporting.junit_reporter import JUnitReporter, junit_target_identity
+from skillevaluator.tier1.commands import emit_reports
+
+_TEXT_ANALYZER = Path(__file__).resolve().parents[2] / "src/skillevaluator/tier3/reference_skills/text-analyzer"
+
+
+def _cases(root: ET.Element) -> list[ET.Element]:
+ return list(root.iter("testcase"))
+
+
+def _count_children(cases: list[ET.Element], tag: str) -> int:
+ return sum(1 for case in cases if case.find(tag) is not None)
+
+
+def _assert_counts_match(root: ET.Element) -> None:
+ cases = _cases(root)
+ failures = _count_children(cases, "failure")
+ errors = _count_children(cases, "error")
+ skipped = _count_children(cases, "skipped")
+ assert int(root.attrib["tests"]) == len(cases)
+ assert int(root.attrib["failures"]) == failures
+ assert int(root.attrib["errors"]) == errors
+ assert int(root.attrib["skipped"]) == skipped
+ for suite in root.findall("testsuite"):
+ suite_cases = suite.findall("testcase")
+ assert int(suite.attrib["tests"]) == len(suite_cases)
+ assert int(suite.attrib["failures"]) == _count_children(suite_cases, "failure")
+ assert int(suite.attrib["errors"]) == _count_children(suite_cases, "error")
+ assert int(suite.attrib["skipped"]) == _count_children(suite_cases, "skipped")
+
+
+def test_name_and_extension() -> None:
+ reporter = JUnitReporter()
+ assert reporter.name == "junit"
+ assert reporter.get_file_extension() == ".junit.xml"
+
+
+def test_pass_emits_testcase_without_failure() -> None:
+ result = ValidationResult(validator_name="SCHEMA", validator_description="Schema checks")
+ result.add_success("manifest_found", "Found SKILL.md in skill directory")
+ result.add_success("frontmatter_valid", "Parsed successfully")
+
+ document = JUnitReporter().render_all([result])
+ root = ET.fromstring(document)
+
+ assert root.tag == "testsuites"
+ assert len(root.findall("testsuite")) == 1
+ suite = root.find("testsuite")
+ assert suite is not None
+ assert suite.attrib["name"] == "SCHEMA"
+ cases = suite.findall("testcase")
+ assert [case.attrib["name"] for case in cases] == ["manifest_found", "frontmatter_valid"]
+ assert all(case.find("failure") is None and case.find("skipped") is None for case in cases)
+ _assert_counts_match(root)
+
+
+def test_fail_includes_file_and_line() -> None:
+ result = ValidationResult(validator_name="SECRETS", validator_description="Hardcoded secrets")
+ result.add_finding(
+ Finding(
+ category="SECRET",
+ severity=Severity.CRITICAL,
+ check_name="aws-access-key-id",
+ message="AWS Access Key ID detected",
+ file_path="config/settings.py",
+ line_number=15,
+ suggestion="Remove hardcoded key. Use environment variables.",
+ )
+ )
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ case = root.find("testsuite/testcase")
+ assert case is not None
+ assert case.attrib["name"] == "aws-access-key-id (config/settings.py:15)"
+ assert case.attrib["file"] == "config/settings.py"
+ assert case.attrib["line"] == "15"
+ failure = case.find("failure")
+ assert failure is not None
+ assert failure.attrib["message"] == "AWS Access Key ID detected"
+ assert "config/settings.py:15" in (failure.text or "")
+ assert "AWS Access Key ID detected" in (failure.text or "")
+ _assert_counts_match(root)
+ assert int(root.attrib["failures"]) == 1
+ assert int(root.attrib["skipped"]) == 0
+
+
+def test_skipped_and_incomplete_are_not_all_passed() -> None:
+ skipped = ValidationResult(validator_name="SCHEMA", validator_description="Schema checks")
+ skipped.metadata["skipped"] = True
+ skipped.metadata["skip_reason"] = "skipped with --skip"
+
+ incomplete = ValidationResult(validator_name="BANDIT", validator_description="Bandit")
+ incomplete.add_error("Bandit did not return valid JSON; scan did not complete")
+ incomplete.mark_scan_incomplete("bandit")
+
+ root = ET.fromstring(JUnitReporter().render_all([skipped, incomplete]))
+ suites = {suite.attrib["name"]: suite for suite in root.findall("testsuite")}
+
+ skipped_case = suites["SCHEMA"].find("testcase")
+ assert skipped_case is not None
+ skipped_el = skipped_case.find("skipped")
+ assert skipped_el is not None
+ assert "skipped with --skip" in (skipped_el.attrib.get("message") or "")
+ assert skipped_case.find("failure") is None
+
+ incomplete_suite = suites["BANDIT"]
+ incomplete_cases = incomplete_suite.findall("testcase")
+ assert all(case.find("skipped") is None for case in incomplete_cases)
+ incomplete_case = next(case for case in incomplete_cases if case.attrib["name"] == "incomplete/bandit")
+ error_el = incomplete_case.find("error")
+ assert error_el is not None
+ assert error_el.attrib["type"] == "incomplete"
+ assert "scan did not complete" in (error_el.attrib.get("message") or "")
+ execution = next(case for case in incomplete_cases if case.attrib["name"] == "error").find("error")
+ assert execution is not None
+ assert execution.attrib["type"] == "execution"
+ assert int(incomplete_suite.attrib["failures"]) == 0
+ assert int(incomplete_suite.attrib["errors"]) == 2
+ assert int(root.attrib["errors"]) == 2
+ assert int(root.attrib["skipped"]) == 1
+ passing = [
+ case
+ for case in _cases(root)
+ if case.find("failure") is None and case.find("error") is None and case.find("skipped") is None
+ ]
+ assert passing == []
+ _assert_counts_match(root)
+
+
+def test_incomplete_scan_does_not_skip_other_cases() -> None:
+ result = ValidationResult(validator_name="Security Scan", validator_description="Security")
+ for name in ("check_a", "check_b", "check_c"):
+ result.add_success(name, f"{name} passed")
+ result.mark_scan_incomplete("skillspector")
+ result.add_warning("skillspector timed out after 300 seconds")
+ result.add_finding(
+ Finding(
+ category="SECURITY",
+ severity=Severity.LOW,
+ check_name="skillspector_timeout",
+ message="skillspector timed out after 300 seconds",
+ file_path="SKILL.md",
+ )
+ )
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ cases = {case.attrib["name"]: case for case in _cases(root)}
+ for name in ("check_a", "check_b", "check_c", "skillspector_timeout (SKILL.md)"):
+ assert cases[name].find("skipped") is None
+ assert cases[name].find("failure") is None
+ incomplete = cases["incomplete/skillspector"]
+ assert incomplete.find("skipped") is None
+ error = incomplete.find("error")
+ assert error is not None
+ assert error.attrib["type"] == "incomplete"
+ assert error.attrib["message"] == "skillspector timed out after 300 seconds"
+ assert int(root.attrib["tests"]) == 5
+ assert int(root.attrib["failures"]) == 0
+ assert int(root.attrib["errors"]) == 1
+ assert int(root.attrib["skipped"]) == 0
+ _assert_counts_match(root)
+
+
+def test_incomplete_scan_is_an_error_with_the_scanner_reason() -> None:
+ result = ValidationResult(validator_name="Security Scan", validator_description="Security")
+ result.mark_scan_incomplete("skillspector")
+ result.add_warning("skillspector not installed; install it to run the security scan")
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ (case,) = _cases(root)
+ assert case.attrib["name"] == "incomplete/skillspector"
+ assert case.find("skipped") is None
+ error = case.find("error")
+ assert error is not None
+ assert error.attrib["type"] == "incomplete"
+ assert error.attrib["message"] == "skillspector not installed; install it to run the security scan"
+ assert int(root.attrib["failures"]) + int(root.attrib["errors"]) >= 1
+ assert int(root.attrib["errors"]) == 1
+ assert int(root.attrib["skipped"]) == 0
+ _assert_counts_match(root)
+
+
+def test_incomplete_scan_without_reason_uses_generic_message() -> None:
+ result = ValidationResult(validator_name="Audit", validator_description="Dependency audit")
+ result.mark_scan_incomplete("pip-audit")
+ result.add_finding(
+ Finding(
+ category="DEPENDENCIES",
+ severity=Severity.INFO,
+ check_name="pip_audit",
+ message="Dependencies could not be audited",
+ file_path="requirements.txt",
+ )
+ )
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ error = next(case for case in _cases(root) if case.attrib["name"] == "incomplete/pip-audit").find("error")
+ assert error is not None
+ assert error.attrib["message"] == "pip-audit scan did not complete"
+ assert int(root.attrib["errors"]) == 1
+ assert int(root.attrib["skipped"]) == 0
+ _assert_counts_match(root)
+
+
+def test_execution_errors_beside_an_incomplete_scan_are_junit_errors() -> None:
+ result = ValidationResult(validator_name="Code Risk", validator_description="Code risk")
+ result.add_error("Semgrep did not return valid JSON; scan did not complete")
+ result.mark_scan_incomplete("semgrep")
+ result.fail_gate("Code risk score 40 is below the minimum 70")
+ result.add_finding(
+ Finding(
+ category="BANDIT",
+ severity=Severity.HIGH,
+ check_name="B602",
+ message="subprocess call with shell=True",
+ file_path="scripts/run.py",
+ line_number=3,
+ )
+ )
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ cases = {case.attrib["name"]: case for case in _cases(root)}
+ execution = cases["error"].find("error")
+ assert execution is not None
+ assert execution.attrib["type"] == "execution"
+ assert execution.attrib["message"] == "Semgrep did not return valid JSON; scan did not complete"
+ assert cases["error"].find("failure") is None
+ gate = cases["gate_failure"].find("failure")
+ assert gate is not None
+ assert gate.attrib["message"] == "Code risk score 40 is below the minimum 70"
+ assert cases["B602 (scripts/run.py:3)"].find("failure") is not None
+ assert cases["incomplete/semgrep"].find("error").attrib["type"] == "incomplete"
+ assert int(root.attrib["failures"]) == 2
+ assert int(root.attrib["errors"]) == 2
+ _assert_counts_match(root)
+
+
+def test_independent_error_without_an_incomplete_scan_stays_a_failure() -> None:
+ result = ValidationResult(validator_name="SCHEMA", validator_description="Schema checks")
+ result.add_error("No SKILL.md found in demo")
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ (case,) = _cases(root)
+ assert case.attrib["name"] == "error"
+ assert case.find("error") is None
+ assert case.find("failure") is not None
+ assert int(root.attrib["failures"]) == 1
+ assert int(root.attrib["errors"]) == 0
+ _assert_counts_match(root)
+
+
+def test_advisory_execution_errors_are_not_errors() -> None:
+ result = ValidationResult(validator_name="CONTENT_DEDUP")
+ result.add_error("Embedding provider error: connection refused")
+ result.mark_scan_incomplete("embedding-provider")
+ result.metadata["gating"] = {"tier": 2, "blocking": False}
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ cases = {case.attrib["name"]: case for case in _cases(root)}
+ assert all(case.find("failure") is None and case.find("error") is None for case in cases.values())
+ out = cases["error"].find("system-out")
+ assert out is not None
+ assert out.text == "Advisory, does not gate: Embedding provider error: connection refused"
+ assert cases["error"].find("skipped") is None
+ assert cases["incomplete/embedding-provider"].find("skipped") is not None
+ assert int(root.attrib["errors"]) == 0
+ assert int(root.attrib["skipped"]) == 1
+ _assert_counts_match(root)
+
+
+def test_xml_forbidden_characters_are_stripped() -> None:
+ result = ValidationResult(validator_name="SCHEMA\x00", validator_description="schema")
+ result.add_finding(
+ Finding(
+ category="SCHEMA",
+ severity=Severity.HIGH,
+ check_name="bad\x01name",
+ message="line\x00with\x08bell\x07 and \x0bvt",
+ file_path="SKILL\x00.md",
+ line_number=2,
+ )
+ )
+
+ document = JUnitReporter().render_all([result])
+ for forbidden in ("\x00", "\x01", "\x07", "\x08", "\x0b"):
+ assert forbidden not in document
+ root = ET.fromstring(document)
+ case = root.find("testsuite/testcase")
+ assert case is not None
+ assert "\x00" not in case.attrib["name"]
+ failure = case.find("failure")
+ assert failure is not None
+ assert "line" in (failure.attrib.get("message") or "")
+ _assert_counts_match(root)
+
+
+def test_markup_in_messages_is_escaped_and_parseable() -> None:
+ result = ValidationResult(validator_name="QUALITY", validator_description="quality")
+ result.add_finding(
+ Finding(
+ category="QUALITY",
+ severity=Severity.HIGH,
+ check_name="unsafe",
+ message="use <script> & 'quotes'",
+ file_path="SKILL.md",
+ line_number=3,
+ )
+ )
+
+ document = JUnitReporter().render_all([result])
+ root = ET.fromstring(document)
+ failure = root.find("testsuite/testcase/failure")
+ assert failure is not None
+ assert failure.attrib["message"] == "use <script> & 'quotes'"
+ assert "<script>" in (failure.text or "")
+ assert "&lt;script&gt;" in document
+ _assert_counts_match(root)
+
+
+def test_counts_consistency_across_suites() -> None:
+ passed = ValidationResult(validator_name="SCHEMA")
+ passed.add_success("ok", "ok")
+ failed = ValidationResult(validator_name="SECRETS")
+ failed.add_finding(
+ Finding(
+ category="SECRET",
+ severity=Severity.HIGH,
+ check_name="generic-api-key",
+ message="key",
+ file_path="src/api.py",
+ line_number=8,
+ )
+ )
+ skipped = ValidationResult(validator_name="LICENSE")
+ skipped.metadata["skipped"] = True
+ skipped.metadata["skip_reason"] = "not applicable"
+
+ root = ET.fromstring(JUnitReporter().render_all([passed, failed, skipped]))
+ assert len(root.findall("testsuite")) == 3
+ assert int(root.attrib["tests"]) == 3
+ assert int(root.attrib["failures"]) == 1
+ assert int(root.attrib["skipped"]) == 1
+ _assert_counts_match(root)
+
+
+def test_quality_score_and_threshold_in_system_out() -> None:
+ result = ValidationResult(validator_name="Quality Score (4-Dimension Analysis)")
+ result.metadata["quality_scores"] = {"overall_score": 88.8, "grade": "B"}
+ result.metadata["quality_config"] = {"min_score": 70}
+ result.add_success("quality_score", "Score: 88.8/100 (Grade: B)")
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ suite_out = root.find("testsuite/system-out")
+ assert suite_out is not None
+ assert "Score: 88.8/100 (Grade: B)" in (suite_out.text or "")
+ assert "Threshold: 70/100" in (suite_out.text or "")
+ _assert_counts_match(root)
+
+
+def test_warning_findings_are_not_failures() -> None:
+ result = ValidationResult(validator_name="QUALITY")
+ result.add_finding(
+ Finding(
+ category="QUALITY",
+ severity=Severity.MEDIUM,
+ check_name="quality_reliability",
+ message="No troubleshooting section documented",
+ file_path="SKILL.md",
+ )
+ )
+ result.fail_gate("Quality score 71.0/100 is below the required 80/100 in SKILL.md")
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ cases = {case.attrib["name"]: case for case in _cases(root)}
+ warning = cases["quality_reliability (SKILL.md)"]
+ assert warning.find("failure") is None
+ warning_out = warning.find("system-out")
+ assert warning_out is not None
+ assert "No troubleshooting section documented" in (warning_out.text or "")
+ gate = cases["gate_failure"]
+ assert gate.find("failure") is not None
+ assert "71.0/100" in (gate.find("failure").attrib.get("message") or "")
+ assert int(root.attrib["failures"]) == 1
+ _assert_counts_match(root)
+
+
+def test_medium_finding_recorded_as_blocking_is_a_failure() -> None:
+ result = ValidationResult(validator_name="Code Risk")
+ result.add_structured_finding(
+ Finding(
+ category="BANDIT",
+ severity=Severity.HIGH,
+ check_name="B602:subprocess_popen_with_shell_equals_true",
+ message="subprocess call with shell=True",
+ file_path="scripts/run.py",
+ line_number=3,
+ ),
+ is_error=True,
+ )
+ result.add_structured_finding(
+ Finding(
+ category="BANDIT",
+ severity=Severity.MEDIUM,
+ check_name="B301:blacklist",
+ message="Pickle can be unsafe when used to deserialize untrusted data",
+ file_path="scripts/load.py",
+ line_number=7,
+ ),
+ is_error=True,
+ )
+ result.add_structured_finding(
+ Finding(
+ category="BANDIT",
+ severity=Severity.MEDIUM,
+ check_name="B108:hardcoded_tmp_directory",
+ message="Probable insecure usage of temp file",
+ file_path="scripts/tmp.py",
+ line_number=2,
+ ),
+ is_error=False,
+ )
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ cases = {case.attrib["name"]: case for case in _cases(root)}
+ pickle_case = cases["B301:blacklist (scripts/load.py:7)"]
+ failure = pickle_case.find("failure")
+ assert failure is not None
+ assert "scripts/load.py:7" in (failure.text or "")
+ assert pickle_case.attrib["file"] == "scripts/load.py"
+ assert pickle_case.attrib["line"] == "7"
+ assert cases["B108:hardcoded_tmp_directory (scripts/tmp.py:2)"].find("failure") is None
+ assert "error" not in cases
+ assert int(root.attrib["failures"]) == 2
+ _assert_counts_match(root)
+
+
+def _scored_tier3(verdict: str, *, blocking: bool) -> ValidationResult:
+ result = ValidationResult(validator_name="AGENT_EVAL")
+ result.metadata["agent_eval"] = {"execution_status": "succeeded", "verdict": verdict, "overall_score": 41.0}
+ result.add_success("agent_eval", f"Tier 3 evaluation complete: verdict {verdict.upper()}; best agent demo")
+ result.passed = True
+ result.metadata["gating"] = {"tier": 3, "blocking": blocking}
+ return result
+
+
+def test_blocking_tier3_verdict_that_fails_the_gate_is_a_failure() -> None:
+ for verdict in ("fail", "neutral"):
+ root = ET.fromstring(JUnitReporter().render_all([_scored_tier3(verdict, blocking=True)]))
+ cases = {case.attrib["name"]: case for case in _cases(root)}
+ assert cases["agent_eval"].find("failure") is None
+ failure = cases["gate_failure"].find("failure")
+ assert failure is not None
+ assert failure.attrib["message"] == f"Tier 3 verdict {verdict.upper()} does not pass the required gate"
+ assert int(root.attrib["failures"]) == 1
+ _assert_counts_match(root)
+
+
+def test_advisory_tier3_verdict_is_not_a_failure() -> None:
+ root = ET.fromstring(JUnitReporter().render_all([_scored_tier3("fail", blocking=False)]))
+ assert all(case.find("failure") is None for case in _cases(root))
+ assert int(root.attrib["failures"]) == 0
+ _assert_counts_match(root)
+
+
+def test_blocking_tier3_that_could_not_run_reports_the_reason() -> None:
+ from skillevaluator.evaluation.tier3_report import advisory_skip_result
+
+ result = advisory_skip_result("ANTHROPIC_API_KEY is not set; Tier 3 did not run")
+ result.metadata["gating"] = {"tier": 3, "blocking": True}
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ failures = [case.find("failure") for case in _cases(root) if case.find("failure") is not None]
+ assert len(failures) == 1
+ assert failures[0].attrib["message"] == "ANTHROPIC_API_KEY is not set; Tier 3 did not run"
+ _assert_counts_match(root)
+
+ result.metadata["gating"] = {"tier": 3, "blocking": False}
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ assert all(case.find("failure") is None for case in _cases(root))
+ skipped = root.find("testsuite/testcase/skipped")
+ assert skipped is not None
+ assert skipped.attrib["message"] == "ANTHROPIC_API_KEY is not set; Tier 3 did not run"
+
+
+def test_blocking_skip_that_fails_run_status_is_a_failure() -> None:
+ from skillevaluator.evaluation.tier3_report import advisory_skip_result
+ from skillevaluator.reporting.run_status import Status, result_status
+
+ result = advisory_skip_result("Tier 3 skipped with --skip")
+ result.passed = True
+ result.metadata["skipped"] = True
+ result.metadata["skip_reason"] = "Tier 3 skipped with --skip"
+ result.metadata["gating"] = {"tier": 3, "blocking": True}
+ assert result_status(result) == Status.FAILED
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ cases = _cases(root)
+ assert all(case.find("skipped") is None for case in cases)
+ failure = root.find("testsuite/testcase[@name='gate_failure']/failure")
+ assert failure is not None
+ assert failure.attrib["message"] == "Tier 3 skipped with --skip"
+ assert int(root.attrib["failures"]) == 1
+ assert int(root.attrib["skipped"]) == 0
+ _assert_counts_match(root)
+
+ result.metadata["gating"] = {"tier": 3, "blocking": False}
+ assert result_status(result) == Status.SKIPPED
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ skipped = root.find("testsuite/testcase/skipped")
+ assert skipped is not None
+ assert skipped.attrib["message"] == "Tier 3 skipped with --skip"
+ assert int(root.attrib["failures"]) == 0
+ _assert_counts_match(root)
+
+
+def test_advisory_tier2_findings_and_errors_are_not_failures() -> None:
+ result = ValidationResult(validator_name="CONTENT_DEDUP")
+ result.add_finding(
+ Finding(
+ category="CONTENT_DEDUP",
+ severity=Severity.HIGH,
+ check_name="duplicate_section",
+ message="Section duplicates references/guide.md",
+ file_path="SKILL.md",
+ line_number=12,
+ )
+ )
+ result.add_error("Similarity model returned no scores")
+ result.metadata["gating"] = {"tier": 2, "blocking": False}
+
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ cases = {case.attrib["name"]: case for case in _cases(root)}
+ assert all(case.find("failure") is None for case in cases.values())
+ finding_out = cases["duplicate_section (SKILL.md:12)"].find("system-out")
+ assert finding_out is not None
+ assert (finding_out.text or "").startswith("Advisory, does not gate: SKILL.md:12: Section duplicates")
+ assert int(root.attrib["failures"]) == 0
+ _assert_counts_match(root)
+
+ result.metadata["gating"] = {"tier": 2, "blocking": True}
+ root = ET.fromstring(JUnitReporter().render_all([result]))
+ assert int(root.attrib["failures"]) == 2
+ assert "gate_failure" not in {case.attrib["name"] for case in _cases(root)}
+ _assert_counts_match(root)
+
+
+def test_paths_are_relative_to_scanned_root(tmp_path: Path) -> None:
+ repo = tmp_path / "repo"
+ skill = repo / "skills" / "demo"
+ skill.mkdir(parents=True)
+ result = ValidationResult(validator_name="QUALITY")
+ result.add_finding(
+ Finding(
+ category="QUALITY",
+ severity=Severity.HIGH,
+ check_name="spacing",
+ message="issue",
+ file_path="SKILL.md",
+ line_number=2,
+ )
+ )
+
+ root = ET.fromstring(JUnitReporter(workspace_root=repo, scan_root=skill).render_all([result]))
+ case = root.find("testsuite/testcase")
+ assert case is not None
+ assert case.attrib["file"] == "skills/demo/SKILL.md"
+ failure = case.find("failure")
+ assert failure is not None
+ assert "skills/demo/SKILL.md:2" in (failure.text or "")
+
+
+def test_emit_reports_writes_junit_file(tmp_path: Path) -> None:
+ result = ValidationResult(validator_name="SCHEMA")
+ result.add_success("manifest_found", "Found SKILL.md")
+ output_dir = tmp_path / "reports"
+ emit_reports(
+ [result],
+ report_formats=("junit",),
+ output_dir=output_dir,
+ basename="skillevaluator-quality",
+ announce_paths=False,
+ )
+ path = output_dir / "skillevaluator-quality.junit.xml"
+ assert path.is_file()
+ root = ET.fromstring(path.read_text(encoding="utf-8"))
+ assert root.tag == "testsuites"
+ _assert_counts_match(root)
+
+
+def test_quality_check_cli_writes_junit_xml(tmp_path: Path) -> None:
+ reports = tmp_path / "reports"
+ result = CliRunner().invoke(
+ cli,
+ ["quality-check", str(_TEXT_ANALYZER), "-r", "junit", "-o", str(reports)],
+ )
+ assert result.exit_code == 0, result.output
+ matches = list(reports.glob("*.junit.xml"))
+ assert matches == [reports / "skillevaluator-quality.junit.xml"]
+ root = ET.fromstring(matches[0].read_text(encoding="utf-8"))
+ assert root.tag == "testsuites"
+ assert int(root.attrib["tests"]) >= 1
+ _assert_counts_match(root)
+ ET.fromstring(matches[0].read_text(encoding="utf-8"))
+
+
+def test_single_check_command_paths_are_relative_to_git_root(tmp_path: Path, monkeypatch) -> None:
+ """A single-check command reports the same repository-relative file as ``validate``, in JUnit and SARIF."""
+ repo = tmp_path / "repo"
+ skill = repo / "skills" / "demo"
+ shutil.copytree(_TEXT_ANALYZER, skill)
+ subprocess.run(["git", "init", "-q", str(repo)], check=True)
+ reports = tmp_path / "reports"
+
+ def lint(_path: Path) -> list[ValidationResult]:
+ result = ValidationResult(validator_name="SCRIPT_LINT")
+ result.add_finding(
+ Finding(
+ category="SCRIPT_LINT",
+ severity=Severity.HIGH,
+ check_name="script_lint",
+ message="Unsafe call",
+ file_path="SKILL.md",
+ line_number=2,
+ )
+ )
+ return [result]
+
+ monkeypatch.setattr("skillevaluator.cli.run_lint_scripts", lint)
+
+ CliRunner().invoke(cli, ["lint-scripts", str(skill), "-r", "junit", "-r", "sarif", "-o", str(reports)])
+
+ (junit,) = reports.glob("*.junit.xml")
+ files = {case.attrib.get("file") for case in _cases(ET.fromstring(junit.read_text(encoding="utf-8")))}
+ assert "skills/demo/SKILL.md" in files
+ (sarif,) = reports.glob("*.sarif.json")
+ sarif_text = sarif.read_text(encoding="utf-8")
+ assert '"uri": "skills/demo/SKILL.md"' in sarif_text
+
+
+def test_tier1_workflow_with_a_relative_path_reports_git_root_relative_files(tmp_path: Path, monkeypatch) -> None:
+ """``tier1 skills/demo`` from the repository root names ``skills/demo/SKILL.md`` once, in JUnit and SARIF."""
+ repo = tmp_path / "repo"
+ skill = repo / "skills" / "demo"
+ shutil.copytree(_TEXT_ANALYZER, skill)
+ subprocess.run(["git", "init", "-q", str(repo)], check=True)
+ reports = tmp_path / "reports"
+
+ def tier1(skill_path: Path, **_: object) -> list[ValidationResult]:
+ # Validators build finding paths from the root they are handed.
+ result = ValidationResult(validator_name="QUALITY")
+ result.add_finding(
+ Finding(
+ category="QUALITY",
+ severity=Severity.HIGH,
+ check_name="quality_correctness",
+ message="issue",
+ file_path=str(skill_path / "SKILL.md"),
+ line_number=2,
+ )
+ )
+ return [result]
+
+ monkeypatch.setattr("skillevaluator.tier_workflows.run_tier1_workflow", tier1)
+ monkeypatch.chdir(repo)
+
+ CliRunner().invoke(cli, ["tier1", "skills/demo", "-r", "junit", "-r", "sarif", "-o", str(reports)])
+
+ (junit,) = reports.glob("*.junit.xml")
+ files = {case.attrib.get("file") for case in _cases(ET.fromstring(junit.read_text(encoding="utf-8")))}
+ assert files == {"skills/demo/SKILL.md"}
+ (sarif,) = reports.glob("*.sarif.json")
+ assert '"uri": "skills/demo/SKILL.md"' in sarif.read_text(encoding="utf-8")
+
+
+def test_target_identity_qualifies_suite_and_classname() -> None:
+ result = ValidationResult(validator_name="SCHEMA")
+ result.add_success("manifest_exists", "Found SKILL.md")
+
+ root = ET.fromstring(JUnitReporter(target_identity="group-a/demo").render_all([result]))
+ suite = root.find("testsuite")
+ assert suite is not None
+ assert suite.attrib["name"] == "group-a/demo::SCHEMA"
+ case = suite.find("testcase")
+ assert case is not None
+ assert case.attrib["classname"] == "group-a/demo::SCHEMA"
+ assert case.attrib["name"] == "manifest_exists"
+
+
+def test_target_identity_prefers_repository_then_catalog_then_name(tmp_path: Path) -> None:
+ repo = tmp_path / "repo"
+ skill = repo / "skills" / "group-a" / "demo"
+ skill.mkdir(parents=True)
+
+ assert junit_target_identity(skill, repo, repo / "skills") == "skills/group-a/demo"
+ # A non-Git catalog validates each skill with the skill itself as its root.
+ assert junit_target_identity(skill, skill, repo / "skills") == "group-a/demo"
+ assert junit_target_identity(skill, skill) == "demo"
+ assert junit_target_identity(None) == ""
+
+
+def test_catalog_with_repeated_leaf_names_keeps_identities_distinct(tmp_path: Path) -> None:
+ catalog = tmp_path / "catalog"
+ for group in ("group-a", "group-b"):
+ shutil.copytree(_TEXT_ANALYZER, catalog / group / "demo")
+ reports = tmp_path / "reports"
+
+ CliRunner().invoke(
+ cli,
+ [
+ "validate",
+ str(catalog),
+ "--tiers",
+ "1",
+ "--checks",
+ "schema",
+ "--workers",
+ "1",
+ "--no-autopilot",
+ "-r",
+ "junit",
+ "-o",
+ str(reports),
+ ],
+ )
+
+ files = sorted(reports.rglob("*.junit.xml"))
+ assert [path.relative_to(reports).parent.as_posix() for path in files] == ["group-a/demo", "group-b/demo"]
+ identities: list[tuple[str, str]] = []
+ classnames: set[str] = set()
+ for path in files:
+ for case in _cases(ET.fromstring(path.read_text(encoding="utf-8"))):
+ identities.append((case.attrib["classname"], case.attrib["name"]))
+ classnames.add(case.attrib["classname"].split("::", 1)[0])
+ assert identities
+ assert len(identities) == len(set(identities))
+ assert classnames == {"group-a/demo", "group-b/demo"}
+
+
+def _findings_result(order: list[tuple[str, str, int | None]]) -> ValidationResult:
+ result = ValidationResult(validator_name="QUALITY", validator_description="Quality")
+ for check_name, file_path, line in order:
+ result.add_finding(
+ Finding(
+ category="QUALITY",
+ severity=Severity.LOW,
+ check_name=check_name,
+ message=f"{check_name} in {file_path}",
+ file_path=file_path,
+ line_number=line,
+ )
+ )
+ return result
+
+
+def test_finding_case_names_do_not_depend_on_finding_order() -> None:
+ findings = [
+ ("quality_correctness", "SKILL.md", 12),
+ ("quality_correctness", "SKILL.md", 40),
+ ("quality_correctness", "references/api.md", None),
+ ]
+
+ def names(order: list[tuple[str, str, int | None]]) -> set[str]:
+ root = ET.fromstring(JUnitReporter().render_all([_findings_result(order)]))
+ return {case.attrib["name"] for case in _cases(root)}
+
+ first = names(findings)
+ assert first == {
+ "quality_correctness (SKILL.md:12)",
+ "quality_correctness (SKILL.md:40)",
+ "quality_correctness (references/api.md)",
+ }
+ assert names(list(reversed(findings))) == first
+ added = names([("quality_correctness", "SKILL.md", 5), *findings])
+ assert first <= added
diff --git a/tests/reporting/test_plugin_reports_runtime_composition.py b/tests/reporting/test_plugin_reports_runtime_composition.py
index 586385d7..76670b00 100644
--- a/tests/reporting/test_plugin_reports_runtime_composition.py
+++ b/tests/reporting/test_plugin_reports_runtime_composition.py
@@ -8,7 +8,7 @@ from copy import deepcopy
import pytest
from skillevaluator.models import ValidationResult
-from skillevaluator.reporting import HTMLReporter
+from skillevaluator.reporting import HTMLReporter, JUnitReporter
from skillevaluator.reporting.plugin_runtime import project_plugin_runtime
from skillevaluator.reporting.plugin_static import project_plugin_static
@@ -83,3 +83,24 @@ def test_invalid_retained_runtime_is_rejected_before_html_rendering(entrypoint):
else:
plugin_reports.augment_plugin_report(reporter, "previously rendered document", results)
assert reporter.calls == []
+
+
[email protected]("with_runtime", [False, True], ids=["static", "static-and-runtime"])
+def test_junit_keeps_plugin_evidence_out_of_the_xml(with_runtime):
+ from skillevaluator.reporting import plugin_reports
+
+ metadata = {"plugin": {"name": "retained-plugin", "component_inventory": {"complete": True, "components": []}}}
+ if with_runtime:
+ metadata["plugin_runtime_report"] = project_plugin_runtime(
+ {"run_dir": "/absent/saved-run", "execution_status": "succeeded"},
+ provenance={"plugin": "retained-plugin", "runtime_evidence": {}},
+ ).payload()
+ results = [ValidationResult(validator_name="SCHEMA", metadata=metadata)]
+ assert project_plugin_static(results) is not None
+ reporter = JUnitReporter()
+ plain = reporter.render_all(results)
+
+ # Neither the static nor the runtime adapter adds to JUnit, and neither raises.
+ assert plugin_reports.augment_plugin_report(reporter, None, results) == plain
+ assert plugin_reports.augment_plugin_report(reporter, plain, results) == plain
+ assert plugin_reports.render_plugin_report(reporter, results) == plain
diff --git a/tests/reporting/test_reporters.py b/tests/reporting/test_reporters.py
index c833149c..6625876e 100644
--- a/tests/reporting/test_reporters.py
+++ b/tests/reporting/test_reporters.py
@@ -3152,7 +3152,7 @@ def test_cli_harbor_job_labels_remain_neutral_and_literal(colored):
@pytest.mark.skipif(os.name == "nt", reason="only POSIX file names carry undecodable bytes as surrogate escapes")
[email protected]("report_format", ["json", "markdown", "html", "sarif"])
[email protected]("report_format", ["json", "markdown", "html", "sarif", "junit"])
def test_reports_are_written_for_a_file_name_that_is_not_utf8(tmp_path: Path, report_format: str) -> None:
# On Linux, os.listdir returns the name b"caf\xe9.md" as "caf\udce9.md".
skill = tmp_path / "skill"
@@ -3177,8 +3177,8 @@ def test_reports_are_written_for_a_file_name_that_is_not_utf8(tmp_path: Path, re
output_dir=output_dir,
target_path=str(skill),
announce_paths=False,
- sarif_scan_root=skill,
- sarif_repository_root=tmp_path,
+ scan_root=skill,
+ repository_root=tmp_path,
)
(report,) = [path for path in output_dir.iterdir() if path.name != "BENCHMARK.md"]
@@ -3186,3 +3186,6 @@ def test_reports_are_written_for_a_file_name_that_is_not_utf8(tmp_path: Path, re
assert "Unexpected" in text
if report_format == "sarif":
assert "skill/caf%E9.md" in text
+ if report_format == "junit":
+ assert 'file="skill/caf%E9.md"' in text
+ assert "Unexpected 'caf\\xe9.md' in skill root" in text
diff --git a/tests/test_cli.py b/tests/test_cli.py
index b3f9c41c..83693713 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -343,6 +343,7 @@ def test_validate_preserves_linked_root_support_when_tier2_is_disabled(tmp_path:
(".html", "json,html,markdown"),
(".md", "json,html,markdown"),
(".sarif.json", "sarif"),
+ (".junit.xml", "junit"),
],
)
def test_similarity_cli_rejects_catalog_collision_with_every_selected_report(
@@ -1470,3 +1471,39 @@ def test_cli_environment_kwargs_sensitive_credential_exits_code_2_without_traceb
assert "Invalid value for '--ek'" in result.output
assert "Sensitive key or value detected" in result.output
assert "Traceback" not in result.output
+
+
+def test_validate_junit_reports_scanner_crash_as_error(tmp_path: Path, monkeypatch) -> None:
+ import xml.etree.ElementTree as ET
+
+ skill = tmp_path / "demo"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text(
+ "---\nname: demo\ndescription: Exercise the JUnit mapping for a scanner that did not complete.\n---\n",
+ encoding="utf-8",
+ )
+ reports = tmp_path / "reports"
+
+ def crashed_scan(_path: Path, **_kwargs) -> list[ValidationResult]:
+ result = ValidationResult(validator_name="Code Risk", validator_description="Code risk")
+ result.add_error("Bandit did not return valid JSON; scan did not complete")
+ result.mark_scan_incomplete("bandit")
+ return [result]
+
+ monkeypatch.setattr("skillevaluator.cli.run_validation", crashed_scan)
+
+ result = CliRunner().invoke(
+ cli,
+ ["validate", "--no-tier3", str(skill), "--no-dedup", "--checks", "schema", "-r", "junit", "-o", str(reports)],
+ )
+
+ assert result.exit_code != 0, result.output
+ (report,) = reports.rglob("*.junit.xml")
+ root = ET.fromstring(report.read_text(encoding="utf-8"))
+ errors = {case.attrib["name"]: case.find("error") for case in root.iter("testcase")}
+ assert errors["error"] is not None
+ assert errors["error"].attrib["type"] == "execution"
+ assert errors["incomplete/bandit"] is not None
+ assert errors["incomplete/bandit"].attrib["type"] == "incomplete"
+ assert int(root.attrib["errors"]) == 2
+ assert int(root.attrib["failures"]) == 0