Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

fix(ci): apply reviewed baselines and preserve scan completeness evidence (#453)

Christopher Kevinb0461bab709b
diff --git a/.github/workflows/evaluate-all-tiers.yml b/.github/workflows/evaluate-all-tiers.yml
index 138081c4..9de0a046 100644
--- a/.github/workflows/evaluate-all-tiers.yml
+++ b/.github/workflows/evaluate-all-tiers.yml
@@ -26,6 +26,9 @@ on:
min-score:
type: number
default: 70
+ security-baselines:
+ type: boolean
+ default: false
env-mode:
description: docker or local; cloud backends are not supported here
type: string
@@ -84,6 +87,7 @@ jobs:
image: ${{ inputs.image }}
paths: ${{ inputs.paths }}
min-score: ${{ inputs.min-score }}
+ security-baselines: ${{ inputs.security-baselines }}
scan-mode: ${{ needs.eligibility.outputs.scan-mode || inputs.scan-mode }}
artifact-name: skill-evaluator-tier1
llm: false
diff --git a/.github/workflows/evaluate-skills.yml b/.github/workflows/evaluate-skills.yml
index 0d5386e8..3cf18519 100644
--- a/.github/workflows/evaluate-skills.yml
+++ b/.github/workflows/evaluate-skills.yml
@@ -44,6 +44,10 @@ on:
description: Skills scanned at once, 1 to 16; 1 scans one skill at a time
type: number
default: 4
+ security-baselines:
+ description: Apply per-skill baselines from the reviewed target/current commit manifest
+ type: boolean
+ default: false
secrets:
LLM_API_KEY:
required: false
@@ -106,9 +110,10 @@ jobs:
with:
persist-credentials: false
# Changed mode needs commits and trees for the merge base, not old
- # file contents. Full scans need only the checked-out commit.
- fetch-depth: ${{ env.SCAN_MODE != 'changed' && 1 || 0 }}
- filter: ${{ env.SCAN_MODE == 'changed' && 'blob:none' || '' }}
+ # file contents. Reviewed baselines need target-commit blobs too,
+ # including when all skills are selected; the container cannot fetch.
+ fetch-depth: ${{ !inputs.security-baselines && env.SCAN_MODE != 'changed' && 1 || 0 }}
+ filter: ${{ !inputs.security-baselines && env.SCAN_MODE == 'changed' && 'blob:none' || '' }}
ref: ${{ github.event.pull_request.head.sha || github.sha }}
- name: Validate the immutable image reference
env:
@@ -130,6 +135,8 @@ jobs:
IMAGE: ${{ inputs.image }}
DIFF_BASE_SHA: ${{ github.event.pull_request.base.sha }}
DIFF_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
+ SECURITY_BASELINES: ${{ inputs.security-baselines }}
+ POLICY_SOURCE_SHA: ${{ github.event.pull_request.base.sha || github.sha }}
SKILL_PATHS: ${{ inputs.paths }}
MIN_SCORE: ${{ inputs.min-score }}
LLM_ENABLED: ${{ inputs.llm }}
@@ -161,6 +168,7 @@ jobs:
--mount "type=bind,src=$RUNNER_TEMP/skill-reports,dst=/reports" \
--env SKILL_PATHS --env MIN_SCORE --env LLM_ENABLED --env LLM_PROVIDER --env LLM_MODEL "${llm_secret_args[@]}" \
--env SCAN_MODE --env DIFF_BASE_SHA --env DIFF_HEAD_SHA --env SCAN_WORKERS \
+ --env SECURITY_BASELINES --env POLICY_SOURCE_SHA \
--env CALLER_WORKFLOW_SHA \
--env GITHUB_ACTIONS --env REPORT_IMAGE --env REPORT_URL --env REPORT_RUN_URL --env REPORT_COMMIT \
"$IMAGE"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e8b235e..b122a44c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -303,6 +303,16 @@ All notable changes to SkillEvaluator are documented in this file.
### Fixed
+- Repository CI can opt in to reviewed, per-skill SkillSpector baselines from
+ the PR or merge request's target revision. Policy files from the proposed
+ changes cannot approve their own exceptions.
+- Security checks preserve authored evaluation files and their findings while
+ excluding generated outputs. Fully inspected skills with only missing-path
+ reference caveats retain visible warnings instead of an incomplete-scan
+ failure; actual coverage gaps and analyzer failures still block.
+- PII findings clarify that required author attribution is accepted while
+ duplicate contact addresses need removal, replacement, or a reviewed waiver.
+
- A `tier3 evaluate --skip-with-skill` run with two or more agents now records
the dataset-size status in `result.json` and the `tier3 evaluate` summary. It
is taken from the agent with the best baseline score, as in the reports.
diff --git a/ci/README.md b/ci/README.md
index dcedfd69..e17554fb 100644
--- a/ci/README.md
+++ b/ci/README.md
@@ -37,6 +37,7 @@ policy label. Profile names do not control network access or report visibility.
| `artifact-name` | Keep `skill-evaluator-tier1` for the optional publisher |
| `report-base-url` | Optional own Pages URL, only after hosted publication is configured |
| `scan-workers` | `4`; skills scanned at once, from 1 to 16. `1` scans one skill at a time |
+| `security-baselines` | `false`; explicitly apply reviewed per-skill SkillSpector baselines as described below |
The runtime discovers exact-case `SKILL.md` files, rejects unsafe paths and
symlinks, deduplicates overlapping roots and bounds each invocation to 100
@@ -57,6 +58,8 @@ shared files outside the configured roots are not inferred as dependencies.
Use `scan-mode: all` when changes to those shared resources require evaluation.
Changed-skill selection checks out full history without old file contents (a
blobless clone); full scans fetch only the scanned commit.
+Enabling reviewed security baselines fetches full, unfiltered history so target
+policy files are available without network access inside the scanner image.
Static scanning is network connected: vulnerability databases may receive
package metadata. Dependency auditing never installs packages or runs build
scripts: requirements must provide exact package/version pins. Unpinned, URL,
@@ -90,6 +93,60 @@ 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.
+## Reviewed security baselines
+
+This source capability requires a supporting workflow and image release; it is
+not added retroactively to already published onboarding bundles. Enable
+`security-baselines: true` on the GitHub reusable workflow, or set GitLab's
+`SKILL_EVAL_SECURITY_BASELINES: "true"`. Both default to false. This option
+applies SkillSpector exceptions only; it does not disable PII or security checks,
+change the quality gate, or forward the separate CLI `--pii-waivers` option.
+
+If a central component wraps the GitHub workflow, update its approved workflow
+and image pins together and forward the `security-baselines` boolean to the
+scan job. Each consumer keeps its own reviewed mapping and baseline files.
+
+Commit the fixed manifest `.skillevaluator/skillspector-baselines.yaml`:
+
+```yaml
+version: 1
+baselines:
+ legacy/sample-expert: config/security-baselines/sample-expert.json
+```
+
+Keys are exact repository-relative skill directories, and values are
+repository-relative native SkillSpector YAML or JSON baseline files. There are
+no globs. Unmapped skills receive no baseline. Paths must be canonical, without
+absolute paths, parent traversal, control characters, or links; the manifest
+rejects duplicate keys, YAML anchors and aliases, and unknown top-level keys.
+The manifest is limited to 64 KiB and 1,000 mappings, each baseline to 2 MiB,
+and the combined policy files to 16 MiB. The credential preflight also applies
+its existing line and redaction limits to the policy files.
+
+Both the mapping and baseline bytes come from the same approved Git commit:
+the pull request's target commit on GitHub, or GitLab's target-branch commit.
+For detached same-project GitLab merge requests without a target SHA, the job
+fetches the actual target branch before scanning; it never substitutes the
+merge base or candidate head. Fork GitLab merge requests require an exact
+platform-provided target SHA already available in the checkout and fail closed
+otherwise. Push/manual runs use their current commit. A pull request proposing
+the first manifest must merge through review before this option can use it;
+the candidate's new or edited approvals never apply to that same pull request.
+
+Missing policy commits, manifests, files, or invalid mappings fail configuration.
+Selected baseline bytes are materialized read-only in private temporary storage
+outside the skill tree and passed with `--skillspector-baseline` only to the
+mapped skill. The scanner retains its normal validation of the baseline format.
+Exact fingerprints still bind the source content and scanner version; regenerate
+and review them after either changes, or use deliberate narrow reviewed rules.
+Baselines cannot clear incomplete analysis.
+
+The retained `summary.json` records the policy commit, manifest path, digest, and
+`mapped_skill_count` in `execution.security_baselines`, and each mapped skill's baseline file and
+digest in `skills[].security_baseline`. The skill's native report records whether
+the baseline applied and what it suppressed. Policy files receive the same
+credential preflight and report redaction as skill content.
+
## Optional hosted reports and PR feedback
This is additional setup, not a `comment: true` switch in the basic scan file.
diff --git a/ci/gitlab/all-tiers.yml b/ci/gitlab/all-tiers.yml
index dfbf9b96..4e9e404f 100644
--- a/ci/gitlab/all-tiers.yml
+++ b/ci/gitlab/all-tiers.yml
@@ -1,9 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
-# Include this at a reviewed commit. The legacy Tier 1 runner is unchanged.
+# Include this at a reviewed commit. Tier 1 uses the shared image runner.
variables:
SKILL_EVAL_PATHS: skills
SKILL_EVAL_SCAN_MODE: auto
SKILL_EVAL_MIN_SCORE: '70'
+ SKILL_EVAL_SECURITY_BASELINES: 'false'
SKILL_EVAL_RUNNER: docker
SKILL_EVAL_ENVIRONMENT: skillevaluator
SKILL_EVAL_TIERS: '1,2,3'
@@ -42,6 +43,16 @@ skill-evaluation:
trap 'rm -rf "$reports_dir"' EXIT
export SKILL_PATHS="$SKILL_EVAL_PATHS"
export MIN_SCORE="$SKILL_EVAL_MIN_SCORE"
+ export SECURITY_BASELINES="${SKILL_EVAL_SECURITY_BASELINES:-false}"
+ unset POLICY_SOURCE_SHA
+ case "$SECURITY_BASELINES" in
+ true|false) ;;
+ *) echo "SKILL_EVAL_SECURITY_BASELINES must be true or false." >&2; exit 1 ;;
+ esac
+ if [ "$SECURITY_BASELINES" = true ]; then
+ POLICY_SOURCE_SHA="$(python -I /opt/skillevaluator/ci/prepare_security_baselines.py)"
+ export POLICY_SOURCE_SHA
+ fi
# Report links must be HTTPS; an instance served over HTTP gets no job link.
case "${CI_JOB_URL:-}" in
https://*) export REPORT_RUN_URL="$CI_JOB_URL" ;;
diff --git a/ci/gitlab/skill-evaluation.yml b/ci/gitlab/skill-evaluation.yml
index d41a5bc4..ca9e5443 100644
--- a/ci/gitlab/skill-evaluation.yml
+++ b/ci/gitlab/skill-evaluation.yml
@@ -6,6 +6,7 @@ variables:
SKILL_EVAL_PATHS: "skills"
SKILL_EVAL_SCAN_MODE: "auto"
SKILL_EVAL_MIN_SCORE: "70"
+ SKILL_EVAL_SECURITY_BASELINES: "false"
skill-evaluation:
stage: test
@@ -27,6 +28,16 @@ skill-evaluation:
trap 'rm -rf "$reports_dir"' EXIT
export SKILL_PATHS="$SKILL_EVAL_PATHS"
export MIN_SCORE="$SKILL_EVAL_MIN_SCORE"
+ export SECURITY_BASELINES="${SKILL_EVAL_SECURITY_BASELINES:-false}"
+ unset POLICY_SOURCE_SHA
+ case "$SECURITY_BASELINES" in
+ true|false) ;;
+ *) echo "SKILL_EVAL_SECURITY_BASELINES must be true or false." >&2; exit 1 ;;
+ esac
+ if [ "$SECURITY_BASELINES" = true ]; then
+ POLICY_SOURCE_SHA="$(python -I /opt/skillevaluator/ci/prepare_security_baselines.py)"
+ export POLICY_SOURCE_SHA
+ fi
# Report links must be HTTPS; an instance served over HTTP gets no job link.
case "${CI_JOB_URL:-}" in
https://*) export REPORT_RUN_URL="$CI_JOB_URL" ;;
diff --git a/ci/prepare_security_baselines.py b/ci/prepare_security_baselines.py
new file mode 100644
index 00000000..313d5ace
--- /dev/null
+++ b/ci/prepare_security_baselines.py
@@ -0,0 +1,91 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: INP001, T201 -- trusted GitLab bootstrap, before the offline scan.
+"""Resolve the approved GitLab policy commit; print only its exact object ID."""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+# The entrypoint uses Python isolated mode. Add only its image-owned sibling
+# directory, never the candidate checkout or a consumer-provided PYTHONPATH.
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from security_baselines import SHA
+from select_changed_skills import SelectionError, _git
+
+
+def policy_source(workspace: Path, environ: dict[str, str]) -> str:
+ """Never use the candidate or merge base as MR policy authority."""
+ merge_request = environ.get("CI_PIPELINE_SOURCE") == "merge_request_event"
+ revision = environ.get("CI_MERGE_REQUEST_TARGET_BRANCH_SHA" if merge_request else "CI_COMMIT_SHA", "")
+ if revision:
+ if not SHA.fullmatch(revision):
+ raise ValueError("The platform policy revision must be an exact commit ID.")
+ resolved = _git(workspace, "rev-parse", revision + "^{commit}").decode().strip()
+ if resolved != revision:
+ raise ValueError("The platform policy revision must identify an available commit.")
+ return revision
+ if not merge_request:
+ raise ValueError("Security baselines require the platform's current commit.")
+ project = environ.get("CI_PROJECT_ID", "")
+ if not project or project != environ.get("CI_MERGE_REQUEST_TARGET_PROJECT_ID"):
+ raise ValueError(
+ "Fork MR security baselines require an available exact target-branch commit; source origin is not trusted."
+ )
+ branch = environ.get("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", "")
+ if not branch:
+ raise ValueError("Security baselines require the merge request's target branch.")
+ reference = "refs/heads/" + branch
+ _git(workspace, "check-ref-format", reference)
+ env = {key: value for key, value in environ.items() if key in ("PATH", "LANG", "LC_ALL")}
+ env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT="0")
+ # Only same-project MRs fetch origin. Preserve the full checkout's ancestry
+ # for changed-skill selection: a depth-limited fetch can mark an existing
+ # ancestor shallow and disconnect the recorded MR diff base. Existing
+ # checkout authentication may be required; no remote URL or stderr is logged.
+ process = subprocess.run(
+ [
+ "git",
+ "-C",
+ str(workspace),
+ "-c",
+ "core.hooksPath=/dev/null",
+ "-c",
+ "core.fsmonitor=false",
+ "fetch",
+ "--no-tags",
+ "--no-filter",
+ "origin",
+ reference,
+ ],
+ env=env,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ check=False,
+ timeout=60,
+ )
+ if process.returncode:
+ raise ValueError("Could not fetch the approved target branch for security baselines.")
+ revision = _git(workspace, "rev-parse", "FETCH_HEAD^{commit}").decode().strip()
+ if not SHA.fullmatch(revision):
+ raise ValueError("The fetched policy revision is not an exact commit.")
+ return revision
+
+
+def main() -> int:
+ try:
+ print(policy_source(Path(os.environ["CI_PROJECT_DIR"]).resolve(strict=True), dict(os.environ)))
+ except (KeyError, OSError, ValueError, SelectionError, subprocess.TimeoutExpired):
+ print(
+ "Could not establish the trusted target/current policy commit; security baselines were not applied.",
+ file=sys.stderr,
+ )
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/ci/run_tier1.py b/ci/run_tier1.py
index 13dec035..46af0da5 100644
--- a/ci/run_tier1.py
+++ b/ci/run_tier1.py
@@ -12,6 +12,7 @@ many skills are scanned at once; rows, logs and annotations keep skill order.
from __future__ import annotations
import argparse
+import contextlib
import functools
import json
import os
@@ -28,6 +29,11 @@ from pathlib import Path
from skillevaluator.reporting.html import _validated_ci_context
from skillevaluator.utils.secret_redaction import Redactor
+try:
+ from security_baselines import BaselineConfigurationError, load_security_baselines
+except ModuleNotFoundError:
+ from ci.security_baselines import BaselineConfigurationError, load_security_baselines
+
try:
from secret_redaction import collect_sensitive_values, sanitized_outputs
except ModuleNotFoundError:
@@ -400,6 +406,7 @@ def evaluate_skill(
timeout: float,
execute,
tokens: set[str],
+ baseline: dict | None = None,
) -> tuple[dict, dict | None, bool]:
"""Run one evaluator process; return row fields, its report and whether time ran out.
@@ -415,9 +422,14 @@ def evaluate_skill(
# directory, never in the upload directory. Docker mounts /audit-tmp
# as tmpfs, so cancellation cannot upload half-written secrets. The
# name carries the report directory so concurrent scans are traceable.
- with tempfile.TemporaryDirectory(
- prefix=f"skillevaluator-private-{output.name}-", dir=env.get("TMPDIR")
- ) as temporary:
+ with (
+ tempfile.TemporaryDirectory(
+ prefix=f"skillevaluator-private-{output.name}-", dir=env.get("TMPDIR")
+ ) as temporary,
+ tempfile.TemporaryDirectory(prefix="skillevaluator-policy-", dir=env.get("TMPDIR"))
+ if baseline is not None
+ else contextlib.nullcontext() as policy_directory,
+ ):
raw = Path(temporary).resolve(strict=True)
if raw.is_relative_to(workspace) or raw.is_relative_to(output.parent):
raise ValueError("A private scanner directory must be outside the workspace and reports.")
@@ -437,6 +449,11 @@ def evaluate_skill(
"-o",
str(raw),
]
+ if baseline is not None:
+ policy_path = Path(policy_directory) / Path(baseline["file"]).name
+ policy_path.write_bytes(baseline["content"])
+ policy_path.chmod(0o400)
+ argv.extend(["--skillspector-baseline", str(policy_path)])
with (raw / "stdout.log").open("xb") as stdout, (raw / "stderr.log").open("xb") as stderr:
process = execute(
argv, cwd=workspace, env=env, stdout=stdout, stderr=stderr, check=False, timeout=timeout
@@ -521,6 +538,10 @@ def run(workspace: Path, reports: Path, environ: dict[str, str], *, execute=None
if reports.is_relative_to(workspace):
raise ConfigurationError("The report directory must be outside the read-only workspace.")
env, llm = child_environment(environ)
+ baselines, baseline_context, policy_tokens = load_security_baselines(workspace, environ)
+ tokens.update(policy_tokens)
+ if baseline_context is not None:
+ context["security_baselines"] = baseline_context
score = environ.get("MIN_SCORE", "70")
if not score.isascii() or not score.isdigit() or len(score) > 3 or int(score) > 100:
raise ConfigurationError("MIN_SCORE must be an integer between 0 and 100.")
@@ -561,7 +582,14 @@ def run(workspace: Path, reports: Path, environ: dict[str, str], *, execute=None
if clock() >= deadline:
raise ValueError("Credential preflight exceeded the scan time limit.")
redactor = Redactor(tokens)
- metadata = json.dumps({"selection": selection, "execution": context}, ensure_ascii=True)
+ metadata = json.dumps(
+ {
+ "selection": selection,
+ "execution": context,
+ "baseline_files": [baseline["file"] for baseline in baselines.values()],
+ },
+ ensure_ascii=True,
+ )
if redactor.text(metadata) != metadata:
raise ValueError("A credential is present in report context.")
except (OSError, ValueError, UnicodeError, RecursionError) as exc:
@@ -572,10 +600,10 @@ def run(workspace: Path, reports: Path, environ: dict[str, str], *, execute=None
"Credential preflight could not safely prepare the scan; no results were published."
) from exc
environments = [worker_environment(env, slot) for slot in range(1, min(workers, len(selected)) + 1)]
- except (ConfigurationError, SelectionError, OSError) as exc:
+ except (ConfigurationError, SelectionError, BaselineConfigurationError, OSError) as exc:
message = (
str(exc)
- if isinstance(exc, (ConfigurationError, SelectionError))
+ if isinstance(exc, (ConfigurationError, SelectionError, BaselineConfigurationError))
else "The workspace or runtime configuration could not be read."
)
summary = _summary([], error=message)
@@ -607,6 +635,9 @@ def run(workspace: Path, reports: Path, environ: dict[str, str], *, execute=None
}
for index, target in enumerate(selected, 1)
]
+ for row in rows:
+ if baseline := baselines.get(row["path"]):
+ row["security_baseline"] = {key: baseline[key] for key in ("file", "digest")}
def checkpoint() -> None:
summary = _summary(rows)
@@ -653,6 +684,7 @@ def run(workspace: Path, reports: Path, environ: dict[str, str], *, execute=None
timeout=remaining,
execute=execute,
tokens=tokens,
+ baseline=baselines.get(rows[index]["path"]),
)
except Exception:
outcome = ({"error": "Evaluator execution failed unexpectedly; no result is claimed."}, None, False)
diff --git a/ci/secret_redaction.py b/ci/secret_redaction.py
index a52fdc0a..d5e0be39 100644
--- a/ci/secret_redaction.py
+++ b/ci/secret_redaction.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import json
import os
import re
+from collections.abc import Iterable
from pathlib import Path
from skillevaluator.reporting import HTMLReporter, MarkdownReporter, SARIFReporter
@@ -44,10 +45,6 @@ def collect_sensitive_values(skill: Path) -> set[str]:
We scan matches even in comments or configured exceptions: another scanner
can still quote those values. Never put collected values into a report.
"""
- validator = SecurityValidator(use_llm=False)
- patterns = [item for item in validator._compile_pii_patterns([]) if item[0] in SENSITIVE_PII_CATEGORIES]
- tokens: set[str] = set()
- total = 0
files = []
def inaccessible(_error):
@@ -58,46 +55,49 @@ def collect_sensitive_values(skill: Path) -> set[str]:
if len(files) > MAX_FILES:
raise ValueError("The credential preflight exceeded its file limit.")
with SecureRoot(skill) as root:
- for path in files:
- raw, _ = root.read_bytes(path.relative_to(skill), MAX_FILE_BYTES)
- total += len(raw)
- if total > MAX_TOTAL_BYTES:
- raise ValueError("The credential preflight exceeded its size limit.")
- text = (
- raw.decode("utf-16", errors="ignore")
- if raw.startswith((b"\xff\xfe", b"\xfe\xff"))
- else raw.decode("utf-8-sig", errors="ignore")
- )
- # 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:
- raise ValueError("The credential preflight exceeded its line length limit.")
- 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
+ return collect_sensitive_bytes(root.read_bytes(path.relative_to(skill), MAX_FILE_BYTES)[0] for path in files)
+
+
+def collect_sensitive_bytes(contents: Iterable[bytes]) -> set[str]:
+ """Use the same bounded credential preflight for files and trusted Git blobs."""
+ validator = SecurityValidator(use_llm=False)
+ patterns = [item for item in validator._compile_pii_patterns([]) if item[0] in SENSITIVE_PII_CATEGORIES]
+ tokens: set[str] = set()
+ total = 0
+ for index, raw in enumerate(contents, 1):
+ total += len(raw)
+ if index > MAX_FILES or len(raw) > MAX_FILE_BYTES or total > MAX_TOTAL_BYTES:
+ raise ValueError("The credential preflight exceeded its file or size limit.")
+ text = (
+ raw.decode("utf-16", errors="ignore")
+ if raw.startswith((b"\xff\xfe", b"\xfe\xff"))
+ else raw.decode("utf-8-sig", errors="ignore")
+ )
+ # Split on newlines only, as the scanners do. Other Unicode separators
+ # can sit inside a quoted credential and must not split its evidence.
+ for line in re.split(r"\r\n?|\n", text):
+ if len(line) > MAX_LINE_CHARS:
+ raise ValueError("The credential preflight exceeded its line length limit.")
+ 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 not blocks:
- raise ValueError("A private key could not be safely redacted.")
- for block in blocks:
- tokens.add(block)
- tokens.update(line.strip() for line in block.splitlines()[1:-1] if line.strip())
- if len(tokens) > MAX_TOKENS or any(len(token.encode("utf-8")) > MAX_TOKEN_BYTES for token in tokens):
- raise ValueError("The credential preflight exceeded its redaction limit.")
+ if "PRIVATE KEY-----" in text:
+ blocks = re.findall(r"-----BEGIN [^\r\n]*PRIVATE KEY-----[\s\S]*?-----END [^\r\n]*PRIVATE KEY-----", text)
+ if not blocks:
+ raise ValueError("A private key could not be safely redacted.")
+ for block in blocks:
+ tokens.add(block)
+ tokens.update(line.strip() for line in block.splitlines()[1:-1] if line.strip())
+ if len(tokens) > MAX_TOKENS or any(len(token.encode("utf-8")) > MAX_TOKEN_BYTES for token in tokens):
+ raise ValueError("The credential preflight exceeded its redaction limit.")
# Replacing a very short secret throughout a report can corrupt schema keys
# and identities. Fail closed rather than risk emitting it or a false verdict.
if any(len(token) < 4 for token in tokens):
diff --git a/ci/security_baselines.py b/ci/security_baselines.py
new file mode 100644
index 00000000..d62384ae
--- /dev/null
+++ b/ci/security_baselines.py
@@ -0,0 +1,166 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+# ruff: noqa: INP001 -- shared trusted CI helper.
+"""Read per-skill security approvals from an explicit, immutable Git revision.
+
+Both the mapping and baseline bytes come from Git objects, never the candidate
+working tree. The caller supplies the platform's target commit for a PR/MR and
+the scanned commit for a push. This helper performs no network operations.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from pathlib import Path, PurePosixPath
+
+import yaml
+
+from skillevaluator.utils.structured_data import load_bounded_yaml
+from skillevaluator.validators.security import _BoundedSkillSpectorBaselineLoader
+
+try:
+ from secret_redaction import collect_sensitive_bytes
+ from select_changed_skills import SelectionError, _git, has_control_character
+except ModuleNotFoundError:
+ from ci.secret_redaction import collect_sensitive_bytes
+ from ci.select_changed_skills import SelectionError, _git, has_control_character
+
+MANIFEST = ".skillevaluator/skillspector-baselines.yaml"
+MAX_MANIFEST_BYTES = 64 * 1024
+MAX_BASELINE_BYTES = 2 * 1024 * 1024
+MAX_TOTAL_BYTES = 16 * 1024 * 1024
+MAX_BASELINES = 1000
+SHA = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})")
+
+
+class BaselineConfigurationError(ValueError):
+ """Reviewed policy could not be loaded; no scan should start."""
+
+
+def _path(value: object, *, skill: bool = False) -> str:
+ if not isinstance(value, str) or not value:
+ raise BaselineConfigurationError("Security baseline paths must be bounded relative paths.")
+ try:
+ size = len(value.encode("utf-8"))
+ except UnicodeError as exc:
+ raise BaselineConfigurationError("Security baseline paths must contain valid UTF-8 text.") from exc
+ if size > 4096:
+ raise BaselineConfigurationError("Security baseline paths must be bounded relative paths.")
+ path = PurePosixPath(value)
+ if (
+ path.is_absolute()
+ or ".." in path.parts
+ or "\\" in value
+ or ":" in value
+ or has_control_character(value)
+ or value != path.as_posix()
+ or (value == "." and not skill)
+ ):
+ raise BaselineConfigurationError("Security baseline paths must be canonical relative paths without traversal.")
+ return value
+
+
+def _blob(workspace: Path, revision: str, path: str, limit: int) -> bytes:
+ listing = _git(workspace, "ls-tree", "-l", "-z", revision, "--", path)
+ records = listing.split(b"\0")
+ if len(records) != 2 or records[1] or b"\t" not in records[0]:
+ raise BaselineConfigurationError("A reviewed security baseline file is missing from the policy commit.")
+ header, name = records[0].split(b"\t", 1)
+ fields = header.split()
+ if len(fields) != 4 or fields[0] not in (b"100644", b"100755") or fields[1] != b"blob" or name != path.encode():
+ raise BaselineConfigurationError("Reviewed security baseline files must be regular Git blobs, not links.")
+ if not fields[3].isdigit() or int(fields[3]) > limit:
+ raise BaselineConfigurationError("A reviewed security baseline file exceeds its size limit.")
+ content = _git(workspace, "cat-file", "blob", fields[2].decode("ascii"))
+ if len(content) != int(fields[3]):
+ raise BaselineConfigurationError("A reviewed security baseline Git blob could not be read completely.")
+ return content
+
+
+def _decoded_policy_bytes(raw: bytes) -> bytes:
+ """Also inspect decoded strings that scanner reports can echo after YAML escapes."""
+ parsed = yaml.load(raw.decode("utf-8"), Loader=_BoundedSkillSpectorBaselineLoader)
+ return json.dumps(parsed, ensure_ascii=False, indent=2, default=str).encode("utf-8")
+
+
+def load_security_baselines(workspace: Path, environ: dict[str, str]) -> tuple[dict[str, dict], dict | None, set[str]]:
+ """Return immutable baseline bytes keyed by exact skill path and audit facts."""
+ enabled = environ.get("SECURITY_BASELINES", "false")
+ if enabled not in ("true", "false"):
+ raise BaselineConfigurationError("SECURITY_BASELINES must be true or false.")
+ if enabled == "false":
+ return {}, None, set()
+ revision = environ.get("POLICY_SOURCE_SHA", "")
+ if not SHA.fullmatch(revision):
+ raise BaselineConfigurationError("Security baselines require an exact POLICY_SOURCE_SHA commit.")
+ try:
+ resolved = _git(workspace, "rev-parse", "--show-toplevel", revision + "^{commit}", "--").decode().splitlines()
+ if len(resolved) != 3 or Path(resolved[0]).resolve() != workspace or resolved[1:] != [revision, "--"]:
+ raise BaselineConfigurationError("The security policy revision must identify a commit in this checkout.")
+ raw = _blob(workspace, revision, MANIFEST, MAX_MANIFEST_BYTES)
+ try:
+ text = raw.decode("utf-8")
+ if any(getattr(event, "anchor", None) is not None for event in yaml.parse(text)):
+ raise ValueError("Aliases and anchors are not allowed in a security approval manifest.")
+ manifest = load_bounded_yaml(text)
+ except (ValueError, UnicodeError, RecursionError, yaml.YAMLError) as exc:
+ raise BaselineConfigurationError("The reviewed security baseline manifest is invalid YAML.") from exc
+ if (
+ not isinstance(manifest, dict)
+ or set(manifest) != {"version", "baselines"}
+ or type(manifest["version"]) is not int
+ or manifest["version"] != 1
+ or not isinstance(manifest["baselines"], dict)
+ or len(manifest["baselines"]) > MAX_BASELINES
+ ):
+ raise BaselineConfigurationError(
+ "The reviewed manifest requires version: 1 and a bounded baselines mapping."
+ )
+ baselines, files, total = {}, {}, len(raw)
+ for skill_path, file_path in manifest["baselines"].items():
+ skill_path, file_path = _path(skill_path, skill=True), _path(file_path)
+ if file_path not in files:
+ content = _blob(workspace, revision, file_path, MAX_BASELINE_BYTES)
+ total += len(content)
+ if total > MAX_TOTAL_BYTES:
+ raise BaselineConfigurationError("Reviewed security baselines exceed the total size limit.")
+ files[file_path] = content
+ content = files[file_path]
+ baselines[skill_path] = {
+ "file": file_path,
+ "digest": "sha256:" + hashlib.sha256(content).hexdigest(),
+ "content": content,
+ }
+ try:
+ inputs = [raw, *files.values()]
+ tokens = collect_sensitive_bytes([*inputs, *(_decoded_policy_bytes(content) for content in inputs)])
+ except (
+ ValueError,
+ UnicodeError,
+ yaml.YAMLError,
+ TypeError,
+ RecursionError,
+ IndexError,
+ AttributeError,
+ KeyError,
+ OverflowError,
+ ) as exc:
+ raise BaselineConfigurationError(
+ "Credential preflight could not safely inspect reviewed security policy."
+ ) from exc
+ return (
+ baselines,
+ {
+ "source_commit": revision,
+ "manifest": MANIFEST,
+ "manifest_digest": "sha256:" + hashlib.sha256(raw).hexdigest(),
+ "mapped_skill_count": len(baselines),
+ },
+ tokens,
+ )
+ except SelectionError as exc:
+ raise BaselineConfigurationError(
+ "The reviewed security policy commit or its files are unavailable; verify checkout history."
+ ) from exc
diff --git a/ci/templates/all-tiers/gitlab-all-tiers.yml b/ci/templates/all-tiers/gitlab-all-tiers.yml
index 9a10417a..07e8089d 100644
--- a/ci/templates/all-tiers/gitlab-all-tiers.yml
+++ b/ci/templates/all-tiers/gitlab-all-tiers.yml
@@ -17,6 +17,7 @@ variables:
SKILL_EVAL_TOOLS_REPOSITORY: NVIDIA/SkillEvaluator
SKILL_EVAL_TOOLS_REF: RELEASE_WORKFLOW_SHA
SKILL_EVAL_PATHS: skills
+ SKILL_EVAL_SECURITY_BASELINES: 'false'
SKILL_EVAL_TIERS: '1,2,3'
SKILL_EVAL_ENV_MODE: docker
SKILL_EVAL_PROVIDER: openai
diff --git a/ci/templates/all-tiers/skill-checks-all-tiers.yml b/ci/templates/all-tiers/skill-checks-all-tiers.yml
index c81072da..743611e0 100644
--- a/ci/templates/all-tiers/skill-checks-all-tiers.yml
+++ b/ci/templates/all-tiers/skill-checks-all-tiers.yml
@@ -22,6 +22,7 @@ jobs:
tiers: '1,2,3'
paths: skills
min-score: 70
+ security-baselines: false
scan-mode: auto
env-mode: docker
provider: openai
diff --git a/ci/templates/gitlab-skill-checks.yml b/ci/templates/gitlab-skill-checks.yml
index 663535cc..a168beb2 100644
--- a/ci/templates/gitlab-skill-checks.yml
+++ b/ci/templates/gitlab-skill-checks.yml
@@ -10,6 +10,7 @@ variables:
SKILL_EVAL_IMAGE: ghcr.io/nvidia/skillevaluator-tier1@sha256:RELEASE_IMAGE_DIGEST
SKILL_EVAL_PATHS: "skills"
SKILL_EVAL_MIN_SCORE: "70"
+ SKILL_EVAL_SECURITY_BASELINES: "false"
# GitLab requires merge-request rules directly in the root file, even when a
# job is included. Preserve your existing workflow rules if you have them.
diff --git a/ci/templates/skill-checks-llm.yml b/ci/templates/skill-checks-llm.yml
index 4ac06671..fdb7ea3c 100644
--- a/ci/templates/skill-checks-llm.yml
+++ b/ci/templates/skill-checks-llm.yml
@@ -15,6 +15,7 @@ jobs:
image: ghcr.io/nvidia/skillevaluator-tier1@sha256:RELEASE_IMAGE_DIGEST
paths: skills
min-score: 70
+ security-baselines: false
scan-mode: all
llm: true
llm-provider: openai
diff --git a/ci/templates/skill-checks.yml b/ci/templates/skill-checks.yml
index ce31cab5..0f10170a 100644
--- a/ci/templates/skill-checks.yml
+++ b/ci/templates/skill-checks.yml
@@ -19,5 +19,7 @@ jobs:
image: ghcr.io/nvidia/skillevaluator-tier1@sha256:RELEASE_IMAGE_DIGEST
paths: skills
min-score: 70
+ # Enable only after the reviewed baseline manifest reaches the target branch.
+ security-baselines: false
scan-mode: auto
llm: false
diff --git a/docs/github-actions.mdx b/docs/github-actions.mdx
index a5ed670b..462eff14 100644
--- a/docs/github-actions.mdx
+++ b/docs/github-actions.mdx
@@ -84,6 +84,28 @@ Failed scans retain their available reports too. The HTML separates the
**verdict** from the **quality score**: a high score does not override a failed
required security or schema check.
+<AccordionGroup>
+ <Accordion title="Why is an author email reported as PII?">
+ The required `metadata.author` attribution is accepted. Extra copies in
+ contact fields, body text, or reference documents are checked separately.
+ Keep the author field and use a handle or contact-directory link for extra
+ contact information. See [author attribution and approved exceptions](/skills/skillevaluator/tier1-validation#author-attribution-and-contact-emails).
+ </Accordion>
+ <Accordion title="Use reviewed security baselines">
+ This requires a workflow and image version that include baseline support;
+ existing released templates do not gain it automatically.
+
+ Set `security-baselines: true` in the reusable scan job and add a reviewed
+ `.skillevaluator/skillspector-baselines.yaml` mapping each skill to its
+ baseline. For PRs, CI reads both the mapping and baseline from the target
+ branch, so merge the approved policy before expecting it to apply.
+
+ Regenerate and review fingerprint exceptions when the scanner version
+ changes. Baselines do not waive PII checks or incomplete analysis. The [baseline setup guide](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/README.md#reviewed-security-baselines)
+ covers the file format and shared-component forwarding.
+ </Accordion>
+</AccordionGroup>
+
<Frame caption="Report example: the skill scored 98.2 but did not meet a configured 100-point threshold. The shared renderer is used by both GitHub and GitLab.">
<img src="./assets/repository-ci-results-example.png" alt="SkillEvaluator report table showing the skill verdict, score and link to its detailed report" />
</Frame>
diff --git a/docs/gitlab-ci.mdx b/docs/gitlab-ci.mdx
index 6bffe6f9..addc0ce9 100644
--- a/docs/gitlab-ci.mdx
+++ b/docs/gitlab-ci.mdx
@@ -104,6 +104,19 @@ Skill result: "skills/glossary-builder" — FAILED
</Tabs>
<AccordionGroup>
+ <Accordion title="Author emails and reviewed security exceptions">
+ Keep the required `metadata.author` attribution. Extra email copies in
+ contact fields or documents are checked separately; use a handle or a
+ contact-directory link instead. See [author attribution](/skills/skillevaluator/tier1-validation#author-attribution-and-contact-emails).
+
+ For reviewed SkillSpector exceptions, set
+ `SKILL_EVAL_SECURITY_BASELINES: "true"` and add
+ `.skillevaluator/skillspector-baselines.yaml` using a template and image
+ version that include baseline support. CI reads the approved mapping
+ and baseline files from the merge request's target revision. Regenerate and
+ review fingerprint exceptions when the scanner version changes. Baselines
+ do not waive PII or incomplete analysis. Follow the [baseline setup guide](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/README.md#reviewed-security-baselines).
+ </Accordion>
<Accordion title="When does it run?">
`SKILL_EVAL_SCAN_MODE: auto` evaluates changed skills in detached
merge-request pipelines and all configured skills on the default branch or
diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx
index aaa746e4..d298c096 100644
--- a/docs/tier1-validation.mdx
+++ b/docs/tier1-validation.mdx
@@ -454,6 +454,18 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice
</Accordion>
</AccordionGroup>
+## Author attribution and contact emails
+
+Keep the required `metadata.author: Name <email>` attribution in `SKILL.md`.
+The PII check accepts that recognized author line. The same address in another
+field, body text, or a reference document is a separate occurrence and can still
+fail the check.
+
+Use a name, team handle, or contact-directory link for additional contact
+information. If a real address must remain, record a reviewed, time-limited
+[PII waiver](#pii-waivers) for that occurrence. An organization-owned email
+domain does not automatically exempt every address in the repository.
+
## 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.
diff --git a/src/skillevaluator/config/pii_patterns.yaml b/src/skillevaluator/config/pii_patterns.yaml
index e009f997..b4b24699 100644
--- a/src/skillevaluator/config/pii_patterns.yaml
+++ b/src/skillevaluator/config/pii_patterns.yaml
@@ -58,7 +58,7 @@ emails:
- pattern: '(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@(?!(?:[a-z0-9-]+\.)*(?:example\.(?:com|net|org)|test\.com|test|example|invalid|localhost)\.*(?![a-z0-9.-])|odata\.)[A-Za-z0-9.-]+\.[A-Za-z]{2,}'
severity: high
description: Non-placeholder email address
- suggestion: "Remove the address or use a placeholder like [email protected]"
+ suggestion: "Keep required metadata.author attribution. Replace other contact addresses with a handle, a contact-directory link, or [email protected]; use a reviewed --pii-waivers entry if the address is required."
exceptions:
# Third-party license attributions (copyright notices are legitimate)
- "Copyright"
diff --git a/src/skillevaluator/reporting/json_reporter.py b/src/skillevaluator/reporting/json_reporter.py
index 7ad012e3..b4230ee5 100644
--- a/src/skillevaluator/reporting/json_reporter.py
+++ b/src/skillevaluator/reporting/json_reporter.py
@@ -37,6 +37,7 @@ from skillevaluator.reporting.finding_summary import (
)
from skillevaluator.reporting.run_status import Status, resolve_run_status, result_status
from skillevaluator.skillspector_provenance import sanitize_skillspector_provenance_metadata
+from skillevaluator.skillspector_reference_caveats import sanitize_reference_caveat_metadata
from skillevaluator.source_identity import recorded_evaluated_source
if TYPE_CHECKING:
@@ -355,6 +356,10 @@ class JSONReporter(ReporterBase):
if isinstance(skillspector_baseline, dict):
data["skillspector_baseline"] = dict(skillspector_baseline)
+ reference_caveats = sanitize_reference_caveat_metadata(result.metadata.get("skillspector_reference_caveats"))
+ if reference_caveats is not None:
+ data["skillspector_reference_caveats"] = reference_caveats
+
# Tier 3: Agent evaluation data
ae = result.metadata.get("agent_eval")
if ae:
diff --git a/src/skillevaluator/reporting/retained.py b/src/skillevaluator/reporting/retained.py
index 37d73510..cee7c198 100644
--- a/src/skillevaluator/reporting/retained.py
+++ b/src/skillevaluator/reporting/retained.py
@@ -18,6 +18,7 @@ from skillevaluator.reporting.base import is_cleanly_skipped, is_tier2_result, i
from skillevaluator.reporting.html import HTMLReporter
from skillevaluator.reporting.run_status import resolve_run_status, result_status
from skillevaluator.skillspector_provenance import sanitize_skillspector_provenance_metadata
+from skillevaluator.skillspector_reference_caveats import sanitize_reference_caveat_metadata
class RetainedReportError(ValueError):
@@ -249,6 +250,10 @@ def retained_results(
metadata["skillspector_version"] = _text(row["skillspector_version"], "skillspector_version")
# Revalidated like every report boundary; a non-canonical record is left out.
metadata.update(sanitize_skillspector_provenance_metadata(row))
+ if "skillspector_reference_caveats" in row:
+ reference_caveats = sanitize_reference_caveat_metadata(row["skillspector_reference_caveats"])
+ _require(reference_caveats is not None, "Invalid skillspector_reference_caveats")
+ metadata["skillspector_reference_caveats"] = reference_caveats
if "publication_target_conflict" in row:
metadata["publication_target_conflict"] = _text(
row["publication_target_conflict"], "publication_target_conflict"
diff --git a/src/skillevaluator/skillspector_reference_caveats.py b/src/skillevaluator/skillspector_reference_caveats.py
new file mode 100644
index 00000000..4bb0b422
--- /dev/null
+++ b/src/skillevaluator/skillspector_reference_caveats.py
@@ -0,0 +1,238 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Lightweight evidence checks for fully inspected bundles with reference caveats.
+
+SkillSpector 2.13.3's MCP gate allows this narrow case while retaining the
+scanner's partial/CAUTION verdict. Missing targets are not certified. The
+adapter must still validate findings, risk, inventory and requested LLM work.
+"""
+
+from collections.abc import Mapping, Set
+from pathlib import PurePosixPath
+
+_COMPLETENESS_FIELDS = frozenset(
+ {
+ "total_components",
+ "scanned_components",
+ "coverage_percent",
+ "is_complete",
+ "status",
+ "execution_successful",
+ "fully_inspected_files",
+ "partially_inspected_files",
+ "entirely_uninspected_files",
+ "ledger_exceptions",
+ "scope_exclusions",
+ "analyzer_statuses",
+ "references",
+ "limitations",
+ "findings_before_filtering",
+ "findings_after_filtering",
+ }
+)
+_EXCEPTION_FIELDS = frozenset(
+ {
+ "outcome",
+ "phase",
+ "reason_code",
+ "message",
+ "path",
+ "start_line",
+ "end_line",
+ "fatal",
+ "analyzers",
+ }
+)
+_WORK_FIELDS = ("planned_work", "completed", "partial", "skipped", "failed", "unaccounted")
+_STATUS_FIELDS = frozenset({"analyzer_id", "status", "reason_code", "message", *_WORK_FIELDS})
+
+
+def reference_caveat_metadata(
+ data: Mapping,
+ *,
+ scanner_version: tuple[int, int, int] | None,
+ required_analyzers: Set[str],
+ universal_analyzers: Set[str],
+ optional_analyzers: Set[str],
+ use_llm: bool,
+) -> dict[str, object] | None:
+ """Return honest warning metadata only for the verified 2.x report contract."""
+ if scanner_version is None or not (2, 13, 3) <= scanner_version < (3, 0, 0):
+ return None
+ risk = data.get("risk_assessment")
+ if not isinstance(risk, dict):
+ return None
+ completeness = data.get("analysis_completeness")
+ if (
+ not isinstance(completeness, dict)
+ or set(completeness) != _COMPLETENESS_FIELDS
+ or data.get("execution_successful") is not True
+ or completeness.get("execution_successful") is not True
+ or completeness.get("status") != "partial"
+ or completeness.get("is_complete") is not False
+ or completeness.get("limitations") != []
+ # Keep unfamiliar exclusion evidence outside this narrow exception.
+ or completeness.get("scope_exclusions") != []
+ or completeness.get("coverage_percent") != 100
+ or completeness.get("partially_inspected_files") != 0
+ or completeness.get("entirely_uninspected_files") != 0
+ ):
+ return None
+ total = completeness.get("total_components")
+ if (
+ type(total) is not int
+ or total <= 0
+ or completeness.get("scanned_components") != total
+ or completeness.get("fully_inspected_files") != total
+ ):
+ return None
+
+ components = data.get("components")
+ if not isinstance(components, list) or len(components) != total:
+ return None
+ component_lines: dict[str, int] = {}
+ for component in components:
+ if not isinstance(component, dict):
+ return None
+ path, lines = component.get("path"), component.get("lines")
+ if (
+ not isinstance(path, str)
+ or not path
+ or path in component_lines
+ or PurePosixPath(path).is_absolute()
+ or ".." in PurePosixPath(path).parts
+ or "\\" in path
+ or "\x00" in path
+ or type(lines) is not int
+ or lines < 0
+ ):
+ return None
+ component_lines[path] = lines
+
+ exceptions = completeness.get("ledger_exceptions")
+ if not isinstance(exceptions, list) or not exceptions:
+ return None
+ exception_locations: set[tuple[str, int]] = set()
+ for row in exceptions:
+ if not isinstance(row, dict) or not set(row) <= _EXCEPTION_FIELDS:
+ return None
+ path, start, end = row.get("path"), row.get("start_line"), row.get("end_line")
+ if (
+ row.get("reason_code") != "reference_missing"
+ or row.get("phase") != "reference_resolution"
+ or row.get("outcome") != "partial"
+ or row.get("fatal") is not False
+ or row.get("analyzers", []) != []
+ or not isinstance(path, str)
+ or path not in component_lines
+ or type(start) is not int
+ or type(end) is not int
+ or not 0 < start <= end <= component_lines[path]
+ ):
+ return None
+ exception_locations.add((path, start))
+
+ references = completeness.get("references")
+ if not isinstance(references, list):
+ return None
+ missing_locations: set[tuple[str, int]] = set()
+ for reference in references:
+ if not isinstance(reference, dict):
+ return None
+ status = reference.get("status")
+ if status == "missing":
+ path, line = reference.get("source_path"), reference.get("line")
+ if (
+ not isinstance(path, str)
+ or path not in component_lines
+ or type(line) is not int
+ or not 0 < line <= component_lines[path]
+ or reference.get("target_path") is not None
+ or reference.get("disposition") != "partial"
+ ):
+ return None
+ missing_locations.add((path, line))
+ elif status == "resolved":
+ if (
+ not isinstance(reference.get("target_path"), str)
+ or reference["target_path"] not in component_lines
+ or reference.get("disposition") != "analyzed"
+ ):
+ return None
+ elif status != "rejected" or reference.get("disposition") != "out_of_scope":
+ # Ambiguity, unavailable target bytes, and unknown states still block.
+ return None
+ if missing_locations != exception_locations:
+ return None
+
+ statuses = completeness.get("analyzer_statuses")
+ if not isinstance(statuses, list):
+ return None
+ observed: set[str] = set()
+ for row in statuses:
+ if not isinstance(row, dict) or not set(row) <= _STATUS_FIELDS:
+ return None
+ analyzer = row.get("analyzer_id")
+ if not isinstance(analyzer, str) or analyzer in observed:
+ return None
+ observed.add(analyzer)
+ if any(type(row.get(field)) is not int or row[field] < 0 for field in _WORK_FIELDS):
+ return None
+ if any(row[field] != 0 for field in ("partial", "skipped", "failed", "unaccounted")):
+ return None
+ state = row.get("status")
+ if state == "completed":
+ if row["planned_work"] != row["completed"]:
+ return None
+ elif state == "not_applicable":
+ if row.get("reason_code") != "no_applicable_files" or any(row[field] for field in _WORK_FIELDS):
+ return None
+ elif state == "disabled":
+ if (
+ use_llm
+ or analyzer not in optional_analyzers
+ or row.get("reason_code") != "disabled_by_configuration"
+ or any(row[field] for field in _WORK_FIELDS)
+ ):
+ return None
+ else:
+ return None
+ if analyzer in universal_analyzers and (state != "completed" or row["completed"] != total):
+ return None
+ if not (required_analyzers | universal_analyzers) <= observed:
+ return None
+
+ return {
+ "status": "partial",
+ "recommendation": risk.get("recommendation"),
+ "reason_code": "reference_missing",
+ "count": len(exceptions),
+ "fully_inspected_files": total,
+ "missing_targets_verified": False,
+ }
+
+
+def sanitize_reference_caveat_metadata(value: object) -> dict[str, object] | None:
+ """Retain only bounded, canonical caveat metadata at report boundaries."""
+ if (
+ not isinstance(value, dict)
+ or set(value)
+ != {
+ "status",
+ "recommendation",
+ "reason_code",
+ "count",
+ "fully_inspected_files",
+ "missing_targets_verified",
+ }
+ or value.get("status") != "partial"
+ or value.get("recommendation") not in ("CAUTION", "DO_NOT_INSTALL")
+ or value.get("reason_code") != "reference_missing"
+ or value.get("missing_targets_verified") is not False
+ or any(
+ type(value.get(key)) is not int or not 0 < value[key] < 2**31 for key in ("count", "fully_inspected_files")
+ )
+ ):
+ return None
+ return dict(value)
diff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.py
index de4b0aac..2ecf1293 100644
--- a/src/skillevaluator/validators/security.py
+++ b/src/skillevaluator/validators/security.py
@@ -52,6 +52,7 @@ from skillevaluator.provider_config import (
skillspector_reasoning_effort,
)
from skillevaluator.skillspector_provenance import SKILLSPECTOR_LLM_ANALYZERS, sanitize_skillspector_llm_provenance
+from skillevaluator.skillspector_reference_caveats import reference_caveat_metadata
from skillevaluator.spdx import is_spdx_only_html_comment
from skillevaluator.utils.path_security import matches_filesystem_name
from skillevaluator.utils.scanner_install import prepare_skillspector
@@ -198,7 +199,10 @@ _SKILLSPECTOR_DIMINISHING_WEIGHTS = (1.0, 0.5, 0.25)
# Ledger exceptions quoted in an incomplete-analysis error, and the length of each quoted field.
_SKILLSPECTOR_INCOMPLETE_EXAMPLES = 3
_SKILLSPECTOR_REPORT_TEXT_MAX_CHARS = 200
-_SKILLSPECTOR_SCAN_EXCLUDED_DIRS = SCAN_EXCLUDED_DIRS - {"__pycache__"}
+# Evaluation definitions and helpers are authored inputs, including when linked
+# from SKILL.md. Keep them and shipped bytecode visible to SkillSpector; generated
+# results below these directories still match the existing output exclusions.
+_SKILLSPECTOR_SCAN_EXCLUDED_DIRS = SCAN_EXCLUDED_DIRS - {"__pycache__", "evals", ".evals"}
_SKILLSPECTOR_PROVIDER_MAP = {
"anthropic": "anthropic",
"bedrock": "bedrock",
@@ -2107,11 +2111,13 @@ class SecurityValidator(ValidatorBase):
explicit baseline, and that report must then account for them.
A ``partial`` analysis makes the scan INCOMPLETE unless its only gaps are
- referenced PNG or JPEG images that the files under *scanned_root* confirm
- (:func:`_skillspector_passive_raster_note`); that is a warning instead.
+ verified passive images or missing-reference caveats with complete
+ bundled-file inspection. Those remain visible warnings, not claims that
+ referenced targets were inspected or that the scanner reported SAFE.
*scanned_root* is the directory the report's relative paths start from.
"""
partial_reported = False
+ accepted_reference_caveats = None
if "error" in data and data["error"] is not None:
result.add_error("skillspector reported an error; security scan did not complete")
return False
@@ -2524,10 +2530,19 @@ class SecurityValidator(ValidatorBase):
and not_applicable_evidence_valid
and docs_only_analyzer_states_valid
)
+ accepted_reference_caveats = reference_caveat_metadata(
+ data,
+ scanner_version=skillspector_version,
+ required_analyzers=required_analyzer_ids,
+ universal_analyzers=_SKILLSPECTOR_COMMON_UNIVERSAL_ANALYZERS | {"artifact_integrity"},
+ optional_analyzers=_SKILLSPECTOR_OPTIONAL_ANALYZERS,
+ use_llm=use_llm,
+ )
if (
is_complete
or uses_statusless_completeness_schema
or complete_by_applicability
+ or accepted_reference_caveats is not None
) and counts["total_components"]:
universal_analyzer_ids = _SKILLSPECTOR_COMMON_UNIVERSAL_ANALYZERS | (
{"artifact_integrity"} if uses_completeness_schema else set()
@@ -2643,7 +2658,11 @@ class SecurityValidator(ValidatorBase):
data.get("components"),
scanned_root,
)
- if raster_note is not None:
+ if accepted_reference_caveats is not None:
+ # Add the warning only after all inventory, finding and
+ # risk-accounting checks below have accepted the report.
+ pass
+ elif raster_note is not None:
result.add_warning(raster_note)
else:
result.add_error(
@@ -3011,6 +3030,36 @@ class SecurityValidator(ValidatorBase):
)
return False
+ if accepted_reference_caveats is not None:
+ result.metadata["skillspector_reference_caveats"] = accepted_reference_caveats
+ locations = ", ".join(
+ f"{_skillspector_report_text(row['path'])}:{row['start_line']}"
+ for row in ledger_exceptions[:_SKILLSPECTOR_INCOMPLETE_EXAMPLES]
+ )
+ remaining = len(ledger_exceptions) - _SKILLSPECTOR_INCOMPLETE_EXAMPLES
+ if remaining > 0:
+ locations = f"{locations} (+{remaining} more)"
+ result.add_finding(
+ Finding(
+ category="SCAN",
+ severity=Severity.INFO,
+ check_name="skillspector_reference_caveats",
+ message=(
+ f"SkillSpector inspected all {accepted_reference_caveats['fully_inspected_files']} bundled file(s). "
+ f"{accepted_reference_caveats['count']} missing-reference caveat(s) remain; "
+ f"review referenced paths at {locations}. "
+ "Referenced targets were not verified; the scanner's original partial status is retained."
+ ),
+ file_path=ledger_exceptions[0]["path"],
+ line_number=ledger_exceptions[0]["start_line"],
+ suggestion="Review the referenced paths; only files bundled in this skill were inspected.",
+ metadata={
+ "scanner_status": "partial",
+ "scanner_recommendation": recommendation,
+ "missing_targets_verified": False,
+ },
+ )
+ )
return True
@staticmethod
@@ -3596,7 +3645,7 @@ class SecurityValidator(ValidatorBase):
if source_root is None:
if path.name in SCAN_EXCLUDED_FILES:
return True
- return any(part in SCAN_EXCLUDED_DIRS for part in path.parts)
+ return any(part in _SKILLSPECTOR_SCAN_EXCLUDED_DIRS for part in path.parts)
root = Path(os.path.abspath(source_root)) # noqa: PTH100 - do not follow untrusted path links
candidate = path if path.is_absolute() else root / path
@@ -3611,7 +3660,7 @@ class SecurityValidator(ValidatorBase):
current = root
for part in relative.parts[:-1]:
current /= part
- if matches_filesystem_name(current, SCAN_EXCLUDED_DIRS):
+ if matches_filesystem_name(current, _SKILLSPECTOR_SCAN_EXCLUDED_DIRS):
return True
return False
@@ -3809,9 +3858,14 @@ class SecurityValidator(ValidatorBase):
baseline["suppressed_by_severity"] = by_severity
baseline["suppressed_rule_ids"] = summary.get("rule_ids") if isinstance(summary.get("rule_ids"), list) else []
llm_stage_suppressed = llm_suppressed if isinstance(llm_suppressed, int) else None
+ # Coverage advisories remain visible, but are not active scanner issues
+ # and cannot be suppressed by a reviewed vulnerability baseline.
+ active_findings = [
+ finding for finding in result.findings if finding.check_name != "skillspector_reference_caveats"
+ ]
blocking = sum(
1
- for finding in result.findings
+ for finding in active_findings
if (finding.severity if isinstance(finding.severity, Severity) else Severity(str(finding.severity).lower()))
in (Severity.CRITICAL, Severity.HIGH)
)
@@ -3821,7 +3875,7 @@ class SecurityValidator(ValidatorBase):
"runtime_scanner_version": runtime_version,
"suppressed_findings": suppressed,
"llm_stage_suppressed_findings": llm_stage_suppressed,
- "active_findings": len(result.findings),
+ "active_findings": len(active_findings),
"active_blocking_findings": blocking,
}
)
@@ -4840,19 +4894,24 @@ class SecurityValidator(ValidatorBase):
result: ValidationResult,
skill_path: Path,
) -> None:
- """Run LLM second-pass verification on all findings.
+ """Run LLM second-pass verification on security findings.
Findings the LLM classifies as false_positive with high confidence
are downgraded to INFO severity and annotated in metadata.
"""
- if not result.findings:
+ # This diagnostic reports scanner coverage, not a vulnerability whose
+ # truth can be adjudicated by the model. Keep its evidence unchanged.
+ findings = [
+ finding for finding in result.findings if finding.check_name != "skillspector_reference_caveats"
+ ]
+ if not findings:
return
from skillevaluator.inference import FindingVerifier
- logger.info(f"Running LLM verification on {len(result.findings)} finding(s)")
+ logger.info(f"Running LLM verification on {len(findings)} finding(s)")
verifier = FindingVerifier()
- verdicts = verifier.verify(result.findings, skill_path)
+ verdicts = verifier.verify(findings, skill_path)
if not verdicts:
result.mark_scan_incomplete("llm-verification")
@@ -4862,7 +4921,7 @@ class SecurityValidator(ValidatorBase):
suppressed = 0
verified = 0
- for idx, finding in enumerate(result.findings):
+ for idx, finding in enumerate(findings):
verdict_data = verdicts.get(idx)
if not isinstance(verdict_data, dict) or not verdict_data:
continue
@@ -4895,14 +4954,14 @@ class SecurityValidator(ValidatorBase):
result.recalculate_from_findings()
result.add_message(f"LLM verification downgraded {suppressed} finding(s) to INFO (false positives)")
- unverified = len(result.findings) - verified
+ unverified = len(findings) - verified
if unverified:
result.mark_scan_incomplete("llm-verification")
noun = "finding" if unverified == 1 else "findings"
verb = "was" if unverified == 1 else "were"
cause = f": {verifier.last_failure}" if verifier.last_failure else ""
result.add_message(
- f"LLM verification returned verdicts for {verified} of {len(result.findings)} findings; "
+ f"LLM verification returned verdicts for {verified} of {len(findings)} findings; "
f"{unverified} {noun} {verb} not verified{cause}"
)
elif not suppressed:
diff --git a/tests/ci/test_evaluate_workflow.py b/tests/ci/test_evaluate_workflow.py
index c1bfd664..8c824394 100644
--- a/tests/ci/test_evaluate_workflow.py
+++ b/tests/ci/test_evaluate_workflow.py
@@ -34,10 +34,17 @@ def test_pr_history_mode_and_attempt_artifact_wiring():
)
# Only changed mode fetches history, and it skips old file contents.
# The numbers are ordered so that 0, which is falsy, is never the && operand.
- assert checkout["with"]["fetch-depth"] == "${{ env.SCAN_MODE != 'changed' && 1 || 0 }}"
- assert checkout["with"]["filter"] == "${{ env.SCAN_MODE == 'changed' && 'blob:none' || '' }}"
+ assert (
+ checkout["with"]["fetch-depth"] == "${{ !inputs.security-baselines && env.SCAN_MODE != 'changed' && 1 || 0 }}"
+ )
+ assert (
+ checkout["with"]["filter"]
+ == "${{ !inputs.security-baselines && env.SCAN_MODE == 'changed' && 'blob:none' || '' }}"
+ )
assert checkout["with"]["ref"] == env["DIFF_HEAD_SHA"] == "${{ github.event.pull_request.head.sha || github.sha }}"
assert env["DIFF_BASE_SHA"] == "${{ github.event.pull_request.base.sha }}"
+ assert env["POLICY_SOURCE_SHA"] == "${{ github.event.pull_request.base.sha || github.sha }}"
+ assert env["SECURITY_BASELINES"] == "${{ inputs.security-baselines }}"
assert env["LLM_API_KEY"] == "${{ inputs.llm && secrets.LLM_API_KEY || '' }}"
assert env["CALLER_WORKFLOW_SHA"] == "${{ github.workflow_sha }}"
assert env["SCAN_WORKERS"] == "${{ inputs.scan-workers }}"
@@ -70,7 +77,15 @@ def test_real_workflow_shell_preserves_container_boundary_and_secret_selection(t
subprocess.run(["bash", "-e", "-o", "pipefail", "-c", scan["run"]], env=env, check=True, capture_output=True)
args = json.loads(captured.read_text())
passed_environment = [args[index + 1] for index, arg in enumerate(args) if arg == "--env"]
- assert {"SCAN_MODE", "DIFF_BASE_SHA", "DIFF_HEAD_SHA", "MIN_SCORE", "SCAN_WORKERS"}.issubset(passed_environment)
+ assert {
+ "SCAN_MODE",
+ "DIFF_BASE_SHA",
+ "DIFF_HEAD_SHA",
+ "MIN_SCORE",
+ "SCAN_WORKERS",
+ "POLICY_SOURCE_SHA",
+ "SECURITY_BASELINES",
+ }.issubset(passed_environment)
assert ("LLM_API_KEY" in args) is (llm == "true")
for flag in ("--read-only", "--user", "--cap-drop", "--security-opt"):
assert flag in args
diff --git a/tests/ci/test_gitlab_template.py b/tests/ci/test_gitlab_template.py
index b7f5fc70..9cd30be6 100644
--- a/tests/ci/test_gitlab_template.py
+++ b/tests/ci/test_gitlab_template.py
@@ -68,6 +68,18 @@ def test_gitlab_job_runs_all_skills_on_push_and_keeps_output(tmp_path):
assert evidence == ["all", "", "", "80"]
+def test_gitlab_baseline_opt_in_rejects_noncanonical_boolean_and_inherited_policy(tmp_path):
+ result, evidence = _run_template(
+ tmp_path,
+ {
+ "SKILL_EVAL_SECURITY_BASELINES": "TRUE",
+ "POLICY_SOURCE_SHA": "a" * 40,
+ },
+ )
+ assert result.returncode != 0
+ assert evidence is None
+
+
def test_gitlab_job_uses_mr_diff_and_retains_failed_results(tmp_path):
result, evidence = _run_template(
tmp_path,
diff --git a/tests/ci/test_prepare_security_baselines.py b/tests/ci/test_prepare_security_baselines.py
new file mode 100644
index 00000000..31e5b1c7
--- /dev/null
+++ b/tests/ci/test_prepare_security_baselines.py
@@ -0,0 +1,95 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+"""Resolve GitLab policy authority using real commits and a local Git remote."""
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).parents[2]
+HELPER = ROOT / "ci/prepare_security_baselines.py"
+
+
+def git(root, *args):
+ return subprocess.check_output(["git", "-C", str(root), "-c", "commit.gpgSign=false", *args], text=True).strip()
+
+
+def repository(tmp_path):
+ remote = tmp_path / "remote"
+ remote.mkdir()
+ git(remote, "init", "-q", "-b", "main")
+ git(remote, "config", "user.name", "Baseline test")
+ git(remote, "config", "user.email", "[email protected]")
+ (remote / "policy").write_text("approved\n")
+ git(remote, "add", ".")
+ git(remote, "commit", "-qm", "approved")
+ base = git(remote, "rev-parse", "HEAD")
+ git(remote, "checkout", "-qb", "feature")
+ (remote / "policy").write_text("candidate\n")
+ git(remote, "commit", "-qam", "candidate")
+ head = git(remote, "rev-parse", "HEAD")
+ checkout = tmp_path / "checkout"
+ subprocess.run(["git", "clone", "-q", str(remote), str(checkout)], check=True)
+ return checkout, base, head
+
+
+def run(workspace, **extra):
+ env = {key: value for key, value in os.environ.items() if key in ("PATH", "LANG", "LC_ALL")}
+ env.update(
+ {
+ "CI_PROJECT_DIR": str(workspace),
+ "CI_PIPELINE_SOURCE": "merge_request_event",
+ "CI_PROJECT_ID": "42",
+ "CI_MERGE_REQUEST_TARGET_PROJECT_ID": "42",
+ "CI_MERGE_REQUEST_TARGET_BRANCH_NAME": "main",
+ **extra,
+ }
+ )
+ return subprocess.run([sys.executable, "-I", str(HELPER)], env=env, capture_output=True, text=True)
+
+
+def test_detached_gitlab_mr_resolves_target_branch_instead_of_candidate_or_merge_base(tmp_path):
+ workspace, base, head = repository(tmp_path)
+ result = run(workspace, CI_COMMIT_SHA=head, CI_MERGE_REQUEST_DIFF_BASE_SHA="0" * 40)
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == base
+
+
+def test_gitlab_target_fetch_preserves_existing_diff_base_ancestry(tmp_path):
+ workspace, base, intermediate = repository(tmp_path)
+ git(workspace, "config", "user.name", "Baseline test")
+ git(workspace, "config", "user.email", "[email protected]")
+ (workspace / "policy").write_text("candidate follow-up\n")
+ git(workspace, "commit", "-qam", "candidate follow-up")
+ head = git(workspace, "rev-parse", "HEAD")
+ git(tmp_path / "remote", "update-ref", "refs/heads/main", intermediate)
+ assert git(workspace, "merge-base", base, head) == base
+ result = run(workspace, CI_COMMIT_SHA=head, CI_MERGE_REQUEST_DIFF_BASE_SHA=base)
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == intermediate
+ assert git(workspace, "merge-base", base, head) == base
+ assert git(workspace, "rev-parse", "--is-shallow-repository") == "false"
+
+
+def test_gitlab_push_uses_platform_commit(tmp_path):
+ workspace, _, head = repository(tmp_path)
+ result = run(workspace, CI_PIPELINE_SOURCE="push", CI_COMMIT_SHA=head)
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == head
+
+
+def test_gitlab_fork_without_available_exact_target_sha_fails_closed(tmp_path):
+ workspace, _, head = repository(tmp_path)
+ result = run(workspace, CI_COMMIT_SHA=head, CI_MERGE_REQUEST_TARGET_PROJECT_ID="99")
+ assert result.returncode != 0
+ assert "target" in result.stderr.lower()
+
+
+def test_gitlab_fork_can_use_available_platform_target_commit(tmp_path):
+ workspace, base, head = repository(tmp_path)
+ result = run(
+ workspace, CI_COMMIT_SHA=head, CI_MERGE_REQUEST_TARGET_PROJECT_ID="99", CI_MERGE_REQUEST_TARGET_BRANCH_SHA=base
+ )
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == base
diff --git a/tests/ci/test_run_tier1.py b/tests/ci/test_run_tier1.py
index 072c29f5..9b419267 100644
--- a/tests/ci/test_run_tier1.py
+++ b/tests/ci/test_run_tier1.py
@@ -584,6 +584,267 @@ def selection_checkout(tmp_path):
return workspace, repository_commit(workspace)
+def baseline_checkout(tmp_path, manifest=None):
+ workspace, _ = selection_checkout(tmp_path)
+ policy = workspace / ".skillevaluator/skillspector-baselines.yaml"
+ policy.parent.mkdir()
+ policy.write_text(manifest or "version: 1\nbaselines:\n skills/a: policies/a.json\n")
+ baseline = workspace / "policies/a.json"
+ baseline.parent.mkdir()
+ baseline.write_text(json.dumps({"version": 2, "rules": [{"id": "PE5", "reason": "Reviewed exact policy"}]}))
+ return workspace, repository_commit(workspace), baseline.read_bytes()
+
+
+def test_security_baselines_use_reviewed_mapping_and_bytes_not_pr_head(tmp_path):
+ workspace, approved, approved_bytes = baseline_checkout(tmp_path)
+ (workspace / ".skillevaluator/skillspector-baselines.yaml").write_text(
+ "version: 1\nbaselines:\n skills/b: policies/a.json\n"
+ )
+ (workspace / "policies/a.json").write_text('{"version":2,"rules":[]}')
+ head = repository_commit(workspace)
+ calls, observed = [], []
+ fixture = fake_cli([(0, payload()), (0, payload())], calls)
+
+ def execute(argv, **kwargs):
+ if "--skillspector-baseline" in argv:
+ path = Path(argv[argv.index("--skillspector-baseline") + 1])
+ observed.append((argv[2], path.read_bytes(), path.is_relative_to(workspace)))
+ return fixture(argv, **kwargs)
+
+ reports = tmp_path / "reports"
+ assert (
+ runner.run(
+ workspace,
+ reports,
+ {
+ "SKILL_PATHS": "skills",
+ "SECURITY_BASELINES": "true",
+ "POLICY_SOURCE_SHA": approved,
+ "REPORT_COMMIT": head,
+ },
+ execute=execute,
+ )
+ == 0
+ )
+ assert observed == [(str(workspace / "skills/a"), approved_bytes, False)]
+ summary = json.loads((reports / "summary.json").read_text())
+ evidence = summary["execution"]["security_baselines"]
+ assert evidence["source_commit"] == approved
+ assert evidence["manifest"] == ".skillevaluator/skillspector-baselines.yaml"
+ assert re.fullmatch(r"sha256:[0-9a-f]{64}", evidence["manifest_digest"])
+ assert summary["skills"][0]["security_baseline"]["file"] == "policies/a.json"
+ assert "security_baseline" not in summary["skills"][1]
+
+
+def test_security_baselines_can_use_current_push_commit(tmp_path):
+ workspace, head, expected = baseline_checkout(tmp_path)
+ calls, observed = [], []
+ fixture = fake_cli([(0, payload()), (0, payload())], calls)
+
+ def execute(argv, **kwargs):
+ if "--skillspector-baseline" in argv:
+ observed.append(Path(argv[argv.index("--skillspector-baseline") + 1]).read_bytes())
+ return fixture(argv, **kwargs)
+
+ assert (
+ runner.run(
+ workspace,
+ tmp_path / "reports",
+ {
+ "SKILL_PATHS": "skills",
+ "SECURITY_BASELINES": "true",
+ "POLICY_SOURCE_SHA": head,
+ },
+ execute=execute,
+ )
+ == 0
+ )
+ assert observed == [expected]
+
+
+def test_security_baseline_audit_field_does_not_collide_with_configured_secret_fragment(tmp_path):
+ workspace, approved, _ = baseline_checkout(tmp_path)
+ (workspace / "skills/a/example.txt").write_text('secret="configuredSuperSecret987654321"\n')
+ calls, reports = [], tmp_path / "reports"
+ assert (
+ runner.run(
+ workspace,
+ reports,
+ {"SKILL_PATHS": "skills/a", "SECURITY_BASELINES": "true", "POLICY_SOURCE_SHA": approved},
+ execute=fake_cli([(0, payload())], calls),
+ )
+ == 0
+ )
+ assert len(calls) == 1
+ summary = json.loads((reports / "summary.json").read_text())
+ assert summary["execution"]["security_baselines"]["mapped_skill_count"] == 1
+ assert "configured_skills" not in summary["execution"]["security_baselines"]
+ assert "withheld" in (reports / "skill-001/stdout.log").read_text()
+
+
+def test_security_baselines_require_explicit_opt_in(tmp_path):
+ workspace, head, _ = baseline_checkout(tmp_path)
+ calls = []
+ assert (
+ runner.run(
+ workspace,
+ tmp_path / "reports",
+ {
+ "SKILL_PATHS": "skills",
+ "POLICY_SOURCE_SHA": head,
+ },
+ execute=fake_cli([(0, payload()), (0, payload())], calls),
+ )
+ == 0
+ )
+ assert all("--skillspector-baseline" not in argv for argv, _ in calls)
+
+
[email protected]("enabled", ["TRUE", " true ", "False", "yes"])
+def test_security_baselines_reject_noncanonical_boolean_input(tmp_path, enabled):
+ workspace, head, _ = baseline_checkout(tmp_path)
+ calls = []
+ assert (
+ runner.run(
+ workspace,
+ tmp_path / "reports",
+ {
+ "SKILL_PATHS": "skills",
+ "SECURITY_BASELINES": enabled,
+ "POLICY_SOURCE_SHA": head,
+ },
+ execute=fake_cli([(0, payload()), (0, payload())], calls),
+ )
+ == 1
+ )
+ assert not calls
+
+
[email protected]("source", ["", "HEAD", "0" * 40])
+def test_security_baselines_fail_closed_without_exact_available_policy_commit(tmp_path, source):
+ workspace, _, _ = baseline_checkout(tmp_path)
+ calls = []
+ assert (
+ runner.run(
+ workspace,
+ tmp_path / "reports",
+ {
+ "SKILL_PATHS": "skills",
+ "SECURITY_BASELINES": "true",
+ "POLICY_SOURCE_SHA": source,
+ },
+ execute=fake_cli([(0, payload()), (0, payload())], calls),
+ )
+ == 1
+ )
+ assert not calls
+
+
+ "manifest",
+ [
+ "version: 1\nbaselines:\n skills/a: policies/a.json\n skills/a: policies/b.json\n",
+ "version: 1\nbaselines:\n skills/a: ../a.json\n",
+ "version: 1\nbaselines:\n ../skills/a: policies/a.json\n",
+ "version: 2\nbaselines: {}\n",
+ "version: 1\nbaselines:\n skills/a: policies/missing.json\n",
+ "version: 1\nbaselines:\n skills/a: &approved policies/a.json\n skills/b: *approved\n",
+ 'version: 1\nbaselines:\n "skills/\\uD800": policies/a.json\n',
+ 'version: 1\nbaselines:\n skills/a: "policies/\\uD800.json"\n',
+ ],
+)
+def test_security_baselines_reject_invalid_reviewed_manifest_before_scanning(tmp_path, manifest):
+ workspace, approved, _ = baseline_checkout(tmp_path, manifest)
+ calls = []
+ assert (
+ runner.run(
+ workspace,
+ tmp_path / "reports",
+ {
+ "SKILL_PATHS": "skills",
+ "SECURITY_BASELINES": "true",
+ "POLICY_SOURCE_SHA": approved,
+ },
+ execute=fake_cli([(0, payload()), (0, payload())], calls),
+ )
+ == 1
+ )
+ assert not calls
+
+
+def test_security_baselines_reject_symlink_blob_from_approved_commit(tmp_path):
+ workspace, _, _ = baseline_checkout(tmp_path)
+ (workspace / "policies/a.json").unlink()
+ (workspace / "policies/a.json").symlink_to("../secret")
+ approved = repository_commit(workspace)
+ calls = []
+ assert (
+ runner.run(
+ workspace,
+ tmp_path / "reports",
+ {
+ "SKILL_PATHS": "skills",
+ "SECURITY_BASELINES": "true",
+ "POLICY_SOURCE_SHA": approved,
+ },
+ execute=fake_cli([(0, payload()), (0, payload())], calls),
+ )
+ == 1
+ )
+ assert not calls
+
+
[email protected]("escaped", [False, True])
+def test_security_baselines_redact_credentials_only_in_approved_policy_bytes(tmp_path, escaped):
+ workspace, _, _ = baseline_checkout(tmp_path)
+ token = "nvapi-" + "A1" * 25
+ approved_content = json.dumps({"version": 2, "scanner_version": token, "rules": []})
+ if escaped:
+ approved_content = approved_content.replace(token, "\\u006e" + token[1:])
+ (workspace / "policies/a.json").write_text(approved_content)
+ approved = repository_commit(workspace)
+ (workspace / "policies/a.json").write_text('{"version":2,"rules":[]}')
+ repository_commit(workspace)
+ report = payload(passed=False)
+ report["results"][0]["findings"][0]["message"] = "Baseline scanner version mismatch: " + token
+ reports = tmp_path / "reports"
+ assert (
+ runner.run(
+ workspace,
+ reports,
+ {
+ "SKILL_PATHS": "skills/a",
+ "SECURITY_BASELINES": "true",
+ "POLICY_SOURCE_SHA": approved,
+ },
+ execute=fake_cli([(1, report)], []),
+ )
+ == 1
+ )
+ assert all(token.encode() not in path.read_bytes() for path in reports.rglob("*") if path.is_file())
+ assert "withheld" in (reports / "skill-001/stdout.log").read_text()
+
+
[email protected]("content", ['!!int ""', '!!timestamp ""', '!!bool ""'])
+def test_security_baselines_reject_malformed_scalar_before_scanning(tmp_path, content):
+ workspace, _, _ = baseline_checkout(tmp_path)
+ (workspace / "policies/a.json").write_text(content)
+ approved = repository_commit(workspace)
+ calls, reports = [], tmp_path / "reports"
+ assert (
+ runner.run(
+ workspace,
+ reports,
+ {"SKILL_PATHS": "skills", "SECURITY_BASELINES": "true", "POLICY_SOURCE_SHA": approved},
+ execute=fake_cli([(0, payload()), (0, payload())], calls),
+ )
+ == 1
+ )
+ assert not calls
+ summary = json.loads((reports / "summary.json").read_text())
+ assert "Credential preflight" in summary["error"]
+
+
def test_changed_mode_runs_only_changed_skill_from_real_git_history(tmp_path):
workspace, base = selection_checkout(tmp_path)
(workspace / "skills/a/SKILL.md").write_text("# Changed skill\n")
@@ -796,12 +1057,15 @@ def test_quality_threshold_is_forwarded_to_evaluator(tmp_path, score, workers):
skill(workspace, "skills/a")
skill(workspace, "skills/b")
calls = []
- assert runner.run(
- workspace,
- tmp_path / "reports",
- {"SKILL_PATHS": "skills", "MIN_SCORE": score, "SCAN_WORKERS": workers},
- execute=fake_cli([(0, payload()), (0, payload())], calls),
- ) == 0
+ assert (
+ runner.run(
+ workspace,
+ tmp_path / "reports",
+ {"SKILL_PATHS": "skills", "MIN_SCORE": score, "SCAN_WORKERS": workers},
+ execute=fake_cli([(0, payload()), (0, payload())], calls),
+ )
+ == 0
+ )
assert len(calls) == 2
for argv, _env in calls:
assert argv[argv.index("--min-score") + 1] == score
@@ -812,12 +1076,15 @@ def test_invalid_quality_threshold_fails_without_running_scanner(tmp_path, score
workspace = tmp_path / "workspace"
skill(workspace, "skills/a")
calls = []
- assert runner.run(
- workspace,
- tmp_path / "reports",
- {"SKILL_PATHS": "skills", "MIN_SCORE": score},
- execute=fake_cli([(0, payload())], calls),
- ) == 1
+ assert (
+ runner.run(
+ workspace,
+ tmp_path / "reports",
+ {"SKILL_PATHS": "skills", "MIN_SCORE": score},
+ execute=fake_cli([(0, payload())], calls),
+ )
+ == 1
+ )
assert not calls
summary = json.loads((tmp_path / "reports/summary.json").read_text())
assert summary["overall_status"] == "error"
diff --git a/tests/fixtures/skillspector-2.13.3-reference-caveat/README.md b/tests/fixtures/skillspector-2.13.3-reference-caveat/README.md
new file mode 100644
index 00000000..52fdeb42
--- /dev/null
+++ b/tests/fixtures/skillspector-2.13.3-reference-caveat/README.md
@@ -0,0 +1,15 @@
+# Missing-reference report
+
+`report.json` is the unmodified output of SkillSpector 2.13.3 scanning the synthetic
+`SKILL.md` in this directory, on 2026-11-10. No customer content is included.
+
+The pinned image was
+`ghcr.io/nvidia/skillevaluator-tier1@sha256:a3baec51f48145cdf9de05a5ab054d9576f62f1de0f5276b788410f5c17747d4`.
+Only `SKILL.md` was mounted at `/workspace`. The entrypoint was
+`/opt/skillspector/bin/skillspector scan /workspace/. --format json --no-llm`,
+with network disabled and a read-only root filesystem. It exited 0.
+
+All bundled content was inspected. The report remains `partial` / `CAUTION`
+because a runtime example path and a version string were interpreted as missing
+local references. Acceptance as a warning must preserve those caveats; it cannot
+certify the absent targets or ignore any other inspection gap.
diff --git a/tests/fixtures/skillspector-2.13.3-reference-caveat/SKILL.md b/tests/fixtures/skillspector-2.13.3-reference-caveat/SKILL.md
new file mode 100644
index 00000000..b02334a6
--- /dev/null
+++ b/tests/fixtures/skillspector-2.13.3-reference-caveat/SKILL.md
@@ -0,0 +1,13 @@
+---
+name: reference-caveat-example
+description: Explain configuration examples without executing code.
+metadata:
+ author: Example Maintainer <[email protected]>
+ version: "1.0"
+---
+
+# Reference example
+
+Explain how another project can create `examples/config.yaml` at runtime.
+The example package version is `1.2.3`.
+Do not run commands or claim the other project was inspected.
diff --git a/tests/fixtures/skillspector-2.13.3-reference-caveat/report.json b/tests/fixtures/skillspector-2.13.3-reference-caveat/report.json
new file mode 100644
index 00000000..11ff72be
--- /dev/null
+++ b/tests/fixtures/skillspector-2.13.3-reference-caveat/report.json
@@ -0,0 +1,498 @@
+{
+ "skill": {
+ "name": "reference-caveat-example",
+ "source": "/workspace",
+ "scanned_at": "2026-11-10T22:48:35.286725+00:00"
+ },
+ "risk_assessment": {
+ "score": 0,
+ "severity": "LOW",
+ "recommendation": "CAUTION",
+ "max_issue_severity": "NONE"
+ },
+ "components": [
+ {
+ "path": "SKILL.md",
+ "type": "markdown",
+ "lines": 13,
+ "executable": false,
+ "size_bytes": 386,
+ "source_url": null,
+ "source_identity": null,
+ "source_digest": null
+ }
+ ],
+ "structured_summaries": [],
+ "issues": [],
+ "suppressed_count": 0,
+ "suppressed": [],
+ "metadata": {
+ "has_executable_scripts": false,
+ "skillspector_version": "2.13.3",
+ "llm_requested": false,
+ "llm_available": false,
+ "meta_analysis_applied": false,
+ "inference_usage": [],
+ "llm_provenance": {
+ "schema_version": 1,
+ "provider": {
+ "configured_adapter": "unknown",
+ "resolved_adapter": "unknown",
+ "effective_adapter": "not_applicable",
+ "effective_adapters": [],
+ "service": "unknown",
+ "routing": {
+ "deployment_override": null,
+ "deployment_source": "unknown",
+ "api_version": null,
+ "api_version_source": "unknown"
+ }
+ },
+ "analyzers": [
+ {
+ "analyzer_id": "mcp_tool_poisoning",
+ "model": "z-ai/glm-5.3",
+ "model_source": "resolved_configuration",
+ "analyzer_revision": {
+ "value": "2.13.3",
+ "source": "skillspector_package",
+ "source_revision": {
+ "value": "unknown",
+ "source": "unknown"
+ }
+ }
+ },
+ {
+ "analyzer_id": "semantic_developer_intent",
+ "model": "z-ai/glm-5.3",
+ "model_source": "resolved_configuration",
+ "analyzer_revision": {
+ "value": "2.13.3",
+ "source": "skillspector_package",
+ "source_revision": {
+ "value": "unknown",
+ "source": "unknown"
+ }
+ }
+ },
+ {
+ "analyzer_id": "semantic_quality_policy",
+ "model": "z-ai/glm-5.3",
+ "model_source": "resolved_configuration",
+ "analyzer_revision": {
+ "value": "2.13.3",
+ "source": "skillspector_package",
+ "source_revision": {
+ "value": "unknown",
+ "source": "unknown"
+ }
+ }
+ },
+ {
+ "analyzer_id": "semantic_security_discovery",
+ "model": "z-ai/glm-5.3",
+ "model_source": "resolved_configuration",
+ "analyzer_revision": {
+ "value": "2.13.3",
+ "source": "skillspector_package",
+ "source_revision": {
+ "value": "unknown",
+ "source": "unknown"
+ }
+ }
+ },
+ {
+ "analyzer_id": "meta_analyzer",
+ "model": "z-ai/glm-5.3",
+ "model_source": "resolved_configuration",
+ "analyzer_revision": {
+ "value": "2.13.3",
+ "source": "skillspector_package",
+ "source_revision": {
+ "value": "unknown",
+ "source": "unknown"
+ }
+ }
+ }
+ ],
+ "sampling": {
+ "temperature": {
+ "requested": null,
+ "source": "provider_default",
+ "forwarded_to_client": null,
+ "adapter_support": false,
+ "provider_support": "unknown"
+ },
+ "seed": {
+ "requested": null,
+ "source": "unset",
+ "forwarded_to_client": null,
+ "adapter_support": false,
+ "provider_support": "unknown"
+ },
+ "reasoning_effort": {
+ "requested": null,
+ "source": "provider_default",
+ "forwarded_to_client": null,
+ "adapter_support": false,
+ "provider_support": "unknown"
+ }
+ },
+ "determinism": {
+ "classification": "not_applicable",
+ "control_status": "not_applied",
+ "provider_guarantee": false,
+ "reason": "LLM analysis was not executed for this scan."
+ }
+ },
+ "filtering_mode": "heuristic"
+ },
+ "execution_successful": true,
+ "analysis_completeness": {
+ "total_components": 1,
+ "scanned_components": 1,
+ "coverage_percent": 100.0,
+ "is_complete": false,
+ "status": "partial",
+ "execution_successful": true,
+ "fully_inspected_files": 1,
+ "partially_inspected_files": 0,
+ "entirely_uninspected_files": 0,
+ "ledger_exceptions": [
+ {
+ "outcome": "partial",
+ "phase": "reference_resolution",
+ "reason_code": "reference_missing",
+ "message": "A local path-like reference does not match any bundled artifact, such as a file the skill writes at runtime.",
+ "path": "SKILL.md",
+ "start_line": 11,
+ "end_line": 11,
+ "fatal": false
+ },
+ {
+ "outcome": "partial",
+ "phase": "reference_resolution",
+ "reason_code": "reference_missing",
+ "message": "A local path-like reference does not match any bundled artifact, such as a file the skill writes at runtime.",
+ "path": "SKILL.md",
+ "start_line": 12,
+ "end_line": 12,
+ "fatal": false
+ }
+ ],
+ "scope_exclusions": [],
+ "analyzer_statuses": [
+ {
+ "analyzer_id": "artifact_integrity",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "behavioral_ast",
+ "status": "not_applicable",
+ "planned_work": 0,
+ "completed": 0,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0,
+ "reason_code": "no_applicable_files",
+ "message": "No files matched this analyzer's applicability contract."
+ },
+ {
+ "analyzer_id": "behavioral_taint_tracking",
+ "status": "not_applicable",
+ "planned_work": 0,
+ "completed": 0,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0,
+ "reason_code": "no_applicable_files",
+ "message": "No files matched this analyzer's applicability contract."
+ },
+ {
+ "analyzer_id": "bundled_execution_surface",
+ "status": "not_applicable",
+ "planned_work": 0,
+ "completed": 0,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0,
+ "reason_code": "no_applicable_files",
+ "message": "No files matched this analyzer's applicability contract."
+ },
+ {
+ "analyzer_id": "mcp_least_privilege",
+ "status": "not_applicable",
+ "planned_work": 0,
+ "completed": 0,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0,
+ "reason_code": "no_applicable_files",
+ "message": "No files matched this analyzer's applicability contract."
+ },
+ {
+ "analyzer_id": "mcp_rug_pull",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "mcp_tool_poisoning",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "meta_analyzer",
+ "status": "not_applicable",
+ "planned_work": 0,
+ "completed": 0,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0,
+ "reason_code": "no_applicable_files",
+ "message": "No files matched this analyzer's applicability contract."
+ },
+ {
+ "analyzer_id": "semantic_developer_intent",
+ "status": "disabled",
+ "planned_work": 0,
+ "completed": 0,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0,
+ "reason_code": "disabled_by_configuration",
+ "message": "Analyzer was disabled by the requested configuration."
+ },
+ {
+ "analyzer_id": "semantic_quality_policy",
+ "status": "disabled",
+ "planned_work": 0,
+ "completed": 0,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0,
+ "reason_code": "disabled_by_configuration",
+ "message": "Analyzer was disabled by the requested configuration."
+ },
+ {
+ "analyzer_id": "semantic_security_discovery",
+ "status": "disabled",
+ "planned_work": 0,
+ "completed": 0,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0,
+ "reason_code": "disabled_by_configuration",
+ "message": "Analyzer was disabled by the requested configuration."
+ },
+ {
+ "analyzer_id": "static_patterns_agent_snooping",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_anti_refusal",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_data_exfiltration",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_deserialization",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_excessive_agency",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_harmful_content",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_memory_poisoning",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_output_handling",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_privilege_escalation",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_prompt_injection",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_rogue_agent",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_ssrf",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_supply_chain",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_system_prompt_leakage",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_patterns_tool_misuse",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ },
+ {
+ "analyzer_id": "static_yara",
+ "status": "completed",
+ "planned_work": 1,
+ "completed": 1,
+ "partial": 0,
+ "skipped": 0,
+ "failed": 0,
+ "unaccounted": 0
+ }
+ ],
+ "references": [
+ {
+ "source_path": "SKILL.md",
+ "line": 11,
+ "column": 41,
+ "evidence": "Explain how another project can create `examples/config.yaml` at runtime.",
+ "target_path": null,
+ "status": "missing",
+ "disposition": "partial",
+ "reference_kind": "quoted_or_code"
+ },
+ {
+ "source_path": "SKILL.md",
+ "line": 12,
+ "column": 33,
+ "evidence": "The example package version is `1.2.3`.",
+ "target_path": null,
+ "status": "missing",
+ "disposition": "partial",
+ "reference_kind": "quoted_or_code"
+ }
+ ],
+ "limitations": [],
+ "findings_before_filtering": 0,
+ "findings_after_filtering": 0
+ }
+}
diff --git a/tests/validators/test_artifact_dir_exclusion.py b/tests/validators/test_artifact_dir_exclusion.py
index ac0a659c..9045720b 100644
--- a/tests/validators/test_artifact_dir_exclusion.py
+++ b/tests/validators/test_artifact_dir_exclusion.py
@@ -1,13 +1,14 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
-"""Artifact dirs (evals/, results/, ...) must be skipped, not just filtered.
+"""Generated output dirs must be skipped, not just filtered.
A skill that has been through Tier 3 accumulates hundreds of MB under
``evals/results/``. Tier 1 must never traverse those subtrees
(``iter_scannable_files`` pruning), never hand them to scanners that lack
exclude flags (skillspector scans a filtered copy), and never report
findings from them (gitleaks config allowlist, skillspector issue filter).
+SkillSpector retains authored evals/ inputs while pruning their results/.
Regression source: a real skill dir with 798MB / 53k artifact files took
~25 minutes to validate and reported 270 artifact-only secret findings.
"""
@@ -136,7 +137,8 @@ class TestSkillspectorFilteredCopy:
seen["path"] = scanned
seen["has_manifest"] = (scanned / "SKILL.md").is_file()
seen["has_payload"] = (scanned / "payload.py").is_file()
- seen["artifact_dirs"] = sorted(d.name for d in scanned.iterdir() if d.name in SCAN_EXCLUDED_DIRS)
+ seen["root_results"] = (scanned / "results").exists()
+ seen["eval_results"] = (scanned / "evals" / "results").exists()
return _clean_spector_result()
mock_run.side_effect = capture
@@ -145,7 +147,7 @@ class TestSkillspectorFilteredCopy:
assert seen["path"] != skill_with_artifacts.resolve()
assert seen["path"].name == "my-skill"
assert seen["has_manifest"] and seen["has_payload"]
- assert seen["artifact_dirs"] == []
+ assert not seen["root_results"] and not seen["eval_results"]
assert not seen["path"].exists() # temp copy cleaned up afterwards
@patch.object(Tools.skillspector, "_path", "/usr/bin/skillspector")
@@ -273,8 +275,9 @@ class TestSkillspectorFilteredCopy:
("relative", "passes_staged_copy"),
[
("config/skillspector-baseline.yaml", True),
+ ("evals/skillspector-baseline.yaml", True),
# Excluded from the staged copy, so it is outside the scan either way.
- ("evals/skillspector-baseline.yaml", False),
+ ("evals/results/skillspector-baseline.yaml", False),
],
)
@patch.object(Tools.skillspector, "_path", "/usr/bin/skillspector")
@@ -399,7 +402,7 @@ class TestSkillspectorArtifactIssueFilter:
assert SecurityValidator._is_generated_artifact_issue(issue) is True
def test_issue_under_absolute_artifact_path_is_filtered(self):
- issue = {"location": {"file": "/home/u/skill/evals/leak.py", "start_line": 3}}
+ issue = {"location": {"file": "/home/u/skill/evals/results/leak.py", "start_line": 3}}
assert SecurityValidator._is_generated_artifact_issue(issue) is True
def test_live_issue_is_kept(self):
diff --git a/tests/validators/test_security.py b/tests/validators/test_security.py
index eb791c36..1b66c228 100644
--- a/tests/validators/test_security.py
+++ b/tests/validators/test_security.py
@@ -2004,7 +2004,7 @@ print(json.dumps([finding.metadata["matched_value"] for finding in result.findin
"id": "G1",
"severity": "LOW",
"finding": "generated evaluation output",
- "location": {"file": "evals/run-1/output.md", "start_line": 1},
+ "location": {"file": "evals/results/run-1/output.md", "start_line": 1},
}
)
payload = _skillspector_json_report(issues)
diff --git a/tests/validators/test_security_authored_evals.py b/tests/validators/test_security_authored_evals.py
new file mode 100644
index 00000000..522682b0
--- /dev/null
+++ b/tests/validators/test_security_authored_evals.py
@@ -0,0 +1,131 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Security staging preserves authored evaluation inputs and their findings."""
+
+import os
+from pathlib import Path
+
+import pytest
+
+from skillevaluator.utils.tool_runner import Tools
+from skillevaluator.validators.base import ValidationResult
+from skillevaluator.validators.security import SecurityValidator
+
+
[email protected]("eval_dir", ["evals", ".evals"])
[email protected]("use_llm", [False, True])
+def test_staged_security_scan_keeps_authored_eval_inputs(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, eval_dir: str, use_llm: bool
+) -> None:
+ skill = tmp_path / "skill"
+ authored = {
+ "SKILL.md": f"Read [{eval_dir}/config.yml]({eval_dir}/config.yml).\n".encode(),
+ f"{eval_dir}/config.yml": b"dependencies:\n - helper-skill\n",
+ f"{eval_dir}/EVAL.md": b"# Evaluate the skill\n",
+ f"{eval_dir}/evals.json": b'{"evals": []}\n',
+ f"{eval_dir}/scripts/check.py": b"print('authored evaluation helper')\n",
+ f"{eval_dir}/__pycache__/check.pyc": b"shipped bytecode",
+ }
+ for relative, content in authored.items():
+ target = skill / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(content)
+ generated = [skill / "results", skill / eval_dir / "results", skill / eval_dir / ".results"]
+ for directory in generated:
+ directory.mkdir()
+ (directory / "generated.log").write_text("generated output must not be traversed\n")
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "private.txt").write_text("outside the skill\n")
+ link = skill / eval_dir / "external"
+ link.symlink_to(outside, target_is_directory=True)
+ broken_link = skill / eval_dir / "unavailable"
+ broken_link.symlink_to("missing-target", target_is_directory=True)
+
+ real_scandir = os.scandir
+
+ def bounded_scandir(path="."):
+ if not isinstance(path, int):
+ assert Path(path) not in generated, "Generated output directories must not be traversed"
+ assert Path(path) != outside, "Staging must not follow directory symlinks"
+ return real_scandir(path)
+
+ monkeypatch.setattr(os, "scandir", bounded_scandir)
+ monkeypatch.setattr(Tools.skillspector, "_path", "/unused/skillspector")
+ validator = SecurityValidator(use_llm=use_llm)
+ seen: list[tuple[Path, bool]] = []
+
+ def inspect_input(scan_root: Path, *, original_root, use_llm, baseline):
+ assert scan_root != skill.resolve()
+ assert original_root == skill.resolve()
+ for relative, content in authored.items():
+ target = scan_root / relative
+ assert target.is_file(), f"Authored input was removed: {relative}"
+ assert target.read_bytes() == content
+ for directory in generated:
+ assert not (scan_root / directory.relative_to(skill)).exists()
+ assert (scan_root / eval_dir / "external").is_symlink()
+ assert (scan_root / eval_dir / "external").readlink() == outside
+ assert (scan_root / eval_dir / "unavailable").is_symlink()
+ seen.append((scan_root, use_llm))
+ return ValidationResult()
+
+ monkeypatch.setattr(validator, "_run_skillspector_once", inspect_input)
+ validator._run_skillspector(skill)
+
+ assert [llm for _root, llm in seen] == ([False, True] if use_llm else [False])
+ assert all(not root.exists() for root, _llm in seen)
+
+
[email protected]("eval_dir", ["evals", ".evals"])
+def test_authored_evals_alone_do_not_require_staging(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, eval_dir: str
+) -> None:
+ skill = tmp_path / "skill"
+ config = skill / eval_dir / "config.yml"
+ config.parent.mkdir(parents=True)
+ config.write_text("dependencies: []\n")
+ monkeypatch.setattr(Tools.skillspector, "_path", "/unused/skillspector")
+ validator = SecurityValidator()
+ seen = []
+
+ def inspect_input(scan_root: Path, *, original_root, use_llm, baseline):
+ seen.append(scan_root)
+ assert scan_root == skill.resolve()
+ assert original_root is None
+ assert (scan_root / eval_dir / "config.yml").read_text() == "dependencies: []\n"
+ return ValidationResult()
+
+ monkeypatch.setattr(validator, "_run_skillspector_once", inspect_input)
+ validator._run_skillspector(skill)
+
+ assert seen == [skill.resolve()]
+
+
[email protected]("eval_dir", ["evals", ".evals"])
[email protected]("absolute", [False, True])
[email protected]("with_source_root", [False, True])
+def test_authored_eval_finding_is_not_classified_as_generated(
+ tmp_path: Path, eval_dir: str, absolute: bool, with_source_root: bool
+) -> None:
+ skill = tmp_path / "skill"
+ target = skill / eval_dir / "scripts" / "check.py"
+ target.parent.mkdir(parents=True)
+ target.write_text("authored script\n")
+ reported_path = target if absolute else target.relative_to(skill)
+ issue = {"location": {"file": str(reported_path), "start_line": 1}}
+
+ assert not SecurityValidator._is_generated_artifact_issue(issue, source_root=skill if with_source_root else None)
+
+
[email protected]("eval_dir", ["evals", ".evals"])
[email protected]("output_dir", ["results", ".results"])
+def test_generated_eval_output_is_still_classified_as_generated(tmp_path: Path, eval_dir: str, output_dir: str) -> None:
+ skill = tmp_path / "skill"
+ target = skill / eval_dir / output_dir / "output.md"
+ target.parent.mkdir(parents=True)
+ target.write_text("generated output\n")
+ issue = {"location": {"file": str(target.relative_to(skill)), "start_line": 1}}
+
+ assert SecurityValidator._is_generated_artifact_issue(issue, source_root=skill)
diff --git a/tests/validators/test_security_reference_caveats.py b/tests/validators/test_security_reference_caveats.py
new file mode 100644
index 00000000..30c0aadf
--- /dev/null
+++ b/tests/validators/test_security_reference_caveats.py
@@ -0,0 +1,358 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Gate behavior for actual SkillSpector missing-reference reports."""
+
+import json
+from html.parser import HTMLParser
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from skillevaluator.reporting import HTMLReporter, JSONReporter, MarkdownReporter, SARIFReporter
+from skillevaluator.reporting.retained import retained_results
+from skillevaluator.validators.base import Finding, Severity, ValidationResult
+from skillevaluator.validators.security import SecurityValidator
+
+FIXTURE = Path(__file__).parents[1] / "fixtures" / "skillspector-2.13.3-reference-caveat"
+
+
+class ReportText(HTMLParser):
+ """Rendered body text, excluding JSON/script payloads that users cannot read."""
+
+ def __init__(self):
+ super().__init__()
+ self.parts = []
+ self.hidden = 0
+
+ def handle_starttag(self, tag, _attrs):
+ if tag in {"script", "style"}:
+ self.hidden += 1
+
+ def handle_endtag(self, tag):
+ if tag in {"script", "style"}:
+ self.hidden -= 1
+
+ def handle_data(self, data):
+ if not self.hidden:
+ self.parts.append(data)
+
+
+def captured_report() -> dict:
+ return json.loads((FIXTURE / "report.json").read_text())
+
+
+def validate_report(report: dict, *, use_llm: bool = False) -> ValidationResult:
+ result = ValidationResult(validator_name="Security Scan")
+ valid = SecurityValidator._validate_skillspector_report(
+ report,
+ 0,
+ use_llm,
+ "skillspector-llm" if use_llm else "skillspector",
+ result,
+ scanned_root=FIXTURE,
+ )
+ if not valid:
+ result.mark_scan_incomplete("skillspector-llm" if use_llm else "skillspector")
+ return result
+
+
+def test_fully_inspected_missing_reference_report_is_a_visible_warning():
+ """A generic partial gate must not discard complete bundled-file evidence."""
+ report = captured_report()
+ result = validate_report(report)
+
+ assert not result.is_incomplete, result.errors
+ assert not result.errors
+ assert any("Referenced targets were not verified" in warning for warning in result.warnings)
+ assert any("SKILL.md:11" in warning and "SKILL.md:12" in warning for warning in result.warnings)
+ assert result.metadata["skillspector_reference_caveats"] == {
+ "status": "partial",
+ "recommendation": "CAUTION",
+ "reason_code": "reference_missing",
+ "count": 2,
+ "fully_inspected_files": 1,
+ "missing_targets_verified": False,
+ }
+ assert report["analysis_completeness"]["is_complete"] is False
+ assert report["risk_assessment"]["recommendation"] == "CAUTION"
+
+
+ ("field", "value"),
+ [
+ ("reason_code", "reference_unresolved"),
+ ("reason_code", "runtime_limit"),
+ ("reason_code", "opaque_content"),
+ ("fatal", True),
+ ("phase", "cache"),
+ ("outcome", "failed"),
+ ("path", "missing-script.py"),
+ ("start_line", 0),
+ ("end_line", 9999),
+ ("analyzers", ["static_yara"]),
+ ("unknown_limit", True),
+ ],
+)
+def test_other_or_unverifiable_ledger_evidence_still_blocks(field, value):
+ report = captured_report()
+ report["analysis_completeness"]["ledger_exceptions"][0][field] = value
+
+ result = validate_report(report)
+
+ assert result.is_incomplete or result.errors
+ assert "skillspector_reference_caveats" not in result.metadata
+
+
+ ("field", "value"),
+ [
+ ("limitations", ["Analyzer unavailable"]),
+ ("coverage_percent", 99),
+ ("fully_inspected_files", 0),
+ ("partially_inspected_files", 1),
+ ("entirely_uninspected_files", 1),
+ ("execution_successful", False),
+ ("unknown_limit", True),
+ ("scope_exclusions", [{"fatal": True}]),
+ ],
+)
+def test_missing_reference_exception_does_not_hide_other_coverage_gaps(field, value):
+ report = captured_report()
+ report["analysis_completeness"][field] = value
+
+ result = validate_report(report)
+
+ assert result.is_incomplete or result.errors
+ assert "skillspector_reference_caveats" not in result.metadata
+
+
[email protected]("mutation", ["absent", "zero_work", "duplicate", "disabled", "partial"])
+def test_required_universal_analyzer_must_inspect_every_component(mutation):
+ report = captured_report()
+ statuses = report["analysis_completeness"]["analyzer_statuses"]
+ yara = next(row for row in statuses if row["analyzer_id"] == "static_yara")
+ if mutation == "absent":
+ statuses.remove(yara)
+ elif mutation == "zero_work":
+ yara.update(planned_work=0, completed=0)
+ elif mutation == "duplicate":
+ statuses.append(dict(yara))
+ elif mutation == "disabled":
+ yara.update(status="disabled", planned_work=0, completed=0, reason_code="disabled_by_configuration")
+ else:
+ yara.update(status="degraded", completed=0, partial=1)
+
+ result = validate_report(report)
+
+ assert result.is_incomplete or result.errors
+ assert "skillspector_reference_caveats" not in result.metadata
+
+
+def test_analyzer_not_applicable_requires_real_applicability_evidence():
+ report = captured_report()
+ ast = next(
+ row for row in report["analysis_completeness"]["analyzer_statuses"] if row["analyzer_id"] == "behavioral_ast"
+ )
+ ast.pop("reason_code")
+
+ assert validate_report(report).is_incomplete
+
+
[email protected]("version", ["2.13.2", "3.0.0"])
+def test_unverified_scanner_contract_does_not_gain_the_exception(version):
+ report = captured_report()
+ report["metadata"]["skillspector_version"] = version
+
+ assert validate_report(report).is_incomplete
+
+
+def test_requested_llm_analysis_is_still_required():
+ assert validate_report(captured_report(), use_llm=True).is_incomplete
+
+
[email protected]("field", ["risk_assessment", "components"])
+def test_malformed_report_sections_stay_incomplete_without_crashing(field):
+ report = captured_report()
+ report[field] = None
+
+ assert validate_report(report).is_incomplete
+
+
[email protected]("mutation", ["missing_ledger_match", "ambiguous", "invalid_resolved_target"])
+def test_reference_inventory_must_agree_with_the_missing_only_ledger(mutation):
+ report = captured_report()
+ references = report["analysis_completeness"]["references"]
+ if mutation == "missing_ledger_match":
+ references.pop()
+ elif mutation == "ambiguous":
+ references[0]["status"] = "ambiguous"
+ else:
+ references[0].update(status="resolved", disposition="analyzed", target_path={})
+
+ assert validate_report(report).is_incomplete
+
+
+def test_claiming_safe_or_hiding_an_inventory_entry_still_blocks():
+ report = captured_report()
+ report["risk_assessment"]["recommendation"] = "SAFE"
+ result = validate_report(report)
+ assert result.is_incomplete
+ assert "skillspector_reference_caveats" not in result.metadata
+
+ report = captured_report()
+ report["components"] = []
+ assert validate_report(report).is_incomplete
+
+
+def test_reference_warning_and_original_status_survive_report_serialization():
+ result = validate_report(captured_report())
+
+ payload = json.loads(JSONReporter(include_timestamp=False).render(result))
+ assert payload["skillspector_reference_caveats"]["status"] == "partial"
+ assert payload["skillspector_reference_caveats"]["missing_targets_verified"] is False
+ html = HTMLReporter().render(result)
+ assert "Referenced targets were not verified" in html
+ assert "SKILL.md:11" in html
+ reloaded = retained_results(json.loads(JSONReporter(include_timestamp=False).render_all([result])))[0]
+ assert reloaded.metadata["skillspector_reference_caveats"] == result.metadata["skillspector_reference_caveats"]
+ assert "Referenced targets were not verified" in HTMLReporter().render(reloaded)
+
+
+def test_reference_caveat_is_visible_in_actual_ci_render_all_outputs(tmp_path):
+ from ci.secret_redaction import sanitized_outputs
+
+ result = validate_report(captured_report())
+ payload = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ restored = retained_results(payload)
+ (tmp_path / "skillevaluator-tier1.json").write_text(json.dumps(payload))
+ for extension, reporter in (
+ ("html", HTMLReporter()),
+ ("md", MarkdownReporter()),
+ ("sarif.json", SARIFReporter()),
+ ):
+ (tmp_path / f"skillevaluator-tier1.{extension}").write_text(reporter.render_all(restored))
+ sanitized = sanitized_outputs(tmp_path, set())
+ parsed = ReportText()
+ parsed.feed(sanitized["skillevaluator-tier1.html"].decode())
+
+ assert "Referenced targets were not verified" in " ".join(parsed.parts)
+ assert "SKILL.md:11" in " ".join(parsed.parts)
+ assert b"Referenced targets were not verified" in sanitized["skillevaluator-tier1.md"]
+ sarif = json.loads(sanitized["skillevaluator-tier1.sarif.json"])
+ findings = sarif["runs"][0]["results"]
+ assert len(findings) == 1
+ assert "Referenced targets were not verified" in findings[0]["message"]["text"]
+ assert findings[0]["level"] == "note"
+ assert result.summary.warnings == 1
+ assert result.passed
+
+
+def test_reference_caveat_is_not_counted_as_an_active_baseline_finding(tmp_path):
+ from skillevaluator.validators.security import _inspect_skillspector_baseline
+
+ result = validate_report(captured_report())
+ SecurityValidator()._process_skillspector_cli_result(captured_report(), result)
+ baseline_path = tmp_path / "baseline.yaml"
+ baseline_path.write_text("version: 2\nrules: []\nfingerprints: []\n")
+ baseline, error = _inspect_skillspector_baseline(baseline_path)
+ assert error is None
+
+ SecurityValidator._report_skillspector_baseline(result, baseline, static_suppressed=0)
+
+ assert baseline["active_findings"] == 0
+ assert baseline["active_blocking_findings"] == 0
+ assert result.passed
+
+
[email protected]("with_issue", [False, True])
+def test_reference_evidence_advisory_is_not_sent_for_llm_finding_verification(tmp_path, with_issue):
+ result = validate_report(captured_report())
+ advisory = result.findings[0]
+ if with_issue:
+ issue = Finding(
+ category="SECURITY",
+ severity=Severity.HIGH,
+ check_name="Unreviewed execution",
+ message="A genuine issue still needs verification.",
+ file_path="SKILL.md",
+ )
+ result.add_finding(issue)
+
+ with patch("skillevaluator.inference.FindingVerifier") as verifier_cls:
+ verifier_cls.return_value.verify.return_value = {
+ 0: {"verdict": "true_positive", "confidence": "high", "rationale": "Confirmed issue."}
+ }
+ SecurityValidator(verify_llm=True)._verify_findings_with_llm(result, tmp_path)
+
+ if with_issue:
+ verifier_cls.return_value.verify.assert_called_once_with([issue], tmp_path)
+ assert issue.metadata["llm_verdict"] == "true_positive"
+ assert result.errors
+ else:
+ verifier_cls.assert_not_called()
+ assert result.passed
+ assert "llm_verdict" not in advisory.metadata
+ assert not result.is_incomplete
+
+
+ "field,value",
+ [
+ ("status", "complete"),
+ ("recommendation", "SAFE"),
+ ("missing_targets_verified", True),
+ ("count", True),
+ ("fully_inspected_files", 0),
+ ("untrusted_message", "arbitrary text"),
+ ],
+)
+def test_retained_caveat_metadata_cannot_claim_unverified_targets_are_safe(field, value):
+ result = validate_report(captured_report())
+ payload = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ payload["results"][0]["skillspector_reference_caveats"][field] = value
+
+ with pytest.raises(ValueError, match="Invalid skillspector_reference_caveats"):
+ retained_results(payload)
+
+
+def test_existing_security_findings_remain_blocking_with_reference_caveats():
+ path = FIXTURE.parent / "skillspector-2.13.3-passwd-mount" / "separate-read.json"
+ report = json.loads(path.read_text())
+ report["analysis_completeness"].update(
+ status="partial",
+ is_complete=False,
+ ledger_exceptions=[
+ {
+ "outcome": "partial",
+ "phase": "reference_resolution",
+ "reason_code": "reference_missing",
+ "message": "Unverified reference.",
+ "path": "SKILL.md",
+ "start_line": 1,
+ "end_line": 1,
+ "fatal": False,
+ }
+ ],
+ )
+ report["analysis_completeness"]["references"].append(
+ {
+ "source_path": "SKILL.md",
+ "line": 1,
+ "column": 1,
+ "evidence": "Unverified reference.",
+ "target_path": None,
+ "status": "missing",
+ "disposition": "partial",
+ "reference_kind": "quoted_or_code",
+ }
+ )
+ result = validate_report(report)
+ assert not result.is_incomplete
+
+ SecurityValidator()._process_skillspector_cli_result(report, result)
+
+ assert result.errors
+ assert not result.passed
+ assert any(finding.severity.value == "high" for finding in result.findings)