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.

fix(tier1): scope ownership email policy and retain completeness diagnostics (#333)

Christopher Kevin0434e81cb63b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 058f8048..5d6f270f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,14 @@ All notable changes to SkillEvaluator are documented in this file.
### Added
+- Classify explicit `SKILL.md` ownership contacts (`metadata.pic` and
+ `metadata.email`) as `PII.ownership_emails`, still HIGH by default. Add
+ `--policy` to `tier1` and `tier1 validate` so operators can permit reviewed
+ ownership metadata without allowing ordinary email occurrences.
+- Retain bounded SkillSpector completeness diagnostics in JSON reports and
+ show file/line, phase, and reason in incomplete-scan errors. Preserve details
+ across scan stages, folder aggregation, and policy application.
+
- Add an `error_handling` section to the `--quality-config` file for
Reliability's three error-handling rules: the `SKILL.md` mention check and
the `scripts` and `lib` code checks. Each sets `points`, `message`,
@@ -297,6 +305,11 @@ All notable changes to SkillEvaluator are documented in this file.
### Changed
+- A `PII.emails` severity override in `--policy` no longer applies to the
+ `metadata.pic` and `metadata.email` contacts in a skill's own `SKILL.md`. They
+ now report as `PII.ownership_emails`, HIGH by default, so a run that passed
+ through that override fails until the policy also sets `PII.ownership_emails`.
+
- Remove `skillevaluator.quality_config.quality_config_provenance(path, config)`.
Use `load_quality_config_with_provenance(path)` instead: it loads the config
and returns `(config, provenance)`, and its digest covers only the rules a
diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdx
index b32d798b..b596d683 100644
--- a/docs/cli-reference.mdx
+++ b/docs/cli-reference.mdx
@@ -153,6 +153,7 @@ errors, such as an option the workflow does not accept, exit `2`.
| `--quality-config PATH` | packaged `quality-default.yaml` | YAML file that adjusts the quality check's expected headings and error-handling rules; settings it omits keep their packaged values. See [Tier 1: Validation](tier1-validation.mdx#the-checks). |
| `--pii-waivers PATH` | none | Reviewed, expiring PII waivers applied by the `pii` check. See [PII waivers](tier1-validation.mdx#pii-waivers). |
| `--profile TEXT` | `SKILLEVALUATOR_PROFILE`, then `default` | Validation policy; `external` is a compatibility alias |
+| `--policy FILE` | none | Explicit policy overlay, including reviewed ownership-contact severity. See [Tier 1 policies](tier1-validation.mdx#validation-profiles-and-policies). |
| `--previous-version TEXT` | `SKILLEVALUATOR_PREVIOUS_VERSION`, else unset | Previous version for version checks |
| `--skillspector-baseline FILE` | unset | Audited SkillSpector suppression baseline; never discovered from the skill. See [Audited SkillSpector baselines](tier1-validation.mdx#audited-skillspector-baselines). |
diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx
index 3d104295..68d5b8a2 100644
--- a/docs/tier1-validation.mdx
+++ b/docs/tier1-validation.mdx
@@ -176,6 +176,37 @@ Precedence, highest to lowest: `--policy` overlay, `--profile` flag, `SKILLEVALU
`QUALITY.*: info` leaves a below-minimum quality score failing.
</Accordion>
+<Accordion title="Permit reviewed ownership contacts without allowing other email addresses">
+ Contacts in the single-line `metadata.pic` and `metadata.email` fields of
+ the skill's own `SKILL.md` (the one at the root of the scanned skill) use the
+ separate `PII.ownership_emails` check. Both that check and ordinary
+ `PII.emails` findings remain **HIGH and blocking by default**.
+
+ If your repository policy permits those ownership contacts, pass an explicit
+ policy file. The finding stays visible in the report as informational.
+
+ ```yaml title="ownership-policy.yaml"
+ severity_overrides:
+ PII.ownership_emails: info
+ ```
+
+ ```bash
+ skillevaluator tier1 ./skills/my-skill --no-llm --policy ./ownership-policy.yaml
+ ```
+
+ Supported values are one address or `Name <address>` in valid YAML. The same
+ address in body text, a people directory, another metadata field, or another
+ file (including a `SKILL.md` nested in a subdirectory) still uses the ordinary
+ email policy. Ambiguous YAML, aliases, and block scalars also retain that
+ policy. Credential checks remain blocking.
+
+ Keep this policy under repository-owner review; the scanner does not discover
+ or trust a policy from the skill automatically. Existing `PII.emails` overrides
+ apply to ordinary emails; use `PII.ownership_emails` explicitly for these contacts.
+ This option is available on `tier1`, `tier1 validate`, and `validate`. The
+ released reusable CI templates do not yet expose a custom-policy input.
+</Accordion>
+
<Note>
The active profile name is stamped into the HTML report header and JSON report, and printed in the run banner under `--verbose`, so reviewers can see which gate was applied.
</Note>
@@ -702,6 +733,26 @@ Tier 1 checks always gate the exit code inside `validate`. Tier 2 gates when it
## Troubleshooting
<AccordionGroup>
+ <Accordion title="Why is SkillSpector analysis incomplete?">
+ Open the security check's execution error in the CLI, HTML, or Markdown
+ report. It now shows up to three file/line locations with their scanner
+ phase and reason, for example:
+
+ ```text
+ SKILL.md:14 [reference_resolution; reference_missing]
+ ```
+
+ This means the scanner could not resolve or inspect a reference; it is not
+ itself proof of a vulnerability. Review the named source line and whether
+ the reference should be bundled. If the scanner mistook a version or API
+ name for a file, report that detection issue to SkillSpector.
+
+ For more detail, each JSON result's `skillspector_completeness.records`
+ retains the scan stage, up to 20 ledger exceptions, analyzer names, and up
+ to eight limitations. Omission counts make truncation explicit. Folder
+ reports retain the skill name with each record. These diagnostics never
+ turn an incomplete scan into a pass.
+ </Accordion>
<Accordion title="Gitleaks is not installed">
Install it with `brew install gitleaks` or download a binary from the official [Gitleaks releases](https://github.com/gitleaks/gitleaks/releases).
</Accordion>
diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.py
index c33c5eba..77c20884 100644
--- a/src/skillevaluator/cli.py
+++ b/src/skillevaluator/cli.py
@@ -3196,6 +3196,10 @@ def _workflow_report_options(func):
@click.option(
"--profile", default=None, help="Validation policy [default: default; external is a compatibility alias]."
)
+ "--policy", "policy_path", type=click.Path(exists=True, dir_okay=False, path_type=Path), default=None,
+ help="Custom policy YAML overlaid on top of --profile.",
+)
@click.option("--previous-version", default=None, help="Previous version for version checks.")
@click.option(
"--skillspector-baseline", type=SKILLSPECTOR_BASELINE_PATH, default=None, help=_SKILLSPECTOR_BASELINE_HELP
@@ -3210,6 +3214,7 @@ def _tier1_workflow(
quality_config: Path | None,
pii_waivers: Path | None,
profile: str | None,
+ policy_path: Path | None,
previous_version: str | None,
skillspector_baseline: Path | None,
report_formats: tuple[str, ...],
@@ -3220,7 +3225,7 @@ def _tier1_workflow(
from skillevaluator.validators.policy import resolve_policy
try:
- policy = resolve_policy(profile=profile)
+ policy = resolve_policy(profile=profile, policy_path=policy_path)
except (FileNotFoundError, ValueError) as exc:
raise click.ClickException(str(exc)) from exc
_offer_scanner_install(checks, skip)
diff --git a/src/skillevaluator/models/result.py b/src/skillevaluator/models/result.py
index d7c10539..881e1063 100644
--- a/src/skillevaluator/models/result.py
+++ b/src/skillevaluator/models/result.py
@@ -20,6 +20,8 @@ import hashlib
from dataclasses import dataclass, field
from enum import StrEnum
+from skillevaluator.skillspector_diagnostics import merge_completeness
+
class Severity(StrEnum):
"""Standardized severity levels for validation findings.
@@ -647,7 +649,12 @@ class ValidationResult:
incomplete = list(dict.fromkeys([*self.incomplete_scans, *other.incomplete_scans]))
gate_failures = [*self.gate_failures, *other.gate_failures]
scanners = {**self.scanners, **other.scanners}
+ completeness = merge_completeness(
+ self.metadata.get("skillspector_completeness"), other.metadata.get("skillspector_completeness")
+ )
self.metadata.update(other.metadata)
+ if completeness:
+ self.metadata["skillspector_completeness"] = completeness
if incomplete:
self.metadata["incomplete_scans"] = incomplete
if scanners:
@@ -667,6 +674,13 @@ class ValidationResult:
def merge_with_prefix(self, other: ValidationResult, prefix: str) -> None:
"""Merge another result, prefixing all errors/warnings with skill name."""
+ completeness = merge_completeness(
+ self.metadata.get("skillspector_completeness"),
+ other.metadata.get("skillspector_completeness"),
+ prefix=prefix,
+ )
+ if completeness:
+ self.metadata["skillspector_completeness"] = completeness
if not other.passed:
self.passed = False
diff --git a/src/skillevaluator/reporting/json_reporter.py b/src/skillevaluator/reporting/json_reporter.py
index 544079f5..bfd0adbc 100644
--- a/src/skillevaluator/reporting/json_reporter.py
+++ b/src/skillevaluator/reporting/json_reporter.py
@@ -41,6 +41,7 @@ from skillevaluator.reporting.finding_summary import (
summarize_messages,
)
from skillevaluator.reporting.run_status import Status, resolve_run_status, result_status
+from skillevaluator.skillspector_diagnostics import sanitize_completeness
from skillevaluator.skillspector_provenance import sanitize_skillspector_provenance_metadata
from skillevaluator.skillspector_reference_caveats import sanitize_reference_caveat_metadata
from skillevaluator.source_identity import recorded_evaluated_source
@@ -408,6 +409,9 @@ class JSONReporter(ReporterBase):
# Tier 1 SkillSpector LLM provenance (``--llm``), revalidated here so
# only the canonical record reaches the report.
data.update(sanitize_skillspector_provenance_metadata(result.metadata))
+ completeness = sanitize_completeness(result.metadata.get("skillspector_completeness"))
+ if completeness:
+ data["skillspector_completeness"] = completeness
if result.gate_failures:
data["gate_failures"] = result.gate_failures
diff --git a/src/skillevaluator/reporting/retained.py b/src/skillevaluator/reporting/retained.py
index 5de3a474..07cac2b2 100644
--- a/src/skillevaluator/reporting/retained.py
+++ b/src/skillevaluator/reporting/retained.py
@@ -19,6 +19,7 @@ from skillevaluator.reporting.base import is_cleanly_skipped, is_tier2_result, i
from skillevaluator.reporting.html import HTMLReporter
from skillevaluator.reporting.json_reporter import _tier1_scope_strings
from skillevaluator.reporting.run_status import resolve_run_status, result_status
+from skillevaluator.skillspector_diagnostics import sanitize_completeness
from skillevaluator.skillspector_provenance import sanitize_skillspector_provenance_metadata
from skillevaluator.skillspector_reference_caveats import sanitize_reference_caveat_metadata
@@ -252,6 +253,9 @@ def retained_results(
metadata["skillspector_version"] = _text(row["skillspector_version"], "skillspector_version")
# Revalidated like every report boundary; a non-canonical record is left out.
metadata.update(sanitize_skillspector_provenance_metadata(row))
+ completeness = sanitize_completeness(row.get("skillspector_completeness"))
+ if completeness:
+ metadata["skillspector_completeness"] = completeness
if "skillspector_reference_caveats" in row:
reference_caveats = sanitize_reference_caveat_metadata(row["skillspector_reference_caveats"])
_require(reference_caveats is not None, "Invalid skillspector_reference_caveats")
diff --git a/src/skillevaluator/skillspector_diagnostics.py b/src/skillevaluator/skillspector_diagnostics.py
new file mode 100644
index 00000000..1783cef6
--- /dev/null
+++ b/src/skillevaluator/skillspector_diagnostics.py
@@ -0,0 +1,92 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Bounded projections of scanner completeness evidence, never scan verdicts."""
+
+from __future__ import annotations
+
+import unicodedata
+
+_MAX_RECORDS = 64
+_MAX_ROWS = 20
+_MAX_LIMITATIONS = 8
+
+
+def _text(value: object) -> str:
+ # Result models use the merge helper during import-sensitive CLI paths.
+ # Loading utils at module scope would re-import the partially defined models.
+ from skillevaluator.utils.redaction import redact_printable_text
+
+ if not isinstance(value, str):
+ return "unknown"
+ safe = redact_printable_text(value, max_input_chars=4096, max_len=240)
+ return " ".join("".join(" " if unicodedata.category(c).startswith("C") else c for c in safe).split()) or "unknown"
+
+
+def _count(value: object) -> int:
+ return value if type(value) is int and 0 <= value <= 1_000_000_000 else 0
+
+
+def completeness_record(completeness: dict, stage: str) -> dict:
+ """Project only diagnostic fields; do not copy arbitrary scanner payloads."""
+ rows = completeness.get("ledger_exceptions")
+ rows = rows if isinstance(rows, list) else []
+ limits = completeness.get("limitations")
+ limits = limits if isinstance(limits, list) else []
+ exceptions = []
+ for row in rows[:_MAX_ROWS]:
+ if not isinstance(row, dict):
+ continue
+ item = {key: _text(row.get(key)) for key in ("path", "phase", "reason_code")}
+ for key in ("start_line", "end_line"):
+ if _count(row.get(key)):
+ item[key] = _count(row[key])
+ analyzers = row.get("analyzers")
+ if isinstance(analyzers, list):
+ item["analyzers"] = [_text(value) for value in analyzers[:8]]
+ item["omitted_analyzers"] = max(0, len(analyzers) - 8) + _count(row.get("omitted_analyzers"))
+ exceptions.append(item)
+ return {
+ "stage": stage if isinstance(stage, str) and stage in {"skillspector", "skillspector-llm"} else "unknown",
+ "reported_status": "partial",
+ "ledger_exceptions": exceptions,
+ "limitations": [_text(value) for value in limits[:_MAX_LIMITATIONS]],
+ "omitted_exceptions": max(0, len(rows) - _MAX_ROWS),
+ "omitted_limitations": max(0, len(limits) - _MAX_LIMITATIONS),
+ }
+
+
+def sanitize_completeness(value: object) -> dict:
+ """Re-project saved metadata at report boundaries and preserve omission counts."""
+ if not isinstance(value, dict) or not isinstance(value.get("records"), list):
+ return {}
+ records = []
+ for source in value["records"][:_MAX_RECORDS]:
+ if not isinstance(source, dict):
+ continue
+ record = completeness_record(source, source.get("stage"))
+ for key in ("omitted_exceptions", "omitted_limitations"):
+ record[key] += _count(source.get(key))
+ if "skill" in source:
+ record["skill"] = _text(source["skill"])
+ records.append(record)
+ return {
+ "records": records,
+ "omitted_records": _count(value.get("omitted_records")) + max(0, len(value["records"]) - _MAX_RECORDS),
+ }
+
+
+def merge_completeness(left: object, right: object, *, prefix: str | None = None) -> dict:
+ """Keep both scan stages and skill identities when result objects are merged."""
+ a, b = sanitize_completeness(left), sanitize_completeness(right)
+ if not a and not b:
+ return {}
+ incoming = b.get("records", [])
+ if prefix is not None:
+ incoming = [{**record, "skill": _text(prefix)} for record in incoming]
+ return sanitize_completeness(
+ {
+ "records": a.get("records", []) + incoming,
+ "omitted_records": a.get("omitted_records", 0) + b.get("omitted_records", 0),
+ }
+ )
diff --git a/src/skillevaluator/validators/pii_ownership.py b/src/skillevaluator/validators/pii_ownership.py
new file mode 100644
index 00000000..3d9ee98d
--- /dev/null
+++ b/src/skillevaluator/validators/pii_ownership.py
@@ -0,0 +1,71 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Locate explicit ownership contacts without granting them an exemption."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import yaml
+from yaml.events import AliasEvent
+from yaml.nodes import MappingNode, ScalarNode
+
+from skillevaluator.constants import SKILL_MANIFEST_VARIANTS
+from skillevaluator.utils.structured_data import StructuredDataError, load_bounded_yaml
+from skillevaluator.validators.frontmatter_parser import FRONTMATTER_PATTERN
+
+_EMAIL = r"[^<>@\s]+@[^<>@\s]+\.[A-Za-z]{2,}"
+_CONTACT = re.compile(rf"(?P<email>{_EMAIL})|[^<>\n]+ <(?P<named_email>{_EMAIL})>", re.ASCII)
+_FIELDS = frozenset({"pic", "email"})
+
+
+def ownership_email_spans(file_path: Path, content: str) -> dict[int, list[tuple[int, int]]]:
+ """Return source spans for single-line metadata.pic/email contact values.
+
+ Only literal, unambiguous YAML scalars qualify. Invalid or oversized YAML,
+ aliases, merged keys, block scalars and prose retain ordinary email policy.
+ Spans, rather than whole lines or values, keep adjacent fields independent.
+ """
+ if file_path.name not in SKILL_MANIFEST_VARIANTS:
+ return {}
+ match = FRONTMATTER_PATTERN.match(content)
+ if match is None or len(match[1]) > 65_536:
+ return {}
+ raw = match[1]
+ try:
+ load_bounded_yaml(raw)
+ if any(isinstance(event, AliasEvent) or getattr(event, "anchor", None) for event in yaml.parse(raw)):
+ return {}
+ root = yaml.compose(raw, Loader=yaml.SafeLoader)
+ except (StructuredDataError, yaml.YAMLError, RecursionError):
+ return {}
+ if not isinstance(root, MappingNode):
+ return {}
+ spans: dict[int, list[tuple[int, int]]] = {}
+ for key, metadata in root.value:
+ if not isinstance(key, ScalarNode) or key.value != "metadata" or not isinstance(metadata, MappingNode):
+ continue
+ for field, value in metadata.value:
+ if (
+ not isinstance(field, ScalarNode)
+ or field.value not in _FIELDS
+ or not isinstance(value, ScalarNode)
+ or value.tag != "tag:yaml.org,2002:str"
+ or value.style in {"|", ">"}
+ or value.start_mark.line != value.end_mark.line
+ or not _CONTACT.fullmatch(value.value)
+ ):
+ continue
+ # YAML source begins on file line 2. Escaped/multiline contacts
+ # remain ordinary PII unless the literal email is present here.
+ contact = _CONTACT.fullmatch(value.value)
+ assert contact is not None
+ source = raw[value.start_mark.index : value.end_mark.index]
+ email = contact["email"] or contact["named_email"]
+ offset = source.find(email)
+ if offset >= 0:
+ start = value.start_mark.column + offset
+ spans.setdefault(value.start_mark.line + 2, []).append((start, start + len(email)))
+ return spans
diff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.py
index 6e6f5d0b..ec88f3d0 100644
--- a/src/skillevaluator/validators/security.py
+++ b/src/skillevaluator/validators/security.py
@@ -56,6 +56,7 @@ from skillevaluator.provider_config import (
resolve_llm_provider,
skillspector_reasoning_effort,
)
+from skillevaluator.skillspector_diagnostics import completeness_record, merge_completeness
from skillevaluator.skillspector_provenance import SKILLSPECTOR_LLM_ANALYZERS, sanitize_skillspector_llm_provenance
from skillevaluator.skillspector_reference_caveats import reference_caveat_metadata
from skillevaluator.spdx import is_spdx_only_html_comment
@@ -75,6 +76,7 @@ from skillevaluator.validators.base import (
ValidatorBase,
iter_scannable_files,
)
+from skillevaluator.validators.pii_ownership import ownership_email_spans
from skillevaluator.validators.pii_waivers import PIIWaiverSet, configured_pii_categories, pii_evidence_sha256
from skillevaluator.validators.skillspector_scope import (
IssueScope,
@@ -3713,9 +3715,15 @@ class SecurityValidator(ValidatorBase):
for note in gap_notes:
result.add_warning(note)
else:
- result.add_error(
- _skillspector_incomplete_analysis_error(completeness_status, ledger_exceptions)
+ diagnostic = completeness_record(analysis_completeness, stage_name)
+ result.metadata["skillspector_completeness"] = merge_completeness(
+ result.metadata.get("skillspector_completeness"), {"records": [diagnostic]}
)
+ message = _skillspector_incomplete_analysis_error(completeness_status, ledger_exceptions)
+ if not ledger_exceptions and diagnostic["limitations"]:
+ # No incomplete file to name: the limitation is the only stated reason.
+ message = f"{message}. Limitation: {diagnostic['limitations'][0]}"
+ result.fail_gate(message)
result.mark_scan_incomplete(stage_name)
status = data.get("status")
@@ -5137,7 +5145,9 @@ class SecurityValidator(ValidatorBase):
relative_path = file_path.name
waive = waivers.matcher(file_path) if waivers is not None else None
- for finding_data in self._scan_file_for_pii(file_path, protected_usernames, waive=waive):
+ for finding_data in self._scan_file_for_pii(
+ file_path, protected_usernames, skill_root=skill_path, waive=waive
+ ):
pii_found = True
value = finding_data.get("matched_value")
key: object = (
@@ -5734,6 +5744,7 @@ class SecurityValidator(ValidatorBase):
self,
file_path: Path,
protected_usernames: set[str] | None = None,
+ skill_root: Path | None = None,
*,
waive: Callable[[str, int, str], bool] | None = None,
) -> list[dict]:
@@ -5744,6 +5755,10 @@ class SecurityValidator(ValidatorBase):
directory so the method stays usable standalone. ``waive`` returns
whether a PII waiver covers a candidate (category, line, value); a
waived candidate is skipped as if it did not match.
+
+ ``skill_root`` is the directory being scanned. Only the manifest sitting
+ directly in it may declare ownership contacts; a ``SKILL.md`` nested
+ deeper in the tree is ordinary content. It defaults to the file's parent.
"""
if protected_usernames is None:
protected_usernames = self._protected_home_usernames(file_path.parent)
@@ -5756,6 +5771,9 @@ class SecurityValidator(ValidatorBase):
lines = content.split("\n")
author_emails = self._frontmatter_author_emails(file_path, lines)
+ skill_root = file_path.parent if skill_root is None else skill_root
+ is_root_manifest = skill_root in (file_path.parent, file_path)
+ ownership_spans = ownership_email_spans(file_path, content) if is_root_manifest else {}
comment_lines = _comment_line_numbers(file_path, lines)
global_exceptions = self.pii_patterns.get("exceptions", {}).get("allowed_paths", [])
compiled = self._compile_pii_patterns(global_exceptions)
@@ -5773,6 +5791,7 @@ class SecurityValidator(ValidatorBase):
protected_usernames,
author_emails,
comment_lines,
+ ownership_spans,
waive=waive,
)
return findings
@@ -5830,6 +5849,7 @@ class SecurityValidator(ValidatorBase):
protected_usernames: set[str] | None = None,
author_emails: dict[int, str] | None = None,
comment_lines: frozenset[int] | None = None,
+ ownership_spans: dict[int, list[tuple[int, int]]] | None = None,
*,
waive: Callable[[str, int, str], bool] | None = None,
) -> None:
@@ -5843,6 +5863,7 @@ class SecurityValidator(ValidatorBase):
"""
protected_usernames = protected_usernames or set()
author_emails = author_emails or {}
+ ownership_spans = ownership_spans or {}
comment_lines = comment_lines if comment_lines is not None else _comment_line_numbers(file_path, lines)
line_exceptions = exceptions
excepted_card_digits: frozenset[str] = frozenset()
@@ -5859,7 +5880,11 @@ class SecurityValidator(ValidatorBase):
scan_line = line
if category == "emails" and (author_email := author_emails.get(line_num)):
- scan_line = re.sub(re.escape(author_email), "[email protected]", line, count=1, flags=re.IGNORECASE)
+ # Keep source offsets intact for adjacent ownership contacts in
+ # flow YAML; substituting a different-length address shifts them.
+ scan_line = re.sub(
+ re.escape(author_email), lambda match: " " * len(match.group()), line, count=1, flags=re.IGNORECASE
+ )
matches = list(regex.finditer(scan_line))
if excepted_card_digits:
@@ -5912,19 +5937,39 @@ class SecurityValidator(ValidatorBase):
if category == "gps_coordinates" and self._is_near_zero_gps(line):
confidence = "low"
- findings.append(
- {
+ # Preserve the first occurrence of each email class on a line.
+ # An ownership contact must not hide an ordinary address beside it.
+ candidates = [(category, match)]
+ if category == "emails":
+ classes = {}
+ for candidate in matches:
+ check = (
+ "ownership_emails"
+ if candidate.span() in ownership_spans.get(line_num, [])
+ else "emails"
+ )
+ classes.setdefault(check, candidate)
+ candidates = list(classes.items())
+ for check, candidate in candidates:
+ finding = {
"file": file_path.name,
"line": line_num,
"line_content": line,
"severity": pattern_def.get("severity", "medium"),
"description": pattern_def.get("description", category),
"suggestion": pattern_def.get("suggestion"),
- "category": category,
+ "category": check,
"confidence": confidence,
- "matched_value": self._reported_value(match),
+ "matched_value": self._reported_value(candidate),
}
- )
+ if check == "ownership_emails":
+ finding["description"] = "Ownership contact email in skill metadata"
+ finding["suggestion"] = (
+ "Review whether ownership contacts are permitted for this repository. "
+ "If approved, set PII.ownership_emails to info in an explicit --policy file; "
+ "otherwise remove the address or use a placeholder."
+ )
+ findings.append(finding)
@staticmethod
def _reported_value(match: re.Match) -> str:
diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.json
index 7d879ddb..587bda20 100644
--- a/tests/golden/cli_surface.json
+++ b/tests/golden/cli_surface.json
@@ -2249,6 +2249,14 @@
"param_type": "option",
"type": "text"
},
+ {
+ "name": "policy_path",
+ "opts": [
+ "--policy"
+ ],
+ "param_type": "option",
+ "type": "file"
+ },
{
"name": "previous_version",
"opts": [
@@ -2368,6 +2376,14 @@
"param_type": "option",
"type": "text"
},
+ {
+ "name": "policy_path",
+ "opts": [
+ "--policy"
+ ],
+ "param_type": "option",
+ "type": "file"
+ },
{
"name": "previous_version",
"opts": [
diff --git a/tests/validators/test_pii_ownership.py b/tests/validators/test_pii_ownership.py
new file mode 100644
index 00000000..7d870c7f
--- /dev/null
+++ b/tests/validators/test_pii_ownership.py
@@ -0,0 +1,189 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Ownership policy applies only to explicit contact metadata, never a domain."""
+
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from skillevaluator.cli import cli
+from skillevaluator.models.result import Severity
+from skillevaluator.validators.policy import ValidationPolicy, apply_policy
+from skillevaluator.validators.security import SecurityValidator
+
+ADDRESS = "[email protected]"
+POLICY = ValidationPolicy(severity_overrides={"PII.ownership_emails": Severity.INFO})
+
+
+def scan(tmp_path: Path, frontmatter: str, body: str = "", name: str = "SKILL.md"):
+ skill = tmp_path / "contact-skill"
+ skill.mkdir(exist_ok=True)
+ (skill / name).write_text(f"---\nname: contact-skill\n{frontmatter}\n---\n{body}\n", encoding="utf-8")
+ result = SecurityValidator(submitter_usernames=[]).validate_pii_only(skill)
+ return skill, result
+
+
[email protected]("field", ["pic", "email"])
[email protected]("value", [ADDRESS, f'"Maintainer <{ADDRESS}>"', f"'{ADDRESS}'"])
+def test_ownership_requires_explicit_policy_and_remains_visible(tmp_path, field, value):
+ _, result = scan(tmp_path, f"metadata:\n {field}: {value}")
+ assert not result.passed
+ assert [(f.check_name, f.severity) for f in result.findings] == [("ownership_emails", Severity.HIGH)]
+ apply_policy([result], POLICY)
+ assert result.passed
+ assert result.findings[0].severity == Severity.INFO
+ assert result.findings[0].metadata["matched_value"] == ADDRESS
+
+
+def test_same_address_in_body_and_metadata_stays_independently_blocking(tmp_path):
+ _, result = scan(tmp_path, f"metadata:\n pic: {ADDRESS}", f"Contact {ADDRESS} for access.")
+ apply_policy([result], POLICY)
+ assert not result.passed
+ assert {f.check_name for f in result.findings} == {"emails", "ownership_emails"}
+ assert all(f.metadata["occurrence_count"] == 1 for f in result.findings)
+
+
[email protected]("order", ["owner-first", "body-first"])
+def test_flow_metadata_does_not_hide_another_address_on_the_same_line(tmp_path, order):
+ fields = [f"pic: {ADDRESS}", f"description: {ADDRESS}"]
+ if order == "body-first":
+ fields.reverse()
+ _, result = scan(tmp_path, "metadata: {" + ", ".join(fields) + "}")
+ apply_policy([result], POLICY)
+ assert not result.passed
+ assert {f.check_name for f in result.findings} == {"emails", "ownership_emails"}
+
+
[email protected]("ordinary", [False, True])
+def test_author_exemption_preserves_adjacent_flow_contact_offsets(tmp_path, author, ordinary):
+ extra = f", description: {ADDRESS}" if ordinary else ""
+ _, result = scan(
+ tmp_path,
+ f'metadata: {{\n author: "Author <{author}>", pic: {ADDRESS}{extra}}}',
+ )
+ apply_policy([result], POLICY)
+ assert result.passed is not ordinary
+ expected = {"ownership_emails", "emails"} if ordinary else {"ownership_emails"}
+ assert {f.check_name for f in result.findings} == expected
+ assert all(f.metadata["matched_value"] == ADDRESS for f in result.findings)
+
+
+ "frontmatter",
+ [
+ f"pic: {ADDRESS}",
+ f"metadata:\n description: {ADDRESS}",
+ f"metadata:\n nested:\n pic: {ADDRESS}",
+ f"metadata:\n pic: Contact {ADDRESS} for support",
+ f"metadata:\n pic: 'Maintainer <{ADDRESS}'",
+ f"metadata:\n pic: '{ADDRESS}>'",
+ f"metadata:\n pic: |\n {ADDRESS}",
+ f"metadata:\n pic: {ADDRESS}\n pic: [email protected]",
+ f"metadata: [\n pic: {ADDRESS}",
+ f"original: &owner {ADDRESS}\nmetadata:\n pic: *owner",
+ f"original: &owner {{pic: {ADDRESS}}}\nmetadata:\n <<: *owner",
+ f"metadata:\n pic: {ADDRESS}\nlarge: " + "x" * 65_536,
+ ],
+)
+def test_ambiguous_or_unrecognized_metadata_retains_ordinary_email_policy(tmp_path, frontmatter):
+ _, result = scan(tmp_path, frontmatter)
+ apply_policy([result], POLICY)
+ assert not result.passed
+ assert {f.check_name for f in result.findings} == {"emails"}
+
+
+def test_other_markdown_files_cannot_claim_skill_ownership_metadata(tmp_path):
+ _, result = scan(tmp_path, f"metadata:\n pic: {ADDRESS}", name="contacts.md")
+ assert {f.check_name for f in result.findings} == {"emails"}
+
+
[email protected]("name", ["SKILL.md", "skill.md"])
[email protected]("nested", ["references", "references/vendored/deep", "scripts"])
+def test_nested_skill_manifest_cannot_claim_ownership_metadata(tmp_path, nested, name):
+ skill, _ = scan(tmp_path, "description: Plain skill")
+ folder = skill / nested
+ folder.mkdir(parents=True)
+ (folder / name).write_text(
+ f"---\nname: vendored\nmetadata:\n pic: {ADDRESS}\n---\nVendored notes.\n", encoding="utf-8"
+ )
+ result = SecurityValidator(submitter_usernames=[]).validate_pii_only(skill)
+ apply_policy([result], POLICY)
+ assert not result.passed
+ assert [(f.check_name, f.severity) for f in result.findings] == [("emails", Severity.HIGH)]
+ assert result.findings[0].metadata["occurrences"] == [{"file": f"{nested}/{name}", "line": 4}]
+
+
+def test_root_ownership_does_not_cover_nested_manifest_contacts(tmp_path):
+ skill, _ = scan(tmp_path, f"metadata:\n pic: {ADDRESS}")
+ (skill / "references").mkdir()
+ (skill / "references" / "SKILL.md").write_text(
+ f"---\nname: vendored\nmetadata:\n pic: {ADDRESS}\n email: [email protected]\n---\n", encoding="utf-8"
+ )
+ result = SecurityValidator(submitter_usernames=[]).validate_pii_only(skill)
+ apply_policy([result], POLICY)
+ assert not result.passed
+ by_check = {(f.check_name, f.metadata["matched_value"]): f.severity for f in result.findings}
+ assert by_check == {
+ ("ownership_emails", ADDRESS): Severity.INFO,
+ ("emails", ADDRESS): Severity.HIGH,
+ ("emails", "[email protected]"): Severity.HIGH,
+ }
+
+
+def test_nested_manifest_is_not_exempt_when_scanning_a_skill_collection(tmp_path):
+ collection = tmp_path / "skills"
+ skill = collection / "contact-skill"
+ (skill / "references").mkdir(parents=True)
+ (skill / "SKILL.md").write_text("---\nname: contact-skill\ndescription: Plain skill\n---\n", encoding="utf-8")
+ (skill / "references" / "SKILL.md").write_text(
+ f"---\nname: vendored\nmetadata:\n pic: {ADDRESS}\n---\n", encoding="utf-8"
+ )
+ result = SecurityValidator(submitter_usernames=[]).validate_pii_only(collection)
+ apply_policy([result], POLICY)
+ assert not result.passed
+ assert any(f.check_name == "emails" and f.severity == Severity.HIGH for f in result.findings)
+
+
+def test_credentials_in_the_same_skill_still_block(tmp_path):
+ _, result = scan(tmp_path, f"metadata:\n pic: {ADDRESS}", 'password = "sample-sensitive-value"')
+ apply_policy([result], POLICY)
+ assert not result.passed
+ assert any(f.category == "PII" and f.check_name != "ownership_emails" for f in result.findings)
+
+
[email protected]("subcommand", [[], ["validate"]])
+def test_tier1_policy_option_controls_real_pii_scan(tmp_path, subcommand):
+ skill, _ = scan(tmp_path, f"metadata:\n pic: {ADDRESS}")
+ policy = tmp_path / "policy.yaml"
+ policy.write_text("severity_overrides:\n PII.ownership_emails: info\n", encoding="utf-8")
+ args = [
+ "tier1",
+ *subcommand,
+ str(skill),
+ "--checks",
+ "pii",
+ "--no-llm",
+ "-r",
+ "json,html,markdown",
+ "-o",
+ str(tmp_path / "reports"),
+ ]
+ runner = CliRunner()
+ assert runner.invoke(cli, args).exit_code == 1
+ approved = runner.invoke(cli, [*args, "--policy", str(policy)])
+ assert approved.exit_code == 0, approved.output
+ import json
+
+ report = json.loads((tmp_path / "reports" / "skillevaluator-tier1.json").read_text())
+ assert report["overall_passed"]
+ findings = [f for result in report["results"] for f in result["findings"]]
+ assert any(f["check_name"] == "ownership_emails" and f["severity"] == "info" for f in findings)
+
+
+def test_tier1_rejects_missing_policy_before_scanning(tmp_path):
+ skill, _ = scan(tmp_path, f"metadata:\n pic: {ADDRESS}")
+ result = CliRunner().invoke(cli, ["tier1", str(skill), "--policy", str(tmp_path / "missing.yaml")])
+ assert result.exit_code == 2
diff --git a/tests/validators/test_skillspector_diagnostics.py b/tests/validators/test_skillspector_diagnostics.py
new file mode 100644
index 00000000..99295d9f
--- /dev/null
+++ b/tests/validators/test_skillspector_diagnostics.py
@@ -0,0 +1,171 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Completeness evidence survives validation, merging, and report rendering."""
+
+import json
+from pathlib import Path
+
+import pytest
+from rich.text import Text
+
+from skillevaluator.models.result import Finding, Severity, ValidationResult
+from skillevaluator.reporting import CLIReporter, HTMLReporter, JSONReporter, MarkdownReporter
+from skillevaluator.reporting.retained import retained_results
+from skillevaluator.skillspector_diagnostics import (
+ completeness_record,
+ merge_completeness,
+ sanitize_completeness,
+)
+from skillevaluator.validators.policy import apply_policy, default_policy, load_policy_file
+from skillevaluator.validators.security import SecurityValidator
+
+
+def partial_result() -> ValidationResult:
+ payload = json.loads((Path(__file__).parents[1] / "fixtures" / "skillspector-2.13.3-safe-no-llm.json").read_text())
+ payload["risk_assessment"]["recommendation"] = "CAUTION"
+ payload["analysis_completeness"].update(
+ is_complete=False,
+ status="partial",
+ ledger_exceptions=[
+ {
+ "fatal": False,
+ "path": "SKILL.md",
+ "start_line": 8,
+ "phase": "reference_resolution",
+ "reason_code": "reference_missing",
+ "analyzers": [],
+ }
+ ],
+ )
+ result = ValidationResult(validator_name="Security Scan")
+ assert SecurityValidator._validate_skillspector_report(payload, 0, False, "skillspector", result)
+ return result
+
+
[email protected]("terminal", ["dumb", "xterm-256color"])
+def test_partial_evidence_is_retained_without_turning_it_into_a_pass(monkeypatch, terminal):
+ monkeypatch.setenv("TERM", terminal)
+ monkeypatch.delenv("NO_COLOR", raising=False)
+ result = partial_result()
+ apply_policy([result], default_policy())
+ assert result.status == "incomplete"
+ assert not result.passed
+ assert result.findings == [] # Coverage diagnostics are not security defects.
+ for reporter in (CLIReporter(), HTMLReporter(), MarkdownReporter(), JSONReporter()):
+ output = reporter.render(result)
+ if isinstance(reporter, CLIReporter):
+ output = Text.from_ansi(output).plain
+ assert "reference_missing" in output
+ assert "SKILL.md:8" in output
+ data = json.loads(JSONReporter().render(result))
+ row = data["skillspector_completeness"]["records"][0]["ledger_exceptions"][0]
+ assert row["path"] == "SKILL.md"
+ assert row["start_line"] == 8
+ assert row["phase"] == "reference_resolution"
+
+
+def test_merge_preserves_both_stages_and_skill_identity():
+ static, llm = partial_result(), partial_result()
+ llm.metadata["skillspector_completeness"]["records"][0]["stage"] = "skillspector-llm"
+ static.merge(llm)
+ folder = ValidationResult()
+ folder.merge_with_prefix(static, "contact-skill")
+ records = json.loads(JSONReporter().render(folder))["skillspector_completeness"]["records"]
+ assert [record["stage"] for record in records] == ["skillspector", "skillspector-llm"]
+ assert {record["skill"] for record in records} == {"contact-skill"}
+ assert folder.is_incomplete
+
+
+def test_policy_recalculation_keeps_completeness_error_and_retained_report_evidence(tmp_path):
+ result = partial_result()
+ result.add_structured_finding(
+ Finding(
+ category="PII",
+ check_name="ownership_emails",
+ severity=Severity.HIGH,
+ message="contact",
+ file_path="SKILL.md",
+ )
+ )
+ policy_path = tmp_path / "policy.yaml"
+ policy_path.write_text("severity_overrides:\n PII.ownership_emails: info\n")
+ apply_policy([result], load_policy_file(policy_path))
+ assert result.status == "incomplete"
+ assert any("reference_missing" in error for error in result.errors)
+ retained = retained_results(json.loads(JSONReporter().render_all([result])))[0]
+ assert retained.metadata["skillspector_completeness"] == result.metadata["skillspector_completeness"]
+ assert "reference_missing" in HTMLReporter().render(retained)
+
+
+def test_diagnostic_text_and_lists_are_bounded_redacted_and_idempotent():
+ secret = "ghp_" + "a" * 36
+ raw = {
+ "ledger_exceptions": [
+ {
+ "path": f"references/{secret}/file.md\n\x1b[31mextra",
+ "phase": "static",
+ "reason_code": "opaque_content",
+ "analyzers": ["analyzer"] * 12,
+ "start_line": True,
+ "unexpected": "must not persist",
+ }
+ ]
+ * 25,
+ "limitations": ["password=fictional-password " + "x" * 800] * 10,
+ }
+ record = completeness_record(raw, "skillspector")
+ assert record["omitted_exceptions"] == 5
+ assert record["omitted_limitations"] == 2
+ assert record["ledger_exceptions"][0]["omitted_analyzers"] == 4
+ assert "start_line" not in record["ledger_exceptions"][0]
+ encoded = json.dumps(record)
+ assert secret not in encoded and "fictional-password" not in encoded
+ assert "must not persist" not in encoded and "\\u001b" not in encoded and "\\n" not in encoded
+ wrapped = {"records": [record], "omitted_records": 0}
+ assert sanitize_completeness(wrapped) == wrapped
+ merged = merge_completeness(wrapped, {"records": [record] * 70})
+ assert len(merged["records"]) == 64
+ assert merged["omitted_records"] == 7
+ assert sanitize_completeness(merged) == merged
+
+
+def test_saved_diagnostic_metadata_is_revalidated_at_json_boundary():
+ result = partial_result()
+ record = result.metadata["skillspector_completeness"]["records"][0]
+ record["unexpected_secret"] = "not part of contract"
+ record["ledger_exceptions"][0]["path"] = "password=fictional-password"
+ output = JSONReporter().render(result)
+ assert "fictional-password" not in output
+ assert "unexpected_secret" not in output
+
+
[email protected]("stage", [[], {}, None, True, 3, "unsupported"])
+def test_malformed_saved_stage_cannot_crash_json_or_retained_reports(stage):
+ result = partial_result()
+ result.metadata["skillspector_completeness"]["records"][0]["stage"] = stage
+ data = json.loads(JSONReporter().render_all([result]))
+ assert data["results"][0]["skillspector_completeness"]["records"][0]["stage"] == "unknown"
+ # Exercise the independent retained-report input boundary as well.
+ data["results"][0]["skillspector_completeness"]["records"][0]["stage"] = stage
+ retained = retained_results(data)[0]
+ assert retained.is_incomplete
+ assert retained.metadata["skillspector_completeness"]["records"][0]["stage"] == "unknown"
+ assert "reference_missing" in HTMLReporter().render(retained)
+
+
+def test_limitation_only_partial_report_keeps_its_reason_in_the_error():
+ payload = json.loads((Path(__file__).parents[1] / "fixtures" / "skillspector-2.13.3-safe-no-llm.json").read_text())
+ payload["risk_assessment"]["recommendation"] = "CAUTION"
+ payload["analysis_completeness"].update(
+ is_complete=False,
+ status="partial",
+ ledger_exceptions=[],
+ limitations=["Binary assets were not inspected"],
+ )
+ result = ValidationResult(validator_name="Security Scan")
+
+ SecurityValidator._validate_skillspector_report(payload, 0, False, "skillspector", result)
+
+ assert result.status == "incomplete"
+ assert any("Limitation: Binary assets were not inspected" in error for error in result.errors)