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(ci): add reusable Tier 1 scans and GitHub onboarding (#238)
Narendran Raghavanad4b89534700
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 470abef7..b6246e1f 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -121,7 +121,7 @@ jobs:name: HTML parser compatibility (Python ${{ matrix.python-version }})needs: classify-changesif: ${{ !cancelled() && needs.classify-changes.outputs.docs_only != 'true' }}- # Exact older Python patches have setup-python artifacts for 24.04, not 26.04.+ # These older Python patch releases have setup-python builds for Ubuntu 24.04.runs-on: ubuntu-24.04strategy:fail-fast: falsediff --git a/CHANGELOG.md b/CHANGELOG.mdindex a82405fa..b5915ee3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -37,6 +37,10 @@ All notable changes to SkillEvaluator are documented in this file.- Dependency audits inspect pinned package versions without installing packagesor executing build scripts. Unpinned, URL and other unresolved requirementsreport incomplete coverage instead of executing package resolution.+- The CLI reference now compares the direct `tier1`, `tier2`, and `tier3`+ workflows with `validate --tiers`: which tiers run, Tier 1 dependency and LLM+ stages, report files, and exit codes. It also states that `--tiers` must+ include Tier 1, so Tier 2 or Tier 3 alone runs through its direct workflow.- README and onboarding docs now offer two first-run paths: a lightweight,keyless quality check on a bundled skill, or an NVIDIA Build rubric evaluationwith eligible free prototyping access. Installation adds extras as needed,@@ -55,6 +59,24 @@ All notable changes to SkillEvaluator are documented in this file.- PII credential findings mask their values and source lines. GitHub CI stagesscanner output privately, redacts recognized credential values from retainedreports and logs, and withholds detailed output when redaction cannot finish.+- Local Claude Code trials retain Harbor's instruction environment variables so+ prompts reach `claude --print`. The exception accepts only the legacy+ `HARBOR_INSTRUCTION` name and Claude Code's UUID-named instruction variable;+ protected paths, loader controls, and unrelated Harbor variables retain their+ existing filtering ([#245](https://github.com/NVIDIA/SkillEvaluator/issues/245)).++- Tier 3 reports preserve unavailable evaluator lift as `null` when no baseline+ ran, rather than reporting a measured zero. CLI evaluator tables display+ missing or unavailable scores as `n/a` without interrupting JSON and HTML+ report generation; measured zeroes retain their numeric formatting+ ([#240](https://github.com/NVIDIA/SkillEvaluator/issues/240)).++- Explicit searches of `/` (`find`, `grep -r`, `rg`, `ag`, `du` and `tree` with a+ `/` operand, and native search tools rooted at `/`) now count as wasted tool+ calls whether or not they name the expected skill or script, including when+ output is redirected or the search runs inside `sh -c`. Host and bundled+ scoring agree, while scoped searches and slash-valued patterns retain their+ classification.- PII email scans recognize all RFC 2606 reserved domains, including theirsubdomains, mixed-case forms, trailing dots, and prose ellipses. A local-partboundary prevents quadratic rescanning of long excluded addresses. Ordinarydiff --git a/ci/README.md b/ci/README.mdindex d97a6ff8..a18924b8 100644--- a/ci/README.md+++ b/ci/README.md@@ -53,17 +53,19 @@ Artifacts expire after the configured retention period;hosted history is an optional separate surface. Quality scores are not scannerpass percentages or proof of useful live-agent behavior.-Before scanning, CI collects values matched by the bundled credential patterns-across the selected skills. Raw scanner files stay in private temporary storage;-recognized values are removed from retained reports and annotations. When a-credential or an LLM key is present, raw scanner logs are withheld; the-structured reports remain available. The preflight is bounded to 10,000 files,-32 MiB per file, 128 MiB per skill and 8,192 characters per line, with bounded-redaction values. If it cannot safely inspect or redact the input, the run-reports an error without publishing detailed scan output. This is not a-guarantee that every credential or transformed value is detected. Remove and-rotate exposed credentials; reports and Git history from previous runs are not-rewritten automatically.+Before scanning, CI collects values matched by the bundled credential patterns,+NVIDIA API keys, and unquoted `KEY=value` and `Bearer` credentials across the+selected skills. Raw scanner files stay in private temporary storage. Recognized+values, parts of them cut or escaped by a scanner, and database URL passwords+are removed from retained reports and annotations. Retained Markdown and SARIF+are rendered from the redacted JSON. When a credential or an LLM key is present,+raw scanner logs are withheld; the structured reports remain available. The+preflight is bounded to 10,000 files, 32 MiB per file, 128 MiB per skill and+8,192 characters per line, with bounded redaction values. If it cannot safely+inspect or redact the input, the run reports an error without publishing+detailed scan output. This is not a guarantee that every credential or+transformed value is detected. Remove and rotate exposed credentials; reports+and Git history from previous runs are not rewritten automatically.## Optional hosted reports and PR feedbackdiff --git a/ci/publish_reports.py b/ci/publish_reports.pyindex 57ea7fa1..5bdfd403 100644--- a/ci/publish_reports.py+++ b/ci/publish_reports.py@@ -528,17 +528,44 @@ def _caller_blob(api, repository: str, sha: str) -> str:return caller["sha"]+def _fork_associations(api, repository: str, run: dict) -> list:+ """Find an open fork PR from API run metadata; GitHub never records it on the run."""+ head_repository = run.get("head_repository")+ if head_repository is None:+ raise StalePublication("The fork for this PR run was deleted, so the run cannot be verified.")+ name = head_repository.get("full_name") if isinstance(head_repository, dict) else None+ if name == repository:+ raise StalePublication("The PR is closed or no longer associated with this run.")+ branch = run.get("head_branch")+ if not isinstance(name, str) or REPO_PATTERN.fullmatch(name) is None or not isinstance(branch, str) or not branch:+ raise PublicationError("The PR run lacks a valid head repository and branch.")+ head = urllib.parse.quote(name.split("/", 1)[0], safe="") + ":" + urllib.parse.quote(branch, safe="")+ pulls = api.get(f"/repos/{repository}/pulls?state=open&head={head}&per_page=100")+ if not isinstance(pulls, list) or any(not isinstance(pr, dict) for pr in pulls):+ raise PublicationError("The fork PR run has an unsupported pull request listing.")+ matches = [+ pr+ for pr in pulls+ if ((pr.get("head") or {}).get("repo") or {}).get("full_name") == name+ and ((pr.get("base") or {}).get("repo") or {}).get("full_name") == repository+ ]+ if not matches:+ raise StalePublication("The fork PR is closed or merged; no open PR uses this run's fork branch.")+ return matches++def _executed_caller_blob(api, repository: str, run: dict) -> str:"""Reconstruct unambiguous PR merge content from GitHub-recorded revisions.The run API exposes the PR head, not GITHUB_WORKFLOW_SHA. Never accept amerge revision asserted by an artifact or the PR's current mutable ref.+ Fork runs have no recorded PR, so the PR API supplies the same revisions."""if run["event"] != "pull_request":return _caller_blob(api, repository, run["head_sha"])associations = run.get("pull_requests")if associations == []:- raise StalePublication("The PR is closed or no longer associated with this run.")+ associations = _fork_associations(api, repository, run)if not isinstance(associations, list) or len(associations) != 1:raise PublicationError("The PR run lacks an unambiguous recorded base revision; update the branch and rerun.")association = associations[0]diff --git a/ci/run_tier1.py b/ci/run_tier1.pyindex 82670f02..cf2297b2 100644--- a/ci/run_tier1.py+++ b/ci/run_tier1.py@@ -31,6 +31,11 @@ try:except ModuleNotFoundError:from ci.native_reports import render_native_reports+try:+ from publish_reports import PublicationError, validate_report+except ModuleNotFoundError:+ from ci.publish_reports import PublicationError, validate_report+try:from report_views import finding_repository_path, render_reportsexcept ModuleNotFoundError:@@ -77,7 +82,13 @@ def discover_skills(workspace: Path, roots: str) -> list[Path]:discovered: set[Path] = set()for raw in configured:relative = Path(raw)- if relative.is_absolute() or ".." in relative.parts or "\\" in raw or ":" in raw:+ if (+ relative.is_absolute()+ or ".." in relative.parts+ or "\\" in raw+ or ":" in raw+ or any(ord(character) < 32 or ord(character) == 127 for character in raw)+ ):raise ConfigurationError("Skill roots must be relative directories without parent traversal.")current = workspacefor part in relative.parts:@@ -458,9 +469,17 @@ def run(for result in data["results"]))- if not row["passed"] and row["overall_status"] == "passed":+ try:+ # The publisher rejects the whole artifact for one contradictory+ # report. Check it the same way here so only this skill is lost.+ validate_report(data, row)+ consistent = True+ except PublicationError:+ consistent = False+ if not consistent or (not row["passed"] and row["overall_status"] == "passed"):row["overall_status"] = "error"row["incomplete_scans"] = []+ row["passed"] = Falserow["error"] = "Process exit or validator results contradict the report verdict."else:row.pop("error", None)diff --git a/ci/secret_redaction.py b/ci/secret_redaction.pyindex 3395920b..286d50ef 100644--- a/ci/secret_redaction.py+++ b/ci/secret_redaction.py@@ -11,6 +11,8 @@ import osimport refrom pathlib import Path+from skillevaluator.reporting import MarkdownReporter, SARIFReporter+from skillevaluator.reporting.retained import retained_resultsfrom skillevaluator.utils.secret_redaction import SENSITIVE_PII_CATEGORIES, Redactor, sensitive_valuesfrom skillevaluator.utils.secure_fs import SecureRootfrom skillevaluator.validators.security import SecurityValidator@@ -21,6 +23,18 @@ MAX_FILES = 10000MAX_TOKENS = 4096MAX_TOKEN_BYTES = 1024 * 1024MAX_LINE_CHARS = 8192+# The PII patterns need a quoted value. Also collect NVIDIA API keys and the+# unquoted KEY=value and Bearer forms. Such a value must contain letters and+# digits, so ordinary words and variable names are not collected. Lengths are+# bounded to limit backtracking and to stay within the redaction limits.+NVIDIA_API_KEY = re.compile(r"\bnvapi-[A-Za-z0-9_-]{40,250}")+UNQUOTED_VALUES = (+ re.compile(+ r"(?i)(?:secret|password|passwd|pwd|api[-_]?key|apikey|auth[-_]?token)\w{0,64}\s*[=:]\s*"+ r"([A-Za-z0-9_+-][A-Za-z0-9_+/=-]{15,255})(?=[\s\"'`;&|,)\]}]|$)"+ ),+ re.compile(r"(?i)\bbearer\s+([A-Za-z0-9_+-][A-Za-z0-9_+/=.~-]{15,255})(?=[\s\"'`;&|,)\]}]|$)"),+)def collect_sensitive_values(skill: Path) -> set[str]:@@ -53,7 +67,10 @@ def collect_sensitive_values(skill: Path) -> set[str]:if raw.startswith((b"\xff\xfe", b"\xfe\xff"))else raw.decode("utf-8-sig", errors="ignore"))- for line in text.splitlines():+ # Split lines as the scanners read them, on newlines only.+ # str.splitlines() also splits on characters such as U+2028 and+ # form feed, which can sit inside a quoted credential.+ for line in re.split(r"\r\n?|\n", text):# Some PII patterns can backtrack heavily on very long input.# Refuse the scan before applying them to unbounded lines.if len(line) > MAX_LINE_CHARS:@@ -61,6 +78,14 @@ def collect_sensitive_values(skill: Path) -> set[str]:for category, pattern, _exceptions, _definition in patterns:for match in pattern.finditer(line):tokens.update(sensitive_values(category, match.group(), line))+ tokens.update(NVIDIA_API_KEY.findall(line))+ for pattern in UNQUOTED_VALUES:+ tokens.update(+ value+ for value in pattern.findall(line)+ if any(character.isdigit() for character in value)+ and any(character.isalpha() for character in value)+ )if "PRIVATE KEY-----" in text:blocks = re.findall(r"-----BEGIN [^\r\n]*PRIVATE KEY-----[\s\S]*?-----END [^\r\n]*PRIVATE KEY-----", text@@ -92,6 +117,7 @@ def sanitized_outputs(raw: Path, tokens: set[str]) -> dict[str, bytes]:sanitized = {}total = 0redactor = Redactor(tokens)+ document = Nonewith SecureRoot(raw) as root:for name in allowed:path = raw / name@@ -106,9 +132,23 @@ def sanitized_outputs(raw: Path, tokens: set[str]) -> dict[str, bytes]:b"Raw scanner log withheld while credential redaction is active. See the structured reports.\n")continue+ if name in {"skillevaluator-tier1.md", "skillevaluator-tier1.sarif.json"}:+ # These files cut and escape text, so a value can survive a+ # literal search. Render them from the redacted JSON instead.+ if document is None:+ raise ValueError("The evaluator did not produce JSON evidence.")+ try:+ results = retained_results(document)+ except ValueError:+ # The runner rejects this JSON next; keep the other evidence.+ continue+ reporter = MarkdownReporter() if name.endswith(".md") else SARIFReporter()+ sanitized[name] = reporter.render_all(results).encode("utf-8")+ continuetext = content.decode("utf-8")if name.endswith(".json"):- text = json.dumps(redactor.object(json.loads(text)), ensure_ascii=True, allow_nan=False, indent=2)+ document = redactor.object(json.loads(text))+ text = json.dumps(document, ensure_ascii=True, allow_nan=False, indent=2)else:text = redactor.text(text)sanitized[name] = text.encode("utf-8")diff --git a/docs/github-actions.mdx b/docs/github-actions.mdxindex 4bb2bace..4f222d17 100644--- a/docs/github-actions.mdx+++ b/docs/github-actions.mdx@@ -67,11 +67,13 @@ detailed Markdown, SARIF and scanner logs. Failed and incomplete scans retaintheir available reports; missing evidence is not a pass. Quality scores and thepass/fail decision are separate.-Known credential values detected by the PII patterns are redacted from CI-reports. When a credential or an LLM key is present, raw scanner logs are-withheld. This is not a guarantee that every possible credential or-transformed value will be detected. Remove and rotate exposed credentials;-previously published reports and Git history are not retroactively redacted.+Known credential values detected by the PII patterns, NVIDIA API keys, and+unquoted `KEY=value` and `Bearer` credentials are redacted from CI reports,+including parts of them that a scanner cuts or escapes. When a credential or an+LLM key is present, raw scanner logs are withheld. This is not a guarantee that+every possible credential or transformed value will be detected. Remove and+rotate exposed credentials; previously published reports and Git history are not+retroactively redacted.The dedicated workflow runs independently alongside existing build and testworkflows. It does not automatically wait for them. GitHub's `needs` connectsdiff --git a/src/skillevaluator/utils/secret_redaction.py b/src/skillevaluator/utils/secret_redaction.pyindex be05c185..f541a077 100644--- a/src/skillevaluator/utils/secret_redaction.py+++ b/src/skillevaluator/utils/secret_redaction.py@@ -8,6 +8,7 @@ from __future__ import annotationsimport htmlimport jsonimport re+from itertools import groupbyfrom urllib.parse import quote, unquote, urlsplitSENSITIVE_PII_CATEGORIES = frozenset(@@ -22,6 +23,14 @@ SENSITIVE_PII_CATEGORIES = frozenset(})REDACTED = "[REDACTED]"+REPEATED_REDACTED = re.compile(f"(?:{re.escape(REDACTED)}){{2,}}")+# Snippets can cut a database URL before the "@" that ends its credentials,+# and a short password only matches as a whole value. Mask user:password after+# a database scheme even when the text ends inside it. A bare port is kept.+DATABASE_USERINFO = re.compile(+ r"(?i)\b((?:postgres(?:ql)?|mysql|mariadb|mongodb|rediss?)(?:\+\w+)?://)"+ r"[^\s/?#@:\"'`<>]*:(?:[^\s/?#@\"'`<>]+(?=@)|(?!\d*$)[^\s/?#@\"'`<>]+$)"+)def sensitive_values(category: str, matched: str, line: str = "") -> set[str]:@@ -45,22 +54,60 @@ def sensitive_values(category: str, matched: str, line: str = "") -> set[str]:return {value for value in values if value}+def _invisible(character: str) -> bool:+ # The Unicode check echoes these characters as U+2423 in line content.+ return not character.isprintable() and character not in " \t\r\n"+++def _visible_forms(token: str) -> set[str]:+ """Add the forms another check can echo for a value with invisible characters."""+ if not any(_invisible(character) for character in token):+ return {token}+ visible = "".join(character for character in token if not _invisible(character))+ if len(visible) < 8:+ return {token}+ forms = {token, visible, "".join("\u2423" if _invisible(character) else character for character in token)}+ pieces = ("".join(group) for hidden, group in groupby(token, key=_invisible) if not hidden)+ forms.update(piece for piece in pieces if len(piece) >= 8)+ return forms+++def _password_tails(token: str) -> set[str]:+ """Return the ends of a short URL password, each with the "@" after it."""+ try:+ password = urlsplit(token).password if "://" in token else None+ except ValueError:+ return set()+ # Upstream text can start inside the password and cut off the scheme, so+ # DATABASE_USERINFO does not match. A password shorter than 16 characters+ # has no partial values, but the "@" after it still marks its end.+ if not password or len(password) >= 16:+ return set()+ return {password[start:] + "@" for start in range(1, len(password) - 7)}++def variants(tokens: set[str]) -> tuple[str, ...]:- """Include encoded values and truncated prefixes of credential literals."""+ """Include encoded values and truncated parts of credential literals."""encoded: set[str] = set()pattern_size = 0- for token in tokens:+ tails = {tail for value in tokens for tail in _password_tails(value)}+ for token in {form for value in tokens for form in _visible_forms(value)} | tails:forms = {token,html.escape(token),html.escape(token, quote=False),json.dumps(token)[1:-1],quote(token, safe=""),+ html.escape(token, quote=False).replace("|", "|").replace("`", "`"),}context = (- "://" in token+ # A password tail is matched only as a whole value.+ token in tails+ or "://" in tokenor token.startswith("-----BEGIN ")or re.match(r"(?i)^(?:secret|password|passwd|pwd|api[-_]?key|apikey|auth[-_]?token|bearer)\s*[=:]", token)+ # A connection string match holds ordinary words; its password is collected separately.+ or token.lower().endswith("password="))for value in forms:candidates = [value]@@ -68,6 +115,11 @@ def variants(tokens: set[str]) -> tuple[str, ...]:if len(value) > 512:raise ValueError("A credential is too long for safe partial-value redaction.")candidates.extend(value[:length] for length in range(5, len(value)))+ # Upstream text can also start inside a value, or start and end+ # inside it. Match every window of 8 characters and suffixes of 8+ # to 15, so no fragment of 8 or more characters is left.+ candidates.extend(value[-length:] for length in range(8, 16))+ candidates.extend(value[start : start + 8] for start in range(len(value) - 7))for candidate in candidates:if candidate not in encoded:pattern_size += len(candidate)@@ -86,10 +138,19 @@ class Redactor:values = variants(tokens)if sum(len(value) for value in values) > 1024 * 1024:raise ValueError("Credential redaction patterns exceed their limit.")- self.pattern = re.compile("|".join(re.escape(value) for value in values)) if values else None+ # Group values by first character so that windows starting with any+ # character stay fast to scan. The longest value in a group wins.+ groups: dict[str, list[str]] = {}+ for value in values:+ groups.setdefault(value[0], []).append(re.escape(value[1:]))+ alternatives = (re.escape(first) + "(?:" + "|".join(rest) + ")" for first, rest in groups.items())+ self.pattern = re.compile("|".join(alternatives)) if values else Nonedef text(self, text: str) -> str:- return self.pattern.sub(REDACTED, text) if self.pattern else text+ if self.pattern:+ # Windows of one value are replaced one at a time; show one marker.+ text = REPEATED_REDACTED.sub(REDACTED, self.pattern.sub(REDACTED, text))+ return DATABASE_USERINFO.sub(lambda match: match.group(1) + REDACTED, text)def object(self, value: object) -> object:if isinstance(value, str):diff --git a/tests/ci/test_publish_reports.py b/tests/ci/test_publish_reports.pyindex 16efa7b4..2d5963a3 100644--- a/tests/ci/test_publish_reports.py+++ b/tests/ci/test_publish_reports.py@@ -325,12 +325,34 @@ def run_record():}+def fork_record(**changes):+ # GitHub never fills pull_requests for a run from a fork PR.+ return {+ **run_record(),+ "event": "pull_request",+ "head_branch": "feature/fork",+ "head_repository": {"full_name": "contributor/consumer"},+ **changes,+ }+++def fork_pull(head_sha="a" * 40, *, base_sha="d" * 40, repo=None):+ return {+ "number": 7,+ "state": "open",+ "head": {"sha": head_sha, "repo": repo or {"full_name": "contributor/consumer"}},+ "base": {"sha": base_sha, "repo": {"full_name": "owner/consumer"}},+ }++class FakeAPI:def __init__(self, *, branch_sha="a" * 40, record=None):self.record = record or run_record()self.branch_sha = branch_sha+ self.paths = []def get(self, path):+ self.paths.append(path)if path.endswith("/actions/runs/123/attempts/1"):return self.recordif "/contents/.github/workflows/skill-checks.yml?ref=" in path:@@ -357,9 +379,11 @@ class FakeAPI:return {"number": 1,"state": "open",- "head": {"sha": self.branch_sha, "repo": {"full_name": "owner/consumer"}},+ "head": {"sha": self.branch_sha, "repo": self.record.get("head_repository")},"base": {"repo": {"full_name": "owner/consumer"}},}+ if "/pulls?state=open&head=" in path:+ return [fork_pull(self.branch_sha, repo=self.record.get("head_repository"))]if path.endswith("/pulls"):return [{"number": 1}]raise AssertionError(path)@@ -595,6 +619,26 @@ def test_pr_caller_does_not_trust_missing_or_current_mutable_base():publisher._executed_caller_blob(FakeAPI(), "owner/consumer", {**run_record(), "event": "pull_request"})+def test_open_fork_pr_run_is_published_without_alias_or_comment(tmp_path):+ api = FakeAPI(record=fork_record())+ metadata = publisher.publish(+ api,+ "owner/consumer",+ 123,+ "https://owner.github.io/consumer",+ tmp_path / "site",+ tmp_path / "output",+ render=fake_render,+ )+ assert metadata["pr_number"] == ""+ assert metadata["is_current"] == "false"+ assert (tmp_path / "site/runs/123/1/index.html").is_file()+ assert not (tmp_path / "site/pr").exists()+ assert [item["run_id"] for item in json.loads((tmp_path / "site/history.json").read_text())] == [123]+ # The fork PR is found from API run metadata, never from artifact data.+ assert "/repos/owner/consumer/pulls?state=open&head=contributor:feature%2Ffork&per_page=100" in api.paths++def test_history_retention_preserves_current_main_and_open_pr_and_prunes_closed(tmp_path):history = []for number in range(1, 6):@@ -1000,10 +1044,45 @@ def test_explicit_fork_evaluator_identity_is_required(monkeypatch):publisher._validate_workflow_provenance(FakeAPI(), "owner/consumer", record)[email protected]("association", [[], [{"base": {"sha": "d" * 40}, "head": {"sha": "e" * 40}}]])-def test_stale_or_closed_pr_is_a_skipped_publisher_run(tmp_path, monkeypatch, association):- record = {**run_record(), "event": "pull_request", "pull_requests": association}- monkeypatch.setattr(publisher, "GitHubAPI", lambda *_args: FakeAPI(record=record))+class ForkLookupAPI(FakeAPI):+ def __init__(self, pulls, **kwargs):+ super().__init__(**kwargs)+ self.pulls = pulls++ def get(self, path):+ if "/pulls?state=open&head=" in path:+ self.paths.append(path)+ return self.pulls+ return super().get(path)+++ "record,pulls,reason",+ [+ pytest.param(+ {**run_record(), "event": "pull_request"},+ None,+ "The PR is closed or no longer associated",+ id="same-repo-pr-merged-after-scan",+ ),+ pytest.param(+ {+ **run_record(),+ "event": "pull_request",+ "pull_requests": [{"base": {"sha": "d" * 40}, "head": {"sha": "e" * 40}}],+ },+ None,+ "The PR head moved",+ id="same-repo-push-during-scan",+ ),+ pytest.param(fork_record(), [], "The fork PR is closed or merged", id="fork-pr-closed-after-scan"),+ pytest.param(fork_record(), [fork_pull("e" * 40)], "The PR head moved", id="fork-push-during-scan"),+ pytest.param(fork_record(head_repository=None), None, "fork for this PR run was deleted", id="deleted-fork"),+ ],+)+def test_stale_or_closed_pr_is_a_skipped_publisher_run(tmp_path, monkeypatch, record, pulls, reason):+ api = ForkLookupAPI(pulls, record=record)+ monkeypatch.setattr(publisher, "GitHubAPI", lambda *_args: api)for key, value in {"GH_TOKEN": "dummy-token","GITHUB_REPOSITORY": "owner/consumer",@@ -1018,7 +1097,42 @@ def test_stale_or_closed_pr_is_a_skipped_publisher_run(tmp_path, monkeypatch, asassert publisher.main() == 0assert "skipped=true" in (tmp_path / "github-output").read_text()assert "skipped" in (tmp_path / "output/summary.md").read_text().lower()+ assert reason in (tmp_path / "output/summary.md").read_text()assert not (tmp_path / "site/runs").exists()+ # Only a fork run with a known head repository looks up its PR.+ assert any("/pulls?" in path for path in api.paths) == (pulls is not None)+++ "record,pulls",+ [+ pytest.param({**run_record(), "event": "pull_request", "pull_requests": None}, None, id="same-repo-missing"),+ pytest.param(+ {+ **run_record(),+ "event": "pull_request",+ "pull_requests": [{"base": {"sha": "d" * 40}, "head": {"sha": "a" * 40}}] * 2,+ },+ None,+ id="same-repo-two-prs",+ ),+ pytest.param(+ {**run_record(), "event": "pull_request", "pull_requests": [{"base": {"sha": "d" * 40}, "head": {}}]},+ None,+ id="same-repo-malformed-head",+ ),+ pytest.param(fork_record(pull_requests=None), None, id="fork-missing"),+ pytest.param(fork_record(head_repository="contributor/consumer"), None, id="fork-malformed-head-repository"),+ pytest.param(fork_record(head_branch=None), None, id="fork-missing-branch"),+ pytest.param(fork_record(), {"items": []}, id="fork-malformed-listing"),+ pytest.param(fork_record(), [fork_pull(), fork_pull()], id="fork-two-prs"),+ pytest.param(fork_record(), [fork_pull(base_sha="main")], id="fork-malformed-base"),+ ],+)+def test_malformed_pr_association_still_fails(record, pulls):+ with pytest.raises(publisher.PublicationError) as raised:+ publisher._validate_workflow_provenance(ForkLookupAPI(pulls, record=record), "owner/consumer", record)+ assert not isinstance(raised.value, publisher.StalePublication)@pytest.mark.parametrize("enabled", [True, False, None])diff --git a/tests/ci/test_run_tier1.py b/tests/ci/test_run_tier1.pyindex 0e3d87b8..fdd542a9 100644--- a/tests/ci/test_run_tier1.py+++ b/tests/ci/test_run_tier1.py@@ -102,9 +102,52 @@ def test_contradictory_passing_report_with_incomplete_scanners_has_publishable_eassert children == {}[email protected]("root", ["/etc", "../skills", "skills/../other", "C:\\skills", "skills\\a"])+ "exit_code,status,changes",+ [+ (1, "failed", {"incomplete_scans": ["semgrep"]}),+ (0, "failed", {}),+ (1, "incomplete", {"incomplete_scans": []}),+ (1, "incomplete", {"incomplete_scans": ["trivy"]}),+ (0, "incomplete", {}),+ (0, "passed", {"total_errors": 1}),+ ],+)+def test_any_contradictory_report_becomes_error_row_without_losing_other_skills(tmp_path, exit_code, status, changes):+ import ci.publish_reports as publisher++ workspace = tmp_path / "workspace"+ skill(workspace, "skills/a")+ skill(workspace, "skills/b")+ report = {**payload(status == "passed", status), **changes}+ reports = tmp_path / "reports"+ runner.run(+ workspace,+ reports,+ {"SKILL_PATHS": "skills", "LLM_ENABLED": "false"},+ execute=fake_cli([(exit_code, report), (0, payload())], []),+ )+ summary = json.loads((reports / "summary.json").read_text())+ assert [row["overall_status"] for row in summary["skills"]] == ["error", "passed"]+ assert summary["skills"][0]["incomplete_scans"] == []+ assert summary["skills"][0]["passed"] is False+ artifact = io.BytesIO()+ with zipfile.ZipFile(artifact, "w") as archive:+ for path in sorted(reports.rglob("*.json")):+ archive.write(path, path.relative_to(reports).as_posix())+ retained, children = publisher.read_artifact(artifact.getvalue())+ assert [row["overall_status"] for row in retained["skills"]] == ["error", "passed"]+ assert list(children) == ["skill-002"]+ assert "Report unavailable" in (reports / "skill-001/skillevaluator-tier1.html").read_text()+++ "root", ["/etc", "../skills", "skills/../other", "C:\\skills", "skills\\a", "sk\tills", "skills/m\x7fskill"]+)def test_rejects_unsafe_roots(tmp_path, root):- with pytest.raises(runner.ConfigurationError):+ skill(tmp_path, "sk\tills/a")+ skill(tmp_path, "skills/m\x7fskill")+ with pytest.raises(runner.ConfigurationError, match="without parent traversal"):runner.discover_skills(tmp_path, root)@@ -370,11 +413,12 @@ def test_incomplete_runtime_rollup_is_not_mislabeled_as_inconsistent_evidence(tmworkspace,reports,{"SKILL_PATHS": "skills"},- execute=fake_cli([(1, payload(True, "incomplete", ["semgrep"]))], []),+ execute=fake_cli([(1, payload(False, "incomplete", ["semgrep"]))], []),)== 1)summary = json.loads((reports / "summary.json").read_text())+ assert summary["skills"][0]["overall_status"] == "incomplete"assert (summary["failed"], summary["incomplete"]) == (1, 1)compact = (reports / "summary.md").read_text()assert "**Tier 1 scan result: INCOMPLETE**" in compactdiff --git a/tests/ci/test_secret_redaction.py b/tests/ci/test_secret_redaction.pyindex 8357d723..4453f20f 100644--- a/tests/ci/test_secret_redaction.py+++ b/tests/ci/test_secret_redaction.py@@ -355,3 +355,257 @@ def test_database_password_is_collected_in_decoded_form():matched = "postgres://user:encoded%[email protected]/db"assert "encoded/password" in sensitive_values("database_credentials", matched)+++def _assert_no_fragment(value: str | bytes, secret: str) -> None:+ text = value.decode() if isinstance(value, bytes) else value+ # Upstream text can start, end or be escaped inside a value. No window of+ # eight characters may remain in any encoding that a report uses.+ for start in range(len(secret) - 7):+ window = secret[start : start + 8]+ forms = {+ window,+ html.escape(window),+ json.dumps(window)[1:-1],+ quote(window, safe=""),+ html.escape(window, quote=False).replace("|", "|").replace("`", "`"),+ }+ if any(form in text for form in forms):+ pytest.fail("A fragment of a synthetic credential was present in a shared output.")+++def _publish(tmp_path: Path, monkeypatch, reports: Path) -> tuple[Path, Path]:+ spec = importlib.util.spec_from_file_location("publisher_fixtures", ROOT / "tests/ci/test_publish_reports.py")+ fixtures = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(fixtures)+ archive = io.BytesIO()+ with zipfile.ZipFile(archive, "w") as zipped:+ for path in reports.rglob("*"):+ if path.is_file():+ zipped.write(path, path.relative_to(reports).as_posix())++ class ArtifactAPI(fixtures.FakeAPI):+ def download_artifact(self, _artifact_id):+ return archive.getvalue()++ monkeypatch.setenv("TRUSTED_EVALUATOR_SHA", "c" * 40)+ monkeypatch.setenv("TRUSTED_CALLER_BLOBS", "b" * 40)+ monkeypatch.syspath_prepend(str(ROOT / "ci"))+ site, feedback = tmp_path / "site", tmp_path / "feedback"+ fixtures.publisher.publish(+ ArtifactAPI(record={**fixtures.run_record(), "conclusion": "failure"}),+ "owner/consumer",+ 123,+ "https://owner.github.io/consumer",+ site,+ feedback,+ )+ return site, feedback+++def test_redactor_masks_values_that_upstream_text_cuts_or_escapes():+ from skillevaluator.utils.secret_redaction import Redactor++ value = "nvapi-" + "Qx7" * 16+ password = "Rt5" * 4 + "|" + "Wm8`" * 3+ redactor = Redactor({value, password})+ cell = html.escape(password, quote=False).replace("|", "|").replace("`", "`")+ for text in (+ # A context window that starts inside a value.+ "window: " + value[3:] + '"\nWEBHOOK = "https://hooks.example.invalid/x"',+ # A window that starts inside a value and is then cut again.+ "excerpt " + value[9:41] + "...",+ json.dumps({"snippet": value[13:]}),+ "| " + cell + " |",+ ):+ safe = redactor.text(text)+ _assert_no_fragment(safe, value)+ _assert_no_fragment(safe, password)+ ordinary = "Dangerous code execution: subprocess.run(cmd, shell=True) in scripts/run.py"+ assert redactor.text(ordinary) == ordinary+++def test_redactor_masks_database_userinfo_when_the_text_ends_inside_it():+ from skillevaluator.utils.secret_redaction import Redactor++ password = "Kp4" * 4+ for redactor in (Redactor({password}), Redactor(set())):+ safe = redactor.text(' url = "postgresql://svc:' + password[:10])+ if password[:6] in safe or "postgresql://" not in safe:+ pytest.fail("A cut database password was not masked.")+ ordinary = [+ "postgresql://db.local:5432/app",+ 'DSN = "postgresql://db.local:5432"',+ "mysql://[email protected]/app",+ "https://user.example.invalid:8443/path",+ ]+ assert [Redactor(set()).text(text) for text in ordinary] == ordinary+ # The connection string match is not a secret; its words stay readable.+ connection = Redactor({'conn_string = "Server=db.local;password='})+ assert connection.text("Hardcoded password in a connection string") == "Hardcoded password in a connection string"+++def test_redactor_masks_a_short_database_password_when_the_text_starts_inside_it(tmp_path):+ from ci.secret_redaction import collect_sensitive_values++ from skillevaluator.utils.secret_redaction import Redactor++ skill = _skill(tmp_path)+ password = "Gh7" * 4 + "Gh"+ (skill / "source.py").write_text('DATABASE_URL = "postgresql://reporting:' + password + '@db.local/app"\n')+ redactor = Redactor(collect_sensitive_values(skill))+ for start in range(1, len(password) - 7):+ # A context window that starts inside the password cuts off the scheme.+ safe = redactor.text(password[start:] + '@db.local/app"\nWEBHOOK = "https://hooks.example.invalid/x"')+ _assert_no_fragment(safe, password)+ assert "db.local/app" in safe+ ordinary = "Send the export to [email protected] after the run."+ assert redactor.text(ordinary) == ordinary+++def test_retained_markdown_and_sarif_are_rendered_from_redacted_json(tmp_path):+ workspace, reports = tmp_path / "workspace", tmp_path / "reports"+ _skill(workspace)+ value = _fixture_value()++ def fake_cli(argv, **kwargs):+ target = Path(argv[argv.index("-o") + 1])+ result = SecurityValidator(use_llm=False).validate_pii_only(Path(argv[2]))+ result.validator_name = "PII Scan"+ result.validator_description = "Detect sensitive identifiers"+ payload = json.loads(JSONReporter(include_timestamp=False).render_all([result]))+ # Another scanner's context window started inside the value.+ payload["results"][0]["findings"][0]["line_content"] = value[3:]+ (target / "skillevaluator-tier1.json").write_text(json.dumps(payload))+ # The evaluator's own files escape and cut text in ways a literal+ # search cannot follow.+ (target / "skillevaluator-tier1.md").write_text("Raw evaluator Markdown " + value.replace("-", "\\-")[:30])+ (target / "skillevaluator-tier1.sarif.json").write_text(json.dumps({"raw": "Raw evaluator SARIF"}))+ return subprocess.CompletedProcess(argv, 1)++ assert runner.run(workspace, reports, {"SKILL_PATHS": "skills"}, execute=fake_cli) == 1+ markdown = (reports / "skill-001/skillevaluator-tier1.md").read_text()+ sarif = json.loads((reports / "skill-001/skillevaluator-tier1.sarif.json").read_text())+ if "Raw evaluator" in markdown or not markdown.startswith("# SkillEvaluator Validation Report"):+ pytest.fail("Retained Markdown was not rendered from the redacted JSON.")+ assert sarif["version"] == "2.1.0"+ assert [item["properties"]["checkName"] for item in sarif["runs"][0]["results"]] == ["hardcoded_secrets"]+ for path in reports.rglob("*"):+ if path.is_file():+ _assert_no_fragment(path.read_bytes(), value)+++def test_preflight_collects_unquoted_nvidia_key_and_bearer_values(tmp_path):+ from ci.secret_redaction import collect_sensitive_values++ skill = _skill(tmp_path)+ key = "nvapi-" + "kl" * 24+ bearer = "Tk9" * 8+ (skill / "source.py").write_text("value = 1\n")+ (skill / "SKILL.md").write_text(+ "---\nname: demo\ndescription: A sample formatting skill.\n---\n# Demo\n\n"+ "```bash\nexport NVIDIA_API_KEY=" + key + "\n"+ "curl -H 'Authorization: Bearer " + bearer + "' https://api.example.invalid\n```\n"+ )+ tokens = collect_sensitive_values(skill)+ if key not in tokens or bearer not in tokens:+ pytest.fail("Credential preflight did not identify an unquoted credential.")+++def test_preflight_does_not_collect_ordinary_words_after_credential_names(tmp_path):+ from ci.secret_redaction import collect_sensitive_values++ skill = _skill(tmp_path)+ (skill / "source.py").write_text("value = 1\n")+ (skill / "SKILL.md").write_text(+ "---\nname: demo\ndescription: A sample formatting skill.\n---\n# Demo\n\n"+ "The password: required for the staging environment.\n"+ "Send the header Authorization: Bearer token_from_the_environment.\n"+ "export NVIDIA_API_KEY=$NVIDIA_API_KEY_FROM_THE_VAULT\n"+ "api_key = load_configuration_value(name)\n"+ "API_KEY_FILE=/run/secrets/provider_key_v2\n"+ # A long encoded blob is not a key; collecting it would stop the scan.+ "api_key: " + "Ab1" * 200 + "\n"+ )+ assert collect_sensitive_values(skill) == set()++[email protected]("mark", ["\u200b", "\ufeff", "\u00a0"])+def test_preflight_matches_values_echoed_with_an_invisible_character_marker(tmp_path, mark):+ from ci.secret_redaction import collect_sensitive_values++ from skillevaluator.utils.secret_redaction import Redactor+ from skillevaluator.validators.unicode_smuggle import UnicodeSmuggleValidator++ skill = _skill(tmp_path)+ leading, middle = "nvapi-" + "Hj6" * 16, "Lm3" * 4 + "Pq2" * 6+ short = "Kp4" * 4+ lines = [+ 'NVIDIA_API_KEY = "' + mark + leading + '"',+ 'DB_PASSWORD = "' + middle[:12] + mark + middle[12:] + '"',+ # A short password is matched only as a whole value.+ 'conn_string = "Server=db.local;password=' + mark + short + ';"',+ ]+ (skill / "source.py").write_text("\n".join(lines) + "\n")+ redactor = Redactor(collect_sensitive_values(skill))+ for line in lines:+ # The Unicode check echoes the line with the character shown as a marker.+ safe = redactor.text(UnicodeSmuggleValidator._safe_line_content(line))+ _assert_no_fragment(safe, leading)+ _assert_no_fragment(safe, middle)+ _assert_no_fragment(safe, short)++[email protected]("separator", ["\u2028", "\u0085", "\x0c"])+def test_preflight_splits_lines_as_the_scanners_do(tmp_path, separator):+ from ci.secret_redaction import collect_sensitive_values++ from skillevaluator.utils.secret_redaction import Redactor+ from skillevaluator.validators.unicode_smuggle import UnicodeSmuggleValidator++ skill = _skill(tmp_path)+ value = "Hj6" * 6 + "Lm3" * 6+ line = 'API_SECRET = "' + value[:10] + separator + value[10:] + '"'+ (skill / "source.py").write_text(line + "\n", encoding="utf-8")+ # The PII scan splits only on newlines, so it still flags the value.+ result = SecurityValidator(use_llm=False).validate_pii_only(skill)+ assert any(f.check_name == "hardcoded_secrets" for f in result.findings)+ tokens = collect_sensitive_values(skill)+ if value[:10] + separator + value[10:] not in tokens:+ pytest.fail("Credential preflight split a quoted value at a line separator.")+ redactor = Redactor(tokens)+ # YARA echoes the raw line. The Unicode check shows the character as a marker.+ for echo in (line, UnicodeSmuggleValidator._safe_line_content(line)):+ _assert_no_fragment(redactor.text(echo), value)+++def test_invisible_character_in_credential_never_reaches_reports_or_pages(tmp_path, capsys, monkeypatch):+ from skillevaluator.validators.unicode_smuggle import UnicodeSmuggleValidator++ workspace, reports = tmp_path / "workspace", tmp_path / "reports"+ skill = _skill(workspace)+ value = "nvapi-" + "Hj6" * 16+ (skill / "source.py").write_text('NVIDIA_API_KEY = "\u200b' + value + '"\n')++ def fake_cli(argv, **kwargs):+ target = Path(argv[argv.index("-o") + 1])+ results = [+ SecurityValidator(use_llm=False).validate_pii_only(Path(argv[2])),+ UnicodeSmuggleValidator().validate(Path(argv[2])),+ ]+ for result, name in zip(results, ("PII Scan", "Unicode Smuggling"), strict=True):+ result.validator_name = name+ result.validator_description = name+ assert any(finding.line_content for finding in results[1].findings)+ (target / "skillevaluator-tier1.json").write_text(JSONReporter(include_timestamp=False).render_all(results))+ return subprocess.CompletedProcess(argv, 1)++ environment = {"SKILL_PATHS": "skills", "GITHUB_ACTIONS": "true"}+ assert runner.run(workspace, reports, environment, execute=fake_cli) == 1+ _assert_no_fragment(capsys.readouterr().out, value)+ site, feedback = _publish(tmp_path, monkeypatch, reports)+ for directory in (reports, site, feedback):+ for path in directory.rglob("*"):+ if path.is_file():+ _assert_no_fragment(path.read_bytes(), value)+ assert (site / "runs/123/1/skill-001/skillevaluator-tier1.html").is_file()