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): reconcile stable finding IDs across report formats (#310)

Narendran Raghavan47620b629e9a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 852fb42d..5bf50af4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -195,6 +195,33 @@ All notable changes to SkillEvaluator are documented in this file.
`tier1` leaves a check out and reports it as skipped. A `scanners` row and the
JSON report record which scanner versions ran.
+- Every finding now has stable IDs for tracking across runs and validators.
+ `finding_id` (`SEF-…`) is derived from the finding's category, check,
+ message, and suggestion, so it survives line moves, whitespace or case
+ changes, and severity overrides. Location text a check copies into its
+ message is left out of it: the `in <file>:<line>` in a secret detection
+ message, also in a folder or plugin run that prefixes the file path, and
+ the `— N occurrences (…)` list a PII scan message ends with. A file name in
+ a message or suggestion, as script lint and secret detection write, stays
+ part of the ID. `occurrence_id` (`SEO-…`) adds the file, line, and line
+ content. Otherwise identical findings in different files or skills
+ share one `finding_id`, so they count as one unique finding with one
+ occurrence per location. When CI redacts a detected credential from a
+ report, it recomputes the IDs from the redacted text and renders the HTML,
+ Markdown, and SARIF copies from that JSON, so no ID is derived from a
+ removed value. The JSON report and the HTML report's embedded data
+ add `finding_counts` (raw records, distinct occurrences, unique findings,
+ and duplicates removed), `finding_groups` (each unique finding with its
+ validators and every location, including each location a PII finding
+ lists for a repeated value, also in a folder run), and `message_counts`
+ (error and warning strings with no finding behind them, such as failed
+ gates and scanner or execution errors, but not the workflow scope note for
+ a stage that configuration skips, plus informational messages other than
+ the `[OK]` line recorded for each passed check); each JSON result also
+ carries its own `finding_counts`. Markdown adds a Finding Reconciliation
+ table, most severe first, and per-finding IDs. `total_errors`,
+ `total_warnings`, and `severity_counts` are unchanged.
+
- `--skillspector-baseline FILE` on `validate`, `tier1`, and `security-scan`
applies an audited SkillSpector suppression baseline, so reviewed false
positives no longer leave the security check failed or `INCOMPLETE`.
@@ -308,6 +335,25 @@ All notable changes to SkillEvaluator are documented in this file.
environment, so each template compiles once per process instead of once per
report.
+- The Markdown summary and the HTML report's summary now count findings the
+ same way: each unique finding once, at its highest severity, however many
+ lines, files, skills or validators report it. Markdown's Total Issues adds
+ distinct occurrences, raw records, and errors and warnings with no finding
+ behind them, such as failed gates and incomplete scans; its severity
+ breakdown counts unique findings. In HTML, the tier cards, the Tier 1
+ Findings and Blocking critical + high numbers, the verdict sentence, the
+ skill finding badges and the gate policy line count unique findings, and
+ the Findings number shows the same occurrence, raw-record and no-finding
+ counts beneath it when they differ from the unique count. Both formats used
+ to add up raw records, so a finding reported on several lines or by two
+ validators counted more than once. The HTML report's embedded and exported
+ data changes `summary.total_issues` the same way: it now counts unique
+ findings plus errors and warnings with no finding behind them, instead of
+ raw errors plus warnings; the raw finding count is in
+ `summary.raw_finding_occurrences` and `finding_counts.raw_occurrences`. The
+ JSON `skills[].issue_count`, contributor totals, `total_errors`,
+ `total_warnings` and `severity_counts` still count raw records.
+
- Tier 3 `accuracy` grades the outcome only. The `SKILL_IDENTIFIED` criterion,
which capped a correct answer from the no-skill baseline at 0.8 on positive
cases, is replaced by `FORMAT_FOLLOWED`: the response follows any output
diff --git a/ci/publish_reports.py b/ci/publish_reports.py
index 0343ce74..1fbe1aa3 100644
--- a/ci/publish_reports.py
+++ b/ci/publish_reports.py
@@ -382,6 +382,13 @@ def read_artifact(payload: bytes) -> tuple[dict, dict[str, dict]]:
redactor = Redactor(tokens)
summary = redactor.object(summary)
reports = redactor.object(reports)
+ from skillevaluator.reporting.finding_summary import refresh_finding_identities
+
+ # IDs hashed from the unredacted text could confirm a guessed value.
+ # Refresh even without collected tokens: the redactor also masks
+ # database userinfo that no token names.
+ for report in reports.values():
+ refresh_finding_identities(report)
validate_summary(summary)
for row in summary["skills"]:
if row["overall_status"] != "error":
diff --git a/ci/secret_redaction.py b/ci/secret_redaction.py
index 286d50ef..a52fdc0a 100644
--- a/ci/secret_redaction.py
+++ b/ci/secret_redaction.py
@@ -11,7 +11,8 @@ import os
import re
from pathlib import Path
-from skillevaluator.reporting import MarkdownReporter, SARIFReporter
+from skillevaluator.reporting import HTMLReporter, MarkdownReporter, SARIFReporter
+from skillevaluator.reporting.finding_summary import refresh_finding_identities
from skillevaluator.reporting.retained import retained_results
from skillevaluator.utils.secret_redaction import SENSITIVE_PII_CATEGORIES, Redactor, sensitive_values
from skillevaluator.utils.secure_fs import SecureRoot
@@ -132,9 +133,10 @@ def sanitized_outputs(raw: Path, tokens: set[str]) -> dict[str, bytes]:
b"Raw scanner log withheld while credential redaction is active. See the structured reports.\n"
)
continue
- if name in {"skillevaluator-tier1.md", "skillevaluator-tier1.sarif.json"}:
+ if name in {"skillevaluator-tier1.html", "skillevaluator-tier1.md", "skillevaluator-tier1.sarif.json"}:
# These files cut and escape text, so a value can survive a
- # literal search. Render them from the redacted JSON instead.
+ # literal search, and the HTML embeds finding IDs hashed from
+ # the unredacted text. Render them from the redacted JSON.
if document is None:
raise ValueError("The evaluator did not produce JSON evidence.")
try:
@@ -142,12 +144,23 @@ def sanitized_outputs(raw: Path, tokens: set[str]) -> dict[str, bytes]:
except ValueError:
# The runner rejects this JSON next; keep the other evidence.
continue
- reporter = MarkdownReporter() if name.endswith(".md") else SARIFReporter()
+ reporter = (
+ HTMLReporter()
+ if name.endswith(".html")
+ else MarkdownReporter()
+ if name.endswith(".md")
+ else SARIFReporter()
+ )
sanitized[name] = reporter.render_all(results).encode("utf-8")
continue
text = content.decode("utf-8")
if name.endswith(".json"):
document = redactor.object(json.loads(text))
+ if isinstance(document, dict):
+ # IDs hashed from the unredacted text could confirm a guessed
+ # value. Refresh even without collected tokens: the redactor
+ # also masks database userinfo that no token names.
+ refresh_finding_identities(document)
text = json.dumps(document, ensure_ascii=True, allow_nan=False, indent=2)
else:
text = redactor.text(text)
diff --git a/docs/ci-integration.mdx b/docs/ci-integration.mdx
index 85ccb869..9190d546 100644
--- a/docs/ci-integration.mdx
+++ b/docs/ci-integration.mdx
@@ -247,10 +247,54 @@ When the exit code is not enough — dashboards, custom thresholds, badge genera
| `results[].skillspector_baseline` | object | Single-skill targets with `--skillspector-baseline`, when SkillSpector is installed: `status`, baseline file name and `sha256:` digest (no local path), scanner versions, suppressed (per stage) and active finding counts, and a message. Absent from merged `security-scan` folder reports; `validate` on a folder records it in each skill's report. See [Audited SkillSpector baselines](tier1-validation.mdx#audited-skillspector-baselines) |
| `tier3.run_id` | string | Run-owned Tier 3 identity; duplicated in the Tier 3 summary for consistency checks |
| `severity_counts` | object | Totals for `critical`, `high`, `medium`, `low` |
-| `total_errors`, `total_warnings` | number | Aggregate counts across all validators |
-| `skills` | array | Per-skill `{ name, passed, issue_count }` |
+| `total_errors`, `total_warnings` | number | Raw error and warning records across all validators; a finding that two validators report counts twice |
+| `finding_counts` | object | Reconciled counts: `raw_occurrences`, `distinct_occurrences`, `unique_findings`, `duplicates_removed`, `occurrences_grouped`, `raw_by_severity`, `unique_by_severity` |
+| `finding_groups` | array | One entry per unique finding: `finding_id`, highest `severity`, `message`, `validators`, and every location in `occurrences[]` with its `occurrence_id`, including each location a finding lists in `metadata.occurrences` when its check folds repeats of one value into it (the PII scan does) |
+| `message_counts` | object | `independent_errors` and `independent_warnings`: error and warning strings with no finding behind them, such as `gate_failures` and scanner or execution errors (strings that mirror a finding, and the `Workflow scope:` note for a stage that configuration skips, are not counted); `informational`: informational messages, not counting the `[OK]` line recorded for each passed check |
+| `results[].findings[].finding_id`, `results[].findings[].occurrence_id` | string | Stable finding and location identities (see below) |
+| `skills` | array | Per-skill `{ name, passed, issue_count }`; `issue_count` counts raw finding records |
| `quality_summary` | array | Quality details with `overall_score` (0–100) and `grade` (A–F); a folder target reports the collection average plus a `skill_count` |
+Every finding carries two stable IDs. `finding_id` (`SEF-` plus 20 hex
+characters) hashes the finding's category, check name, message, and suggestion,
+ignoring case and extra whitespace. It does not change when the finding moves
+to another line or file, or when a policy changes its severity, so you can
+track a finding across runs. Location text that a check also writes into its
+message is left out of the hash: the `in <file>:<line>` in a secret detection
+message, also when a folder or plugin run puts the skill or member name in
+front of the finding's file path, and the `— N occurrences (…)` list that the
+PII scan appends when it folds repeats of one value into one finding. Other
+message and suggestion text stays part of the ID: script lint names the script
+in its messages and secret detection names the file in its suggestion, so the
+same problem in two files has two `finding_id` values. `occurrence_id`
+(`SEO-…`) adds the file path, line number, and line content, so it identifies
+one location; the source line itself stays on the finding in
+`results[].findings[]` and is not repeated in `finding_groups`.
+`finding_groups` groups findings by `finding_id` across validators, and each
+result in `results[]` carries its own `finding_counts`. Identical findings in
+different files or skills share one `finding_id`, so they count as one unique
+finding with one occurrence per location. When the CI templates redact a
+detected credential from a report, they recompute the IDs and groups from the
+redacted text and render the HTML, Markdown, and SARIF copies from that JSON,
+so no ID is derived from a removed value; such a finding's IDs differ from a
+local run's.
+
+The Markdown summary and the HTML report count findings the same way: each
+unique finding once, at its highest severity. Markdown's Total Issues also
+shows distinct occurrences, raw records, and the `independent_errors` and
+`independent_warnings`, so a run that fails a gate or leaves a scan
+incomplete without any finding is not reported as zero issues. In HTML, the
+tier cards, the Tier 1 Findings and Blocking critical + high numbers, the
+verdict sentence, the skill finding badges and the gate policy line count
+unique findings, and the Findings number shows the same breakdown beneath it
+when it differs from the unique count. The HTML report's embedded data, which
+Export JSON saves, counts `summary.total_issues` the same way: unique findings
+plus `independent_errors` and `independent_warnings`, where it used to add up
+raw errors and warnings. Its raw finding count is in
+`summary.raw_finding_occurrences` and `finding_counts.raw_occurrences`.
+`total_errors`, `total_warnings`, `severity_counts`, `skills[].issue_count` and
+contributor totals still count raw records.
+
`overall_status` and `overall_passed` describe the configured command gate. They
can be green when an advisory tier did not run, so do not use them as a
publication signal. Require `publication_status == "pass"` (or
diff --git a/docs/reports.mdx b/docs/reports.mdx
index b8b40db4..225d5251 100644
--- a/docs/reports.mdx
+++ b/docs/reports.mdx
@@ -105,10 +105,18 @@ the evidence below it:
repeat a finding are folded away.
- **Run details.** Scope, the target path, provenance and the gate policy.
-A finding is one problem a check reports at one location, with a severity. A
-finding in a failed check blocks the verdict; a finding in a passed check is
-advisory. A quality score below the configured minimum fails the Quality score
-check, so it also blocks the verdict.
+A finding is one problem a check reports, with a severity. The same problem
+reported on several lines, or in several files or skills, counts once at its
+highest severity; each location is an occurrence, including each line a
+PII finding lists when one value repeats. When the unique, occurrence and
+raw record counts differ, or when some errors or warnings have no finding
+behind them, the findings number shows the occurrences, the raw records and
+those errors and warnings beneath it, in the same words as the Markdown
+report's Total Issues. The workflow scope note for a stage that configuration
+skips, such as LLM checks under `--no-llm`, is not counted as a warning there. A finding in a failed check blocks the
+verdict; a finding in a passed check is advisory. A quality score below the
+configured minimum fails the Quality score check, so it also blocks the
+verdict.
The HTML report, the CI index and the Pages history use the same verdict
words: **Passed**, **Changes required**, **Incomplete**, **Skipped** and
diff --git a/src/skillevaluator/models/result.py b/src/skillevaluator/models/result.py
index 3d43fa2a..c2fb481b 100644
--- a/src/skillevaluator/models/result.py
+++ b/src/skillevaluator/models/result.py
@@ -16,6 +16,7 @@ render validation results in various formats.
from __future__ import annotations
+import hashlib
from dataclasses import dataclass, field
from enum import StrEnum
@@ -129,6 +130,104 @@ class Finding:
return f"[{self.category}-{self.severity.value.upper()}]"
return f"[{self.category}-{str(self.severity).upper()}]"
+ @staticmethod
+ def _normalize_identity_text(value: object) -> str:
+ """Normalize human text without coupling identity to formatting."""
+ return " ".join(("" if value is None else str(value)).casefold().split())
+
+ @staticmethod
+ def _location_paths(file_path: object) -> list[str]:
+ """Return ``file_path`` and the shorter paths a message may name it by.
+
+ A folder run prefixes each skill's ``file_path`` with ``[skill] ``
+ and a plugin scan prepends the member's directory, but neither
+ rewrites the message, which still names the path the scanner saw.
+ Longest first, so the most specific match is removed.
+ """
+ path = str(file_path)
+ paths = [path]
+ while path.startswith("[") and "] " in path:
+ path = path.split("] ", 1)[1]
+ paths.append(path)
+ paths.extend(path[index + 1 :] for index, char in enumerate(path[:-1]) if char in "/\\")
+ return paths
+
+ def _identity_message(self) -> str:
+ """Return the message without location text the finding records elsewhere.
+
+ Secret detection writes the finding's own ``in <file>:<line>`` into
+ its message (with the path as the scanner saw it, which may be a
+ suffix of ``file_path``), and the PII scan appends
+ ``— N occurrences (...)`` when it folds repeats of one value into a
+ finding whose ``metadata`` lists them. Leaving that text out keeps ``finding_id`` stable when
+ lines move. Other text, such as a file name a check puts in its
+ message, stays part of the identity.
+ """
+ message = "" if self.message is None else str(self.message)
+ if self.file_path is not None and self.line_number is not None:
+ # Compare with "/" separators: a plugin scan writes file_path with
+ # "/" while the message keeps the scanner's backslashes on Windows.
+ # Each backslash maps to one "/", so a match spans the same text.
+ slashed = message.replace("\\", "/")
+ for location in self._location_paths(self.file_path):
+ text = f" in {location}:{self.line_number}".replace("\\", "/")
+ index = slashed.find(text)
+ if index >= 0:
+ message = message[:index] + message[index + len(text) :]
+ break
+ occurrences = self.metadata.get("occurrences") if isinstance(self.metadata, dict) else None
+ if isinstance(occurrences, list) and len(occurrences) > 1:
+ marker = f" \u2014 {len(occurrences)} occurrences ("
+ index = message.rfind(marker)
+ if index >= 0 and message.endswith(")"):
+ message = message[:index]
+ return message
+
+ @property
+ def finding_id(self) -> str:
+ """Return a deterministic semantic identity independent of location.
+
+ File and line belong to an occurrence. Excluding them, and any copy
+ of them in the message (see ``_identity_message``), lets reporters
+ group the same check across paths and validators while retaining every
+ concrete occurrence in the reconciliation contract. Severity is also
+ excluded, so a policy override or verifier downgrade keeps the ID.
+ """
+ identity = "\x1f".join(
+ (
+ self._normalize_identity_text(self.category),
+ self._normalize_identity_text(self.check_name),
+ self._normalize_identity_text(self._identity_message()),
+ self._normalize_identity_text(self.suggestion),
+ )
+ )
+ digest = hashlib.sha256(identity.encode("utf-8"), usedforsecurity=False).hexdigest()[:20]
+ return f"SEF-{digest}"
+
+ def location_occurrence_id(self, file_path: object, line_number: object, line_content: object = None) -> str:
+ """Return the occurrence ID this finding has at another location.
+
+ A check that folds repeats into one finding, such as the PII scan,
+ lists the other locations in ``metadata["occurrences"]``; reporters
+ give each of them an ID this way. At the finding's own location and
+ line content it equals ``occurrence_id``.
+ """
+ identity = "\x1f".join(
+ (
+ self.finding_id,
+ ("" if file_path is None else str(file_path)).replace("\\", "/"),
+ str(line_number) if line_number is not None else "",
+ self._normalize_identity_text(line_content),
+ )
+ )
+ digest = hashlib.sha256(identity.encode("utf-8"), usedforsecurity=False).hexdigest()[:20]
+ return f"SEO-{digest}"
+
+ @property
+ def occurrence_id(self) -> str:
+ """Return a deterministic identity for this concrete location."""
+ return self.location_occurrence_id(self.file_path, self.line_number, self.line_content)
+
@property
def location(self) -> str:
"""Return formatted location like 'file.py:42'."""
@@ -145,6 +244,8 @@ class Finding:
"""Convert to dictionary for JSON serialization."""
severity_value = self.severity.value if isinstance(self.severity, Severity) else str(self.severity).lower()
return {
+ "finding_id": self.finding_id,
+ "occurrence_id": self.occurrence_id,
"category": self.category,
"severity": severity_value,
"check_name": self.check_name,
@@ -549,6 +650,21 @@ class ValidationResult:
# Prefix findings with skill name in file_path
for finding in other.findings:
+ metadata = finding.metadata
+ listed = metadata.get("occurrences") if isinstance(metadata, dict) else None
+ if isinstance(listed, list):
+ # A check that folds repeats (the PII scan) lists each location
+ # in metadata; prefix those like file_path so the finding's own
+ # location still matches its first listed one.
+ metadata = {
+ **metadata,
+ "occurrences": [
+ {**item, "file": f"[{prefix}] {item['file']}"}
+ if isinstance(item, dict) and isinstance(item.get("file"), str)
+ else item
+ for item in listed
+ ],
+ }
prefixed_finding = Finding(
category=finding.category,
severity=finding.severity,
@@ -558,7 +674,7 @@ class ValidationResult:
line_number=finding.line_number,
line_content=finding.line_content,
suggestion=finding.suggestion,
- metadata=finding.metadata,
+ metadata=metadata,
)
self.findings.append(prefixed_finding)
diff --git a/src/skillevaluator/reporting/finding_summary.py b/src/skillevaluator/reporting/finding_summary.py
new file mode 100644
index 00000000..2a523070
--- /dev/null
+++ b/src/skillevaluator/reporting/finding_summary.py
@@ -0,0 +1,338 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Canonical finding reconciliation shared by every report format.
+
+Validators can report the same problem more than once: one check fires on
+several lines, or two validators flag the same line. Each reporter used to
+derive its own totals from raw validator counts, so one run could show
+different issue counts in JSON, HTML, and Markdown. This module groups raw
+findings by their stable ``finding_id``, keeps every distinct
+``occurrence_id`` as a location, and returns one set of counts that every
+reporter emits.
+"""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import TYPE_CHECKING, Any
+
+from skillevaluator.models import Finding, Severity, ValidationResult
+from skillevaluator.reporting.base import additional_errors, additional_warnings
+
+if TYPE_CHECKING:
+ from collections.abc import Mapping
+
+
+_SEVERITY_ORDER = {"critical": 4, "high": 3, "medium": 2, "low": 1, "info": 0}
+# ValidationResult.add_success records each passed check as "[OK] check: message".
+_SUCCESS_PREFIX = "[OK] "
+# tier_workflows._record_scope records a stage skipped by configuration, such
+# as --no-llm, as a warning with this prefix. It notes scope, not a problem.
+_WORKFLOW_SCOPE_PREFIX = "Workflow scope: "
+
+
+def _occurrence_sort_key(item: dict[str, Any]) -> tuple[str, int, str, str]:
+ """Order occurrences by location without failing on malformed values."""
+ line_number = item["line_number"]
+ return (
+ str(item["file_path"] or ""),
+ line_number if isinstance(line_number, int) else 0,
+ str(item["validator"] or ""),
+ item["occurrence_id"],
+ )
+
+
+def _finding_occurrences(finding: Finding, validator: str) -> list[dict[str, Any]]:
+ """Return every location one raw finding reports.
+
+ That is the finding's own location plus, when the check folded repeats
+ of one value into this finding (the PII scan does), each other location
+ listed in ``metadata["occurrences"]`` as ``{"file": ..., "line": ...}``.
+ The source line stays on the finding in ``results[].findings[]``, under
+ the same ``occurrence_id``; copying it here would roughly double a report
+ in which one check fires on many lines.
+ """
+ entries = [
+ {
+ "occurrence_id": finding.occurrence_id,
+ "validator": validator,
+ "file_path": finding.file_path,
+ "line_number": finding.line_number,
+ }
+ ]
+ listed = finding.metadata.get("occurrences") if isinstance(finding.metadata, dict) else None
+ if not isinstance(listed, list):
+ return entries
+ for item in listed:
+ if not isinstance(item, dict) or "file" not in item:
+ continue
+ file_path, line_number = item.get("file"), item.get("line")
+ if file_path == finding.file_path and line_number == finding.line_number:
+ continue
+ entries.append(
+ {
+ "occurrence_id": finding.location_occurrence_id(file_path, line_number),
+ "validator": validator,
+ "file_path": file_path,
+ "line_number": line_number,
+ }
+ )
+ return entries
+
+
+def _finalize_summary(
+ groups: dict[str, dict[str, Any]], raw_by_severity: dict[str, int], reported_occurrences: int
+) -> dict[str, Any]:
+ """Finalize counts and stable ordering for a set of finding groups.
+
+ ``reported_occurrences`` counts every location the raw records report,
+ so ``duplicates_removed`` is the number of those locations that repeat
+ one already counted.
+ """
+ unique_by_severity = dict.fromkeys(_SEVERITY_ORDER, 0)
+ for group in groups.values():
+ unique_by_severity.setdefault(group["severity"], 0)
+ unique_by_severity[group["severity"]] += 1
+ group["validators"].sort()
+ group["occurrences"].sort(key=_occurrence_sort_key)
+ group["occurrence_count"] = len(group["occurrences"])
+
+ raw_count = sum(raw_by_severity.values())
+ distinct_occurrences = sum(group["occurrence_count"] for group in groups.values())
+ unique_count = len(groups)
+ return {
+ "raw_occurrences": raw_count,
+ "distinct_occurrences": distinct_occurrences,
+ "unique_findings": unique_count,
+ "duplicates_removed": reported_occurrences - distinct_occurrences,
+ "occurrences_grouped": distinct_occurrences - unique_count,
+ "raw_by_severity": raw_by_severity,
+ "unique_by_severity": unique_by_severity,
+ "groups": sorted(groups.values(), key=lambda group: group["finding_id"]),
+ }
+
+
+def summarize_findings(results: list[ValidationResult]) -> dict[str, Any]:
+ """Group raw findings by stable identity and retain every occurrence."""
+ groups: dict[str, dict[str, Any]] = {}
+ seen_occurrences: dict[str, set[str]] = {}
+ raw_by_severity = dict.fromkeys(_SEVERITY_ORDER, 0)
+ reported_occurrences = 0
+
+ for result in results:
+ for finding in result.findings:
+ severity = (
+ finding.severity.value if isinstance(finding.severity, Severity) else str(finding.severity).lower()
+ )
+ raw_by_severity.setdefault(severity, 0)
+ raw_by_severity[severity] += 1
+ finding_id = finding.finding_id
+ group = groups.get(finding_id)
+ if group is None:
+ group = {
+ "finding_id": finding_id,
+ "category": finding.category,
+ "severity": severity,
+ "check_name": finding.check_name,
+ "message": finding.message,
+ "suggestion": finding.suggestion,
+ "metadata": finding.metadata or None,
+ "validators": [],
+ "occurrences": [],
+ }
+ groups[finding_id] = group
+ seen_occurrences[finding_id] = set()
+ elif _SEVERITY_ORDER.get(severity, 0) > _SEVERITY_ORDER.get(group["severity"], 0):
+ group["severity"] = severity
+
+ if result.validator_name not in group["validators"]:
+ group["validators"].append(result.validator_name)
+ for occurrence in _finding_occurrences(finding, result.validator_name):
+ reported_occurrences += 1
+ if occurrence["occurrence_id"] not in seen_occurrences[finding_id]:
+ seen_occurrences[finding_id].add(occurrence["occurrence_id"])
+ group["occurrences"].append(occurrence)
+
+ return _finalize_summary(groups, raw_by_severity, reported_occurrences)
+
+
+def merge_finding_summaries(summaries: list[dict[str, Any]]) -> dict[str, Any]:
+ """Merge per-result summaries without hashing the same findings again."""
+ groups: dict[str, dict[str, Any]] = {}
+ raw_by_severity = dict.fromkeys(_SEVERITY_ORDER, 0)
+ reported_occurrences = 0
+ for summary in summaries:
+ reported_occurrences += summary["distinct_occurrences"] + summary["duplicates_removed"]
+ for severity, count in summary["raw_by_severity"].items():
+ raw_by_severity.setdefault(severity, 0)
+ raw_by_severity[severity] += count
+ for incoming in summary["groups"]:
+ finding_id = incoming["finding_id"]
+ group = groups.get(finding_id)
+ if group is None:
+ groups[finding_id] = deepcopy(incoming)
+ continue
+ if _SEVERITY_ORDER.get(incoming["severity"], 0) > _SEVERITY_ORDER.get(group["severity"], 0):
+ group["severity"] = incoming["severity"]
+ group["validators"] = sorted(set(group["validators"]) | set(incoming["validators"]))
+ existing_occurrences = {item["occurrence_id"] for item in group["occurrences"]}
+ group["occurrences"].extend(
+ deepcopy(item) for item in incoming["occurrences"] if item["occurrence_id"] not in existing_occurrences
+ )
+
+ return _finalize_summary(groups, raw_by_severity, reported_occurrences)
+
+
+def groups_by_display_priority(summary: Mapping[str, Any]) -> list[dict[str, Any]]:
+ """Return a summary's groups with the most severe and most repeated first.
+
+ ``groups`` stays ordered by ``finding_id`` so machine output is stable.
+ A capped human-readable list uses this order instead, so a critical
+ finding is never hidden behind low-severity ones.
+ """
+ return sorted(
+ summary["groups"],
+ key=lambda group: (
+ -_SEVERITY_ORDER.get(group["severity"], 0),
+ -group["occurrence_count"],
+ group["finding_id"],
+ ),
+ )
+
+
+def finding_counts(summary: dict[str, Any]) -> dict[str, Any]:
+ """Return a summary's reconciliation counts without its finding groups."""
+ return {key: value for key, value in summary.items() if key != "groups"}
+
+
+_IDENTITY_FIELDS = ("finding_id", "occurrence_id")
+
+
+def refresh_finding_identities(document: dict[str, Any]) -> None:
+ """Recompute a JSON report's finding IDs and groups from its current finding text.
+
+ CI removes detected credentials from a report after it is written. IDs
+ hashed before that would no longer match the redacted text, and a short
+ redacted value could be recovered by hashing guesses against them. Call
+ this after redacting: it replaces only the ID and reconciliation fields
+ the report already has, so a report written before finding IDs existed
+ keeps its shape. Message counts do not depend on text and are kept.
+ """
+ rows = document.get("results")
+ if not isinstance(rows, list):
+ return
+ summaries = []
+ for row in rows:
+ if not isinstance(row, dict) or not isinstance(row.get("findings"), list):
+ continue
+ result = ValidationResult(validator_name=str(row.get("validator") or ""))
+ for item in row["findings"]:
+ if not isinstance(item, dict):
+ continue
+ finding = Finding(
+ category=item.get("category"),
+ severity=item.get("severity"),
+ check_name=item.get("check_name"),
+ message=item.get("message"),
+ file_path=item.get("file_path"),
+ line_number=item.get("line_number"),
+ line_content=item.get("line_content"),
+ suggestion=item.get("suggestion"),
+ metadata=item.get("metadata") or {},
+ )
+ for key in _IDENTITY_FIELDS:
+ if key in item:
+ item[key] = getattr(finding, key)
+ result.findings.append(finding)
+ summary = summarize_findings([result])
+ if "finding_counts" in row:
+ row["finding_counts"] = finding_counts(summary)
+ summaries.append(summary)
+ merged = merge_finding_summaries(summaries)
+ if "finding_counts" in document:
+ document["finding_counts"] = finding_counts(merged)
+ if "finding_groups" in document:
+ document["finding_groups"] = merged["groups"]
+
+
+def summarize_messages(results: list[ValidationResult]) -> dict[str, int]:
+ """Count string messages that no structured finding represents.
+
+ Findings also add a mirrored string to a result's ``errors`` or
+ ``warnings`` list. ``independent_errors`` and ``independent_warnings``
+ leave those mirrors out, so they never count a finding twice. They cover
+ problems with no ``Finding`` behind them: failed gates such as a minimum
+ score, scanner and execution errors, and a missing or failed scanner.
+ The ``Workflow scope:`` note recorded when configuration skips a stage,
+ such as LLM checks under ``--no-llm``, is not a problem and is left out
+ of ``independent_warnings``; the raw ``total_warnings`` still counts it.
+ ``informational`` counts informational messages. It leaves out the
+ ``[OK]`` line that ``add_success`` records for every passed check; those
+ checks are listed in ``success_details``.
+ """
+ return {
+ "informational": sum(
+ 1 for result in results for message in result.messages if not str(message).startswith(_SUCCESS_PREFIX)
+ ),
+ "independent_errors": sum(len(additional_errors(result)) for result in results),
+ "independent_warnings": sum(
+ 1
+ for result in results
+ for warning in additional_warnings(result)
+ if not str(warning).startswith(_WORKFLOW_SCOPE_PREFIX)
+ ),
+ }
+
+
+def total_issue_count(counts: Mapping[str, Any], messages: Mapping[str, int]) -> int:
+ """Return the headline issue count: unique findings plus independent errors and warnings."""
+ return counts["unique_findings"] + messages["independent_errors"] + messages["independent_warnings"]
+
+
+def count_phrase(count: int, singular: str, plural: str | None = None) -> str:
+ """Return ``count`` followed by the singular or plural noun."""
+ return f"{count} {singular if count == 1 else plural or f'{singular}s'}"
+
+
+def describe_issue_counts(
+ counts: Mapping[str, Any],
+ messages: Mapping[str, int],
+ *,
+ unique_suffix: str = "",
+ raw_records: bool = False,
+ duplicates: bool = False,
+) -> str:
+ """Describe a report's issue counts in the shared HTML and Markdown wording.
+
+ Unique findings and their distinct occurrences come first; ``raw_records``
+ and ``duplicates`` add the raw record and reconciled duplicate totals.
+ Independent errors and warnings follow, so a run that fails a gate or
+ leaves a scan incomplete without any finding never reads as zero issues.
+ ``unique_suffix`` is appended to the unique count, for example a severity
+ breakdown.
+ """
+ parts = [
+ count_phrase(counts["unique_findings"], "unique finding") + unique_suffix,
+ count_phrase(counts["distinct_occurrences"], "occurrence"),
+ ]
+ if raw_records:
+ parts.append(count_phrase(counts["raw_occurrences"], "raw record"))
+ if duplicates and counts["duplicates_removed"]:
+ parts.append(f"{count_phrase(counts['duplicates_removed'], 'duplicate')} reconciled")
+ finding_text = " / ".join(parts)
+
+ independent = [
+ count_phrase(count, noun)
+ for count, noun in (
+ (messages["independent_errors"], "error"),
+ (messages["independent_warnings"], "warning"),
+ )
+ if count
+ ]
+ if not independent:
+ return finding_text
+ independent_text = f"{' and '.join(independent)} without a finding"
+ if not counts["unique_findings"]:
+ return independent_text
+ return f"{finding_text}; {independent_text}"
diff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.py
index ce8e7b37..b3f9e0ed 100644
--- a/src/skillevaluator/reporting/html.py
+++ b/src/skillevaluator/reporting/html.py
@@ -72,6 +72,13 @@ from skillevaluator.reporting.base import (
from skillevaluator.reporting.base import (
is_tier2_validator_name as _is_tier2_validator_name,
)
+from skillevaluator.reporting.finding_summary import (
+ describe_issue_counts,
+ finding_counts,
+ summarize_findings,
+ summarize_messages,
+ total_issue_count,
+)
from skillevaluator.reporting.harbor_viewer import normalize_agent_eval_harbor_links
from skillevaluator.reporting.presentation import success_is_not_applicable
from skillevaluator.reporting.run_status import Status, resolve_run_status, result_status
@@ -1723,6 +1730,8 @@ class HTMLReporter(ReporterBase):
vdata["findings"].append(
{
+ "finding_id": finding.finding_id,
+ "occurrence_id": finding.occurrence_id,
"category": finding.category,
"severity": finding.severity.value
if hasattr(finding.severity, "value")
@@ -1749,6 +1758,7 @@ class HTMLReporter(ReporterBase):
skill_data["status"] = "incomplete"
skill_data["validators"][vn] = vdata
+ skill_data["finding_count"] = self._unique_finding_count(skill_data)
# Deduplicate findings per validator
for vdata in skill_data["validators"].values():
if vdata["findings"]:
@@ -1859,6 +1869,8 @@ class HTMLReporter(ReporterBase):
confidence = finding.metadata.get("confidence", "high")
skills[skill_name]["validators"][validator_name]["findings"].append(
{
+ "finding_id": finding.finding_id,
+ "occurrence_id": finding.occurrence_id,
"category": finding.category,
"severity": finding.severity.value
if hasattr(finding.severity, "value")
@@ -1878,6 +1890,7 @@ class HTMLReporter(ReporterBase):
# Deduplicate findings within each skill/validator
for skill_data in skills.values():
+ skill_data["finding_count"] = self._unique_finding_count(skill_data)
# Recompute issue_count after deduplication (use occurrences)
deduped_count = 0
for validator_data in skill_data["validators"].values():
@@ -1905,6 +1918,23 @@ class HTMLReporter(ReporterBase):
# Strip and collapse whitespace
return " ".join((msg or "").split())
+ @staticmethod
+ def _unique_finding_count(skill_data: dict[str, Any]) -> int:
+ """Count a skill's findings once per ``finding_id``, before display merging.
+
+ ``issue_count`` keeps counting raw records for the JSON ``skills``
+ list and contributor totals; the skill badge shows this count so it
+ agrees with the summary's Findings number.
+ """
+ return len(
+ {
+ finding["finding_id"]
+ for validator in skill_data["validators"].values()
+ for finding in validator["findings"]
+ if finding.get("finding_id")
+ }
+ )
+
@staticmethod
def _deduplicate_findings(findings: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Aggregate duplicate findings that share the same message, file, and suggestion.
@@ -1913,8 +1943,13 @@ class HTMLReporter(ReporterBase):
into a single entry with an 'occurrences' count and a 'lines' list.
This dramatically reduces visual noise when the same PII pattern
(e.g., "Personal macOS user path") fires on many lines in the same file.
+ A finding's ``occurrence_id`` becomes an ``occurrence_ids`` list on the
+ merged entry, so every merged location keeps its identity. The key
+ also holds ``finding_id`` when present, so two different checks with
+ the same text never merge and an entry's IDs all belong to it.
"""
groups: dict[tuple, dict[str, Any]] = {}
+ seen_occurrences: dict[tuple, set[str]] = {}
for finding in findings:
# Normalize message for deduplication (strip trailing whitespace/newlines)
@@ -1923,6 +1958,7 @@ class HTMLReporter(ReporterBase):
norm_msg,
finding.get("file_path", ""),
finding.get("suggestion", ""),
+ finding.get("finding_id"),
)
if key in groups:
@@ -1945,10 +1981,18 @@ class HTMLReporter(ReporterBase):
new_conf = finding.get("confidence", "high")
if conf_order.get(new_conf, 2) < conf_order.get(existing_conf, 2):
groups[key]["confidence"] = new_conf
+ occurrence_id = finding.get("occurrence_id")
+ if occurrence_id and "occurrence_ids" in groups[key] and occurrence_id not in seen_occurrences[key]:
+ seen_occurrences[key].add(occurrence_id)
+ groups[key]["occurrence_ids"].append(occurrence_id)
else:
entry = dict(finding)
entry["message"] = norm_msg # Store normalized message
entry["occurrences"] = 1
+ if "occurrence_id" in entry:
+ occurrence_id = entry.pop("occurrence_id")
+ entry["occurrence_ids"] = [occurrence_id] if occurrence_id else []
+ seen_occurrences[key] = set(entry["occurrence_ids"])
line_num = finding.get("line_number")
entry["lines"] = [line_num] if line_num else []
# Extract confidence from metadata if present
@@ -2273,7 +2317,12 @@ class HTMLReporter(ReporterBase):
"""Compact stats for a single tier — what the hero chip displays.
Returns ``passed`` (boolean), executed/pass/skip counts,
- ``issue_count`` (sum of findings), and per-severity totals.
+ ``issue_count`` (unique findings, as the Markdown summary counts
+ them), and per-severity totals of those unique findings at their
+ highest severity. ``occurrence_count``, ``raw_finding_count`` and
+ ``duplicates_removed`` sit beside them, and ``issue_detail`` describes
+ them in the shared report wording when they differ from the unique
+ count or when errors or warnings have no finding behind them.
``total == 0`` lets the template hide the chip entirely without an
extra "did this tier run?" predicate.
"""
@@ -2284,20 +2333,15 @@ class HTMLReporter(ReporterBase):
advisory_skipped_count = sum(1 for r in results if is_advisory_agent_eval_skip(r))
failed_count = sum(1 for r in results if result_status(r) == Status.FAILED)
incomplete_count = sum(1 for r in results if result_status(r) == Status.INCOMPLETE)
- issue_count = 0
- critical = high = medium = low = 0
- for r in results:
- issue_count += len(r.findings or [])
- for f in r.findings or []:
- sev = f.severity.value if hasattr(f.severity, "value") else str(f.severity).lower()
- if sev == "critical":
- critical += 1
- elif sev == "high":
- high += 1
- elif sev == "medium":
- medium += 1
- elif sev == "low":
- low += 1
+ findings = summarize_findings(results)
+ messages = summarize_messages(results)
+ unique_by_severity = findings["unique_by_severity"]
+ has_detail = (
+ findings["raw_occurrences"] != findings["unique_findings"]
+ or findings["distinct_occurrences"] != findings["unique_findings"]
+ or messages["independent_errors"]
+ or messages["independent_warnings"]
+ )
return {
"total": total,
"executed_count": executed_count,
@@ -2305,13 +2349,20 @@ class HTMLReporter(ReporterBase):
"skipped_count": skipped_count,
"advisory_skipped_count": advisory_skipped_count,
"failed_count": failed_count,
- "issue_count": issue_count,
+ "issue_count": findings["unique_findings"],
+ "occurrence_count": findings["distinct_occurrences"],
+ "raw_finding_count": findings["raw_occurrences"],
+ "duplicates_removed": findings["duplicates_removed"],
+ "total_issues": total_issue_count(findings, messages),
+ "issue_detail": (
+ describe_issue_counts(findings, messages, raw_records=True, duplicates=True) if has_detail else ""
+ ),
"all_passed": executed_count > 0 and failed_count == 0 and incomplete_count == 0,
"incomplete_count": incomplete_count,
- "critical": critical,
- "high": high,
- "medium": medium,
- "low": low,
+ "critical": unique_by_severity["critical"],
+ "high": unique_by_severity["high"],
+ "medium": unique_by_severity["medium"],
+ "low": unique_by_severity["low"],
}
def _results_to_dict(self, results: list[ValidationResult]) -> list[dict[str, Any]]:
@@ -2354,6 +2405,8 @@ class HTMLReporter(ReporterBase):
for finding in result.findings:
result_dict["findings"].append(
{
+ "finding_id": finding.finding_id,
+ "occurrence_id": finding.occurrence_id,
"category": finding.category,
"severity": finding.severity.value,
"check_name": finding.check_name,
@@ -2748,13 +2801,16 @@ class HTMLReporter(ReporterBase):
all_passed = run_status.headline == Status.PASSED
has_incomplete = run_status.headline == Status.INCOMPLETE
overall_status = run_status.headline.value
- total_errors = sum(r.summary.errors for r in results)
- total_warnings = sum(r.summary.warnings for r in results)
+ finding_summary = summarize_findings(results)
+ message_summary = summarize_messages(results)
skipped_count = sum(1 for r in results if is_cleanly_skipped(r))
passed_count = sum(1 for r in results if r.passed and not r.is_incomplete and not is_cleanly_skipped(r))
advisory_skipped_count = sum(1 for r in results if is_advisory_agent_eval_skip(r))
failed_count = sum(1 for r in results if not passes_required_gate(r))
- total_issues = total_errors + total_warnings
+ # Count unique findings rather than raw validator records that repeat
+ # one finding, plus errors and warnings with no finding behind them
+ # (failed gates, scanner and execution errors), as Markdown does.
+ total_issues = total_issue_count(finding_summary, message_summary)
total_validators = len(results)
executed_count = total_validators - skipped_count
pass_percentage = round((passed_count / executed_count * 100) if executed_count > 0 else 0, 1)
@@ -2838,7 +2894,9 @@ class HTMLReporter(ReporterBase):
"passed_count": tier1_display_passed,
"skipped_count": tier1_display_skipped,
"failed_count": tier1_display_failed,
- "total_issues": sum(result.summary.errors + result.summary.warnings for result in tier1_display_results),
+ # Unique Tier 1 findings plus errors and warnings with no finding
+ # behind them, counted as the Markdown summary counts them.
+ "total_issues": tier1_summary["total_issues"],
"pass_percentage": round(
(tier1_display_passed / tier1_display_total * 100) if tier1_display_total else 0,
1,
@@ -2852,7 +2910,9 @@ class HTMLReporter(ReporterBase):
# exit code. Results produced outside ``validate`` retain the public
# defaults: Tier 1/Tier 2 block and Tier 3 is advisory.
blocking_results: list[ValidationResult] = []
- advisory_results: list[ValidationResult] = []
+ # Per tier, so the gate policy counts findings the way each tier card does.
+ blocking_by_tier: dict[str, list[ValidationResult]] = {}
+ advisory_by_tier: dict[str, list[ValidationResult]] = {}
blocking_tiers: list[str] = []
advisory_tiers: list[str] = []
for tier_name, tier_results, default_blocking in (
@@ -2874,28 +2934,28 @@ class HTMLReporter(ReporterBase):
)
if is_blocking:
blocking_results.append(result)
+ blocking_by_tier.setdefault(tier_name, []).append(result)
tier_blocks = True
else:
- advisory_results.append(result)
+ advisory_by_tier.setdefault(tier_name, []).append(result)
tier_advises = True
if tier_blocks:
blocking_tiers.append(tier_name)
if tier_advises:
advisory_tiers.append(tier_name)
- def _severity_totals(tier_results: list[ValidationResult]) -> dict[str, int]:
+ def _severity_totals(results_by_tier: dict[str, list[ValidationResult]]) -> dict[str, int]:
+ # Each tier's unique findings at their highest severity, as its tier
+ # card counts them; the same finding in two tiers counts in both.
totals = {"critical": 0, "high": 0, "medium": 0, "low": 0}
- for result in tier_results:
- for finding in result.findings:
- severity = (
- finding.severity.value if hasattr(finding.severity, "value") else str(finding.severity).lower()
- )
- if severity in totals:
- totals[severity] += 1
+ for tier_results in results_by_tier.values():
+ unique_by_severity = summarize_findings(tier_results)["unique_by_severity"]
+ for severity in totals:
+ totals[severity] += unique_by_severity[severity]
return totals
- blocking_totals = _severity_totals(blocking_results)
- advisory_totals = _severity_totals(advisory_results)
+ blocking_totals = _severity_totals(blocking_by_tier)
+ advisory_totals = _severity_totals(advisory_by_tier)
blocking_critical = blocking_totals["critical"]
blocking_high = blocking_totals["high"]
blocking_medium = blocking_totals["medium"]
@@ -2983,13 +3043,11 @@ class HTMLReporter(ReporterBase):
tier1_failed_checks = [
plain_check_name(r.validator_name) for r in tier1_results if _result_display_status(r) == "fail"
]
- tier1_blocking_findings = sum(
- 1
- for r in tier1_results
- if not passes_required_gate(r)
- for f in r.findings
- if (f.severity.value if hasattr(f.severity, "value") else str(f.severity).lower()) in {"critical", "high"}
- )
+ # Unique critical and high findings in failed checks, counted like the Findings number.
+ tier1_blocking_by_severity = summarize_findings([r for r in tier1_results if not passes_required_gate(r)])[
+ "unique_by_severity"
+ ]
+ tier1_blocking_findings = tier1_blocking_by_severity["critical"] + tier1_blocking_by_severity["high"]
# Why each incomplete Tier 1 check stopped, in the scanner's words. The
# summary asks for an install only when every scanner is just missing.
tier1_stop_reasons = [
@@ -3026,6 +3084,9 @@ class HTMLReporter(ReporterBase):
"advisory_skipped_count": advisory_skipped_count,
"failed_count": failed_count,
"total_issues": total_issues,
+ "raw_finding_occurrences": finding_summary["raw_occurrences"],
+ "distinct_finding_occurrences": finding_summary["distinct_occurrences"],
+ "duplicates_removed": finding_summary["duplicates_removed"],
"pass_percentage": pass_percentage,
"total_skills": total_skills,
"passed_skills": passed_skills,
@@ -3033,6 +3094,9 @@ class HTMLReporter(ReporterBase):
"publication_status": publication.status,
},
"results": self._results_to_dict(results),
+ "finding_counts": finding_counts(finding_summary),
+ "finding_groups": finding_summary["groups"],
+ "message_counts": message_summary,
"skills": skills_by_name,
"top_issues": top_issues,
"contributors": contributors,
diff --git a/src/skillevaluator/reporting/json_reporter.py b/src/skillevaluator/reporting/json_reporter.py
index 97a63172..7ad012e3 100644
--- a/src/skillevaluator/reporting/json_reporter.py
+++ b/src/skillevaluator/reporting/json_reporter.py
@@ -29,12 +29,18 @@ from skillevaluator.reporting.base import (
result_publication_target_dict,
select_agent_eval_payload,
)
+from skillevaluator.reporting.finding_summary import (
+ finding_counts,
+ merge_finding_summaries,
+ summarize_findings,
+ summarize_messages,
+)
from skillevaluator.reporting.run_status import Status, resolve_run_status, result_status
from skillevaluator.skillspector_provenance import sanitize_skillspector_provenance_metadata
from skillevaluator.source_identity import recorded_evaluated_source
if TYPE_CHECKING:
- from skillevaluator.models import ValidationResult
+ from skillevaluator.models import Finding, ValidationResult
def _json_safe_agent_eval(value: object) -> dict[str, Any]:
@@ -107,6 +113,8 @@ class JSONReporter(ReporterBase):
overall_status = run_status.headline.value
total_errors = sum(r.summary.errors for r in results)
total_warnings = sum(r.summary.warnings for r in results)
+ result_finding_summaries = [summarize_findings([result]) for result in results]
+ finding_summary = merge_finding_summaries(result_finding_summaries)
# Reuse HTML reporter's skill reorganization and contributor extraction
html_reporter = HTMLReporter()
@@ -141,9 +149,17 @@ class JSONReporter(ReporterBase):
"medium": sum(r.summary.medium_count for r in results),
"low": sum(r.summary.low_count for r in results),
},
+ # Raw totals above count every validator record. These reconcile
+ # them into unique findings and distinct locations by stable ID.
+ "finding_counts": finding_counts(finding_summary),
+ "finding_groups": finding_summary["groups"],
+ "message_counts": summarize_messages(results),
"skills": skills_summary,
"contributors": contributors,
- "results": [self._result_to_dict(r) for r in results],
+ "results": [
+ self._result_to_dict(result, finding_summary=result_summary)
+ for result, result_summary in zip(results, result_finding_summaries, strict=True)
+ ],
}
agent_eval = select_agent_eval_payload(results)
@@ -258,8 +274,15 @@ class JSONReporter(ReporterBase):
return json.dumps(data, indent=self.indent, default=str, allow_nan=False)
- def _result_to_dict(self, result: ValidationResult) -> dict[str, Any]:
+ def _result_to_dict(
+ self,
+ result: ValidationResult,
+ *,
+ finding_summary: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
"""Convert ValidationResult to serializable dictionary."""
+ if finding_summary is None:
+ finding_summary = summarize_findings([result])
skipped = is_cleanly_skipped(result)
data: dict[str, Any] = {
"validator": result.validator_name,
@@ -280,20 +303,8 @@ class JSONReporter(ReporterBase):
"medium_count": result.summary.medium_count,
"low_count": result.summary.low_count,
},
- "findings": [
- {
- "category": f.category,
- "severity": f.severity.value,
- "check_name": f.check_name,
- "message": f.message,
- "file_path": f.file_path,
- "line_number": f.line_number,
- "line_content": f.line_content,
- "suggestion": f.suggestion,
- "metadata": f.metadata or None,
- }
- for f in result.findings
- ],
+ "finding_counts": finding_counts(finding_summary),
+ "findings": [self._finding_to_dict(finding) for finding in result.findings],
"success_details": [
{
"check": s.check_name,
@@ -387,5 +398,12 @@ class JSONReporter(ReporterBase):
return data
+ @staticmethod
+ def _finding_to_dict(finding: Finding) -> dict[str, Any]:
+ """Preserve the legacy JSON null for findings without metadata."""
+ data = finding.to_dict()
+ data["metadata"] = data["metadata"] or None
+ return data
+
def get_file_extension(self) -> str:
return ".json"
diff --git a/src/skillevaluator/reporting/markdown.py b/src/skillevaluator/reporting/markdown.py
index 2efdcda4..e4571e76 100644
--- a/src/skillevaluator/reporting/markdown.py
+++ b/src/skillevaluator/reporting/markdown.py
@@ -30,6 +30,12 @@ from skillevaluator.reporting.base import (
is_cleanly_skipped,
select_agent_eval_payload,
)
+from skillevaluator.reporting.finding_summary import (
+ describe_issue_counts,
+ groups_by_display_priority,
+ summarize_findings,
+ summarize_messages,
+)
from skillevaluator.reporting.harbor_viewer import (
harbor_evidence_link_text,
normalize_harbor_viewer_for_display,
@@ -202,6 +208,8 @@ class MarkdownReporter(ReporterBase):
def render_all(self, results: list[ValidationResult]) -> str:
"""Render all results to Markdown with summary."""
lines = []
+ finding_summary = summarize_findings(results)
+ message_summary = summarize_messages(results)
# Header
lines.append("# SkillEvaluator Validation Report")
@@ -275,26 +283,45 @@ class MarkdownReporter(ReporterBase):
if advisory_skip_count:
lines.append(f"| ⏭️ Advisory skips | {advisory_skip_count} |")
- total_errors = sum(r.summary.errors for r in results)
- total_warnings = sum(r.summary.warnings for r in results)
- critical = sum(r.summary.critical_count for r in results)
- high = sum(r.summary.high_count for r in results)
- medium = sum(r.summary.medium_count for r in results)
-
- severity_breakdown = []
- if critical > 0:
- severity_breakdown.append(f"{critical} critical")
- if high > 0:
- severity_breakdown.append(f"{high} high")
- if medium > 0:
- severity_breakdown.append(f"{medium} medium")
-
- issue_str = f"{total_errors + total_warnings}"
- if severity_breakdown:
- issue_str += f" ({', '.join(severity_breakdown)})"
+ # The breakdown qualifies the unique count, so it counts unique findings
+ # at their highest severity rather than raw validator records.
+ unique_by_severity = finding_summary["unique_by_severity"]
+ severity_breakdown = [
+ f"{unique_by_severity[severity]} {severity}"
+ for severity in ("critical", "high", "medium")
+ if unique_by_severity[severity] > 0
+ ]
+ issue_str = describe_issue_counts(
+ finding_summary,
+ message_summary,
+ unique_suffix=f" ({', '.join(severity_breakdown)})" if severity_breakdown else "",
+ raw_records=True,
+ )
lines.append(f"| Total Issues | {issue_str} |")
+ lines.append(f"| Duplicate Occurrences Reconciled | {finding_summary['duplicates_removed']} |")
lines.append("")
+ if finding_summary["groups"]:
+ lines.append("## Finding Reconciliation")
+ lines.append("")
+ lines.append("| Finding ID | Severity | Finding | Occurrences | Validators |")
+ lines.append("|------------|----------|---------|-------------|------------|")
+ # The table is capped, so list the most severe findings first.
+ shown_groups = groups_by_display_priority(finding_summary)[: self.max_findings_shown]
+ for group in shown_groups:
+ # Finding text and validator names are untrusted report input.
+ lines.append(
+ f"| `{group['finding_id']}` "
+ f"| {_markdown_untrusted_table_cell(str(group['severity']).upper())} "
+ f"| {_markdown_untrusted_table_cell(group['message'])} "
+ f"| {group['occurrence_count']} "
+ f"| {_markdown_untrusted_table_cell(', '.join(group['validators']))} |"
+ )
+ remaining_groups = len(finding_summary["groups"]) - len(shown_groups)
+ if remaining_groups > 0:
+ lines.append(f"| ... | | *{remaining_groups} more unique findings* | | |")
+ lines.append("")
+
# Quality Score summary (if any QUALITY results present)
quality_results = [r for r in results if r.metadata.get("quality_scores")]
if quality_results:
@@ -591,6 +618,8 @@ class MarkdownReporter(ReporterBase):
lines.append(f"**{index}. {finding.message}**")
lines.append(f"- File: `{finding.location}`")
lines.append(f"- Check: `{finding.check_name}`")
+ lines.append(f"- Finding ID: `{finding.finding_id}`")
+ lines.append(f"- Occurrence ID: `{finding.occurrence_id}`")
related_paths = _related_paths(finding)
if related_paths:
lines.append(f"- Related paths: {' <-> '.join(f'`{path}`' for path in related_paths)}")
diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2
index 3e38f926..ce0dde3e 100644
--- a/src/skillevaluator/reporting/templates/report.html.j2
+++ b/src/skillevaluator/reporting/templates/report.html.j2
@@ -1531,6 +1531,7 @@
<dt>Findings</dt>
<dd class="kpi-value"><strong>{{ tier1_summary.issue_count or 0 }}</strong></dd>
<dd class="kpi-sub sev-line">{% for level in ['critical', 'high', 'medium', 'low'] %}{% if tier1_summary[level] %}<span class="sev-item"><span class="sev-dot {{ level }}" aria-hidden="true"></span>{{ tier1_summary[level] }} {{ level }}</span> {% endif %}{% endfor %}{% if not tier1_summary.issue_count %}None reported{% endif %}</dd>
+ {% if tier1_summary.issue_detail %}<dd class="kpi-sub kpi-issue-detail">{{ tier1_summary.issue_detail }}</dd>{% endif %}
</div>
<div class="kpi">
<dt>Blocking critical + high</dt>
@@ -1551,7 +1552,7 @@
{% endif %}
</div>
</dl>
- <p class="kpi-legend">A finding is one problem a check reports at one location, with a severity from critical to low. Findings in a failed check block the verdict; findings in a passed check are advisory.</p>
+ <p class="kpi-legend">A finding is one problem a check reports, with a severity from critical to low. The same problem reported on several lines or in several files or {{ content_label_plural | lower }} counts once; each location is an occurrence. Findings in a failed check block the verdict; findings in a passed check are advisory.</p>
{% if fix_first %}
<div class="fix-first">
<h3>{{ 'Worth a look' if t1_key == 'pass' else 'Fix first' }}</h3>
@@ -1564,7 +1565,7 @@
</li>
{% endfor %}
</ol>
- {% if tier1_summary.issue_count > fix_first | selectattr('kind', 'equalto', 'finding') | list | length %}<p class="fix-more">The other findings are listed under their checks below.</p>{% endif %}
+ {% if tier1_summary.occurrence_count > fix_first | selectattr('kind', 'equalto', 'finding') | list | length %}<p class="fix-more">The other findings are listed under their checks below.</p>{% endif %}
</div>
{% endif %}
</section>
@@ -1781,7 +1782,8 @@
<span class="status-badge {{ 'warn' if skill_status == 'incomplete' else skill_status }}">{{ verdict_words.get(skill_status, skill_status | title) }}</span>
<span style="color: var(--text-secondary);">{{ skill_data.validators | length }} checks</span>
{% if not skill_data.passed and skill_data.issue_count is defined and skill_data.issue_count > 0 %}
- <span class="issue-count-badge">{{ skill_data.issue_count }} finding{{ 's' if skill_data.issue_count != 1 else '' }}</span>
+ {% set skill_findings = skill_data.finding_count if skill_data.finding_count is defined else skill_data.issue_count %}
+ <span class="issue-count-badge">{{ skill_findings }} finding{{ 's' if skill_findings != 1 else '' }}</span>
{% endif %}
<span class="expand-text">{{ '▲' if not skill_data.passed else '▼' }}</span>
</div>
diff --git a/tests/ci/test_secret_redaction.py b/tests/ci/test_secret_redaction.py
index 30dd7adb..7e20868d 100644
--- a/tests/ci/test_secret_redaction.py
+++ b/tests/ci/test_secret_redaction.py
@@ -16,6 +16,8 @@ from urllib.parse import quote
import pytest
+from skillevaluator.models import Finding, Severity, ValidationResult
+from skillevaluator.reporting.html import HTMLReporter
from skillevaluator.reporting.json_reporter import JSONReporter
from skillevaluator.validators.security import SecurityValidator
@@ -46,6 +48,32 @@ def _assert_no_secret(value: str | bytes) -> None:
pytest.fail("A synthetic credential was present in a shared output.")
+def _assert_finding_ids_match_text(document: dict) -> None:
+ """Every finding ID in a shared report is hashed from that report's redacted text."""
+ finding_ids = set()
+ for row in document["results"]:
+ for item in row["findings"]:
+ finding = Finding(
+ **{
+ key: item[key]
+ for key in (
+ "category",
+ "severity",
+ "check_name",
+ "message",
+ "file_path",
+ "line_number",
+ "line_content",
+ "suggestion",
+ )
+ }
+ )
+ assert item["finding_id"] == finding.finding_id
+ assert item["occurrence_id"] == finding.occurrence_id
+ finding_ids.add(finding.finding_id)
+ assert {group["finding_id"] for group in document["finding_groups"]} == finding_ids
+
+
def test_pii_findings_do_not_expose_detected_credential(tmp_path):
skill = _skill(tmp_path)
result = SecurityValidator(use_llm=False).validate_pii_only(skill)
@@ -98,6 +126,7 @@ def test_runner_and_retained_publisher_never_export_detected_value(tmp_path, cap
_assert_no_secret(path.read_bytes())
if _fixture_value()[:24].encode() in path.read_bytes():
pytest.fail("A truncated synthetic credential was present in a report.")
+ _assert_finding_ids_match_text(json.loads((reports / "skill-001/skillevaluator-tier1.json").read_text()))
from ci import publish_reports
@@ -124,6 +153,7 @@ def test_runner_and_retained_publisher_never_export_detected_value(tmp_path, cap
zipped.writestr("skill-001/skillevaluator-tier1.json", json.dumps(document))
safe_summary, safe_reports = publish_reports.read_artifact(old_archive.getvalue())
_assert_no_secret(json.dumps({"summary": safe_summary, "retained": safe_reports}))
+ _assert_finding_ids_match_text(safe_reports["skill-001"])
spec = importlib.util.spec_from_file_location("publisher_fixtures", ROOT / "tests/ci/test_publish_reports.py")
fixtures = importlib.util.module_from_spec(spec)
@@ -170,6 +200,164 @@ def test_runner_and_retained_publisher_never_export_detected_value(tmp_path, cap
publish_reports.read_artifact(unsafe_archive.getvalue())
+def test_redacted_report_does_not_keep_ids_hashed_from_the_credential(tmp_path):
+ # A finding ID hashed from text that held a short credential would let a
+ # reader of the redacted report confirm guesses of that credential.
+ skill = _skill(tmp_path / "workspace")
+ pii = SecurityValidator(use_llm=False).validate_pii_only(skill)
+ pii.validator_name = "PII Scan"
+ echo = ValidationResult(validator_name="Code Risk", validator_description="Static analysis")
+ echoed = Finding(
+ "SECURITY",
+ Severity.HIGH,
+ "hardcoded-credential",
+ "Credential in source: " + _fixture_value(),
+ "source.py",
+ 1,
+ line_content='API_KEY = "' + _fixture_value() + '"',
+ )
+ echo.add_finding(echoed)
+ raw = tmp_path / "raw"
+ raw.mkdir()
+ (raw / "skillevaluator-tier1.json").write_text(JSONReporter(include_timestamp=False).render_all([pii, echo]))
+
+ sanitized = runner.sanitized_outputs(raw, runner.collect_sensitive_values(skill))
+
+ _assert_no_secret(sanitized["skillevaluator-tier1.json"])
+ for raw_id in (echoed.finding_id, echoed.occurrence_id):
+ assert raw_id.encode() not in sanitized["skillevaluator-tier1.json"]
+ document = json.loads(sanitized["skillevaluator-tier1.json"])
+ _assert_finding_ids_match_text(document)
+ assert document["finding_counts"]["unique_findings"] == len(document["finding_groups"]) == 2
+ assert document["results"][1]["finding_counts"]["raw_occurrences"] == 1
+
+
+def test_redacted_html_does_not_keep_ids_hashed_from_the_credential(tmp_path):
+ # The HTML report embeds finding and occurrence IDs. Passed through text
+ # redaction alone, it would keep the IDs hashed before the value was masked.
+ skill = _skill(tmp_path / "workspace")
+ echo = ValidationResult(validator_name="Code Risk", validator_description="Static analysis")
+ echoed = Finding(
+ "SECURITY",
+ Severity.HIGH,
+ "hardcoded-credential",
+ "Credential in source: " + _fixture_value(),
+ "source.py",
+ 1,
+ line_content='API_KEY = "' + _fixture_value() + '"',
+ )
+ echo.add_finding(echoed)
+ raw = tmp_path / "raw"
+ raw.mkdir()
+ (raw / "skillevaluator-tier1.json").write_text(
+ JSONReporter(include_timestamp=False).render_all([echo]), encoding="utf-8"
+ )
+ native = HTMLReporter(include_timestamp=False).render_all([echo])
+ assert echoed.finding_id in native and echoed.occurrence_id in native
+ (raw / "skillevaluator-tier1.html").write_text(native, encoding="utf-8")
+
+ sanitized = runner.sanitized_outputs(raw, runner.collect_sensitive_values(skill))
+
+ page = sanitized["skillevaluator-tier1.html"]
+ _assert_no_secret(page)
+ for raw_id in (echoed.finding_id, echoed.occurrence_id):
+ assert raw_id.encode() not in page
+ # The page carries the IDs of the redacted finding, as the JSON does.
+ redacted = json.loads(sanitized["skillevaluator-tier1.json"])["results"][0]["findings"][0]
+ assert redacted["finding_id"].encode() in page
+ assert redacted["occurrence_id"].encode() in page
+
+
+def _database_url_line() -> str:
+ # Synthetic driver-qualified URL; the PII collector does not name its password.
+ return 'DATABASE_URL = "postgresql+psycopg2://admin:' + "hunter" + '[email protected]/app"'
+
+
+def test_ids_are_refreshed_when_only_database_userinfo_is_masked(tmp_path, monkeypatch):
+ # The redactor masks database userinfo even when no token was collected.
+ # IDs hashed from the unmasked line would let a reader confirm a guess.
+ workspace, reports = tmp_path / "workspace", tmp_path / "reports"
+ skill = workspace / "skills" / "demo"
+ skill.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("---\nname: demo\ndescription: A sample formatting skill.\n---\n# Demo\n")
+ (skill / "config.py").write_text(_database_url_line() + "\n")
+ assert runner.collect_sensitive_values(skill) == set()
+ scan = ValidationResult(validator_name="SkillSpector", validator_description="Static analysis")
+ quoted = Finding(
+ "SECURITY",
+ Severity.HIGH,
+ "hardcoded-database-url",
+ "Database URL with credentials",
+ "config.py",
+ 1,
+ line_content=_database_url_line(),
+ )
+ scan.add_finding(quoted)
+ raw_report = JSONReporter(include_timestamp=False).render_all([scan])
+
+ def fake_cli(argv, **kwargs):
+ (Path(argv[argv.index("-o") + 1]) / "skillevaluator-tier1.json").write_text(raw_report)
+ return subprocess.CompletedProcess(argv, 1)
+
+ assert runner.run(workspace, reports, {"SKILL_PATHS": "skills", "GITHUB_ACTIONS": "true"}, execute=fake_cli) == 1
+ shared = (reports / "skill-001/skillevaluator-tier1.json").read_text(encoding="utf-8")
+ assert "admin:hunter" not in shared
+ assert quoted.occurrence_id not in shared
+ document = json.loads(shared)
+ assert "[REDACTED]@db.example.net" in document["results"][0]["findings"][0]["line_content"]
+ _assert_finding_ids_match_text(document)
+
+ # A retained report from an older run still quotes the URL with the IDs
+ # hashed from it; the publisher masks it and refreshes the IDs.
+ from ci import publish_reports
+
+ stale = json.loads(shared)
+ stale_finding = stale["results"][0]["findings"][0]
+ stale_finding["line_content"] = _database_url_line()
+ stale_finding["occurrence_id"] = quoted.occurrence_id
+ stale["finding_groups"][0]["occurrences"][0]["occurrence_id"] = quoted.occurrence_id
+ stale["finding_groups"][0]["occurrences"][0]["line_content"] = _database_url_line()
+ archive = io.BytesIO()
+ with zipfile.ZipFile(archive, "w") as zipped:
+ zipped.writestr("summary.json", (reports / "summary.json").read_text(encoding="utf-8"))
+ zipped.writestr("skill-001/skillevaluator-tier1.json", json.dumps(stale))
+ _summary, retained = publish_reports.read_artifact(archive.getvalue())
+ published = json.dumps(retained)
+ assert "admin:hunter" not in published
+ assert quoted.occurrence_id not in published
+ _assert_finding_ids_match_text(retained["skill-001"])
+
+
+def test_refreshing_ids_keeps_the_shape_of_reports_written_before_ids() -> None:
+ from skillevaluator.reporting.finding_summary import refresh_finding_identities
+
+ document = {
+ "results": [
+ {
+ "validator": "Code Risk",
+ "findings": [
+ {
+ "category": "SECURITY",
+ "severity": "high",
+ "check_name": "shell",
+ "message": "subprocess call with shell=True",
+ "file_path": "run.py",
+ "line_number": 3,
+ "line_content": None,
+ "suggestion": None,
+ "metadata": None,
+ }
+ ],
+ }
+ ]
+ }
+ before = json.loads(json.dumps(document))
+
+ refresh_finding_identities(document)
+
+ assert document == before
+
+
def test_interrupted_scan_never_copies_raw_output(tmp_path, capsys):
workspace, reports = tmp_path / "workspace", tmp_path / "reports"
_skill(workspace)
diff --git a/tests/reporting/test_mixed_execution_errors.py b/tests/reporting/test_mixed_execution_errors.py
index ed441833..f674c5d8 100644
--- a/tests/reporting/test_mixed_execution_errors.py
+++ b/tests/reporting/test_mixed_execution_errors.py
@@ -133,6 +133,22 @@ def test_tier2_cli_reports_preserve_analysis_errors_with_findings(tmp_path: Path
assert [finding["check_name"] for finding in result["findings"]] == (
[] if outcome == "errors_only" else ["duplicate"]
)
+ # Analysis errors count as issues beside any finding, so an errors-only run
+ # never reports zero issues.
+ assert payload["message_counts"]["independent_errors"] == int(failed_clusters > 0)
+ # The skipped catalog comparison is a workflow-scope note in every case. It
+ # stays a raw warning but records scope, not an issue without a finding.
+ assert any(warning.startswith("Workflow scope: ") for warning in result["legacy"]["warnings"])
+ assert payload["message_counts"]["independent_warnings"] == 0
+ markdown_lines = (reports / "skillevaluator-tier2.md").read_text(encoding="utf-8").splitlines()
+ finding_text = "1 unique finding (1 high) / 1 occurrence / 1 raw record"
+ assert [line for line in markdown_lines if line.startswith("| Total Issues |")] == [
+ {
+ "mixed": f"| Total Issues | {finding_text}; 1 error without a finding |",
+ "errors_only": "| Total Issues | 1 error without a finding |",
+ "finding_only": f"| Total Issues | {finding_text} |",
+ }[outcome]
+ ]
html = _VisibleHTMLText()
html.feed((reports / "skillevaluator-tier2.html").read_text(encoding="utf-8"))
@@ -155,8 +171,9 @@ def test_tier2_cli_reports_preserve_analysis_errors_with_findings(tmp_path: Path
assert f"{failed_clusters} of 2 content clusters" in text
assert "structured-output support" in text
duplicate_message = "Duplicate content found within SKILL.md:"
- # Markdown intentionally repeats the finding in its table and details.
- expected_findings = {"cli": 1, "html": 1, "markdown": 2}
+ # Markdown intentionally repeats the finding in its reconciliation table,
+ # its findings table, and its details.
+ expected_findings = {"cli": 1, "html": 1, "markdown": 3}
assert {name: text.count(duplicate_message) for name, text in outputs.items()} == {
name: count if outcome != "errors_only" else 0 for name, count in expected_findings.items()
}
@@ -179,3 +196,23 @@ def test_additional_errors_excludes_only_existing_finding_messages_without_mutat
assert additional_errors(result) == [diagnostic]
assert asdict(result) == before
+
+
[email protected]("prefixed", [False, True])
+def test_additional_warnings_excludes_only_existing_finding_messages_without_mutation(prefixed: bool) -> None:
+ from skillevaluator.reporting.base import additional_warnings
+
+ result = ValidationResult(validator_name="Code Risk")
+ result.add_finding(Finding("CODE", Severity.LOW, "style", "Prefer explicit encoding", "run.py", line_number=4))
+ diagnostic = "bandit not installed."
+ result.add_warning(diagnostic)
+ if prefixed:
+ merged = ValidationResult(validator_name="Code Risk")
+ merged.merge_with_prefix(result, "sample-skill")
+ result = merged
+ diagnostic = f"[sample-skill] {diagnostic}"
+ before = asdict(result)
+
+ assert len(result.warnings) == 2
+ assert additional_warnings(result) == [diagnostic]
+ assert asdict(result) == before
diff --git a/tests/reporting/test_report_redesign.py b/tests/reporting/test_report_redesign.py
index eb8f2307..cf9c2a5e 100644
--- a/tests/reporting/test_report_redesign.py
+++ b/tests/reporting/test_report_redesign.py
@@ -230,7 +230,8 @@ def test_executive_summary_states_one_verdict_reason_and_four_kpis() -> None:
"Quality",
]
assert "Minimum 70 to pass" in summary
- assert summary.count("A finding is one problem a check reports at one location") == 1
+ assert summary.count("A finding is one problem a check reports,") == 1
+ assert "each location is an occurrence" in summary
assert "<h3>Fix first</h3>" in summary
diff --git a/tests/reporting/test_reporters.py b/tests/reporting/test_reporters.py
index 777e792e..f144391e 100644
--- a/tests/reporting/test_reporters.py
+++ b/tests/reporting/test_reporters.py
@@ -594,6 +594,726 @@ class TestJSONReporter:
assert reporter.name == "json"
+def _repeated_finding_results() -> list[ValidationResult]:
+ """Same semantic finding across validators and concrete locations."""
+ results = [
+ ValidationResult(validator_name="SECURITY", validator_description="Security"),
+ ValidationResult(validator_name="CODE_RISK", validator_description="Code risk"),
+ ]
+ for result, line_number in ((results[0], 8), (results[0], 12), (results[1], 8)):
+ result.add_finding(
+ Finding(
+ category="SECURITY",
+ severity=Severity.HIGH,
+ check_name="unsafe-command",
+ message="Unsafe command execution",
+ file_path="scripts/run.py",
+ line_number=line_number,
+ suggestion="Use an argument vector.",
+ )
+ )
+ results[0].add_message("Scanned executable helpers")
+ return results
+
+
+def _exec_summary(html: str) -> str:
+ """Return the Tier 1 executive summary: verdict, KPIs and Fix first."""
+ return html.split('<section class="exec-summary', 1)[1].split("</section>", 1)[0]
+
+
+def _findings_kpi(html: str) -> tuple[str, str]:
+ """Return the Findings KPI value and its reconciliation detail line ("" when absent)."""
+ summary = _exec_summary(html)
+ value = re.search(r'<dt>Findings</dt>\s*<dd class="kpi-value"><strong>(\d+)</strong></dd>', summary)
+ assert value is not None
+ detail = re.search(r'<dd class="kpi-sub kpi-issue-detail">([^<]*)</dd>', summary)
+ return value.group(1), detail.group(1) if detail else ""
+
+
+def test_finding_identity_is_semantic_and_occurrence_identity_is_location_bound() -> None:
+ first = Finding(
+ category="SECURITY",
+ severity=Severity.HIGH,
+ check_name="unsafe-command",
+ message="Unsafe command execution",
+ file_path="scripts/run.py",
+ line_number=8,
+ suggestion="Use an argument vector.",
+ )
+ second = Finding(
+ category="security",
+ severity=Severity.MEDIUM,
+ check_name="unsafe-command",
+ message=" Unsafe command execution ",
+ file_path="scripts/run.py",
+ line_number=12,
+ suggestion="Use an argument vector.",
+ )
+
+ assert first.finding_id == second.finding_id
+ assert re.fullmatch(r"SEF-[0-9a-f]{20}", first.finding_id)
+ assert first.occurrence_id != second.occurrence_id
+ assert re.fullmatch(r"SEO-[0-9a-f]{20}", first.occurrence_id)
+ # IDs are part of the serialized finding and stable across processes.
+ assert first.to_dict()["finding_id"] == first.finding_id
+ assert first.to_dict()["occurrence_id"] == first.occurrence_id
+ assert first.finding_id == "SEF-cca71f6c36db0948f02b"
+
+
+def test_occurrence_identity_distinguishes_line_zero_from_no_line() -> None:
+ common = {
+ "category": "SECURITY",
+ "severity": Severity.HIGH,
+ "check_name": "unsafe-command",
+ "message": "Unsafe command execution",
+ "file_path": "scripts/run.py",
+ }
+
+ assert Finding(**common, line_number=0).occurrence_id != Finding(**common, line_number=None).occurrence_id
+
+
+def test_secret_finding_id_ignores_the_location_written_into_its_message() -> None:
+ from skillevaluator.tier1.plugin_checks import _attribute_scan_result
+ from skillevaluator.validators.secrets import SecretsValidator
+
+ def scan(file_path: str, line: int) -> ValidationResult:
+ result = ValidationResult(validator_name="Secrets Detection")
+ SecretsValidator()._process_findings(
+ [{"RuleID": "generic-api-key", "Description": "Generic API Key", "File": file_path, "StartLine": line}],
+ result,
+ )
+ return result
+
+ findings = [scan("scripts/run.py", line).findings[0] for line in (10, 11)]
+ # A folder run prefixes the skill name and a plugin scan the member
+ # directory to file_path; neither rewrites the message.
+ for line in (10, 11):
+ folder = ValidationResult(validator_name="Secrets Detection")
+ folder.merge_with_prefix(scan("scripts/run.py", line), "alpha")
+ member = scan("scripts/run.py", line)
+ _attribute_scan_result(member, "skills/alpha", Path("/view"), Path("/plugin"))
+ findings.extend([folder.findings[0], member.findings[0]])
+ assert {finding.file_path for finding in findings} == {
+ "scripts/run.py",
+ "[alpha] scripts/run.py",
+ "skills/alpha/scripts/run.py",
+ }
+
+ # The message still names the location; only the identity leaves it out.
+ assert findings[0].message == "Generic API Key in scripts/run.py:10 [generic-api-key]"
+ assert findings[-1].message == "Generic API Key in scripts/run.py:11 [generic-api-key]"
+ assert len({finding.finding_id for finding in findings}) == 1
+ assert len({finding.occurrence_id for finding in findings}) == 6
+ # The suggestion names the file, so a secret in another file is another finding.
+ other = scan("scripts/other.py", 10).findings[0]
+ assert "scripts/other.py" in other.suggestion
+ assert other.finding_id != findings[0].finding_id
+
+
+def test_secret_finding_id_ignores_a_windows_location_in_its_message() -> None:
+ from skillevaluator.validators.secrets import SecretsValidator
+
+ def scan(line: int) -> Finding:
+ result = ValidationResult(validator_name="Secrets Detection")
+ SecretsValidator()._process_findings(
+ [
+ {
+ "RuleID": "generic-api-key",
+ "Description": "Generic API Key",
+ "File": "scripts\\run.py",
+ "StartLine": line,
+ }
+ ],
+ result,
+ )
+ [finding] = result.findings
+ # On Windows, plugin member attribution writes file_path with "/"
+ # while the message keeps the path Gitleaks reported.
+ finding.file_path = "skills/alpha/scripts/run.py"
+ return finding
+
+ moved = [scan(line) for line in (10, 11)]
+
+ assert moved[0].message == "Generic API Key in scripts\\run.py:10 [generic-api-key]"
+ assert moved[0].finding_id == moved[1].finding_id
+ assert moved[0].occurrence_id != moved[1].occurrence_id
+ # A path that is not the finding's own location stays part of the identity.
+ other = Finding("SECRETS", Severity.HIGH, "generic-api-key", "Key in other\\run.py:10", "scripts/run.py", 10)
+ renamed = Finding("SECRETS", Severity.HIGH, "generic-api-key", "Key in other\\run.py:11", "scripts/run.py", 11)
+ assert other.finding_id != renamed.finding_id
+
+
+def test_repeated_pii_finding_id_survives_line_moves(tmp_path) -> None:
+ from skillevaluator.validators.security import SecurityValidator
+
+ def scan(name: str, padding: str, repeats: int) -> Finding:
+ skill = tmp_path / name
+ skill.mkdir()
+ body = "".join(f"See /Users/johndoe/notes{index}.\n" for index in range(repeats))
+ (skill / "SKILL.md").write_text(
+ "---\nname: demo\ndescription: A sample skill.\n---\n# Demo\n" + padding + body, encoding="utf-8"
+ )
+ result = SecurityValidator(use_llm=False).validate_pii_only(skill)
+ [finding] = [finding for finding in result.findings if "/Users/johndoe/" in finding.message]
+ return finding
+
+ repeated = scan("repeated", "", 2)
+ moved = scan("moved", "\n", 2)
+ single = scan("single", "", 1)
+
+ assert "2 occurrences (SKILL.md lines 6, 7)" in repeated.message
+ assert "2 occurrences (SKILL.md lines 7, 8)" in moved.message
+ assert repeated.finding_id == moved.finding_id == single.finding_id
+ assert repeated.occurrence_id != moved.occurrence_id
+
+
+def test_occurrence_identity_uses_forward_slashes() -> None:
+ common = {
+ "category": "SECURITY",
+ "severity": Severity.HIGH,
+ "check_name": "unsafe-command",
+ "message": "Unsafe command execution",
+ "line_number": 3,
+ }
+
+ windows = Finding(**common, file_path="scripts\\run.py")
+ posix = Finding(**common, file_path="scripts/run.py")
+
+ assert windows.occurrence_id == posix.occurrence_id
+
+
+def test_occurrences_with_and_without_a_line_number_sort_without_error() -> None:
+ from skillevaluator.reporting.finding_summary import summarize_findings
+
+ result = ValidationResult(validator_name="SECURITY", validator_description="Security")
+ for line_number in (None, 3):
+ result.add_finding(
+ Finding(
+ category="SECURITY",
+ severity=Severity.HIGH,
+ check_name="unsafe-command",
+ message="Unsafe command execution",
+ file_path="scripts/run.py",
+ line_number=line_number,
+ )
+ )
+
+ summary = summarize_findings([result])
+
+ assert summary["unique_findings"] == 1
+ assert summary["distinct_occurrences"] == 2
+ assert [item["line_number"] for item in summary["groups"][0]["occurrences"]] == [None, 3]
+ data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ assert data["finding_groups"][0]["occurrence_count"] == 2
+ assert "1 unique finding (1 high) / 2 occurrences" in MarkdownReporter().render_all([result])
+ assert _findings_kpi(HTMLReporter(include_timestamp=False).render_all([result]))[0] == "1"
+
+
+def _unsafe_command(severity: Severity, line_number: int) -> Finding:
+ return Finding(
+ category="SECURITY",
+ severity=severity,
+ check_name="unsafe-command",
+ message="Unsafe command execution",
+ file_path="scripts/run.py",
+ line_number=line_number,
+ suggestion="Use an argument vector.",
+ )
+
+
+def test_reconciled_finding_keeps_its_highest_severity_in_every_format() -> None:
+ # JSON merges per-result summaries; HTML and Markdown summarize all
+ # results at once. Both paths must keep the higher severity.
+ medium = ValidationResult(validator_name="SECURITY", validator_description="Security")
+ medium.add_finding(_unsafe_command(Severity.MEDIUM, 8))
+ high = ValidationResult(validator_name="CODE_RISK", validator_description="Code risk")
+ high.add_finding(_unsafe_command(Severity.HIGH, 8))
+ results = [medium, high]
+
+ data = json.loads(JSONReporter(include_timestamp=False).render_all(results))
+ html_data = _html_report_data(HTMLReporter(include_timestamp=False).render_all(results))
+ for document in (data, html_data):
+ assert [group["severity"] for group in document["finding_groups"]] == ["high"]
+ assert document["finding_counts"]["unique_by_severity"]["high"] == 1
+ assert document["finding_counts"]["unique_by_severity"]["medium"] == 0
+ assert "| Total Issues | 1 unique finding (1 high) / 1 occurrence / 2 raw records |" in (
+ MarkdownReporter().render_all(results)
+ )
+
+ # One validator reporting the finding as medium, then high, blocks as high.
+ single = ValidationResult(validator_name="SECURITY", validator_description="Security")
+ single.add_finding(_unsafe_command(Severity.MEDIUM, 8))
+ single.add_finding(_unsafe_command(Severity.HIGH, 12))
+ summary = _exec_summary(HTMLReporter(include_timestamp=False).render_all([single]))
+ assert re.search(r'Blocking critical \+ high</dt>\s*<dd class="kpi-value"><strong[^>]*>1</strong>', summary)
+
+
+def test_finding_reconciliation_contract_matches_json_markdown_and_html(monkeypatch) -> None:
+ results = _repeated_finding_results()
+
+ original_to_dict = Finding.to_dict
+ to_dict_calls = 0
+
+ def counting_to_dict(finding):
+ nonlocal to_dict_calls
+ to_dict_calls += 1
+ return original_to_dict(finding)
+
+ monkeypatch.setattr(Finding, "to_dict", counting_to_dict)
+
+ json_data = json.loads(JSONReporter(include_timestamp=False).render_all(results))
+ assert to_dict_calls == 3
+ markdown = MarkdownReporter(include_timestamp=False).render_all(results)
+ html = HTMLReporter(include_timestamp=False).render_all(results)
+ html_data = _html_report_data(html)
+
+ expected = {
+ "raw_occurrences": 3,
+ "distinct_occurrences": 2,
+ "unique_findings": 1,
+ "duplicates_removed": 1,
+ "occurrences_grouped": 1,
+ "raw_by_severity": {"critical": 0, "high": 3, "medium": 0, "low": 0, "info": 0},
+ "unique_by_severity": {"critical": 0, "high": 1, "medium": 0, "low": 0, "info": 0},
+ }
+ assert json_data["finding_counts"] == expected
+ assert html_data["finding_counts"] == expected
+ # Error strings that mirror findings are not counted again.
+ assert json_data["message_counts"] == {
+ "informational": 1,
+ "independent_errors": 0,
+ "independent_warnings": 0,
+ }
+ assert html_data["message_counts"] == json_data["message_counts"]
+ # Raw totals stay available for existing consumers.
+ assert json_data["total_errors"] == 3
+ assert [result["finding_counts"]["raw_occurrences"] for result in json_data["results"]] == [2, 1]
+
+ group = json_data["finding_groups"][0]
+ assert group["finding_id"].startswith("SEF-")
+ assert group["occurrence_count"] == 2
+ assert group["validators"] == ["CODE_RISK", "SECURITY"]
+ assert [item["line_number"] for item in group["occurrences"]] == [8, 12]
+ assert html_data["finding_groups"] == json_data["finding_groups"]
+ assert json_data["results"][0]["findings"][0]["finding_id"] == group["finding_id"]
+ assert json_data["results"][0]["findings"][0]["metadata"] is None
+ assert html_data["results"][0]["findings"][0]["finding_id"] == group["finding_id"]
+ assert html_data["summary"]["total_issues"] == 1
+ # A display entry that merges two lines keeps both occurrence IDs.
+ merged_entry = next(iter(html_data["skills"].values()))["validators"]["SECURITY"]["findings"][0]
+ assert merged_entry["occurrences"] == 2
+ assert "occurrence_id" not in merged_entry
+ assert sorted(merged_entry["occurrence_ids"]) == sorted(item["occurrence_id"] for item in group["occurrences"])
+
+ # The severity breakdown qualifies the unique count, so it is not raw.
+ assert "| Total Issues | 1 unique finding (1 high) / 2 occurrences / 3 raw records |" in markdown
+ assert "| Duplicate Occurrences Reconciled | 1 |" in markdown
+ assert "Messages (" not in markdown
+ assert f"| `{group['finding_id']}` | HIGH | Unsafe command execution | 2 |" in markdown
+ assert f"- Occurrence ID: `{group['occurrences'][0]['occurrence_id']}`" in markdown
+ # The HTML summary counts the way Markdown does: one unique high finding,
+ # with its occurrences and raw records beside it.
+ assert _findings_kpi(html) == ("1", "1 unique finding / 2 occurrences / 3 raw records / 1 duplicate reconciled")
+ summary = _exec_summary(html)
+ assert '<span class="sev-dot high" aria-hidden="true"></span>1 high</span>' in summary
+ assert re.search(r'Blocking critical \+ high</dt>\s*<dd class="kpi-value"><strong[^>]*>1</strong>', summary)
+ assert "1 critical or high finding in those checks" in summary
+ assert "each location is an occurrence" in summary
+ # Fix first lists one place; the second occurrence is under its check.
+ assert "The other findings are listed under their checks below." in summary
+ assert '<span class="issue-count-badge">1 finding</span>' in html
+
+
+def test_tier1_dashboard_reconciles_only_tier1_findings() -> None:
+ results = [*_repeated_finding_results(), _similarity_result(severity=Severity.HIGH)]
+
+ html = HTMLReporter(include_timestamp=False).render_all(results)
+ html_data = _html_report_data(html)
+
+ # The embedded summary covers every tier; the Tier 1 card and KPI cover Tier 1 only.
+ assert html_data["summary"]["total_issues"] == 2
+ assert html_data["finding_counts"]["raw_occurrences"] == 4
+ assert _findings_kpi(html) == ("1", "1 unique finding / 2 occurrences / 3 raw records / 1 duplicate reconciled")
+ tier_cards = html.split('class="tier-cards', 1)[1].split('<section class="exec-summary', 1)[0]
+ assert re.search(r"<strong>1</strong> finding</span>", tier_cards)
+ assert '<span class="tier-card-sev-pill high">1 high</span>' in tier_cards
+ assert re.search(r"<strong>1</strong> duplicate\(s\)</span>", tier_cards)
+ # The gate policy counts each tier's unique findings.
+ gate_policy = html.split('class="gate-policy"', 1)[1].split("</div>", 1)[0]
+ assert "0 critical · 2 high · 0 medium · 0 low" in gate_policy
+
+
+def test_tier1_dashboard_counts_only_tier1_errors_without_findings() -> None:
+ tier2 = _similarity_result(severity=Severity.HIGH)
+ tier2.add_error("Similarity provider request failed")
+ results = [*_repeated_finding_results(), tier2]
+
+ html = HTMLReporter(include_timestamp=False).render_all(results)
+
+ assert _findings_kpi(html) == ("1", "1 unique finding / 2 occurrences / 3 raw records / 1 duplicate reconciled")
+ assert "without a finding" not in _html_tab(html, "tier1")
+ assert _html_report_data(html)["summary"]["total_issues"] == 3
+
+
+def _gate_only_result() -> ValidationResult:
+ result = ValidationResult(validator_name="QUALITY", validator_description="Quality")
+ result.fail_gate("Quality score 42 is below the required minimum 70")
+ return result
+
+
+def _incomplete_scan_error_result() -> ValidationResult:
+ result = ValidationResult(validator_name="SECRETS", validator_description="Secrets")
+ result.add_error("gitleaks crashed before writing its report")
+ result.mark_scan_incomplete("gitleaks")
+ return result
+
+
+def _incomplete_scan_warning_result() -> ValidationResult:
+ result = ValidationResult(validator_name="CODE_RISK", validator_description="Code risk")
+ result.add_warning("bandit not installed.")
+ result.mark_scan_incomplete("bandit")
+ return result
+
+
+ ("build_result", "verdict", "expected_text", "expected_messages"),
+ [
+ (_gate_only_result, "fail", "1 error without a finding", (1, 0)),
+ (_incomplete_scan_error_result, "incomplete", "1 error without a finding", (1, 0)),
+ (_incomplete_scan_warning_result, "incomplete", "1 warning without a finding", (0, 1)),
+ ],
+ ids=["gate-only", "incomplete-scan-error", "incomplete-scan-warning"],
+)
+def test_issue_counts_include_errors_and_warnings_without_findings(
+ build_result, verdict: str, expected_text: str, expected_messages: tuple[int, int]
+) -> None:
+ # A failed gate or an incomplete scan without any finding is not zero issues.
+ results = [build_result()]
+
+ json_data = json.loads(JSONReporter(include_timestamp=False).render_all(results))
+ markdown = MarkdownReporter(include_timestamp=False).render_all(results)
+ html = HTMLReporter(include_timestamp=False).render_all(results)
+ html_data = _html_report_data(html)
+
+ independent_errors, independent_warnings = expected_messages
+ assert json_data["finding_counts"]["unique_findings"] == 0
+ assert json_data["message_counts"] == {
+ "informational": 0,
+ "independent_errors": independent_errors,
+ "independent_warnings": independent_warnings,
+ }
+ assert html_data["message_counts"] == json_data["message_counts"]
+ assert html_data["summary"]["total_issues"] == 1
+ assert f"| Total Issues | {expected_text} |" in markdown
+ summary = _exec_summary(html)
+ assert f'<span class="verdict-chip {"warn" if verdict == "incomplete" else verdict}">' in summary
+ assert _findings_kpi(html) == ("0", expected_text)
+ assert "None reported" in summary
+
+
+def test_issue_counts_put_errors_without_findings_after_unique_findings() -> None:
+ results = _repeated_finding_results()
+ results[0].fail_gate("Security policy requires a clean scan")
+
+ markdown = MarkdownReporter(include_timestamp=False).render_all(results)
+ html = HTMLReporter(include_timestamp=False).render_all(results)
+
+ assert (
+ "| Total Issues | 1 unique finding (1 high) / 2 occurrences / 3 raw records; 1 error without a finding |"
+ ) in markdown
+ assert _findings_kpi(html) == (
+ "1",
+ "1 unique finding / 2 occurrences / 3 raw records / 1 duplicate reconciled; 1 error without a finding",
+ )
+ assert _html_report_data(html)["summary"]["total_issues"] == 2
+
+
+def test_findings_kpi_has_no_detail_line_when_every_record_is_unique() -> None:
+ result = ValidationResult(validator_name="SECURITY", validator_description="Security")
+ for line_number, message in ((3, "Unsafe command execution"), (9, "Hard-coded token")):
+ result.add_finding(
+ Finding(
+ category="SECURITY",
+ severity=Severity.HIGH,
+ check_name="unsafe-command",
+ message=message,
+ file_path="scripts/run.py",
+ line_number=line_number,
+ )
+ )
+
+ html = HTMLReporter(include_timestamp=False).render_all([result])
+
+ assert _findings_kpi(html) == ("2", "")
+ assert '<span class="issue-count-badge">2 findings</span>' in html
+
+
+def test_workflow_scope_note_is_not_an_issue_without_a_finding() -> None:
+ from skillevaluator.tier_workflows import _record_scope
+
+ result = ValidationResult(validator_name="Schema Validation", validator_description="Schema")
+ result.add_success(check_name="schema", message="Frontmatter is valid")
+ _record_scope([result], 1, {"llm": {"status": "skipped", "reason": "LLM checks disabled by --no-llm."}})
+ assert result.warnings == ["Workflow scope: llm skipped. LLM checks disabled by --no-llm."]
+
+ html = HTMLReporter(include_timestamp=False).render_all([result])
+ assert _findings_kpi(html) == ("0", "")
+ assert _html_report_data(html)["summary"]["total_issues"] == 0
+ data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ assert data["message_counts"]["independent_warnings"] == 0
+ assert data["total_warnings"] == 1
+ assert "| Total Issues | 0 unique findings / 0 occurrences / 0 raw records |" in MarkdownReporter().render_all(
+ [result]
+ )
+
+
+def test_folded_pii_finding_counts_each_listed_location_as_an_occurrence(tmp_path) -> None:
+ from skillevaluator.reporting.finding_summary import refresh_finding_identities
+ from skillevaluator.validators.security import SecurityValidator
+
+ skill = tmp_path / "demo"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text(
+ "---\nname: demo\ndescription: A sample skill.\n---\n# Demo\n\n\n"
+ "See /Users/johndoe/a.\nSee /Users/johndoe/b.\n",
+ encoding="utf-8",
+ )
+ result = SecurityValidator(use_llm=False).validate_pii_only(skill)
+ result.validator_name = "PII Scan"
+ [finding] = [finding for finding in result.findings if "/Users/johndoe/" in finding.message]
+ assert finding.metadata["occurrence_count"] == 2
+
+ data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ [group] = [group for group in data["finding_groups"] if group["finding_id"] == finding.finding_id]
+ assert group["occurrence_count"] == 2
+ assert [(item["file_path"], item["line_number"]) for item in group["occurrences"]] == [
+ ("SKILL.md", 8),
+ ("SKILL.md", 9),
+ ]
+ assert finding.occurrence_id in {item["occurrence_id"] for item in group["occurrences"]}
+ counts = data["finding_counts"]
+ assert counts["distinct_occurrences"] == counts["raw_occurrences"] + 1
+ assert counts["duplicates_removed"] == 0
+ # Refreshing the IDs of an unredacted report changes nothing.
+ refreshed = copy.deepcopy(data)
+ refresh_finding_identities(refreshed)
+ assert refreshed == data
+
+ markdown = MarkdownReporter().render_all([result])
+ assert re.search(rf"\| `{finding.finding_id}` \| HIGH \| [^|]+ \| 2 \| PII Scan \|", markdown)
+ html = HTMLReporter(include_timestamp=False).render_all([result])
+ html_data = _html_report_data(html)
+ assert html_data["finding_counts"] == data["finding_counts"]
+ assert html_data["finding_groups"] == data["finding_groups"]
+ unique = counts["unique_findings"]
+ occurrences = counts["distinct_occurrences"]
+ assert f"/ {occurrences} occurrences /" in _findings_kpi(html)[1]
+ assert _findings_kpi(html)[0] == str(unique)
+
+
+def test_folded_pii_finding_in_a_folder_run_counts_each_location_once(tmp_path) -> None:
+ from skillevaluator.validators.security import SecurityValidator
+
+ for name, body in (("support", "Mail [email protected].\nAlso [email protected].\n"), ("other", "Nothing.\n")):
+ skill = tmp_path / name
+ skill.mkdir()
+ (skill / "SKILL.md").write_text(
+ f"---\nname: {name}\ndescription: A sample skill.\n---\n{body}",
+ encoding="utf-8",
+ )
+ original = ValidationResult(validator_name="PII Scan")
+ original.add_finding(
+ Finding(
+ category="PII",
+ severity=Severity.HIGH,
+ check_name="pii",
+ message="Folded",
+ file_path="SKILL.md",
+ line_number=5,
+ metadata={"occurrences": [{"file": "SKILL.md", "line": 5}, {"file": "SKILL.md", "line": 6}]},
+ )
+ )
+ ValidationResult(validator_name="PII Scan").merge_with_prefix(original, "support")
+ # Prefixing a merged copy leaves the original finding's metadata alone.
+ assert original.findings[0].metadata["occurrences"][0]["file"] == "SKILL.md"
+
+ result = SecurityValidator(use_llm=False).validate_pii_only(tmp_path)
+ result.validator_name = "PII Scan"
+ [finding] = [finding for finding in result.findings if "[email protected]" in finding.message]
+ assert finding.file_path == "[support] SKILL.md"
+ assert "2 occurrences" in finding.message
+
+ data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ [group] = [group for group in data["finding_groups"] if group["finding_id"] == finding.finding_id]
+ assert [(item["file_path"], item["line_number"]) for item in group["occurrences"]] == [
+ ("[support] SKILL.md", 5),
+ ("[support] SKILL.md", 6),
+ ]
+ assert group["occurrence_count"] == 2
+ assert finding.occurrence_id in {item["occurrence_id"] for item in group["occurrences"]}
+ assert data["finding_counts"]["distinct_occurrences"] == data["finding_counts"]["raw_occurrences"] + 1
+
+ markdown = MarkdownReporter().render_all([result])
+ assert re.search(rf"\| `{finding.finding_id}` \| HIGH \| [^|]+ \| 2 \| PII Scan \|", markdown)
+
+
+def test_finding_group_occurrences_do_not_copy_the_source_line() -> None:
+ result = ValidationResult(validator_name="Code Risk")
+ for line_number in (3, 9):
+ result.add_finding(
+ Finding(
+ category="SECURITY",
+ severity=Severity.MEDIUM,
+ check_name="shell",
+ message="subprocess call with shell=True",
+ file_path="run.py",
+ line_number=line_number,
+ line_content="subprocess.run(command, shell=True) # " + "x" * 200,
+ )
+ )
+
+ data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ html_data = _html_report_data(HTMLReporter(include_timestamp=False).render_all([result]))
+ [group] = data["finding_groups"]
+ assert html_data["finding_groups"] == data["finding_groups"]
+ # Each location keeps its identity; its source line is on the finding
+ # with the same occurrence_id, not repeated in the group.
+ assert [sorted(item) for item in group["occurrences"]] == [
+ ["file_path", "line_number", "occurrence_id", "validator"]
+ ] * 2
+ by_occurrence = {finding["occurrence_id"]: finding for finding in data["results"][0]["findings"]}
+ assert all(by_occurrence[item["occurrence_id"]]["line_content"] for item in group["occurrences"])
+ assert json.dumps(data).count("x" * 200) == 2
+
+
+def test_html_skill_entries_merge_only_occurrences_of_one_finding() -> None:
+ # Two checks with the same message and suggestion are two findings.
+ result = ValidationResult(validator_name="SECURITY", validator_description="Security")
+ for check_name, line_number in (("rule-a", 3), ("rule-b", 9)):
+ result.add_finding(
+ Finding(
+ category="SECURITY",
+ severity=Severity.HIGH,
+ check_name=check_name,
+ message="Unsafe command execution",
+ file_path="scripts/run.py",
+ line_number=line_number,
+ suggestion="Use an argument vector.",
+ )
+ )
+
+ data = _html_report_data(HTMLReporter(include_timestamp=False).render_all([result]))
+
+ group_of = {
+ item["occurrence_id"]: group["finding_id"] for group in data["finding_groups"] for item in group["occurrences"]
+ }
+ [skill] = data["skills"].values()
+ entries = [entry for validator in skill["validators"].values() for entry in validator["findings"]]
+ assert len(entries) == skill["finding_count"] == 2
+ for entry in entries:
+ assert entry["occurrence_ids"]
+ assert {group_of[occurrence_id] for occurrence_id in entry["occurrence_ids"]} == {entry["finding_id"]}
+
+
+def test_same_finding_in_several_skills_counts_once_with_one_occurrence_per_skill() -> None:
+ collection = ValidationResult(validator_name="SCHEMA", validator_description="Schema")
+ for skill in ("alpha", "beta", "gamma"):
+ per_skill = ValidationResult(validator_name="SCHEMA", validator_description="Schema")
+ per_skill.add_finding(
+ Finding("SCHEMA", Severity.HIGH, "missing-description", "Missing description field", "SKILL.md", 1)
+ )
+ collection.merge_with_prefix(per_skill, skill)
+ results = [collection]
+
+ json_data = json.loads(JSONReporter(include_timestamp=False).render_all(results))
+ markdown = MarkdownReporter(include_timestamp=False).render_all(results)
+ html = HTMLReporter(include_timestamp=False).render_all(results)
+
+ # Identical findings in different skills share one finding_id.
+ assert json_data["finding_counts"]["unique_findings"] == 1
+ assert json_data["finding_counts"]["distinct_occurrences"] == 3
+ assert [item["file_path"] for item in json_data["finding_groups"][0]["occurrences"]] == [
+ "[alpha] SKILL.md",
+ "[beta] SKILL.md",
+ "[gamma] SKILL.md",
+ ]
+ assert "| Total Issues | 1 unique finding (1 high) / 3 occurrences / 3 raw records |" in markdown
+ assert _findings_kpi(html) == ("1", "1 unique finding / 3 occurrences / 3 raw records")
+ # Each skill still has its own finding, and JSON skills[] keeps raw records.
+ assert html.count('<span class="issue-count-badge">1 finding</span>') == 3
+ assert sorted((skill["name"], skill["issue_count"]) for skill in json_data["skills"]) == [
+ ("alpha", 1),
+ ("beta", 1),
+ ("gamma", 1),
+ ]
+
+
+def test_markdown_reconciliation_table_lists_the_most_severe_findings_first() -> None:
+ result = ValidationResult(validator_name="SECURITY", validator_description="Security")
+ lows = [
+ Finding("SECURITY", Severity.LOW, "style", f"Low finding {index}", "SKILL.md", index + 1) for index in range(12)
+ ]
+ # Pick a critical finding that falls past the 10-row cap in finding_id order.
+ critical = next(
+ finding
+ for finding in (
+ Finding("SECURITY", Severity.CRITICAL, "secret", f"Hard-coded AWS key {index}", "config.py", 4)
+ for index in range(1000)
+ )
+ if sum(low.finding_id < finding.finding_id for low in lows) >= 10
+ )
+ for finding in [*lows, critical]:
+ result.add_finding(finding)
+ finding_ids = sorted(finding.finding_id for finding in result.findings)
+ assert finding_ids.index(critical.finding_id) >= 10
+
+ markdown = MarkdownReporter(include_timestamp=False).render_all([result])
+ json_data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+
+ table = markdown.split("## Finding Reconciliation", 1)[1].split("\n\n", 2)[1]
+ rows = [line for line in table.splitlines() if line.startswith("| `SEF-")]
+ assert len(rows) == 10
+ assert rows[0].startswith(f"| `{critical.finding_id}` | CRITICAL | {critical.message} |")
+ assert "*3 more unique findings*" in table
+ # Machine output stays ordered by finding_id.
+ assert [group["finding_id"] for group in json_data["finding_groups"]] == finding_ids
+
+
+def test_message_counts_leave_out_passed_check_lines() -> None:
+ result = ValidationResult(validator_name="SECURITY", validator_description="Security")
+ result.add_success("no-secrets", "No secrets found")
+ result.add_success("no-shell", "No shell commands")
+ result.add_message("Scanned 4 files")
+
+ json_data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+
+ assert json_data["message_counts"] == {"informational": 1, "independent_errors": 0, "independent_warnings": 0}
+
+
+def test_markdown_finding_reconciliation_escapes_untrusted_text() -> None:
+ result = ValidationResult(validator_name="SECURITY | @maintainers", validator_description="Security")
+ result.add_finding(
+ Finding(
+ category="SECURITY",
+ severity=Severity.HIGH,
+ check_name="unsafe-command",
+ message="bad | <img src=x onerror=alert(1)> [click](https://example.com) @maintainers",
+ file_path="scripts/run.py",
+ line_number=3,
+ )
+ )
+
+ markdown = MarkdownReporter(include_timestamp=False).render_all([result])
+
+ row = next(line for line in markdown.splitlines() if line.startswith(f"| `{result.findings[0].finding_id}`"))
+ assert len(row.strip("|").split("|")) == 5
+ assert "<img" not in row
+ assert "&lt;img" in row
+ assert "](" not in row
+ assert "@maintainers" not in row
+ assert "&#64;maintainers" in row
+
+
class TestSARIFReporter:
"""Tests for SARIFReporter."""
diff --git a/tests/validators/test_pii_grouping.py b/tests/validators/test_pii_grouping.py
index df17d08d..1460c259 100644
--- a/tests/validators/test_pii_grouping.py
+++ b/tests/validators/test_pii_grouping.py
@@ -114,3 +114,22 @@ class TestPiiGroupingByValue:
result = SecurityValidator().validate_pii_only(skill)
values = {f.metadata.get("matched_value") for f in _email_findings(result)}
assert values == {"[email protected]", "[email protected]"}
+
+
+def test_folder_run_counts_folded_locations_once(tmp_path):
+ from skillevaluator.models.result import ValidationResult
+ from skillevaluator.reporting.finding_summary import summarize_findings
+
+ skill = tmp_path / "support"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text(
+ "---\nname: support\ndescription: support helper\n---\nMail [email protected] now.\nCC [email protected] too.\n"
+ )
+ single = SecurityValidator(use_llm=False).validate_pii_only(skill)
+ parent = ValidationResult()
+ parent.merge_with_prefix(single, "support")
+
+ [finding] = [f for f in parent.findings if f.check_name == "emails"]
+ assert {item["file"] for item in finding.metadata["occurrences"]} == {finding.file_path}
+ summary = summarize_findings([parent])
+ assert summary["distinct_occurrences"] == summarize_findings([single])["distinct_occurrences"]