Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat(pii): add evidence-bound PII waivers and skip Proton profile paths (#307)
Narendran Raghavan27645cd01fa5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ebcd2e63..5bba55bd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -229,6 +229,21 @@ All notable changes to SkillEvaluator are documented in this file.`tier1` leaves a check out and reports it as skipped. A `scanners` row and theJSON report record which scanner versions ran.+- `--pii-waivers PATH` on `validate`, `tier1`, and `pii-scan` accepts a+ reviewed PII value without relaxing the whole check through a severity+ override. Each waiver names the PII check, the file (relative to the waiver+ file's directory), the line, the SHA-256 digest that PII findings now report+ as `evidence_sha256`, a reason, an owner, and a `created`/`expires` window+ of at most 366 days, and it stops applying as soon as any of them no longer+ matches. Other values on the same line are still reported. Reports list each+ waiver for a scanned file as applied (INFO), stale (LOW), or expired+ (MEDIUM), so one file can serve single-skill, folder, and catalog runs. A+ malformed file is rejected with exit code 2; through the Python API it+ applies no waivers and fails the PII scan with a HIGH+ `invalid-pii-waiver-file` finding. Credential checks cannot be waived, and+ their findings, like any finding whose value reports mask, carry no digest.+ Waivers are never discovered automatically inside the scanned skill; pass+ the file with `--pii-waivers`.- 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@@ -1166,6 +1181,18 @@ All notable changes to SkillEvaluator are documented in this file.`skillspector_applicability` block. `security-scan` and targets of `unknown`type keep the unrestricted scan.+- PII scans no longer report Proton (Steam Play) prefix paths such as+ `compatdata/<appid>/pfx/drive_c/users/steamuser/` as personal macOS paths:+ `steamuser` is the profile name Proton uses for every player. Other user+ names, `steamuser` outside a `pfx/drive_c` prefix, profile paths followed by+ a `..` segment later on the line, and Windows `C:\Users\steamuser` paths are+ still reported. When a Proton path and a personal path share a line, the+ personal path is reported.++- An unrelated `/home/<user>/` path no longer hides a personal home path later+ on the same line; the PII scan drops such paths before it picks the line's+ first match.+### Security- Linux local mode now launches Bubblewrap by the absolute path that passed itsdiff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex d4e4b9e3..651b60c6 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -133,6 +133,7 @@ errors, such as an option the workflow does not accept, exit `2`.| `--llm / --no-llm` | Enabled when a provider is configured | Enable or skip rubric, LLM security, and finding verification; explicit `--llm` requires valid provider configuration || `--min-score INTEGER` | `70` | Minimum passing quality and rubric score, from 0 to 100; quality severity overrides cannot waive the minimum || `--quality-config PATH` | packaged `quality-default.yaml` | YAML file that replaces the quality check's expected-heading rules. 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 || `--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). |@@ -249,6 +250,7 @@ Static checks; LLM-free by default. Tier 1 gates the exit code and always runs.| `--skillspector-baseline FILE` | unset | Audited SkillSpector suppression baseline for the `security` check; never discovered from the skill. See [Audited SkillSpector baselines](tier1-validation.mdx#audited-skillspector-baselines). || `--min-score INTEGER` | `70` | Minimum quality score (0–100) required per skill when the `quality` check runs; policy severity overrides cannot waive this gate. || `--quality-config PATH` | packaged `quality-default.yaml` | YAML file that replaces the quality check's expected-heading rules. See [Tier 1: Validation](tier1-validation.mdx#the-checks). |+| `--pii-waivers PATH` | none | Reviewed, expiring PII waivers applied by the `pii` check; forwarded to each skill of a catalog run. See [PII waivers](tier1-validation.mdx#pii-waivers). |### Tier 2 · Deduplication@@ -361,6 +363,7 @@ skillevaluator pii-scan ./my-skill| Flag | Default | Effect || --- | --- | --- || `--llm-verify` | off | Use LLM verification to reduce false positives. |+| `--pii-waivers PATH` | none | Apply reviewed, expiring PII waivers from this YAML file. See [PII waivers](tier1-validation.mdx#pii-waivers). |Plus the standard report options.diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdxindex b3d255b8..3d35ab7d 100644--- a/docs/tier1-validation.mdx+++ b/docs/tier1-validation.mdx@@ -252,8 +252,12 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `liceCommon placeholders such as `YOUR_API_KEY_HERE`, `example`, `test`, `dummy`, and `placeholder`, along with `@example.com` and `@test.com`, are excluded, as are configured allowed paths.+ Proton (Steam Play) game prefixes are not personal paths: `pfx/drive_c/users/steamuser/` is the same fixed Windows profile for every player. Other user names, the same profile outside a `pfx/drive_c` prefix (for example `~/.wine/drive_c/users/steamuser/` or `/Users/steamuser/`), and a profile path followed by a `..` segment anywhere later on its line are still reported, as is any other personal path on the same line.+A card-shaped number is reported only when it passes the Luhn checksum; all-zero numbers do not. Digits inside a canonical GUID/UUID, such as the COM interface ID `{00000000-0000-0000-C000-000000000046}`, are treated as an identifier unless a payment label (`card_number`, `credit_card`, `cc_no`, `cc_number`, `pan`, and similar) directly precedes the GUID on its line or ends the line before it. Every card-shaped number on a line is checked, so an identifier or non-card number earlier on the line does not hide a card after it.+ To accept a specific reviewed value, use a [PII waiver](#pii-waivers) rather than a `PII.*` severity override, which would relax every finding of that check.+The home-path check compares detected user paths against the submitter's identity. When no identity is available, that check is skipped and logged — set `SKILLEVALUATOR_SUBMITTER` (or add `author` to `SKILL.md`) to enable it. `SKILLEVALUATOR_SUBMITTER` is combined with `GITHUB_ACTOR`, `USER`, `LOGNAME`, `USERNAME`, the OS login name, and the skill's declared author — every identity that resolves is protected.</Accordion>@@ -436,6 +440,46 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice</Accordion></AccordionGroup>+## PII waivers++A PII waiver accepts one reviewed value at one place, for example a public support address that a skill must document. Pass the waiver file with `--pii-waivers PATH` on `validate`, `tier1`, or `pii-scan`. Waivers are never discovered automatically inside the scanned skill, so a skill cannot waive its own findings. Keep it outside the skill: a waiver file inside the scanned tree ships with the skill and is PII-scanned like any other file, owners and reasons included.++```yaml title="pii-waivers.yaml"+version: 1+waivers:+ - id: PII-001+ category: emails+ file: skills/support/SKILL.md+ line: 12+ evidence_sha256: 3f1d… # 64 hex characters, copied from the PII finding+ reason: Public support address of the documented service+ owner: docs-team+ created: 2026-10-01+ expires: 2027-01-01+```++```bash title="Apply reviewed waivers"+skillevaluator validate ./skills/support --pii-waivers ./pii-waivers.yaml+```++- `category` is the PII check name (`emails`, `personal_paths`, `phone_numbers`, and so on) and `line` is the line of the value. Credential checks (`database_credentials`, `hardcoded_secrets`, `jwt_tokens`, `github_tokens`, `aws_identifiers`, `webhook_urls`, `private_keys`) cannot be waived: remove or rotate the credential instead.+- `file` is relative to the directory that holds the waiver file (the directory of the link, when the waiver file is a symlink), so one file covers single-skill, folder, and catalog runs. Absolute paths, `..`, and control characters are rejected. A path through a symlinked directory, such as `.claude/skills/support/SKILL.md` when `.claude/skills/support` links to `skills/support`, names the same file as the path without the link.+- `evidence_sha256` comes from the `evidence_sha256` metadata of the PII finding in the JSON report. It is a SHA-256 digest of the check name and the case-folded value, so the waiver file never contains the value. A digest is an identifier, not encryption: a short value such as an SSN can be recovered from it by trying every candidate. Findings report a digest only for a value the report shows in full, so credential findings, and any other finding whose value reports mask because it contains a credential, carry none.+- `reason` needs at least 8 characters, `owner` names the reviewer or team, and the waiver applies through `expires`. Dates are UTC calendar dates; `created` may be at most one day after the UTC date, so a reviewer east of UTC can enter their local date, and `expires` may not be before `created` or more than 366 days after it, so every waiver comes up for review at least yearly.++A waiver applies only while the check, file, line, and value all match. When the value changes or moves, the finding is reported again, and other values on the same line are reported as usual. The outcome of each waiver the run judges is in the reports under the `PII_WAIVER` category:++| Check | Severity | Meaning |+| --- | --- | --- |+| `applied-pii-waiver` | INFO | The waiver suppressed the finding. |+| `stale-pii-waiver` | LOW | No current finding matches the waiver; update or remove it. |+| `expired-pii-waiver` | MEDIUM | The waiver is past `expires`; the finding is reported again. |+| `invalid-pii-waiver-file` | HIGH | The file could not be applied, so no waiver from it was used. |++A run judges only the waivers whose file lies in a skill or folder it scanned; a waiver for a deleted file there is stale. A run on one skill, and each skill of a catalog run, reports the waivers for that skill's files and leaves the other waivers in the file unjudged. Waiver findings name the file the way the PII findings of the same report do, for example `[support] SKILL.md` in a folder run; the waiver's own `file` value is in the `waiver_file` metadata. They do not repeat the waiver's `evidence_sha256`, because the run may now mask that value.++The command line rejects a malformed waiver file before the run starts, with exit code 2 and the problem named: unknown or missing fields, duplicate ids or keys, unknown or credential check names, and malformed paths, digests, or dates. Waivers apply only to the `pii` check; findings from other checks for the same value, such as Gitleaks secrets, are unaffected.+## Scanner setupInstall `skillevaluator[security]` for the bundled Python scanners (Bandit and pip-audit). Install Semgrep and SkillSpector in separate tool environments, and install Gitleaks separately — it is a Go binary, not a pip package. See [Installation](installation.mdx) for commands and the extras table.@@ -505,7 +549,7 @@ Markdown and HTML reports show the same outcome as a `skillspector_baseline` lin| --- | --- || `0` | Success — every gate passed || `1` | Validation failed — a check failed or required scanner evidence is incomplete |-| `2` | Usage error — an unknown flag, a value outside an option's type or choices, a target path that does not exist, or an invalid `--quality-config` file |+| `2` | Usage error — an unknown flag, a value outside an option's type or choices, a target path that does not exist, or an invalid `--quality-config` or `--pii-waivers` file |Tier 1 checks always gate the exit code inside `validate`. Tier 2 gates when it runs unless `--no-block-on-dedup` is set. Tier 3 is advisory unless `--block-on-agent-eval` is set. The `quality` check requires the composite score to reach `--min-score` (default `70`) as well as no HIGH or CRITICAL quality findings under the active policy. Severity overrides cannot waive the minimum. Reports record the effective gate membership for every tier so saved evidence and process status agree.diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex 1441e69e..e75b9a06 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -19,6 +19,7 @@ import clickfrom skillevaluator import __version__from skillevaluator.cli_help import GroupedOption, RichGroup+from skillevaluator.config import load_pii_patternsfrom skillevaluator.constants import (SIMILARITY_DEFAULT_MAX_ENTRIES,SIMILARITY_DEFAULT_MAX_SCALAR_COMPARISONS,@@ -69,6 +70,12 @@ from skillevaluator.utils.tier2_paths import (paths_refer_to_same_location,sanitize_tier2_results,)+from skillevaluator.validators.pii_waivers import (+ PIIWaiverError,+ configured_pii_categories,+ load_pii_waivers,+ today_utc,+)CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}@@ -135,6 +142,25 @@ _SKILLSPECTOR_BASELINE_HELP = ()+class _PIIWaiversPath(click.Path):+ """A ``--pii-waivers`` file, validated while arguments are parsed."""++ def __init__(self) -> None:+ super().__init__(exists=True, dir_okay=False, path_type=Path)++ def convert(self, value, param, ctx):+ path = super().convert(value, param, ctx)+ try:+ load_pii_waivers(path, configured_pii_categories(load_pii_patterns()), today=today_utc())+ except PIIWaiverError as exc:+ self.fail(f"{path}: {exc}", param, ctx)+ return path+++PII_WAIVERS_PATH = _PIIWaiversPath()+_PII_WAIVERS_HELP = "Apply reviewed, expiring PII waivers from this YAML file to the PII check."++def _validate_similarity_threshold(_ctx: click.Context, _param: click.Parameter, value: float) -> float:if not math.isfinite(value) or not 0.0 <= value <= 1.0:raise click.BadParameter("must be finite and within [0, 1]")@@ -1239,6 +1265,10 @@ def _catalog_child_argv_from_ctx(argv.extend(["--min-score", str(min_score)])if params.get("quality_config"):argv.extend(["--quality-config", str(Path(params["quality_config"]).resolve())])+ if params.get("pii_waivers"):+ # Not resolved: a waiver file's entries are relative to the directory the file (or the+ # symlink to it) is in, so a child must see the same path the parent was given.+ argv.extend(["--pii-waivers", str(Path(params["pii_waivers"]).absolute())])if params.get("external"):argv.append("--external")if params.get("policy_path"):@@ -1809,6 +1839,14 @@ def _print_run_banner(target_path: Path, content_type: str, profile: str | None)help_group=_TIER1_GROUP,help="Override the packaged quality-default.yaml with a custom YAML file.",)+ "--pii-waivers",+ type=PII_WAIVERS_PATH,+ default=None,+ cls=GroupedOption,+ help_group=_TIER1_GROUP,+ help=_PII_WAIVERS_HELP,+)@click.option("--profile",default=None,@@ -2071,6 +2109,7 @@ def validate(skillspector_baseline: Path | None,min_score: int,quality_config: Path | None,+ pii_waivers: Path | None,profile: str | None,external: bool,policy_path: Path | None,@@ -2303,6 +2342,7 @@ def validate(skillspector_baseline=skillspector_baseline,min_score=min_score,quality_config=quality_config,+ pii_waivers=pii_waivers,previous_version=previous_version,policy=policy,content_type=resolved_type,@@ -2659,12 +2699,19 @@ def security_scan(@cli.command("pii-scan")@_target_argument@click.option("--llm-verify", is_flag=True, help="Use LLM verification to reduce false positives.")[email protected]("--pii-waivers", type=PII_WAIVERS_PATH, default=None, help=_PII_WAIVERS_HELP)@_report_options-def pii_scan(target_path: Path, llm_verify: bool, report_formats: tuple[str, ...], output_dir: Path) -> None:+def pii_scan(+ target_path: Path,+ llm_verify: bool,+ pii_waivers: Path | None,+ report_formats: tuple[str, ...],+ output_dir: Path,+) -> None:"""Scan for PII and local identifiers."""output_dir = _resolve_file_report_output_location(target_path.resolve(), output_dir, report_formats)if not emit_reports(- run_pii_scan(target_path, llm_verify=llm_verify),+ run_pii_scan(target_path, llm_verify=llm_verify, pii_waivers=pii_waivers),report_formats=report_formats,output_dir=output_dir,basename=report_basename("pii"),@@ -2895,6 +2942,7 @@ def _workflow_report_options(func):default=None,help="Override the packaged quality-default.yaml with a custom YAML file.",)[email protected]("--pii-waivers", type=PII_WAIVERS_PATH, default=None, help=_PII_WAIVERS_HELP)@click.option("--profile", default=None, help="Validation policy [default: default; external is a compatibility alias].")@click.option("--previous-version", default=None, help="Previous version for version checks.")@click.option(@@ -2908,6 +2956,7 @@ def _tier1_workflow(llm: bool | None,min_score: int,quality_config: Path | None,+ pii_waivers: Path | None,profile: str | None,previous_version: str | None,skillspector_baseline: Path | None,@@ -2930,6 +2979,7 @@ def _tier1_workflow(llm=llm,min_score=min_score,quality_config=quality_config,+ pii_waivers=pii_waivers,profile=policy,previous_version=previous_version,skillspector_baseline=skillspector_baseline,diff --git a/src/skillevaluator/config/pii_patterns.yaml b/src/skillevaluator/config/pii_patterns.yamlindex 7eb85f1d..e009f997 100644--- a/src/skillevaluator/config/pii_patterns.yaml+++ b/src/skillevaluator/config/pii_patterns.yaml@@ -13,7 +13,8 @@# - suggestion (optional): how to fix the issue# - exceptions (optional): per-pattern exception list-# Personal file paths+# Personal file paths. Proton's fixed per-game profile pfx/drive_c/users/steamuser/+# names no person and is skipped in code (SecurityValidator._is_proton_virtual_profile).personal_paths:- pattern: "/Users/[^/\\s]+/"severity: highdiff --git a/src/skillevaluator/tier1/commands.py b/src/skillevaluator/tier1/commands.pyindex 9bbd3016..6becf261 100644--- a/src/skillevaluator/tier1/commands.py+++ b/src/skillevaluator/tier1/commands.py@@ -210,6 +210,7 @@ def run_validation(llm_verify: bool = False,min_score: int = 70,quality_config: Path | None = None,+ pii_waivers: Path | None = None,previous_version: str | None = None,policy: ValidationPolicy | None = None,content_type: str | None = None,@@ -240,6 +241,7 @@ def run_validation(audience-aware author rules; finalized severities for all validators areapplied centrally in :func:`emit_reports` via the policy.+ *pii_waivers* is an optional PII waiver file applied by the ``pii`` check.*skillspector_baseline* is an audited SkillSpector suppression baselineapplied to the ``security`` check; it is never discovered from the target."""@@ -293,7 +295,7 @@ def run_validation(return [_run_result("security", "Security Scan", v.description, v.validate_security_only)]def _pii_results() -> list[ValidationResult]:- v = SecurityValidator(use_llm=False, verify_llm=llm_verify)+ v = SecurityValidator(use_llm=False, verify_llm=llm_verify, pii_waiver_path=pii_waivers)return [_run_result("pii", "PII Scan", "Detect PII and local identifiers", v.validate_pii_only)]def _code_integrity_results() -> list[ValidationResult]:@@ -443,8 +445,13 @@ def run_security_scan(]-def run_pii_scan(target_path: Path, *, llm_verify: bool = False) -> list[ValidationResult]:- validator = SecurityValidator(use_llm=False, verify_llm=llm_verify)+def run_pii_scan(+ target_path: Path,+ *,+ llm_verify: bool = False,+ pii_waivers: Path | None = None,+) -> list[ValidationResult]:+ validator = SecurityValidator(use_llm=False, verify_llm=llm_verify, pii_waiver_path=pii_waivers)return [_as_result("PII Scan",diff --git a/src/skillevaluator/tier_workflows.py b/src/skillevaluator/tier_workflows.pyindex aa15f462..708cbb56 100644--- a/src/skillevaluator/tier_workflows.py+++ b/src/skillevaluator/tier_workflows.py@@ -72,6 +72,7 @@ def run_tier1_workflow(quality_config: Path | None,profile: ValidationPolicy,previous_version: str | None,+ pii_waivers: Path | None = None,skillspector_baseline: Path | None = None,skip: str | None = None,) -> list[ValidationResult]:@@ -96,6 +97,7 @@ def run_tier1_workflow(llm_verify=use_llm,min_score=min_score,quality_config=quality_config,+ pii_waivers=pii_waivers,previous_version=previous_version,policy=profile,content_type="skill",diff --git a/src/skillevaluator/validators/pii_waivers.py b/src/skillevaluator/validators/pii_waivers.pynew file mode 100644index 00000000..8744b4bc--- /dev/null+++ b/src/skillevaluator/validators/pii_waivers.py@@ -0,0 +1,430 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Evidence-bound PII waivers.++A waiver accepts one reviewed PII value at one place: a PII category, a file,+a line, and a SHA-256 digest of the value (``evidence_sha256`` in the PII+finding's metadata), with a reason, an owner, and a review window. It stops+applying as soon as any of those no longer match, so it never covers a new+value, a moved line, or a different file.++The waiver file is passed by whoever runs the scan (``--pii-waivers PATH``); a+scanned skill cannot supply its own. Its ``file`` entries are relative to the+directory that holds the waiver file, so one file serves single-skill, folder,+and catalog runs alike; each run reports only the waivers whose file lies in a+skill or folder it scanned. A file that does not load applies no waivers and+fails the PII scan with a HIGH finding.++Credential checks (:data:`~skillevaluator.utils.secret_redaction.SENSITIVE_PII_CATEGORIES`)+cannot be waived. Reports mask their values, so their findings carry no digest:+a digest of a short password would let anyone holding the report test guesses+for it offline. A credential in a skill should be removed or rotated.++Dates are UTC calendar dates. ``created`` may be one day ahead of the UTC date,+because a reviewer east of UTC can already be on the next day.++Example::++ version: 1+ waivers:+ - id: PII-001+ category: emails+ file: skills/support/SKILL.md+ line: 12+ evidence_sha256: <64 lowercase hex characters from the PII finding>+ reason: Public support address of the documented service+ owner: docs-team+ created: 2026-10-01+ expires: 2027-01-01+"""++from __future__ import annotations++import hashlib+import re+import unicodedata+from collections.abc import Callable, Collection, Mapping+from dataclasses import dataclass, field+from datetime import UTC, date, datetime, timedelta+from pathlib import Path, PurePosixPath++import yaml++from skillevaluator.models.result import Finding, Severity+from skillevaluator.quality_config import _yaml_error_detail+from skillevaluator.utils.secret_redaction import SENSITIVE_PII_CATEGORIES+from skillevaluator.utils.structured_data import (+ StructuredDataLimitError,+ StructuredDataSyntaxError,+ _UniqueKeySafeLoader,+ load_bounded_yaml,+)++PII_WAIVER_CATEGORY = "PII_WAIVER"+_WAIVER_FIELDS = ("id", "category", "file", "line", "evidence_sha256", "reason", "owner", "created", "expires")+_SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")+_MIN_REASON_LENGTH = 8+# The local date can be at most one day ahead of the UTC date (UTC+14 at most).+_CREATED_TOLERANCE = timedelta(days=1)+# A waiver is a bounded-time exception that forces periodic review, so it cannot be permanent.+_MAX_WAIVER_WINDOW = timedelta(days=366)+++class PIIWaiverError(ValueError):+ """Raised when a PII waiver file cannot be applied."""+++def pii_evidence_sha256(category: str, value: str) -> str:+ """Return the digest that identifies a PII value in a waiver without storing the value.++ The value is case-folded because PII findings group values case-insensitively.+ A digest is an identifier, not a secret: a short value such as an SSN can be+ recovered from it by trying every candidate. Findings therefore report it only+ for values they show unmasked.+ """+ return hashlib.sha256(f"{category}\x00{value.casefold()}".encode()).hexdigest()+++def configured_pii_categories(pii_patterns: Mapping[str, object]) -> frozenset[str]:+ """Return the PII check names in the PII pattern config; the loader also refuses credential checks."""+ return frozenset(+ name for name, patterns in pii_patterns.items() if name != "exceptions" and isinstance(patterns, list)+ )+++def today_utc() -> date:+ """Return today's date in UTC, the calendar waiver review windows use."""+ return datetime.now(UTC).date()+++@dataclass(frozen=True)+class PIIWaiver:+ """One reviewed PII value at one file and line."""++ waiver_id: str+ category: str+ file: str+ line: int+ evidence_sha256: str+ reason: str+ owner: str+ created: date+ expires: date+++def _text_field(item: dict, name: str, location: str) -> str:+ value = item[name]+ if not isinstance(value, str) or not value.strip():+ raise PIIWaiverError(f"{location}.{name} must be a non-empty string")+ return value.strip()+++def _date_field(item: dict, name: str, location: str) -> date:+ value = item[name]+ if isinstance(value, datetime) or not isinstance(value, date | str):+ raise PIIWaiverError(f"{location}.{name} must be a date (YYYY-MM-DD)")+ if isinstance(value, str):+ try:+ return date.fromisoformat(value)+ except ValueError as exc:+ raise PIIWaiverError(f"{location}.{name} must be a date (YYYY-MM-DD)") from exc+ return value+++def _file_field(item: dict, location: str) -> str:+ value = item["file"]+ if not isinstance(value, str) or not value or "\\" in value:+ raise PIIWaiverError(f"{location}.file must be a relative path with forward slashes")+ path = PurePosixPath(value)+ if (+ path.is_absolute()+ or path.as_posix() != value+ or value == "."+ or ".." in path.parts+ or any(unicodedata.category(character) == "Cc" for character in value)+ ):+ raise PIIWaiverError(f"{location}.file must be a normalized relative path inside the waiver file's directory")+ return value+++def load_pii_waivers(path: Path, categories: Collection[str], *, today: date) -> list[PIIWaiver]:+ """Load a version-1 PII waiver file, rejecting any entry that is not exactly valid.++ Expired waivers load (they are reported, not applied); a waiver created more+ than a day after ``today`` (UTC) does not. Messages name entries by position+ and id, never the file's location, so they are safe to put in reports.+ """+ try:+ text = path.read_text(encoding="utf-8")+ except UnicodeDecodeError as exc:+ raise PIIWaiverError("file is not valid UTF-8") from exc+ except OSError as exc:+ raise PIIWaiverError(f"cannot read file: {exc.strerror or type(exc).__name__}") from exc+ try:+ try:+ raw = load_bounded_yaml(text)+ except StructuredDataSyntaxError:+ # The bounded loader reports no position; the same loader gives a line and column.+ raw = yaml.load(text, Loader=_UniqueKeySafeLoader) # nosec B506+ except StructuredDataLimitError as exc:+ raise PIIWaiverError(f"invalid YAML: {exc}") from exc+ except yaml.YAMLError as exc:+ raise PIIWaiverError(f"invalid YAML: {_yaml_error_detail(exc)}") from exc+ except RecursionError as exc:+ raise PIIWaiverError("invalid YAML: nesting is too deep") from exc+ except (ValueError, TypeError, KeyError, AttributeError) as exc:+ raise PIIWaiverError(f"invalid YAML: cannot parse a value: {exc}") from exc++ if not isinstance(raw, dict) or set(raw) != {"version", "waivers"}:+ raise PIIWaiverError("the top level must contain only 'version: 1' and a 'waivers' list")+ if type(raw["version"]) is not int or raw["version"] != 1:+ raise PIIWaiverError("version must be 1")+ if not isinstance(raw["waivers"], list):+ raise PIIWaiverError("waivers must be a list")++ waivers: list[PIIWaiver] = []+ seen_ids: set[str] = set()+ for index, item in enumerate(raw["waivers"]):+ location = f"waivers[{index}]"+ if not isinstance(item, dict):+ raise PIIWaiverError(f"{location} must be a mapping")+ unknown = sorted(str(key) for key in item if key not in _WAIVER_FIELDS)+ if unknown:+ raise PIIWaiverError(f"{location} has unknown field(s): {', '.join(unknown)}")+ missing = [name for name in _WAIVER_FIELDS if name not in item]+ if missing:+ raise PIIWaiverError(f"{location} is missing: {', '.join(missing)}")++ waiver_id = _text_field(item, "id", location)+ if waiver_id in seen_ids:+ raise PIIWaiverError(f"{location}.id {waiver_id!r} is used more than once")+ seen_ids.add(waiver_id)+ location = f"waiver {waiver_id!r}"++ category = item["category"]+ if isinstance(category, str) and category in SENSITIVE_PII_CATEGORIES:+ raise PIIWaiverError(+ f"{location}.category {category!r} is a credential check and cannot be waived; "+ "remove or rotate the credential"+ )+ if not isinstance(category, str) or category not in categories:+ raise PIIWaiverError(f"{location}.category must be a PII check name such as 'emails'")+ line = item["line"]+ if type(line) is not int or line < 1:+ raise PIIWaiverError(f"{location}.line must be a positive integer")+ digest = item["evidence_sha256"]+ if not isinstance(digest, str) or not _SHA256_PATTERN.fullmatch(digest.lower()):+ raise PIIWaiverError(f"{location}.evidence_sha256 must be 64 hexadecimal characters")+ reason = _text_field(item, "reason", location)+ if len(reason) < _MIN_REASON_LENGTH:+ raise PIIWaiverError(+ f"{location}.reason must explain the review (at least {_MIN_REASON_LENGTH} characters)"+ )+ created = _date_field(item, "created", location)+ expires = _date_field(item, "expires", location)+ if created > today + _CREATED_TOLERANCE:+ raise PIIWaiverError(f"{location}.created is in the future")+ if expires < created:+ raise PIIWaiverError(f"{location}.expires is before created")+ if expires - created > _MAX_WAIVER_WINDOW:+ raise PIIWaiverError(+ f"{location}.expires is more than {_MAX_WAIVER_WINDOW.days} days after created; renew the waiver "+ "after a review instead"+ )++ waivers.append(+ PIIWaiver(+ waiver_id=waiver_id,+ category=category,+ file=_file_field(item, location),+ line=line,+ evidence_sha256=digest.lower(),+ reason=reason,+ owner=_text_field(item, "owner", location),+ created=created,+ expires=expires,+ )+ )+ return waivers+++@dataclass+class PIIWaiverSet:+ """The waivers of one scan, which of them matched evidence, and what the scan covered."""++ path: Path+ waivers: list[PIIWaiver] = field(default_factory=list)+ error: str | None = None+ today: date = field(default_factory=today_utc)+ applied: set[str] = field(default_factory=set)+ # Each directory or file the PII scan covered, as passed and resolved.+ covered: list[tuple[Path, Path]] = field(default_factory=list)+ # Each waiver ``file`` as located by :meth:`_locate`, so a scan resolves it once.+ _located: dict[str, Path | None] = field(default_factory=dict, repr=False)++ @classmethod+ def load(cls, path: Path, categories: Collection[str], *, today: date | None = None) -> PIIWaiverSet:+ """Load ``path``; a file that does not load is kept as an error and applies no waivers."""+ waiver_set = cls(path=path, today=today or today_utc())+ try:+ waiver_set.waivers = load_pii_waivers(path, categories, today=waiver_set.today)+ except PIIWaiverError as exc:+ waiver_set.error = str(exc)+ return waiver_set++ def _base(self) -> Path:+ # The directory the waiver file is in, even when the file itself is a symlink.+ return self.path.absolute().parent.resolve()++ def _locate(self, relative: str) -> Path | None:+ if relative not in self._located:+ located = self._base() / relative+ try:+ self._located[relative] = located.parent.resolve() / located.name+ except (OSError, RuntimeError, ValueError):+ self._located[relative] = None+ return self._located[relative]++ def cover(self, unit: Path) -> None:+ """Record that the PII scan covered ``unit``: one skill, a folder scanned directly, or a file.++ Only waivers whose file lies in a covered unit are reported, so a run on+ one skill, or one child of a catalog run, does not report the waivers of+ skills it never scanned as stale.+ """+ try:+ self.covered.append((unit, unit.absolute().resolve()))+ except (OSError, RuntimeError):+ return++ def _report_path(self, waiver: PIIWaiver, target: Path) -> str | None:+ """Return the waiver's file as the PII findings of a scan of ``target`` name it.++ That is relative to the covered unit, with the ``[skill] `` prefix of a+ folder run, or ``None`` when no covered unit holds the file.+ """+ located = self._locate(waiver.file)+ if located is None:+ return None+ units = [(unit, resolved) for unit, resolved in self.covered if located.is_relative_to(resolved)]+ if not units:+ return None+ unit, resolved = max(units, key=lambda item: len(item[1].parts))+ relative = str(located.relative_to(resolved))+ try:+ is_target = resolved == target.absolute().resolve()+ except (OSError, RuntimeError):+ is_target = False+ return relative if is_target else f"[{unit.name}] {relative}"++ def matcher(self, file_path: Path) -> Callable[[str, int, str], bool] | None:+ """Return a check for PII candidates in ``file_path``, or ``None`` when no waiver names the file.++ The check takes a candidate's category, line, and value, records the+ waiver that covers it, and returns whether one does.+ """+ try:+ located = file_path.absolute().parent.resolve() / file_path.name+ except (OSError, RuntimeError, ValueError):+ return None+ # Compared as located paths, the way findings() judges a waiver, so a waiver that names+ # the file through a symlinked directory applies wherever it is judged.+ # ``created`` was checked when the file loaded; only the expiry date can end a waiver.+ candidates = [+ waiver for waiver in self.waivers if self.today <= waiver.expires and self._locate(waiver.file) == located+ ]+ if not candidates:+ return None++ def waive(category: str, line: int, value: str) -> bool:+ digest = pii_evidence_sha256(category, value)+ for waiver in candidates:+ if waiver.category == category and waiver.line == line and waiver.evidence_sha256 == digest:+ self.applied.add(waiver.waiver_id)+ return True+ return False++ return waive++ def findings(self, target: Path) -> list[tuple[Finding, bool]]:+ """Report the waiver file's outcome for a scan of ``target``.++ An invalid file is one HIGH finding. Otherwise each waiver whose file the+ scan covered is reported as applied, expired, or stale, at the path the+ PII findings of the same report use; ``metadata["waiver_file"]`` keeps+ the waiver's own ``file``. The metadata never holds the waiver's digest:+ the scan may now mask that value (for example, it became part of a+ credential), and the waiver file already holds it. Waivers for files+ outside the scan are not judged. Returns ``(finding, is_error)`` pairs; only an invalid file is+ an error.+ """+ if self.error is not None:+ return [+ (+ Finding(+ category=PII_WAIVER_CATEGORY,+ severity=Severity.HIGH,+ check_name="invalid-pii-waiver-file",+ message=f"PII waiver file {self.path.name} is invalid, so no waiver was applied: {self.error}",+ file_path=self.path.name,+ suggestion="Fix the waiver file; see the PII waiver format in the Tier 1 documentation.",+ ),+ True,+ )+ ]++ reported: list[tuple[Finding, bool]] = []+ for waiver in self.waivers:+ applied = waiver.waiver_id in self.applied+ file_path = self._report_path(waiver, target)+ if file_path is None:+ if not applied:+ continue+ file_path = waiver.file+ metadata = {+ "waiver_id": waiver.waiver_id,+ "waiver_file": waiver.file,+ "pii_category": waiver.category,+ "owner": waiver.owner,+ "reason": waiver.reason,+ "created": waiver.created.isoformat(),+ "expires": waiver.expires.isoformat(),+ }+ if applied:+ finding = Finding(+ category=PII_WAIVER_CATEGORY,+ severity=Severity.INFO,+ check_name="applied-pii-waiver",+ message=f"PII waiver {waiver.waiver_id} accepted the reviewed value for the {waiver.category} check",+ file_path=file_path,+ line_number=waiver.line,+ suggestion=(+ f"Review again before {waiver.expires.isoformat()}; remove the waiver once the value is gone."+ ),+ metadata=metadata,+ )+ elif waiver.expires < self.today:+ finding = Finding(+ category=PII_WAIVER_CATEGORY,+ severity=Severity.MEDIUM,+ check_name="expired-pii-waiver",+ message=f"PII waiver {waiver.waiver_id} expired on {waiver.expires.isoformat()} and was not applied",+ file_path=file_path,+ line_number=waiver.line,+ suggestion="Review the value again and extend the expiry date, or remove the waiver.",+ metadata=metadata,+ )+ else:+ finding = Finding(+ category=PII_WAIVER_CATEGORY,+ severity=Severity.LOW,+ check_name="stale-pii-waiver",+ message=f"PII waiver {waiver.waiver_id} matched no {waiver.category} finding at its file and line",+ file_path=file_path,+ line_number=waiver.line,+ suggestion="Remove the waiver, or update it from the current PII finding after review.",+ metadata=metadata,+ )+ reported.append((finding, False))+ return reporteddiff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.pyindex 95a47424..de4b0aac 100644--- a/src/skillevaluator/validators/security.py+++ b/src/skillevaluator/validators/security.py@@ -64,6 +64,7 @@ from skillevaluator.validators.base import (ValidatorBase,iter_scannable_files,)+from skillevaluator.validators.pii_waivers import PIIWaiverSet, configured_pii_categories, pii_evidence_sha256from skillevaluator.validators.skillspector_scope import (IssueScope,scope_skillspector_issues,@@ -1562,6 +1563,7 @@ class SecurityValidator(ValidatorBase):use_llm: bool = False,verify_llm: bool = False,submitter_usernames: Iterable[str] | None = None,+ pii_waiver_path: Path | None = None,content_type: str | None = None,skillspector_reference_root: Path | None = None,skillspector_baseline: Path | str | None = None,@@ -1577,6 +1579,9 @@ class SecurityValidator(ValidatorBase)::data:`HOME_PATH_SUBMITTER_ENV_VARS`) and the OS login name.Pass an explicit value to wire a CI-provided contributor identityor to make tests deterministic.+ pii_waiver_path: Optional PII waiver file (see+ :mod:`skillevaluator.validators.pii_waivers`) applied by+ :meth:`validate` and :meth:`validate_pii_only`.content_type: Detected agent artifact type (``skill``, ``rules``,``workflows``, or ``plugin``). When set, SkillSpector findingsoutside agent control paths are suppressed (see@@ -1601,6 +1606,9 @@ class SecurityValidator(ValidatorBase):self._home_check_disabled_warned = Falseself.use_llm = use_llmself.verify_llm = verify_llm+ self.pii_waiver_path = Path(pii_waiver_path) if pii_waiver_path is not None else None+ # The waivers of the scan in progress; set only while validate() or validate_pii_only() runs.+ self._pii_waivers: PIIWaiverSet | None = Noneself.content_type = content_typeself.skillspector_reference_root = (Path(skillspector_reference_root).resolve() if skillspector_reference_root is not None else None@@ -1731,10 +1739,13 @@ class SecurityValidator(ValidatorBase):def validate(self, skill_path: Path) -> ValidationResult:"""Run both security and PII scanning on skill(s)."""- return self._validate_with_applicability(+ return self._with_pii_waivers(skill_path,- self._validate_single_skill,- action_description="Scanning",+ lambda: self._validate_with_applicability(+ skill_path,+ self._validate_single_skill,+ action_description="Scanning",+ ),)def validate_security_only(self, skill_path: Path) -> ValidationResult:@@ -1750,13 +1761,38 @@ class SecurityValidator(ValidatorBase):def validate_pii_only(self, skill_path: Path) -> ValidationResult:"""Run only PII detection (no skillspector security scan)."""- result = self._validate_folder_or_skill(- skill_path,- self._scan_for_pii,- action_description="PII scanning",- )- if self.verify_llm and result.findings:- self._verify_findings_with_llm(result, skill_path)++ def scan() -> ValidationResult:+ result = self._validate_folder_or_skill(+ skill_path,+ self._scan_for_pii,+ action_description="PII scanning",+ )+ if self.verify_llm and result.findings:+ self._verify_findings_with_llm(result, skill_path)+ return result++ return self._with_pii_waivers(skill_path, scan)++ def _with_pii_waivers(self, skill_path: Path, scan: Callable[[], ValidationResult]) -> ValidationResult:+ """Run ``scan`` of ``skill_path`` with the configured PII waivers, then report their outcomes once.++ The outcomes are added after the scan (and any LLM verification) at the+ top level, so a folder run reports them once, not per skill. Only the+ waivers for files the scan covered are reported.+ """+ if self.pii_waiver_path is None:+ return scan()+ waivers = PIIWaiverSet.load(self.pii_waiver_path, configured_pii_categories(self.pii_patterns))+ self._pii_waivers = waivers+ try:+ result = scan()+ finally:+ self._pii_waivers = None+ for finding, is_error in waivers.findings(skill_path):+ result.add_structured_finding(finding, is_error=is_error)+ if waivers.applied:+ result.add_message(f"PII waivers suppressed {len(waivers.applied)} reviewed PII value(s)")return resultdef _validate_with_applicability(@@ -3957,6 +3993,9 @@ class SecurityValidator(ValidatorBase):"""Scan files for PII using regex patterns (emails, paths, SSNs, etc.)."""result = ValidationResult()files = self._get_scannable_files(skill_path)+ waivers = self._pii_waivers+ if waivers is not None:+ waivers.cover(skill_path)if not files:result.add_warning("No scannable files found for PII scan")@@ -3993,7 +4032,8 @@ class SecurityValidator(ValidatorBase):except ValueError:relative_path = file_path.name- for finding_data in self._scan_file_for_pii(file_path, protected_usernames):+ 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):pii_found = Truevalue = finding_data.get("matched_value")key: object = (@@ -4042,6 +4082,14 @@ class SecurityValidator(ValidatorBase):if len(occurrences) > 1:message += f" — {len(occurrences)} occurrences ({self._format_occurrences(occurrences)})"message = redactor.text(message)+ metadata = redactor.object(metadata)+ if value and not sensitive and redactor.text(value) == value:+ # Identifies the matched value for a PII waiver (see validators/pii_waivers.py). Only a+ # value the report shows in full gets one: a digest of a masked credential, or of a value+ # that contains one, would let anyone holding the report test guesses for it offline.+ # It is added after redaction, which would otherwise mask a short secret that happens+ # to occur in the hex digest of another value.+ metadata["evidence_sha256"] = pii_evidence_sha256(first["category"], value)finding = Finding(category="PII",@@ -4052,7 +4100,7 @@ class SecurityValidator(ValidatorBase):line_number=first["line"],line_content=None if sensitive else redactor.text(first.get("line_content") or "") or None,suggestion=first.get("suggestion"),- metadata=redactor.object(metadata),+ metadata=metadata,)result.add_structured_finding(finding, is_error=severity in ("CRITICAL", "HIGH"))@@ -4276,6 +4324,39 @@ class SecurityValidator(ValidatorBase):r"(?![a-z0-9])[\"']?(?:\s*[:=]\s*[\"']?|\s+[\"']?)\Z")+ # Proton (Steam Play) runs each Windows game in its own prefix whose only+ # Windows profile is ``pfx/drive_c/users/steamuser/``. Proton uses that name+ # for every player, so the path names no person. ``pfx`` must start a path+ # component. A ``..`` segment after the profile could lead anywhere, so a+ # line with one anywhere after the profile stays reported: Windows folder+ # names often contain spaces and quotes, so the path's end is not reliable.+ # A ``..`` counts as a segment when a path separator (plain or encoded),+ # whitespace, a quote, or another delimiter bounds it on both sides, so+ # ``steamuser/" + "../x"``, ``/ ".." /``, ``"..",``, ``cd ../x`` and+ # ``cd ..&& cd x`` count. Shell ``&`` and ``:`` bound a ``..`` but not ``pfx``.+ _PROTON_PREFIX = "pfx/drive_c"+ _PROTON_PREFIX_BOUNDARIES = frozenset("/\\'\"`=(){}[]<>|*,; \t")+ _DOT_DOT_BOUNDARY = (+ "[" + "".join(re.escape(c) for c in sorted(_PROTON_PREFIX_BOUNDARIES | {"&", ":"})) + r"\s]|%2f|%5c"+ )+ _DOT_DOT_SEGMENT_PATTERN = re.compile(+ rf"(?:^|{_DOT_DOT_BOUNDARY})(?:\.|%2e){{2}}(?=$|{_DOT_DOT_BOUNDARY})", re.IGNORECASE+ )++ @classmethod+ def _is_proton_virtual_profile(cls, match: re.Match, line: str) -> bool:+ """Return whether a personal-path match is Proton's ``pfx/drive_c/users/steamuser/`` profile."""+ value = match.group()+ if not value.isascii() or value.lower() != "/users/steamuser/":+ return False+ start = match.start() - len(cls._PROTON_PREFIX)+ prefix = line[max(start, 0) : match.start()]+ if start < 0 or not prefix.isascii() or prefix.lower().replace("\\", "/") != cls._PROTON_PREFIX:+ return False+ if start > 0 and line[start - 1] not in cls._PROTON_PREFIX_BOUNDARIES:+ return False+ return cls._DOT_DOT_SEGMENT_PATTERN.search(line[match.end() :]) is None+@staticmethoddef _is_near_zero_gps(line: str) -> bool:"""Check if a GPS match contains only near-zero coordinates (Null Island)."""@@ -4545,12 +4626,20 @@ class SecurityValidator(ValidatorBase):"""True when a line is a YAML frontmatter fence, including BOM-prefixed openers."""return line.strip().removeprefix("\ufeff").strip() == "---"- def _scan_file_for_pii(self, file_path: Path, protected_usernames: set[str] | None = None) -> list[dict]:+ def _scan_file_for_pii(+ self,+ file_path: Path,+ protected_usernames: set[str] | None = None,+ *,+ waive: Callable[[str, int, str], bool] | None = None,+ ) -> list[dict]:"""Scan a single file for PII patterns, yielding findings with full context.``protected_usernames`` is the set of author/submitter identities used bythe home-path check; when omitted it is resolved from the file's parent- directory so the method stays usable standalone.+ 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."""if protected_usernames is None:protected_usernames = self._protected_home_usernames(file_path.parent)@@ -4580,6 +4669,7 @@ class SecurityValidator(ValidatorBase):protected_usernames,author_emails,comment_lines,+ waive=waive,)return findings@@ -4636,8 +4726,17 @@ class SecurityValidator(ValidatorBase):protected_usernames: set[str] | None = None,author_emails: dict[int, str] | None = None,comment_lines: frozenset[int] | None = None,+ *,+ waive: Callable[[str, int, str], bool] | None = None,) -> None:- """Check all lines against a single compiled PII pattern."""+ """Check all lines against a single compiled PII pattern.++ Only the first remaining match on a line is reported. Matches are+ filtered before that choice, so a value that is not reported (a version+ literal, the Proton profile, an unrelated home directory, a number that+ is not a card number, or a waived value) does not hide another value on+ the same line.+ """protected_usernames = protected_usernames or set()author_emails = author_emails or {}comment_lines = comment_lines if comment_lines is not None else _comment_line_numbers(file_path, lines)@@ -4687,20 +4786,23 @@ class SecurityValidator(ValidatorBase):continueif category == "ip_addresses":matches = [match for match in matches if not self._is_version_literal(match, line)]- if not matches:- continue- if category == "credit_cards":+ elif category == "personal_paths":+ matches = [match for match in matches if not self._is_proton_virtual_profile(match, line)]+ elif category == "home_paths":+ # /home/<root>/ is PII only when <root> is the author/submitter+ # username; unrelated roots are skipped.+ matches = [match for match in matches if self._is_personal_home_path(match, protected_usernames)]+ elif category == "credit_cards":# Check every candidate: a GUID or non-Luhn number must not hide a later card.previous_line = lines[line_num - 2] if line_num > 1 else ""matches = [match for match in matches if self._is_card_number_candidate(match, line, previous_line)]- if not matches:- continue- match = matches[0]-- # /home/<root>/ is PII only when <root> is the author/submitter- # username; unrelated roots are skipped.- if category == "home_paths" and not self._is_personal_home_path(match, protected_usernames):+ # A waiver is consulted only for a value that would be reported, so+ # it never counts as applied for a value the scan already dropped.+ if waive is not None:+ matches = [match for match in matches if not waive(category, line_num, self._reported_value(match))]+ if not matches:continue+ match = matches[0]confidence = self._estimate_confidence(category, line)if category == "gps_coordinates" and self._is_near_zero_gps(line):@@ -4716,10 +4818,19 @@ class SecurityValidator(ValidatorBase):"suggestion": pattern_def.get("suggestion"),"category": category,"confidence": confidence,- "matched_value": match.group(),+ "matched_value": self._reported_value(match),})+ @staticmethod+ def _reported_value(match: re.Match) -> str:+ """Return the value a PII finding identifies for ``match``, before any display redaction.++ A finding's ``evidence_sha256`` and the waiver check both use this value,+ so a change to which part of a match a finding reports belongs here.+ """+ return match.group()+# ------------------------------------------------------------------# LLM finding verification (delegates to skillevaluator.inference.FindingVerifier)# ------------------------------------------------------------------diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex ba4e0ab2..d7e1b5d9 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -1187,6 +1187,14 @@"param_type": "option","type": "boolean"},+ {+ "name": "pii_waivers",+ "opts": [+ "--pii-waivers"+ ],+ "param_type": "option",+ "type": "file"+ },{"choices": ["cli",@@ -1587,6 +1595,14 @@"param_type": "option","type": "boolean"},+ {+ "name": "pii_waivers",+ "opts": [+ "--pii-waivers"+ ],+ "param_type": "option",+ "type": "file"+ },{"choices": ["cli",@@ -1849,6 +1865,14 @@"param_type": "option","type": "file"},+ {+ "name": "pii_waivers",+ "opts": [+ "--pii-waivers"+ ],+ "param_type": "option",+ "type": "file"+ },{"name": "profile","opts": [@@ -1960,6 +1984,14 @@"param_type": "option","type": "file"},+ {+ "name": "pii_waivers",+ "opts": [+ "--pii-waivers"+ ],+ "param_type": "option",+ "type": "file"+ },{"name": "profile","opts": [@@ -3665,6 +3697,14 @@"param_type": "option","type": "file"},+ {+ "name": "pii_waivers",+ "opts": [+ "--pii-waivers"+ ],+ "param_type": "option",+ "type": "file"+ },{"name": "profile","opts": [diff --git a/tests/test_commands.py b/tests/test_commands.pyindex 579f82b9..7d3c6fb2 100644--- a/tests/test_commands.py+++ b/tests/test_commands.py@@ -8,6 +8,7 @@ import jsonimport shutilimport threadingfrom collections.abc import Callable+from datetime import timedeltafrom pathlib import Pathimport pytest@@ -999,6 +1000,157 @@ def test_cli_rejects_invalid_quality_config_as_usage_error(assert "Traceback" not in output+_PII_WAIVER_COMMANDS = {+ "pii-scan": (["pii-scan"], "skillevaluator-pii.json"),+ "tier1-pii-scan": (["tier1", "pii-scan"], "skillevaluator-pii.json"),+ "tier1": (["tier1", "--checks", "pii", "--no-llm"], "skillevaluator-tier1.json"),+ "validate": (+ ["validate", "--no-tier3", "--no-llm", "--no-tier2", "--checks", "pii"],+ "skillevaluator-output-*.json",+ ),+}+++def _pii_waiver_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command: str, *extra_args: str):+ """Run a PII-scanning command on a copy of the fixture with one non-placeholder address in it."""+ from skillevaluator.validators.pii_waivers import pii_evidence_sha256, today_utc++ skill = tmp_path / "simple"+ shutil.copytree(FIXTURE, skill)+ (skill / "contact.md").write_text("# Contact\nWrite to [email protected] for access.\n", encoding="utf-8")+ waiver = {+ "id": "PII-001",+ "category": "emails",+ "file": "simple/contact.md",+ "line": 2,+ "evidence_sha256": pii_evidence_sha256("emails", "[email protected]"),+ "reason": "Public support address of the documented service",+ "owner": "docs-team",+ "created": (today_utc() - timedelta(days=1)).isoformat(),+ "expires": (today_utc() + timedelta(days=300)).isoformat(),+ }+ (tmp_path / "pii-waivers.yaml").write_text(json.dumps({"version": 1, "waivers": [waiver]}), encoding="utf-8")+ monkeypatch.chdir(tmp_path)+ args, report_glob = _PII_WAIVER_COMMANDS[command]++ result = CliRunner().invoke(cli, [*args, "simple", "--report", "json", "--output-dir", "out", *extra_args])++ (report_path,) = (tmp_path / "out").glob(report_glob)+ report = json.loads(report_path.read_text(encoding="utf-8"))+ checks = [finding["check_name"] for entry in report["results"] for finding in entry["findings"]]+ return result, checks++[email protected]("command", list(_PII_WAIVER_COMMANDS))+def test_pii_waivers_option_applies_reviewed_waivers(+ command: str,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ result, checks = _pii_waiver_run(tmp_path, monkeypatch, command, "--pii-waivers", "pii-waivers.yaml")++ assert result.exit_code == 0, result.output+ assert "emails" not in checks+ assert "applied-pii-waiver" in checks++[email protected]("command", list(_PII_WAIVER_COMMANDS))+def test_pii_scan_without_waivers_still_fails(command: str, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ result, checks = _pii_waiver_run(tmp_path, monkeypatch, command)++ assert result.exit_code != 0+ assert "emails" in checks+ assert "applied-pii-waiver" not in checks++[email protected]("command", list(_PII_WAIVER_COMMANDS))+def test_cli_rejects_invalid_pii_waivers_as_usage_error(command: str, tmp_path: Path) -> None:+ waivers = tmp_path / "pii-waivers.yaml"+ waivers.write_text("version: 1\nwaivers:\n - id: PII-001\n category: emails\n", encoding="utf-8")+ args, _report = _PII_WAIVER_COMMANDS[command]++ result = CliRunner().invoke(cli, [*args, str(FIXTURE), "--pii-waivers", str(waivers)])++ output = _plain_text(result.output)+ assert result.exit_code == 2, result.output+ assert "Invalid value for '--pii-waivers'" in output+ assert "waivers[0] is missing: file, line" in output+ assert "Traceback" not in output++[email protected]("symlinked", [False, True], ids=["file", "symlinked-file"])[email protected]("workers", [None, "2"], ids=["serial", "parallel"])+def test_catalog_validate_reports_each_waiver_only_in_its_own_skill(+ workers: str | None,+ symlinked: bool,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """One waiver file serves the catalog; no child may report its siblings' waivers as stale.++ A symlinked waiver file keeps the link's directory as the base of its entries+ in every child, serial or parallel.+ """+ from skillevaluator.validators.pii_waivers import pii_evidence_sha256, today_utc++ names = ("one", "two", "three")+ waivers = []+ for index, name in enumerate(names, 1):+ skill = tmp_path / "catalog" / name+ shutil.copytree(FIXTURE, skill)+ manifest = skill / "SKILL.md"+ manifest.write_text(+ manifest.read_text(encoding="utf-8").replace("name: simple", f"name: {name}"), encoding="utf-8"+ )+ address = f"{name}@company.com"+ (skill / "contact.md").write_text(f"# Contact\nWrite to {address} for access.\n", encoding="utf-8")+ waivers.append(+ {+ "id": f"PII-00{index}",+ "category": "emails",+ "file": f"catalog/{name}/contact.md",+ "line": 2,+ "evidence_sha256": pii_evidence_sha256("emails", address),+ "reason": "Public support address of the documented service",+ "owner": "docs-team",+ "created": (today_utc() - timedelta(days=1)).isoformat(),+ "expires": (today_utc() + timedelta(days=300)).isoformat(),+ }+ )+ waiver_text = json.dumps({"version": 1, "waivers": waivers})+ if symlinked:+ shared = tmp_path.parent / f"{tmp_path.name}-shared"+ shared.mkdir()+ (shared / "pii-waivers.yaml").write_text(waiver_text, encoding="utf-8")+ try:+ (tmp_path / "pii-waivers.yaml").symlink_to(shared / "pii-waivers.yaml")+ except OSError as exc:+ pytest.skip(f"cannot create a symlink here: {exc}")+ else:+ (tmp_path / "pii-waivers.yaml").write_text(waiver_text, encoding="utf-8")+ monkeypatch.chdir(tmp_path)+ args = ["validate", "--no-tier3", "--no-llm", "--no-tier2", "--checks", "pii", "--pii-waivers", "pii-waivers.yaml"]+ if workers:+ args += ["--workers", workers]++ result = CliRunner().invoke(cli, [*args, "catalog", "--report", "json", "--output-dir", "out"])++ assert result.exit_code == 0, result.output+ for index, name in enumerate(names, 1):+ (report_path,) = (tmp_path / "out" / name).glob("skillevaluator-output-*.json")+ report = json.loads(report_path.read_text(encoding="utf-8"))+ dispositions = [+ (finding["check_name"], finding["metadata"]["waiver_id"], finding["file_path"])+ for entry in report["results"]+ for finding in entry["findings"]+ if finding["category"] == "PII_WAIVER"+ ]+ assert dispositions == [("applied-pii-waiver", f"PII-00{index}", "contact.md")], name+ summary = json.loads((tmp_path / "out" / "catalog-summary.json").read_text(encoding="utf-8"))+ assert summary["severity_totals"]["low"] == 0+ assert summary["passed"] == 3++def test_standalone_tier2_rejects_in_skill_report_output_before_validation(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,diff --git a/tests/validators/test_pii_waivers.py b/tests/validators/test_pii_waivers.pynew file mode 100644index 00000000..5424f808--- /dev/null+++ b/tests/validators/test_pii_waivers.py@@ -0,0 +1,541 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Evidence-bound PII waivers.++A waiver accepts one reviewed value at one file and line. It must stop+applying, visibly, when the value, place, category, or review window changes,+and a waiver file that does not load must apply nothing and fail the scan.+"""++from __future__ import annotations++import json+import time+from datetime import date, timedelta+from pathlib import Path++import pytest+import yaml++from skillevaluator.reporting import JSONReporter, SARIFReporter+from skillevaluator.utils.secret_redaction import SENSITIVE_PII_CATEGORIES+from skillevaluator.validators import pii_waivers+from skillevaluator.validators.pii_waivers import PIIWaiver, PIIWaiverSet, pii_evidence_sha256, today_utc+from skillevaluator.validators.security import SecurityValidator++ADDRESS = "[email protected]"+++def _waiver(**overrides: object) -> dict:+ waiver = {+ "id": "PII-001",+ "category": "emails",+ "file": "skill/contact.md",+ "line": 2,+ "evidence_sha256": pii_evidence_sha256("emails", ADDRESS),+ "reason": "Public support address of the documented service",+ "owner": "docs-team",+ "created": (today_utc() - timedelta(days=30)).isoformat(),+ "expires": (today_utc() + timedelta(days=30)).isoformat(),+ }+ waiver.update(overrides)+ return waiver+++def _loaded(**overrides: object) -> dict:+ """Return :class:`PIIWaiver` fields for a waiver built without the loader."""+ waiver = _waiver(**overrides)+ return {+ "waiver_id": waiver.pop("id"),+ **waiver,+ "created": date.fromisoformat(waiver["created"]),+ "expires": date.fromisoformat(waiver["expires"]),+ }+++def _write_waivers(root: Path, *waivers: dict) -> Path:+ path = root / "pii-waivers.yaml"+ path.write_text(yaml.safe_dump({"version": 1, "waivers": list(waivers)}, sort_keys=False), encoding="utf-8")+ return path+++def skill(tmp_path: Path) -> Path:+ skill = tmp_path / "skill"+ skill.mkdir()+ (skill / "contact.md").write_text(f"# Contact\nWrite to {ADDRESS} for access.\n", encoding="utf-8")+ return skill+++def _scan(target: Path, waiver_path: Path | None):+ return SecurityValidator(submitter_usernames=[], pii_waiver_path=waiver_path).validate_pii_only(target)+++def _pii(result) -> list:+ return [finding for finding in result.findings if finding.category == "PII"]+++def _waiver_checks(result) -> list[str]:+ return [finding.check_name for finding in result.findings if finding.category == "PII_WAIVER"]+++def test_pii_finding_reports_the_digest_a_waiver_needs(skill: Path) -> None:+ (finding,) = _pii(_scan(skill, None))++ assert finding.metadata["evidence_sha256"] == pii_evidence_sha256("emails", ADDRESS)+ assert finding.metadata["occurrences"] == [{"file": "contact.md", "line": 2}]+++def test_matching_waiver_suppresses_the_finding_and_stays_visible(skill: Path, tmp_path: Path) -> None:+ result = _scan(skill, _write_waivers(tmp_path, _waiver()))++ assert result.passed+ assert _pii(result) == []+ (applied,) = [finding for finding in result.findings if finding.category == "PII_WAIVER"]+ assert applied.check_name == "applied-pii-waiver"+ assert applied.severity.value == "info"+ # The same path base as the PII findings of the run; the waiver's own path is kept in metadata.+ assert (applied.file_path, applied.line_number) == ("contact.md", 2)+ assert applied.metadata["waiver_file"] == "skill/contact.md"+ assert applied.metadata["waiver_id"] == "PII-001"+ assert applied.metadata["owner"] == "docs-team"+ assert "PII waivers suppressed 1 reviewed PII value(s)" in result.messages+ rendered = JSONReporter(include_timestamp=False).render(result)+ assert ADDRESS not in rendered+ # The waiver file holds the digest; the report identifies the waiver by id and file only.+ assert "evidence_sha256" not in applied.metadata+ assert pii_evidence_sha256("emails", ADDRESS) not in rendered+++ ("content", "overrides"),+ [+ pytest.param(f"# Contact\n\nWrite to {ADDRESS} for access.\n", {}, id="line-moved"),+ pytest.param("# Contact\nWrite to [email protected] for access.\n", {}, id="value-changed"),+ pytest.param(None, {"file": "skill/other.md"}, id="other-file"),+ pytest.param(None, {"category": "phone_numbers"}, id="other-category"),+ ],+)+def test_waiver_stops_applying_when_the_evidence_changes(+ skill: Path,+ tmp_path: Path,+ content: str | None,+ overrides: dict,+) -> None:+ if content is not None:+ (skill / "contact.md").write_text(content, encoding="utf-8")++ result = _scan(skill, _write_waivers(tmp_path, _waiver(**overrides)))++ assert not result.passed+ assert [finding.check_name for finding in _pii(result)] == ["emails"]+ assert _waiver_checks(result) == ["stale-pii-waiver"]+++def test_waiver_for_a_file_outside_the_scan_is_neither_applied_nor_judged(skill: Path, tmp_path: Path) -> None:+ # Relative to the skill, not to the waiver file, so it names tmp_path/contact.md.+ result = _scan(skill, _write_waivers(tmp_path, _waiver(file="contact.md")))++ assert not result.passed+ assert [finding.check_name for finding in _pii(result)] == ["emails"]+ assert _waiver_checks(result) == []+++def test_waived_value_does_not_hide_another_value_on_the_same_line(skill: Path, tmp_path: Path) -> None:+ (skill / "contact.md").write_text(f"# Contact\nWrite to {ADDRESS} or [email protected].\n", encoding="utf-8")++ result = _scan(skill, _write_waivers(tmp_path, _waiver()))++ assert not result.passed+ assert [finding.metadata["matched_value"] for finding in _pii(result)] == ["[email protected]"]+ assert _waiver_checks(result) == ["applied-pii-waiver"]+++def test_expired_waiver_is_reported_and_not_applied(skill: Path, tmp_path: Path) -> None:+ yesterday = (today_utc() - timedelta(days=1)).isoformat()++ result = _scan(skill, _write_waivers(tmp_path, _waiver(expires=yesterday)))++ assert not result.passed+ assert [finding.check_name for finding in _pii(result)] == ["emails"]+ (expired,) = [finding for finding in result.findings if finding.category == "PII_WAIVER"]+ assert (expired.check_name, expired.severity.value) == ("expired-pii-waiver", "medium")+ assert expired.file_path == "contact.md"+++def test_waiver_applies_on_its_expiry_day(skill: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """A waiver applies through ``expires``; the date is pinned so a run crossing UTC midnight cannot flake."""+ monkeypatch.setattr(pii_waivers, "today_utc", lambda: date(2026, 11, 2))++ result = _scan(skill, _write_waivers(tmp_path, _waiver(created="2026-10-01", expires="2026-11-02")))++ assert result.passed+ assert _waiver_checks(result) == ["applied-pii-waiver"]+++def test_waiver_window_may_span_a_year(skill: Path, tmp_path: Path) -> None:+ created = today_utc() - timedelta(days=1)+ waiver = _waiver(created=created.isoformat(), expires=(created + timedelta(days=366)).isoformat())++ result = _scan(skill, _write_waivers(tmp_path, waiver))++ assert result.passed+ assert _waiver_checks(result) == ["applied-pii-waiver"]+++def test_waiver_file_with_chained_merges_is_rejected_without_expanding_them(skill: Path, tmp_path: Path) -> None:+ """A merge bomb in a checked-out waiver file must fail fast instead of stalling the run."""+ anchors = ["a0: &a0 {k: v}"]+ merge = ", ".join(["*a{}"] * 8)+ anchors += [f"a{i}: &a{i} {{<<: [" + merge.format(*[i - 1] * 8) + "]}" for i in range(1, 12)]+ waiver_path = tmp_path / "pii-waivers.yaml"+ waiver_path.write_text("version: 1\nwaivers: []\n" + "\n".join(anchors) + "\n", encoding="utf-8")++ started = time.monotonic()+ loaded = PIIWaiverSet.load(waiver_path, {"emails"}, today=today_utc())++ assert time.monotonic() - started < 5+ assert loaded.error is not None+ assert loaded.waivers == []+++def test_created_may_be_one_day_ahead_of_utc(skill: Path, tmp_path: Path) -> None:+ """A reviewer east of UTC can enter their local date while UTC is still on the day before."""+ tomorrow = (today_utc() + timedelta(days=1)).isoformat()++ result = _scan(skill, _write_waivers(tmp_path, _waiver(created=tomorrow)))++ assert result.passed+ assert _waiver_checks(result) == ["applied-pii-waiver"]+++# Replaced with a real date when the test runs, not when pytest collects the module: a run that+# starts shortly before 00:00 UTC would otherwise leave it only one day ahead, which is allowed.+_IN_TWO_DAYS = "<in-two-days>"+++ ("document", "expected"),+ [+ pytest.param("version: [1\n", "invalid YAML", id="bad-yaml"),+ pytest.param({"version": 2, "waivers": []}, "version must be 1", id="unknown-version"),+ pytest.param({"version": 1, "waivers": [], "extra": True}, "top level", id="unknown-top-level-key"),+ pytest.param("version: 1\nversion: 1\nwaivers: []\n", "duplicate mapping key", id="duplicate-key"),+ pytest.param({"version": 1, "waivers": {}}, "waivers must be a list", id="waivers-not-list"),+ pytest.param([_waiver(note="x")], "unknown field(s): note", id="unknown-field"),+ pytest.param([{k: v for k, v in _waiver().items() if k != "owner"}], "missing: owner", id="missing-field"),+ pytest.param([_waiver(), _waiver()], "used more than once", id="duplicate-id"),+ pytest.param([_waiver(category="nicknames")], "category", id="unknown-category"),+ pytest.param([_waiver(file="/etc/skill/contact.md")], ".file", id="absolute-path"),+ pytest.param([_waiver(file="../skill/contact.md")], ".file", id="parent-traversal"),+ pytest.param([_waiver(file="skill\\contact.md")], ".file", id="backslash-path"),+ pytest.param([_waiver(file="./skill/contact.md")], ".file", id="unnormalized-path"),+ pytest.param([_waiver(file="skill/a\x00b/contact.md")], ".file", id="nul-in-path"),+ pytest.param([_waiver(file="skill/contact.md\n")], ".file", id="control-character-in-path"),+ pytest.param([_waiver(line=0)], ".line", id="line-zero"),+ pytest.param([_waiver(line=True)], ".line", id="line-bool"),+ pytest.param([_waiver(evidence_sha256="abc")], "evidence_sha256", id="short-digest"),+ pytest.param([_waiver(reason="ok")], ".reason", id="short-reason"),+ pytest.param([_waiver(owner=" ")], ".owner", id="blank-owner"),+ pytest.param([_waiver(created="2026-13-01")], ".created", id="bad-date"),+ pytest.param([_waiver(created=_IN_TWO_DAYS)], "in the future", id="created-in-future"),+ pytest.param([_waiver(created="2026-02-01", expires="2026-01-01")], "before created", id="expires-first"),+ pytest.param([_waiver(created="2026-01-01", expires="2027-01-03")], "more than 366 days", id="window-too-long"),+ pytest.param([_waiver(created="2026-01-01", expires="9999-12-31")], "more than 366 days", id="permanent"),+ ],+)+def test_invalid_waiver_file_applies_nothing_and_fails_the_scan(+ skill: Path,+ tmp_path: Path,+ document: object,+ expected: str,+) -> None:+ waiver_path = tmp_path / "private" / "pii-waivers.yaml"+ waiver_path.parent.mkdir()+ if isinstance(document, list):+ in_two_days = (pii_waivers.today_utc() + timedelta(days=2)).isoformat()+ waivers = [{key: in_two_days if value == _IN_TWO_DAYS else value for key, value in w.items()} for w in document]+ document = {"version": 1, "waivers": waivers}+ text = document if isinstance(document, str) else yaml.safe_dump(document, sort_keys=False)+ waiver_path.write_text(text, encoding="utf-8")++ result = _scan(skill, waiver_path)++ assert not result.passed+ assert [finding.check_name for finding in _pii(result)] == ["emails"]+ (invalid,) = [finding for finding in result.findings if finding.category == "PII_WAIVER"]+ assert (invalid.check_name, invalid.severity.value) == ("invalid-pii-waiver-file", "high")+ assert expected in invalid.message+ assert invalid.file_path == "pii-waivers.yaml"+ assert str(tmp_path) not in JSONReporter(include_timestamp=False).render(result)+++ ("waiver_dir", "waiver_file"),+ [+ pytest.param(".", ".claude/skills/foo/SKILL.md", id="through-the-link"),+ pytest.param(".", "skills/foo/SKILL.md", id="link-free-path"),+ pytest.param(".claude", "skills/foo/SKILL.md", id="waiver-file-beside-the-link"),+ ],+)+def test_waiver_through_a_symlinked_skill_directory_applies(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ waiver_dir: str,+ waiver_file: str,+) -> None:+ """A waiver applies wherever it is judged, whichever path to the file it names."""+ _write_skills(tmp_path / "skills", "foo")+ (tmp_path / ".claude" / "skills").mkdir(parents=True)+ try:+ (tmp_path / ".claude" / "skills" / "foo").symlink_to(tmp_path / "skills" / "foo", target_is_directory=True)+ except OSError as exc:+ pytest.skip(f"cannot create a symlink here: {exc}")+ waiver_path = _write_waivers(tmp_path / waiver_dir, _waiver(file=waiver_file, line=5))+ monkeypatch.chdir(tmp_path)++ result = _scan(Path(".claude", "skills", "foo"), waiver_path)++ assert result.passed+ assert _pii(result) == []+ assert _dispositions(result) == [("applied-pii-waiver", "PII-001", "SKILL.md")]+++def test_waiver_whose_file_cannot_be_located_is_not_judged(skill: Path, tmp_path: Path) -> None:+ """A path the OS rejects (here an embedded NUL) is skipped, never a crash of the scan."""+ waivers = PIIWaiverSet(+ path=tmp_path / "pii-waivers.yaml", waivers=[PIIWaiver(**_loaded(file="skill/a\x00b/contact.md"))]+ )+ waivers.cover(skill)++ assert waivers.matcher(skill / "contact.md") is None+ assert waivers.findings(skill) == []+++def _write_skills(root: Path, *names: str, line: str = f"Write to {ADDRESS}.") -> None:+ for name in names:+ (root / name).mkdir(parents=True)+ (root / name / "SKILL.md").write_text(+ f"---\nname: {name}\ndescription: Contact helper\n---\n{line}\n", encoding="utf-8"+ )+++def _dispositions(result) -> list[tuple[str, str, str]]:+ return [+ (finding.check_name, finding.metadata["waiver_id"], finding.file_path)+ for finding in result.findings+ if finding.category == "PII_WAIVER"+ ]+++def test_folder_scan_binds_waivers_to_paths_under_the_waiver_file(tmp_path: Path) -> None:+ root = tmp_path / "skills"+ _write_skills(root, "one", "two")+ waiver_path = _write_waivers(root, _waiver(file="one/SKILL.md", line=5))++ result = _scan(root, waiver_path)++ assert [finding.file_path for finding in _pii(result)] == ["[two] SKILL.md"]+ # Folder runs name the waiver's file the way they name PII findings.+ assert _dispositions(result) == [("applied-pii-waiver", "PII-001", "[one] SKILL.md")]+++def test_run_on_one_skill_judges_only_that_skills_waivers(tmp_path: Path) -> None:+ """One waiver file serves a whole folder; a run on one skill must not call the others stale."""+ root = tmp_path / "skills"+ _write_skills(root, "one", "two", "three")+ yesterday = (today_utc() - timedelta(days=1)).isoformat()+ waiver_path = _write_waivers(+ root,+ _waiver(id="PII-001", file="one/SKILL.md", line=5),+ _waiver(id="PII-002", file="two/SKILL.md", line=5),+ _waiver(id="PII-003", file="three/SKILL.md", line=5, expires=yesterday),+ )++ single = _scan(root / "one", waiver_path)++ assert single.passed+ assert _dispositions(single) == [("applied-pii-waiver", "PII-001", "SKILL.md")]+ folder = _scan(root, waiver_path)+ assert _dispositions(folder) == [+ ("applied-pii-waiver", "PII-001", "[one] SKILL.md"),+ ("applied-pii-waiver", "PII-002", "[two] SKILL.md"),+ ("expired-pii-waiver", "PII-003", "[three] SKILL.md"),+ ]+++def test_waivers_of_skills_a_folder_run_stopped_before_are_not_judged(tmp_path: Path) -> None:+ root = tmp_path / "skills"+ _write_skills(root, "a-critical", line="SSN 219-09-9999 on file.")+ _write_skills(root, "b-contact")+ waiver_path = _write_waivers(root, _waiver(file="b-contact/SKILL.md", line=5))++ result = _scan(root, waiver_path)++ # A CRITICAL finding stops a folder run, so b-contact was never scanned.+ assert [finding.check_name for finding in _pii(result)] == ["ssn"]+ assert _waiver_checks(result) == []+++def test_waiver_for_a_deleted_file_in_the_scan_is_stale(skill: Path, tmp_path: Path) -> None:+ result = _scan(skill, _write_waivers(tmp_path, _waiver(file="skill/removed.md")))++ assert _dispositions(result) == [("stale-pii-waiver", "PII-001", "removed.md")]+++def test_waiver_dispositions_share_the_sarif_location_of_pii_findings(skill: Path, tmp_path: Path) -> None:+ (skill / "contact.md").write_text(f"# Contact\nWrite to {ADDRESS} or [email protected].\n", encoding="utf-8")+ result = _scan(skill, _write_waivers(tmp_path, _waiver()))++ sarif = json.loads(SARIFReporter(include_timestamp=False).render(result))+ uris = {+ entry["ruleId"]: entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"]+ for entry in sarif["runs"][0]["results"]+ }++ assert set(uris.values()) == {"contact.md"}, uris+++def test_waiver_file_inside_the_scanned_tree_is_scanned_like_any_other_file(skill: Path) -> None:+ """A waiver file kept in the skill ships with it, so its own text is PII-scanned."""+ waiver_path = _write_waivers(skill, _waiver(file="contact.md", owner="[email protected]"))++ result = _scan(skill, waiver_path)++ assert not result.passed+ (owner,) = _pii(result)+ assert (owner.file_path, owner.metadata["matched_value"]) == ("pii-waivers.yaml", "[email protected]")+ # The digest, dates, and paths in the file raise nothing; only the owner address does.+ assert _dispositions(result) == [("applied-pii-waiver", "PII-001", "contact.md")]+++ ("category", "content", "value"),+ [+ pytest.param("home_paths", "Logs live in /home/bob/logs.\n", "/home/bob/", id="unrelated-home-directory"),+ pytest.param("credit_cards", "Card 4111 1111 1111 1112 failed.\n", "4111 1111 1111 1112", id="fails-luhn"),+ ],+)+def test_waiver_for_a_value_the_scan_does_not_report_is_stale(+ skill: Path,+ tmp_path: Path,+ category: str,+ content: str,+ value: str,+) -> None:+ (skill / "contact.md").write_text(f"# Contact\n{content}", encoding="utf-8")+ waiver = _waiver(category=category, evidence_sha256=pii_evidence_sha256(category, value))++ result = _scan(skill, _write_waivers(tmp_path, waiver))++ assert result.passed+ assert _pii(result) == []+ assert _waiver_checks(result) == ["stale-pii-waiver"]+++ ("content", "check"),+ [+ pytest.param(+ "Connect with postgres://svc:[email protected]/app now.\n", "database_credentials", id="credential"+ ),+ # The address is also the password, so the emails finding masks it as well.+ pytest.param('password = "[email protected]"\n', "emails", id="value-holding-a-credential"),+ ],+)+def test_masked_values_carry_no_digest(skill: Path, content: str, check: str) -> None:+ """A digest of a masked value would let anyone holding the report test guesses for it offline."""+ (skill / "contact.md").write_text(f"# Database\n{content}", encoding="utf-8")++ (finding,) = [finding for finding in _pii(_scan(skill, None)) if finding.check_name == check]++ assert finding.metadata["matched_value"] == "[REDACTED]"+ assert "evidence_sha256" not in finding.metadata+++ ("contact", "config"),+ [+ pytest.param(f"Write to {ADDRESS} for access.", f'password = "{ADDRESS}"\n', id="credential-elsewhere"),+ pytest.param(f'password = "{ADDRESS}"', None, id="value-became-a-credential"),+ ],+)[email protected]("expires_in", [30, -1], ids=["applied-or-stale", "expired"])+def test_waiver_findings_carry_no_digest(+ skill: Path,+ tmp_path: Path,+ contact: str,+ config: str | None,+ expires_in: int,+) -> None:+ """Once a waived value is masked anywhere, a digest in the report would let readers test guesses offline."""+ (skill / "contact.md").write_text(f"# Contact\n{contact}\n", encoding="utf-8")+ if config is not None:+ (skill / "config.py").write_text(config, encoding="utf-8")+ expires = (today_utc() + timedelta(days=expires_in)).isoformat()++ result = _scan(skill, _write_waivers(tmp_path, _waiver(expires=expires)))++ assert _waiver_checks(result)+ assert pii_evidence_sha256("emails", ADDRESS) not in JSONReporter(include_timestamp=False).render(result)+++def test_digest_is_not_masked_by_a_credential_elsewhere_in_the_skill(skill: Path) -> None:+ """The digest is added after redaction, so a short password that occurs in its hex stays visible there."""+ digest = pii_evidence_sha256("emails", ADDRESS)+ password = next(digest[i : i + 2] for i in range(len(digest) - 1) if digest[i : i + 2].isdigit())+ (skill / "contact.md").write_text(+ f"# Contact\nWrite to {ADDRESS} for access.\nConnect with postgres://svc:{password}@db.internal.corp/app now.\n",+ encoding="utf-8",+ )++ findings = _pii(_scan(skill, None))++ assert "database_credentials" in [finding.check_name for finding in findings]+ (email,) = [finding for finding in findings if finding.check_name == "emails"]+ assert email.metadata["evidence_sha256"] == digest++[email protected]("category", sorted(SENSITIVE_PII_CATEGORIES))+def test_credential_checks_cannot_be_waived(skill: Path, tmp_path: Path, category: str) -> None:+ """Credentials are removed or rotated, never waived, even with a digest computed from the source."""+ value = "postgres://svc:[email protected]"+ (skill / "contact.md").write_text(f"# Database\nConnect with {value}/app now.\n", encoding="utf-8")+ waiver = _waiver(category=category, evidence_sha256=pii_evidence_sha256(category, value))++ result = _scan(skill, _write_waivers(tmp_path, waiver))++ assert not result.passed+ assert [finding.check_name for finding in _pii(result)] == ["database_credentials"]+ (invalid,) = [finding for finding in result.findings if finding.category == "PII_WAIVER"]+ assert invalid.check_name == "invalid-pii-waiver-file"+ assert f"category {category!r} is a credential check and cannot be waived" in invalid.message+++def test_waiver_digest_follows_the_value_findings_report(+ skill: Path,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Waivers hash whatever a finding reports, so narrowing the reported value cannot break them."""+ monkeypatch.setattr(SecurityValidator, "_reported_value", staticmethod(lambda match: match.group().split("@")[0]))+ (finding,) = _pii(_scan(skill, None))+ assert finding.metadata["matched_value"] == "boss"++ result = _scan(skill, _write_waivers(tmp_path, _waiver(evidence_sha256=finding.metadata["evidence_sha256"])))++ assert result.passed+ assert _waiver_checks(result) == ["applied-pii-waiver"]+++def test_waiver_dispositions_are_added_to_json_reports(skill: Path, tmp_path: Path) -> None:+ stale = _waiver(id="PII-002", line=9)+ result = _scan(skill, _write_waivers(tmp_path, _waiver(), stale))++ findings = json.loads(JSONReporter(include_timestamp=False).render(result))["findings"]++ assert sorted((finding["check_name"], finding["metadata"]["waiver_id"]) for finding in findings) == [+ ("applied-pii-waiver", "PII-001"),+ ("stale-pii-waiver", "PII-002"),+ ]diff --git a/tests/validators/test_security.py b/tests/validators/test_security.pyindex 74710d86..eb791c36 100644--- a/tests/validators/test_security.py+++ b/tests/validators/test_security.py@@ -497,6 +497,140 @@ description: A skill documenting REST API endpointsf"API routes should not trigger personal path detection. Findings: {path_findings}")+ @pytest.mark.parametrize(+ ("file_name", "content"),+ [+ pytest.param(+ "SKILL.md",+ "- Saves: `~/.steam/debian-installation/steamapps/compatdata/1086940/pfx/drive_c/users/steamuser/"+ "AppData/Local/Larian Studios/Baldur's Gate 3/PlayerProfiles/Public/Savegames/Story/test.lsv`\n",+ id="markdown-code-span",+ ),+ pytest.param(+ "SKILL.md",+ "Config lives under ~/.local/share/Steam/steamapps/compatdata/1643320/pfx/drive_c/users/"+ "steamuser/AppData/Local/Stalker2.\n",+ id="markdown-prose",+ ),+ pytest.param(+ "collect.sh",+ 'find "${HOME}/.local/share/Steam/steamapps/compatdata/${STEAM_APPID}/pfx/drive_c/'+ 'users/steamuser/Documents/Benchmark Results" -name "*.csv"\n',+ id="shell-quoted-argument",+ ),+ pytest.param(+ "collect.sh",+ 'save_root="${compat_data}/pfx/drive_c/users/steamuser/AppData/Local/Game/Saves"\n',+ id="shell-assignment",+ ),+ pytest.param(+ "collect.py",+ 'SAVES = compat_data / "pfx/drive_c/users/steamuser/AppData/Local/Game"\n',+ id="python-relative-literal",+ ),+ pytest.param("notes.txt", "pfx\\drive_c/Users/steamuser/Documents/save.dat\n", id="backslash-prefix"),+ pytest.param("notes.txt", "[save](PFX/Drive_C/uSeRs/StEaMuSeR/save.dat)\n", id="mixed-case-link"),+ pytest.param(+ "notes.txt",+ 'cd "compatdata/1/pfx/drive_c/users/steamuser/My Games/Saves..old/v1.. final"\n',+ id="dots-inside-folder-names",+ ),+ ],+ )+ def test_proton_virtual_profile_is_not_a_personal_path(self, tmp_path: Path, file_name: str, content: str):+ """Proton names every player's Windows profile ``steamuser``; that path identifies no one."""+ (tmp_path / file_name).write_text(content, encoding="utf-8")++ result = SecurityValidator(submitter_usernames=[]).validate_pii_only(tmp_path)++ assert [f for f in result.findings if f.check_name == "personal_paths"] == []++ @pytest.mark.parametrize(+ ("content", "reported"),+ [+ pytest.param(+ "pfx/drive_c/users/steamuser/AppData and /Users/alice/Documents\n",+ "/Users/alice/",+ id="native-path-on-same-line",+ ),+ pytest.param("/Users/steamuser/Documents/save.dat\n", "/Users/steamuser/", id="native-macos-user"),+ pytest.param("notpfx/drive_c/users/steamuser/save.dat\n", "/users/steamuser/", id="pfx-not-a-component"),+ pytest.param("~/.wine/drive_c/users/steamuser/save.dat\n", "/users/steamuser/", id="wine-prefix"),+ pytest.param("pfx/drive_c/users/labuser/save.dat\n", "/users/labuser/", id="other-user"),+ pytest.param("pfx/drive_c/users/steamuser/../alice/notes\n", "/users/steamuser/", id="traversal"),+ pytest.param(+ "pfx/drive_c/users/steamuser/My Games/../../alice/notes.txt\n",+ "/users/steamuser/",+ id="space-before-traversal",+ ),+ pytest.param(+ '"pfx/drive_c/users/steamuser/Assassin\'s Creed/../../alice/notes.txt"\n',+ "/users/steamuser/",+ id="quote-before-traversal",+ ),+ pytest.param(+ "pfx/drive_c/users/steamuser/%2e%2e%2falice/notes\n", "/users/steamuser/", id="encoded-traversal"+ ),+ pytest.param(+ 'p = "compatdata/1/pfx/drive_c/users/steamuser/" + "../alice/"\n',+ "/users/steamuser/",+ id="concatenated-traversal",+ ),+ pytest.param(+ 'Path("compatdata/1/pfx/drive_c/users/steamuser/") / ".." / "alice"\n',+ "/users/steamuser/",+ id="pathlib-traversal",+ ),+ pytest.param(+ 'os.path.join("compatdata/1/pfx/drive_c/users/steamuser/", "..", "alice")\n',+ "/users/steamuser/",+ id="joined-traversal",+ ),+ pytest.param(+ "cd compatdata/1/pfx/drive_c/users/steamuser/ && cd ../alice\n",+ "/users/steamuser/",+ id="shell-traversal",+ ),+ pytest.param(+ "cd compatdata/1/pfx/drive_c/users/steamuser/ && cd ..&& cd alice\n",+ "/users/steamuser/",+ id="shell-traversal-before-and",+ ),+ pytest.param(+ "cd compatdata/1/pfx/drive_c/users/steamuser/&&cd ..&&cd alice\n",+ "/users/steamuser/",+ id="shell-traversal-unspaced-and",+ ),+ pytest.param(+ "cd compatdata/1/pfx/drive_c/users/steamuser/ &&cd ..&cd alice\n",+ "/users/steamuser/",+ id="shell-traversal-before-background",+ ),+ pytest.param(+ "PATH=compatdata/1/pfx/drive_c/users/steamuser/bin:..:/usr/bin\n",+ "/users/steamuser/",+ id="path-list-traversal",+ ),+ pytest.param("pfx/drive_c/users/\u017fteamuser/save.dat\n", "/users/\u017fteamuser/", id="lookalike"),+ pytest.param("C:\\Users\\steamuser\\Documents\\save.dat\n", "C:\\Users\\steamuser", id="windows-path"),+ ],+ )+ def test_paths_that_are_not_the_proton_profile_stay_reported(self, tmp_path: Path, content: str, reported: str):+ (tmp_path / "notes.md").write_text(content, encoding="utf-8")++ result = SecurityValidator(submitter_usernames=[]).validate_pii_only(tmp_path)++ assert [f.metadata["matched_value"] for f in result.findings if f.check_name == "personal_paths"] == [reported]++ def test_unrelated_home_path_does_not_hide_a_personal_home_path_on_the_line(self, tmp_path: Path):+ """An unrelated home directory is dropped, not a reason to skip the line."""+ (tmp_path / "notes.md").write_text("cp /home/runner/out.txt /home/alice/backup/\n", encoding="utf-8")++ result = SecurityValidator(submitter_usernames=["alice"]).validate_pii_only(tmp_path)++ home_paths = [f.metadata["matched_value"] for f in result.findings if f.check_name == "home_paths"]+ assert home_paths == ["/home/alice/"]+def test_detects_non_placeholder_email(self, tmp_path: Path):"""Test detection of a non-placeholder email address."""skill_dir = tmp_path / "email-skill"