From 381867eebadfb4af97761c4ac8fa0e40071e8747 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 12:43:11 -0800 Subject: [PATCH 01/15] feat(tier1): name SkillSpector AE1 findings and say why each file was not inspected SkillSpector reports a High AE1 (incomplete referenced artifact analysis) finding at each line that names a file it did not completely inspect. The finding said only "Referenced artifact was not completely inspected", so the reason had to be matched by hand against the incomplete-analysis error. With SkillSpector before v2.12.0 it was titled "Unknown (AE1)" and suggested making the file available although SkillSpector had read part of it. The new skillspector_references module projects the finding's evidence: the target, its disposition and up to 16 reasons, read from the ledger rows of earlier releases, with bounded, redacted text and paths kept only inside the scan. The suggestion names the file and each reason, and the result counts the files and reference lines in skillspector_reference_summary and one message, also across the --llm stage and a folder of skills. Severities, completeness and gates are unchanged. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- src/skillevaluator/skillspector_references.py | 431 +++++++++ src/skillevaluator/validators/security.py | 96 +- ...ctor-2.11.2-perl-help-text-ae1-no-llm.json | 462 +++++++++ ...host-language-parse-limits-ae1-no-llm.json | 894 ++++++++++++++++++ ...or-2.13.3-perl-parse-limit-ae1-no-llm.json | 634 +++++++++++++ .../test_skillspector_ae1_contract.py | 74 ++ ...test_skillspector_reference_diagnostics.py | 618 ++++++++++++ 7 files changed, 3202 insertions(+), 7 deletions(-) create mode 100644 src/skillevaluator/skillspector_references.py create mode 100644 tests/fixtures/skillspector-2.11.2-perl-help-text-ae1-no-llm.json create mode 100644 tests/fixtures/skillspector-2.12.0-host-language-parse-limits-ae1-no-llm.json create mode 100644 tests/fixtures/skillspector-2.13.3-perl-parse-limit-ae1-no-llm.json create mode 100644 tests/validators/test_skillspector_ae1_contract.py create mode 100644 tests/validators/test_skillspector_reference_diagnostics.py diff --git a/src/skillevaluator/skillspector_references.py b/src/skillevaluator/skillspector_references.py new file mode 100644 index 000000000..9daa6eebf --- /dev/null +++ b/src/skillevaluator/skillspector_references.py @@ -0,0 +1,431 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Bounded projections of SkillSpector's incomplete-reference (AE1) evidence. + +SkillSpector reports a High ``AE1`` finding, *Incomplete referenced artifact +analysis*, at each line that names a file it did not completely inspect. From +v2.12.0 the issue's ``evidence`` names the file (``target_path``), its +``target_disposition`` and the ``reasons`` the analysis stopped. Earlier +releases leave ``pattern`` and ``evidence`` empty and name the file only in +the ``finding`` text, such as ``scripts/helper.pl (partial)``; the reasons are +then only in the ``analysis_completeness.ledger_exceptions`` rows for that +file. + +These projections explain a finding to its reader. They never change its +severity, the scan's completeness or a gate. Each text is bounded, free of +control characters and redacted with +:func:`~skillevaluator.utils.redaction.redact_sensitive_text`, and a path is +kept only when it stays inside the scanned artifact. +""" + +from __future__ import annotations + +import math +import os +import posixpath +import re +from collections.abc import Callable, Iterable, Mapping +from pathlib import Path, PurePosixPath, PureWindowsPath +from typing import Any + +from skillevaluator.utils.redaction import redact_sensitive_text + +__all__ = [ + "AE1_PATTERN", + "AE1_RULE_ID", + "REFERENCE_SUMMARY_KEY", + "combine_reference_summaries", + "diagnostic_text", + "index_legacy_reference_reasons", + "is_reference_summary_message", + "issue_diagnostics", + "reference_suggestion", + "reference_summary", + "reference_summary_message", + "reference_summary_record", + "report_path", +] + +AE1_RULE_ID = "AE1" +AE1_PATTERN = "Incomplete referenced artifact analysis" +REFERENCE_SUMMARY_KEY = "skillspector_reference_summary" +_SUMMARY_MESSAGE_PREFIX = "skillspector could not completely inspect " +# The generic remediation of SkillSpector releases before v2.12.0. It suggests +# that the file is absent, which is wrong for a file the scan read in part. +_LEGACY_REMEDIATION = "Make the referenced artifact locally available and fully analyzable, or remove the reference." +_DISPOSITIONS = frozenset({"partial", "failed", "out_of_scope", "uninspected"}) +_LEGACY_FINDING_RE = re.compile(r"(.+) \((partial|failed|out_of_scope|uninspected)\)") +_READ_REASONS = frozenset({"read_error", "stat_error", "file_disappeared", "missing_file_cache"}) +_MAX_REASONS = 16 +_MAX_OCCURRENCES = 128 +_MAX_ANALYZERS = 32 +_MAX_COUNT = (1 << 63) - 1 +_LIMIT_FIELDS = tuple( + (f"{prefix}_{unit}", unit == "seconds") + for prefix in ("observed", "limit") + for unit in ("artifacts", "bytes", "characters", "depth", "findings", "records", "seconds") +) + + +def diagnostic_text(value: object, *, max_length: int = 4096) -> str | None: + """*value* stripped and redacted when it is short text without control characters, else ``None``. + + Nothing else is coerced to text, so a list or an object is ``None``. + """ + if not isinstance(value, str) or not value.strip() or len(value) > max_length: + return None + if any(ord(character) < 32 or ord(character) == 127 for character in value): + return None + return redact_sensitive_text(value.strip()) + + +def _root_prefixes(scan_root: Path | None) -> list[PurePosixPath]: + """The spellings of *scan_root*'s directory that an absolute report path may start with.""" + if scan_root is None: + return [] + prefixes: list[PurePosixPath] = [] + try: + roots = (Path(os.path.abspath(scan_root)), scan_root.resolve(strict=False)) # noqa: PTH100 + directories = [root.parent if root.is_file() else root for root in roots] + except (OSError, RuntimeError): + return prefixes + for directory in directories: + prefix = PurePosixPath(str(directory).replace("\\", "/")) + if prefix not in prefixes: + prefixes.append(prefix) + return prefixes + + +def report_path(value: object, *, scan_root: Path | None = None) -> str | None: + """A SkillSpector report path as POSIX text relative to the scan, else ``None``. + + The path is checked lexically and never resolved, because the file an AE1 + finding names may be missing or unreadable. An absolute path counts only + under *scan_root*. A path with control characters, a Windows drive, or a + ``..`` that leaves the scan, and the scan root itself, are ``None``. + """ + text = diagnostic_text(value) + if text is None: + return None + slash_path = text.replace("\\", "/") + if PurePosixPath(slash_path).is_absolute() or PureWindowsPath(slash_path).drive: + for prefix in _root_prefixes(scan_root): + try: + slash_path = PurePosixPath(slash_path).relative_to(prefix).as_posix() + break + except ValueError: + continue + else: + return None + normalized = posixpath.normpath(slash_path) + if normalized in {".", ".."} or normalized.startswith(("../", "/")): + return None + return normalized + + +def _line(value: object) -> int | None: + return value if type(value) is int and 0 < value <= _MAX_COUNT else None + + +def _reasons(rows: object) -> list[dict]: + """The first reasons of *rows* with only known, valid fields, without repeats.""" + if not isinstance(rows, list): + return [] + reasons: list[dict] = [] + for row in rows[:_MAX_REASONS]: + if not isinstance(row, dict): + continue + reason_code = diagnostic_text(row.get("reason_code"), max_length=128) + if not reason_code: + continue + reason: dict[str, Any] = {"reason_code": reason_code} + for field, max_length in (("phase", 128), ("message", 4096)): + if value := diagnostic_text(row.get(field), max_length=max_length): + reason[field] = value + analyzers = row.get("analyzers") + if isinstance(analyzers, list): + reason["analyzers"] = [ + text for item in analyzers[:_MAX_ANALYZERS] if (text := diagnostic_text(item, max_length=256)) + ] + for field in ("start_line", "end_line"): + if (line := _line(row.get(field))) is not None: + reason[field] = line + metrics = row.get("limits") + if isinstance(metrics, dict): + limits = {} + for key, accepts_float in _LIMIT_FIELDS: + value = metrics.get(key) + numeric = type(value) is int or (accepts_float and type(value) is float) + if numeric and math.isfinite(value) and 0 <= value <= _MAX_COUNT: + limits[key] = value + if limits: + reason["limits"] = limits + if reason not in reasons: + reasons.append(reason) + return reasons + + +def _reference_target(issue: Mapping[str, object], normalize_path: Callable[[object], str | None]): + """``(target, disposition, structured)`` of an AE1 issue, else ``None``. + + *structured* says whether the target came from ``evidence`` (v2.12.0 and + later) rather than from the ``finding`` text of an earlier release, which + counts only when the issue's own location is inside the scan. + """ + evidence = issue.get("evidence") + evidence = evidence if isinstance(evidence, dict) else {} + target = diagnostic_text(evidence.get("target_path")) + structured = target is not None + disposition = evidence.get("target_disposition") + if not structured: + match = _LEGACY_FINDING_RE.fullmatch(diagnostic_text(issue.get("finding")) or "") + location = issue.get("location") + source = location.get("file") if isinstance(location, dict) else None + if match and normalize_path(source) is not None: + target, disposition = match.groups() + if not target or not isinstance(disposition, str) or disposition not in _DISPOSITIONS: + return None + target = normalize_path(target) + return None if target is None else (target, disposition, structured) + + +def index_legacy_reference_reasons( + issues: Iterable[object], + *, + normalize_path: Callable[[object], str | None], + completeness: object = None, +) -> dict[str, list[dict]]: + """The ledger rows of each AE1 target that has no structured reasons, read once. + + At most one row more than an AE1 finding keeps is indexed per target, so + the extra row still shows that the reasons were cut short. Each path is + normalized once, however often it repeats. + """ + if not isinstance(completeness, dict) or not isinstance(completeness.get("ledger_exceptions"), list): + return {} + normalized: dict[str, str | None] = {} + + def normalize_once(path: object) -> str | None: + if not isinstance(path, str): + return normalize_path(path) + if path not in normalized: + normalized[path] = normalize_path(path) + return normalized[path] + + by_target: dict[str, list[dict]] = {} + for issue in issues: + if not isinstance(issue, dict) or issue.get("id") != AE1_RULE_ID: + continue + target_info = _reference_target(issue, normalize_once) + if target_info is None: + continue + target, _disposition, structured = target_info + evidence = issue.get("evidence") + if structured and isinstance(evidence, dict) and evidence.get("reasons"): + continue + by_target.setdefault(target, []) + if not by_target: + return {} + for row in completeness["ledger_exceptions"]: + if not isinstance(row, dict) or not isinstance(row.get("path"), str): + continue + target = normalize_once(row["path"]) + if target in by_target and len(by_target[target]) <= _MAX_REASONS: + by_target[target].append(row) + return by_target + + +def issue_diagnostics( + issue: Mapping[str, object], + *, + normalize_path: Callable[[object], str | None], + completeness: object = None, + legacy_reason_index: Mapping[str, list[dict]] | None = None, +) -> dict: + """Finding metadata that explains an AE1 *issue*: the target, its reasons and the reference lines. + + ``skillspector_evidence`` holds ``target_path``, ``target_disposition`` + and up to 16 ``reasons``, with ``reasons_truncated`` when SkillSpector or + this projection left some out. Before v2.12.0 the reasons come from the + target's ledger rows in *completeness* (or *legacy_reason_index*), and the + finding gets no evidence without them. ``skillspector_occurrences`` lists + up to 128 of the issue's ``occurrences``. Any other issue gets ``{}``. + """ + if issue.get("id") != AE1_RULE_ID: + return {} + target_info = _reference_target(issue, normalize_path) + if target_info is None: + return {} + target, disposition, structured = target_info + evidence = issue.get("evidence") + evidence = evidence if isinstance(evidence, dict) else {} + rows = evidence.get("reasons") if structured else None + if not rows: + if legacy_reason_index is None: + legacy_reason_index = index_legacy_reference_reasons( + [issue], completeness=completeness, normalize_path=normalize_path + ) + rows = legacy_reason_index.get(target, []) + reasons = _reasons(rows) + # A target named only in the finding text needs matching ledger rows; an + # unreadable evidence target must not pass for a structured one. + if not reasons and not structured: + return {} + safe_evidence: dict[str, Any] = {"target_path": target, "target_disposition": disposition, "reasons": reasons} + if evidence.get("reasons_truncated") is True or (isinstance(rows, list) and len(rows) > _MAX_REASONS): + safe_evidence["reasons_truncated"] = True + metadata: dict[str, Any] = {"skillspector_evidence": safe_evidence} + occurrences = issue.get("occurrences") + if isinstance(occurrences, list): + safe_occurrences = [] + for occurrence in occurrences[:_MAX_OCCURRENCES]: + if not isinstance(occurrence, dict) or (path := normalize_path(occurrence.get("file"))) is None: + continue + safe_occurrence: dict[str, Any] = {"file": path} + for field in ("start_line", "end_line"): + if (line := _line(occurrence.get(field))) is not None: + safe_occurrence[field] = line + safe_occurrences.append(safe_occurrence) + metadata["skillspector_occurrences"] = safe_occurrences + if len(occurrences) > _MAX_OCCURRENCES: + metadata["skillspector_occurrences_truncated"] = True + return metadata + + +def _reason_details(reasons: list[dict]) -> list[str]: + """One text per distinct reason, with the analyzers of rows that differ only in them joined.""" + grouped: dict[tuple, list[str]] = {} + for reason in reasons: + limits = reason.get("limits") or {} + key = (reason["reason_code"], reason.get("start_line"), reason.get("message"), tuple(sorted(limits.items()))) + analyzers = grouped.setdefault(key, []) + analyzers.extend(name for name in reason.get("analyzers", []) if name not in analyzers) + details = [] + for (reason_code, start_line, message, limits), analyzers in grouped.items(): + detail = reason_code + if analyzers: + detail += f" ({', '.join(analyzers)})" + if start_line: + detail += f" at target line {start_line}" + if message: + detail += f": {message.rstrip('.')}" + if limits: + detail += "; " + ", ".join(f"{key}={value}" for key, value in limits) + details.append(detail + ".") + return details + + +def reference_suggestion(evidence: Mapping[str, Any], remediation: object) -> str: + """The suggestion of an AE1 finding: what was not inspected, why, and what to do. + + SkillSpector's own remediation is kept unless it is missing or the generic + text of releases before v2.12.0. A specific remedy is then chosen only from + a complete list of reasons, because the visible part of a truncated list + cannot show that one remedy covers every cause. + """ + reasons = evidence["reasons"] + truncated = evidence.get("reasons_truncated") is True + action = diagnostic_text(remediation) + if not action or action == _LEGACY_REMEDIATION: + codes = set() if truncated else {reason["reason_code"] for reason in reasons} + if codes == {"static_parse_limit"}: + action = ( + "Check that SkillSpector is current (`skillevaluator doctor --tier 1` shows its version) and rerun " + "the scan. If the limit remains and the source is valid, report a minimal reproducer to SkillSpector." + ) + elif codes and codes <= _READ_REASONS: + action = "Make sure the referenced file is readable where the scan runs, then rerun the scan." + else: + action = "Resolve the reported analysis limitation and rerun the scan." + target, disposition = evidence["target_path"], evidence["target_disposition"] + summary = f"Referenced artifact {target} was not completely inspected ({disposition})." + if truncated: + summary += ( + " SkillSpector reported more reasons than are shown here: run `skillspector scan` with " + "`--format json` and review the rows for this file in " + "`analysis_completeness.ledger_exceptions`, then address every limitation before rerunning the scan." + ) + return " ".join([summary, *_reason_details(reasons), action]) + + +def reference_summary(findings: Iterable[object]) -> dict | None: + """Count the referenced artifacts and distinct reference lines behind *findings*' AE1 evidence. + + A finding counts when its metadata holds ``skillspector_evidence`` from + :func:`issue_diagnostics`. Its reference lines are its + ``skillspector_occurrences``, else its own location, and the count is a + lower bound when an occurrence list was cut short. + """ + targets: dict[str, set[tuple[object, object]]] = {} + truncated = False + for finding in findings: + metadata = getattr(finding, "metadata", None) + if not isinstance(metadata, dict): + continue + evidence = metadata.get("skillspector_evidence") + if not isinstance(evidence, dict) or not isinstance(evidence.get("target_path"), str): + continue + occurrences = metadata.get("skillspector_occurrences") or [ + {"file": getattr(finding, "file_path", None), "start_line": getattr(finding, "line_number", None)} + ] + truncated |= metadata.get("skillspector_occurrences_truncated") is True + targets.setdefault(evidence["target_path"], set()).update( + (occurrence.get("file"), occurrence.get("start_line")) + for occurrence in occurrences + if isinstance(occurrence, dict) + ) + if not targets: + return None + return { + "affected_artifacts": len(targets), + "reference_occurrences": sum(len(lines) for lines in targets.values()), + "reference_occurrences_truncated": truncated, + } + + +def reference_summary_record(summary: object) -> dict | None: + """*summary* with only its count fields when they are valid, else ``None``.""" + if not isinstance(summary, dict): + return None + targets = summary.get("affected_artifacts") + occurrences = summary.get("reference_occurrences") + if type(targets) is not int or not 0 < targets <= _MAX_COUNT: + return None + if type(occurrences) is not int or not 0 <= occurrences <= _MAX_COUNT: + return None + return { + "affected_artifacts": targets, + "reference_occurrences": occurrences, + "reference_occurrences_truncated": summary.get("reference_occurrences_truncated") is True, + } + + +def combine_reference_summaries(summaries: Iterable[object]) -> dict | None: + """The totals of the valid *summaries*, such as those of each skill in a folder.""" + records = [record for summary in summaries if (record := reference_summary_record(summary)) is not None] + if not records: + return None + return { + "affected_artifacts": min(sum(record["affected_artifacts"] for record in records), _MAX_COUNT), + "reference_occurrences": min(sum(record["reference_occurrences"] for record in records), _MAX_COUNT), + "reference_occurrences_truncated": any(record["reference_occurrences_truncated"] for record in records), + } + + +def reference_summary_message(summary: object) -> str | None: + """The one-line text of a valid *summary*, the same in every report, else ``None``.""" + record = reference_summary_record(summary) + if record is None: + return None + occurrences = record["reference_occurrences"] + count = f"at least {occurrences}" if record["reference_occurrences_truncated"] else str(occurrences) + return ( + f"{_SUMMARY_MESSAGE_PREFIX}{record['affected_artifacts']} referenced artifact(s) across {count} " + "reference occurrence(s); each AE1 finding names the artifact and why its analysis stopped" + ) + + +def is_reference_summary_message(message: object) -> bool: + """Whether *message* is a :func:`reference_summary_message`.""" + return isinstance(message, str) and message.startswith(_SUMMARY_MESSAGE_PREFIX) diff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.py index c9056ebc9..aeb7e5693 100644 --- a/src/skillevaluator/validators/security.py +++ b/src/skillevaluator/validators/security.py @@ -32,6 +32,7 @@ import zlib from collections import Counter from collections.abc import Callable, Iterable, Mapping +from functools import partial from pathlib import Path, PurePosixPath from urllib.parse import unquote @@ -55,6 +56,19 @@ skillspector_reasoning_effort, ) from skillevaluator.skillspector_provenance import SKILLSPECTOR_LLM_ANALYZERS, sanitize_skillspector_llm_provenance +from skillevaluator.skillspector_references import ( + AE1_PATTERN, + AE1_RULE_ID, + REFERENCE_SUMMARY_KEY, + combine_reference_summaries, + index_legacy_reference_reasons, + is_reference_summary_message, + issue_diagnostics, + reference_suggestion, + reference_summary, + reference_summary_message, + report_path, +) 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 @@ -1062,6 +1076,24 @@ def _combine_skillspector_applicability(blocks: list[dict]) -> dict: } +def _record_skillspector_reference_summary(result: ValidationResult) -> None: + """Count the referenced artifacts behind *result*'s AE1 evidence in its metadata and one message. + + The counts come from the findings + (:func:`~skillevaluator.skillspector_references.reference_summary`), so a + second call after the ``--llm`` stage is merged replaces the first count + and its message. + """ + result.messages = [message for message in result.messages if not is_reference_summary_message(message)] + summary = reference_summary(result.findings) + if summary is None: + result.metadata.pop(REFERENCE_SUMMARY_KEY, None) + return + result.metadata[REFERENCE_SUMMARY_KEY] = summary + if message := reference_summary_message(summary): + result.add_message(message) + + def _issue_field(issue: dict): """Return a getter that retrieves a field from *issue*, treating None as empty string.""" @@ -2610,14 +2642,20 @@ def _validate_with_applicability( its scan does not inspect, so their missing references are not accepted. A scan run outside this walk has no known target and accepts none. + + The counts of referenced artifacts that SkillSpector did not + completely inspect are totaled the same way. """ blocks: list[dict] = [] + reference_summaries: list[object] = [] def validate_one(path: Path) -> ValidationResult: child = single_skill_validator(path) block = child.metadata.get("skillspector_applicability") if isinstance(block, dict): blocks.append(block) + if REFERENCE_SUMMARY_KEY in child.metadata: + reference_summaries.append(child.metadata[REFERENCE_SUMMARY_KEY]) return child previous_target_root, self._scan_target_root = self._scan_target_root, skill_path.resolve() @@ -2627,6 +2665,8 @@ def validate_one(path: Path) -> ValidationResult: self._scan_target_root = previous_target_root if blocks: result.metadata["skillspector_applicability"] = _combine_skillspector_applicability(blocks) + if (references := combine_reference_summaries(reference_summaries)) is not None: + result.metadata[REFERENCE_SUMMARY_KEY] = references return result def _validate_single_skill(self, skill_path: Path) -> ValidationResult: @@ -2739,6 +2779,8 @@ def _run_skillspector(self, skill_path: Path) -> ValidationResult: result.metadata["skillspector_llm_applicability"] = llm_applicability if not enrichment.is_incomplete: self._deduplicate_skillspector_findings(result) + # Count each reference line once across both stages. + _record_skillspector_reference_summary(result) if baseline_state is not None: result.metadata["skillspector_baseline"] = baseline_state self._report_skillspector_baseline( @@ -4390,6 +4432,12 @@ def _process_skillspector_cli_result( skipped_inapplicable = 0 skipped_by_role: Counter[str] = Counter() has_critical_or_high = False + completeness = data.get("analysis_completeness") + legacy_reason_index = index_legacy_reference_reasons( + candidate_issues, + normalize_path=partial(report_path, scan_root=source_root), + completeness=completeness, + ) for issue, scope in zip(candidate_issues, scopes, strict=True): if scope is not None and not scope.applicable: removed_issues.append(issue) @@ -4397,7 +4445,12 @@ def _process_skillspector_cli_result( skipped_by_role[scope.file_role] += 1 continue scanned_issues.append(issue) - finding, is_error = self._convert_skillspector_issue(issue) + finding, is_error = self._convert_skillspector_issue( + issue, + completeness=completeness, + scan_root=source_root, + legacy_reason_index=legacy_reason_index, + ) if scope is not None: finding.metadata.update( { @@ -4409,6 +4462,7 @@ def _process_skillspector_cli_result( if is_error: has_critical_or_high = True result.add_structured_finding(finding, is_error=is_error) + _record_skillspector_reference_summary(result) if skipped_generated: result.add_message(f"skillspector ignored {skipped_generated} generated artifact issue(s)") @@ -4892,10 +4946,24 @@ def report(status: str, message: str, *, problem: bool) -> None: report("no_matches", f"SkillSpector baseline loaded but matched no findings ({counts}).", problem=False) @staticmethod - def _convert_skillspector_issue(issue: dict) -> tuple[Finding, bool]: + def _convert_skillspector_issue( + issue: dict, + *, + completeness: object = None, + scan_root: Path | None = None, + legacy_reason_index: Mapping[str, list[dict]] | None = None, + ) -> tuple[Finding, bool]: """Convert a single skillspector issue dict into a Finding. Returns (Finding, is_error) where is_error is True for CRITICAL/HIGH. + + An ``AE1`` (incomplete referenced artifact analysis) finding is named + by its rule when SkillSpector leaves ``pattern`` empty, as releases + before v2.12.0 do. When SkillSpector says which file it did not + completely inspect and why, its metadata and suggestion carry that + (:func:`~skillevaluator.skillspector_references.issue_diagnostics`), + with the reasons of earlier releases read from *completeness* or + *legacy_reason_index*. Paths count only inside *scan_root*. """ g = _issue_field(issue) issue_sev = str(g("severity", "UNKNOWN")).upper() @@ -4904,19 +4972,33 @@ def _convert_skillspector_issue(issue: dict) -> tuple[Finding, bool]: suggestion = f"{explanation} {remediation}".strip() or None code_snippet = g("code_snippet") file_path, line_number = SecurityValidator._parse_issue_location(issue) + raw_pattern = issue.get("pattern") + if issue.get("id") == AE1_RULE_ID and not (isinstance(raw_pattern, str) and raw_pattern.strip()): + pattern = AE1_PATTERN + else: + pattern = g("pattern", "Unknown") + metadata = SecurityValidator._build_issue_metadata(issue) + metadata.update( + issue_diagnostics( + issue, + normalize_path=partial(report_path, scan_root=scan_root), + completeness=completeness, + legacy_reason_index=legacy_reason_index, + ) + ) + if evidence := metadata.get("skillspector_evidence"): + suggestion = reference_suggestion(evidence, remediation) finding = Finding( category="SECURITY", severity=issue_sev, - check_name=f"{g('pattern', 'Unknown')} ({g('id', '?')})", - message=SecurityValidator._build_issue_message( - g("category"), g("finding"), explanation, g("pattern", "Unknown") - ), + check_name=f"{pattern} ({g('id', '?')})", + message=SecurityValidator._build_issue_message(g("category"), g("finding"), explanation, pattern), file_path=file_path, line_number=line_number, line_content=code_snippet[:200] if code_snippet else None, suggestion=suggestion, - metadata=SecurityValidator._build_issue_metadata(issue), + metadata=metadata, ) return finding, issue_sev in ("CRITICAL", "HIGH") diff --git a/tests/fixtures/skillspector-2.11.2-perl-help-text-ae1-no-llm.json b/tests/fixtures/skillspector-2.11.2-perl-help-text-ae1-no-llm.json new file mode 100644 index 000000000..ffbcdf763 --- /dev/null +++ b/tests/fixtures/skillspector-2.11.2-perl-help-text-ae1-no-llm.json @@ -0,0 +1,462 @@ +{ + "skill": { + "name": "perl-test", + "source": "/fixture/perl-help-text", + "scanned_at": "2026-09-23T05:02:31.954220+00:00" + }, + "risk_assessment": { + "score": 37, + "severity": "MEDIUM", + "recommendation": "CAUTION", + "max_issue_severity": "HIGH" + }, + "components": [ + { + "path": "SKILL.md", + "type": "markdown", + "lines": 8, + "executable": false, + "size_bytes": 113, + "source_url": null, + "source_identity": null, + "source_digest": null + }, + { + "path": "scripts/helper.pl", + "type": "other", + "lines": 4, + "executable": true, + "size_bytes": 84, + "source_url": null, + "source_identity": null, + "source_digest": null + } + ], + "structured_summaries": [], + "issues": [ + { + "id": "AE1", + "finding_id": "finding-f92f853411464b5c8cf65403a9458a22", + "category": "analysis-evasion", + "pattern": null, + "severity": "HIGH", + "confidence": 1.0, + "location": { + "file": "SKILL.md", + "start_line": 6, + "end_line": null + }, + "finding": "scripts/helper.pl (partial)", + "explanation": "Referenced artifact was not completely inspected", + "remediation": "Make the referenced artifact locally available and fully analyzable, or remove the reference.", + "code_snippet": "Run `scripts/helper.pl`.", + "intent": null, + "tags": [ + "coverage", + "reference", + "target-disposition:partial" + ], + "evidence": {}, + "match_fingerprint": "c0d52b7e6e0698317ae4805b756ce864fd7673d6cd748e76d0f9c1cfd0464693", + "occurrences": [ + { + "file": "SKILL.md", + "start_line": 6, + "end_line": null + } + ] + }, + { + "id": "AE1", + "finding_id": "finding-f92f853411464b5c8cf65403a9458a22", + "category": "analysis-evasion", + "pattern": null, + "severity": "HIGH", + "confidence": 1.0, + "location": { + "file": "SKILL.md", + "start_line": 8, + "end_line": null + }, + "finding": "scripts/helper.pl (partial)", + "explanation": "Referenced artifact was not completely inspected", + "remediation": "Make the referenced artifact locally available and fully analyzable, or remove the reference.", + "code_snippet": "Run `scripts/helper.pl`.", + "intent": null, + "tags": [ + "coverage", + "reference", + "target-disposition:partial" + ], + "evidence": {}, + "match_fingerprint": "c0d52b7e6e0698317ae4805b756ce864fd7673d6cd748e76d0f9c1cfd0464693", + "occurrences": [ + { + "file": "SKILL.md", + "start_line": 8, + "end_line": null + } + ] + } + ], + "suppressed_count": 0, + "suppressed": [], + "metadata": { + "has_executable_scripts": true, + "skillspector_version": "2.11.2", + "llm_requested": false, + "llm_available": true, + "meta_analysis_applied": false, + "inference_usage": [], + "filtering_mode": "heuristic" + }, + "execution_successful": true, + "analysis_completeness": { + "total_components": 2, + "scanned_components": 1, + "coverage_percent": 50.0, + "is_complete": false, + "status": "partial", + "execution_successful": true, + "fully_inspected_files": 1, + "partially_inspected_files": 1, + "entirely_uninspected_files": 0, + "ledger_exceptions": [ + { + "outcome": "partial", + "phase": "static", + "reason_code": "static_parse_limit", + "message": "A security-relevant expression exceeded a bounded static parser's span limit.", + "path": "scripts/helper.pl", + "start_line": null, + "end_line": null, + "fatal": false, + "analyzers": [ + "static_patterns_tool_misuse" + ] + } + ], + "scope_exclusions": [], + "analyzer_statuses": [ + { + "analyzer_id": "artifact_integrity", + "status": "completed", + "planned_work": 2, + "completed": 2, + "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": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "mcp_rug_pull", + "status": "completed", + "planned_work": 2, + "completed": 2, + "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": "reference_coverage", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "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": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_anti_refusal", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_data_exfiltration", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_deserialization", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_excessive_agency", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_harmful_content", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_memory_poisoning", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_output_handling", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_privilege_escalation", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_prompt_injection", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_rogue_agent", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_ssrf", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_supply_chain", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_system_prompt_leakage", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_tool_misuse", + "status": "degraded", + "planned_work": 2, + "completed": 1, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_yara", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + } + ], + "references": [ + { + "source_path": "SKILL.md", + "line": 6, + "column": 6, + "evidence": "Run `scripts/helper.pl`.", + "target_path": "scripts/helper.pl", + "status": "resolved", + "disposition": "analyzed" + }, + { + "source_path": "SKILL.md", + "line": 8, + "column": 6, + "evidence": "See `scripts/helper.pl`.", + "target_path": "scripts/helper.pl", + "status": "resolved", + "disposition": "analyzed" + } + ], + "limitations": [ + "Analyzer static_patterns_tool_misuse status: degraded." + ], + "findings_before_filtering": 2, + "findings_after_filtering": 2 + } +} diff --git a/tests/fixtures/skillspector-2.12.0-host-language-parse-limits-ae1-no-llm.json b/tests/fixtures/skillspector-2.12.0-host-language-parse-limits-ae1-no-llm.json new file mode 100644 index 000000000..e7ef794f8 --- /dev/null +++ b/tests/fixtures/skillspector-2.12.0-host-language-parse-limits-ae1-no-llm.json @@ -0,0 +1,894 @@ +{ + "skill": { + "name": "host-language-helpers", + "source": "/fixture/skillspector-host-language-parse-limits", + "scanned_at": "2026-10-06T19:44:48.408880+00:00" + }, + "risk_assessment": { + "score": 43, + "severity": "MEDIUM", + "recommendation": "CAUTION", + "max_issue_severity": "HIGH" + }, + "components": [ + { + "path": "SKILL.md", + "type": "markdown", + "lines": 14, + "executable": false, + "size_bytes": 463, + "source_url": null, + "source_identity": null, + "source_digest": null + }, + { + "path": "scripts/check_labels.py", + "type": "python", + "lines": 426, + "executable": true, + "size_bytes": 9375, + "source_url": null, + "source_identity": null, + "source_digest": null + }, + { + "path": "scripts/load_plugins.pl", + "type": "other", + "lines": 13, + "executable": true, + "size_bytes": 438, + "source_url": null, + "source_identity": null, + "source_digest": null + }, + { + "path": "scripts/render_notes.py", + "type": "python", + "lines": 226, + "executable": true, + "size_bytes": 5019, + "source_url": null, + "source_identity": null, + "source_digest": null + } + ], + "structured_summaries": [], + "issues": [ + { + "id": "AE1", + "finding_id": "finding-80e941211cd84e7d9c3a35d235bec776", + "category": "analysis-evasion", + "pattern": "Incomplete referenced artifact analysis", + "severity": "HIGH", + "confidence": 1.0, + "location": { + "file": "SKILL.md", + "start_line": 8, + "end_line": null + }, + "finding": "scripts/render_notes.py (partial)", + "explanation": "Referenced artifact was not completely inspected", + "remediation": "Review the reported expression and analyzer's parsing limitation; correct the scanner if it misinterprets valid source, then rerun the scan. Keep required references; incomplete analysis is not proof of malicious evasion.", + "code_snippet": "Run `scripts/render_notes.py` to format notes as a Markdown report.", + "intent": null, + "tags": [ + "coverage", + "reference", + "target-disposition:partial" + ], + "evidence": { + "target_path": "scripts/render_notes.py", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "message": "A security-relevant expression exceeded a bounded static parser's span limit.", + "phase": "static", + "analyzers": [ + "static_patterns_tool_misuse" + ] + } + ] + }, + "match_fingerprint": "5556136e2af531d0dcffe41f786c5ae92a97ca59d407a9417221a44f6fabaa8f", + "occurrences": [ + { + "file": "SKILL.md", + "start_line": 8, + "end_line": null + } + ] + }, + { + "id": "AE1", + "finding_id": "finding-80e941211cd84e7d9c3a35d235bec776", + "category": "analysis-evasion", + "pattern": "Incomplete referenced artifact analysis", + "severity": "HIGH", + "confidence": 1.0, + "location": { + "file": "SKILL.md", + "start_line": 14, + "end_line": null + }, + "finding": "scripts/render_notes.py (partial)", + "explanation": "Referenced artifact was not completely inspected", + "remediation": "Review the reported expression and analyzer's parsing limitation; correct the scanner if it misinterprets valid source, then rerun the scan. Keep required references; incomplete analysis is not proof of malicious evasion.", + "code_snippet": "Run `scripts/render_notes.py` to format notes as a Markdown report.", + "intent": null, + "tags": [ + "coverage", + "reference", + "target-disposition:partial" + ], + "evidence": { + "target_path": "scripts/render_notes.py", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "message": "A security-relevant expression exceeded a bounded static parser's span limit.", + "phase": "static", + "analyzers": [ + "static_patterns_tool_misuse" + ] + } + ] + }, + "match_fingerprint": "5556136e2af531d0dcffe41f786c5ae92a97ca59d407a9417221a44f6fabaa8f", + "occurrences": [ + { + "file": "SKILL.md", + "start_line": 14, + "end_line": null + } + ] + }, + { + "id": "AE1", + "finding_id": "finding-6f88a68116b44c7e9572c104fa675232", + "category": "analysis-evasion", + "pattern": "Incomplete referenced artifact analysis", + "severity": "HIGH", + "confidence": 1.0, + "location": { + "file": "SKILL.md", + "start_line": 10, + "end_line": null + }, + "finding": "scripts/check_labels.py (partial)", + "explanation": "Referenced artifact was not completely inspected", + "remediation": "Review the target's analysis-completeness ledger and resolve all limitations. Keep required references; incomplete analysis is not proof of malicious evasion.", + "code_snippet": "Run `scripts/check_labels.py` to flag note labels that are too short.", + "intent": null, + "tags": [ + "coverage", + "reference", + "target-disposition:partial" + ], + "evidence": { + "target_path": "scripts/check_labels.py", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_agent_snooping" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_anti_refusal" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_deserialization" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_excessive_agency" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_harmful_content" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_memory_poisoning" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_privilege_escalation" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_prompt_injection" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_rogue_agent" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_ssrf" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_supply_chain" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_system_prompt_leakage" + ] + }, + { + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "phase": "static", + "analyzers": [ + "static_patterns_tool_misuse" + ] + } + ] + }, + "match_fingerprint": "63865fb4b289d8b4a3b4fefe06851d6c37483d27b580df38ae6e943ad578ac72", + "occurrences": [ + { + "file": "SKILL.md", + "start_line": 10, + "end_line": null + } + ] + }, + { + "id": "AE1", + "finding_id": "finding-a19e2dcd5ffd4a84aef20f87e5cb58a5", + "category": "analysis-evasion", + "pattern": "Incomplete referenced artifact analysis", + "severity": "HIGH", + "confidence": 1.0, + "location": { + "file": "SKILL.md", + "start_line": 12, + "end_line": null + }, + "finding": "scripts/load_plugins.pl (partial)", + "explanation": "Referenced artifact was not completely inspected", + "remediation": "Review the reported expression and analyzer's parsing limitation; correct the scanner if it misinterprets valid source, then rerun the scan. Keep required references; incomplete analysis is not proof of malicious evasion.", + "code_snippet": "Run `scripts/load_plugins.pl` to load the optional plugins.", + "intent": null, + "tags": [ + "coverage", + "reference", + "target-disposition:partial" + ], + "evidence": { + "target_path": "scripts/load_plugins.pl", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "message": "A security-relevant expression exceeded a bounded static parser's span limit.", + "phase": "static", + "analyzers": [ + "static_patterns_tool_misuse" + ] + } + ] + }, + "match_fingerprint": "09d8d5e4f0336ce106671f7ba5d8910bf20e192f4d93d2a2cc8ff1930f07a144", + "occurrences": [ + { + "file": "SKILL.md", + "start_line": 12, + "end_line": null + } + ] + } + ], + "suppressed_count": 0, + "suppressed": [], + "metadata": { + "has_executable_scripts": true, + "skillspector_version": "2.12.0", + "llm_requested": false, + "llm_available": false, + "meta_analysis_applied": false, + "inference_usage": [], + "llm_provenance": { + "schema_version": 1, + "provider": { + "configured_adapter": "nv_build", + "resolved_adapter": "nv_build", + "effective_adapter": "not_applicable", + "effective_adapters": [], + "service": "unknown", + "routing": { + "deployment_override": null, + "deployment_source": "not_applicable", + "api_version": null, + "api_version_source": "not_applicable" + } + }, + "analyzers": [ + { + "analyzer_id": "mcp_tool_poisoning", + "model": "z-ai/glm-5.2", + "model_source": "resolved_configuration", + "analyzer_revision": { + "value": "2.12.0", + "source": "skillspector_package", + "source_revision": { + "value": "unknown", + "source": "unknown" + } + } + }, + { + "analyzer_id": "semantic_developer_intent", + "model": "z-ai/glm-5.2", + "model_source": "resolved_configuration", + "analyzer_revision": { + "value": "2.12.0", + "source": "skillspector_package", + "source_revision": { + "value": "unknown", + "source": "unknown" + } + } + }, + { + "analyzer_id": "semantic_quality_policy", + "model": "z-ai/glm-5.2", + "model_source": "resolved_configuration", + "analyzer_revision": { + "value": "2.12.0", + "source": "skillspector_package", + "source_revision": { + "value": "unknown", + "source": "unknown" + } + } + }, + { + "analyzer_id": "semantic_security_discovery", + "model": "z-ai/glm-5.2", + "model_source": "resolved_configuration", + "analyzer_revision": { + "value": "2.12.0", + "source": "skillspector_package", + "source_revision": { + "value": "unknown", + "source": "unknown" + } + } + }, + { + "analyzer_id": "meta_analyzer", + "model": "z-ai/glm-5.2", + "model_source": "resolved_configuration", + "analyzer_revision": { + "value": "2.12.0", + "source": "skillspector_package", + "source_revision": { + "value": "unknown", + "source": "unknown" + } + } + } + ], + "sampling": { + "temperature": { + "requested": null, + "source": "provider_default", + "forwarded_to_client": null, + "adapter_support": true, + "provider_support": "unknown" + }, + "seed": { + "requested": null, + "source": "unset", + "forwarded_to_client": null, + "adapter_support": true, + "provider_support": "unknown" + }, + "reasoning_effort": { + "requested": null, + "source": "provider_default", + "forwarded_to_client": null, + "adapter_support": true, + "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": 4, + "scanned_components": 1, + "coverage_percent": 25.0, + "is_complete": false, + "status": "partial", + "execution_successful": true, + "fully_inspected_files": 1, + "partially_inspected_files": 3, + "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": 14, + "end_line": 14, + "fatal": false + }, + { + "outcome": "partial", + "phase": "static", + "reason_code": "obfuscated_instruction_text", + "message": "Obfuscated instruction text could not be fully evaluated by the deterministic layer.", + "path": "scripts/check_labels.py", + "start_line": null, + "end_line": null, + "fatal": false, + "analyzers": [ + "static_patterns_agent_snooping", + "static_patterns_anti_refusal", + "static_patterns_deserialization", + "static_patterns_excessive_agency", + "static_patterns_harmful_content", + "static_patterns_memory_poisoning", + "static_patterns_privilege_escalation", + "static_patterns_prompt_injection", + "static_patterns_rogue_agent", + "static_patterns_ssrf", + "static_patterns_supply_chain", + "static_patterns_system_prompt_leakage", + "static_patterns_tool_misuse" + ] + }, + { + "outcome": "partial", + "phase": "static", + "reason_code": "static_parse_limit", + "message": "A security-relevant expression exceeded a bounded static parser's span limit.", + "path": "scripts/load_plugins.pl", + "start_line": null, + "end_line": null, + "fatal": false, + "analyzers": [ + "static_patterns_tool_misuse" + ] + }, + { + "outcome": "partial", + "phase": "static", + "reason_code": "static_parse_limit", + "message": "A security-relevant expression exceeded a bounded static parser's span limit.", + "path": "scripts/render_notes.py", + "start_line": null, + "end_line": null, + "fatal": false, + "analyzers": [ + "static_patterns_tool_misuse" + ] + } + ], + "scope_exclusions": [], + "analyzer_statuses": [ + { + "analyzer_id": "artifact_integrity", + "status": "completed", + "planned_work": 4, + "completed": 4, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "behavioral_ast", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "behavioral_taint_tracking", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "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": "completed", + "planned_work": 4, + "completed": 4, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "mcp_rug_pull", + "status": "completed", + "planned_work": 4, + "completed": 4, + "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": "reference_coverage", + "status": "completed", + "planned_work": 4, + "completed": 4, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "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": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_anti_refusal", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_data_exfiltration", + "status": "completed", + "planned_work": 4, + "completed": 4, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_deserialization", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_excessive_agency", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_harmful_content", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_memory_poisoning", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_output_handling", + "status": "completed", + "planned_work": 4, + "completed": 4, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_privilege_escalation", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_prompt_injection", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_rogue_agent", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_ssrf", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_supply_chain", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_system_prompt_leakage", + "status": "degraded", + "planned_work": 4, + "completed": 3, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_tool_misuse", + "status": "degraded", + "planned_work": 4, + "completed": 1, + "partial": 3, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_yara", + "status": "completed", + "planned_work": 4, + "completed": 4, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + } + ], + "references": [ + { + "source_path": "SKILL.md", + "line": 8, + "column": 6, + "evidence": "Run `scripts/render_notes.py` to format notes as a Markdown report.", + "target_path": "scripts/render_notes.py", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 10, + "column": 6, + "evidence": "Run `scripts/check_labels.py` to flag note labels that are too short.", + "target_path": "scripts/check_labels.py", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 12, + "column": 6, + "evidence": "Run `scripts/load_plugins.pl` to load the optional plugins.", + "target_path": "scripts/load_plugins.pl", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 14, + "column": 27, + "evidence": "The report is written to `output/notes.md`. To refresh it, rerun `scripts/render_notes.py`.", + "target_path": null, + "status": "missing", + "disposition": "partial", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 14, + "column": 67, + "evidence": "The report is written to `output/notes.md`. To refresh it, rerun `scripts/render_notes.py`.", + "target_path": "scripts/render_notes.py", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + } + ], + "limitations": [ + "Analyzer static_patterns_agent_snooping status: degraded.", + "Analyzer static_patterns_anti_refusal status: degraded.", + "Analyzer static_patterns_deserialization status: degraded.", + "Analyzer static_patterns_excessive_agency status: degraded.", + "Analyzer static_patterns_harmful_content status: degraded.", + "Analyzer static_patterns_memory_poisoning status: degraded.", + "Analyzer static_patterns_privilege_escalation status: degraded.", + "Analyzer static_patterns_prompt_injection status: degraded.", + "Analyzer static_patterns_rogue_agent status: degraded.", + "Analyzer static_patterns_ssrf status: degraded.", + "Analyzer static_patterns_supply_chain status: degraded.", + "Analyzer static_patterns_system_prompt_leakage status: degraded.", + "Analyzer static_patterns_tool_misuse status: degraded." + ], + "findings_before_filtering": 4, + "findings_after_filtering": 4 + } +} diff --git a/tests/fixtures/skillspector-2.13.3-perl-parse-limit-ae1-no-llm.json b/tests/fixtures/skillspector-2.13.3-perl-parse-limit-ae1-no-llm.json new file mode 100644 index 000000000..04a8af6a4 --- /dev/null +++ b/tests/fixtures/skillspector-2.13.3-perl-parse-limit-ae1-no-llm.json @@ -0,0 +1,634 @@ +{ + "skill": { + "name": "parser-limit", + "source": "/fixture/perl-parse-limit", + "scanned_at": "2026-11-09T20:24:13.924525+00:00" + }, + "risk_assessment": { + "score": 47, + "severity": "MEDIUM", + "recommendation": "CAUTION", + "max_issue_severity": "HIGH" + }, + "components": [ + { + "path": "SKILL.md", + "type": "markdown", + "lines": 8, + "executable": false, + "size_bytes": 115, + "source_url": null, + "source_identity": null, + "source_digest": null + }, + { + "path": "scripts/helper.pl", + "type": "other", + "lines": 4, + "executable": true, + "size_bytes": 10068, + "source_url": null, + "source_identity": null, + "source_digest": null + } + ], + "structured_summaries": [], + "issues": [ + { + "id": "AE1", + "finding_id": "finding-a395ee2dac254767a5c45f7304a13b31", + "category": "analysis-evasion", + "pattern": "Incomplete referenced artifact analysis", + "severity": "HIGH", + "confidence": 1.0, + "location": { + "file": "SKILL.md", + "start_line": 6, + "end_line": null + }, + "finding": "scripts/helper.pl (partial)", + "explanation": "Referenced artifact was not completely inspected", + "remediation": "Review the reported expression and analyzer's parsing limitation; correct the scanner if it misinterprets valid source, then rerun the scan. Keep required references; incomplete analysis is not proof of malicious evasion.", + "code_snippet": "Run `scripts/helper.pl`.", + "intent": null, + "tags": [ + "coverage", + "reference", + "target-disposition:partial" + ], + "evidence": { + "target_path": "scripts/helper.pl", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "message": "A security-relevant expression exceeded a bounded static parser's span limit.", + "phase": "static", + "analyzers": [ + "static_patterns_tool_misuse" + ] + } + ] + }, + "match_fingerprint": "c0d52b7e6e0698317ae4805b756ce864fd7673d6cd748e76d0f9c1cfd0464693", + "occurrences": [ + { + "file": "SKILL.md", + "start_line": 6, + "end_line": null + } + ] + }, + { + "id": "AE1", + "finding_id": "finding-7a7136068927491faf28c70524170900", + "category": "analysis-evasion", + "pattern": "Incomplete referenced artifact analysis", + "severity": "HIGH", + "confidence": 1.0, + "location": { + "file": "SKILL.md", + "start_line": 8, + "end_line": null + }, + "finding": "scripts/helper.pl (partial)", + "explanation": "Referenced artifact was not completely inspected", + "remediation": "Review the reported expression and analyzer's parsing limitation; correct the scanner if it misinterprets valid source, then rerun the scan. Keep required references; incomplete analysis is not proof of malicious evasion.", + "code_snippet": "See `scripts/helper.pl`.", + "intent": null, + "tags": [ + "coverage", + "reference", + "target-disposition:partial" + ], + "evidence": { + "target_path": "scripts/helper.pl", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "message": "A security-relevant expression exceeded a bounded static parser's span limit.", + "phase": "static", + "analyzers": [ + "static_patterns_tool_misuse" + ] + } + ] + }, + "match_fingerprint": "c0d52b7e6e0698317ae4805b756ce864fd7673d6cd748e76d0f9c1cfd0464693", + "occurrences": [ + { + "file": "SKILL.md", + "start_line": 8, + "end_line": null + } + ] + }, + { + "id": "MP2", + "finding_id": "finding-75adfa157a174c068f0b13a178d36ac1", + "category": "Memory Poisoning", + "pattern": "Context Window Stuffing", + "severity": "MEDIUM", + "confidence": 0.8, + "location": { + "file": "scripts/helper.pl", + "start_line": 4, + "end_line": null, + "start_column": 13 + }, + "finding": " safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe", + "explanation": "Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.", + "remediation": "Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.", + "code_snippet": "#!/usr/bin/env perl\nuse strict;\nuse warnings;\nprint \"Use rm safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe safe ", + "intent": null, + "tags": [ + "Memory Poisoning" + ], + "evidence": {}, + "match_fingerprint": "589cb86726122bb31efb1e8289a726412d9ad8198b634d5e4f52d782036d2bd1", + "occurrences": [ + { + "file": "scripts/helper.pl", + "start_line": 4, + "end_line": null, + "start_column": 13 + } + ] + } + ], + "suppressed_count": 0, + "suppressed": [], + "metadata": { + "has_executable_scripts": true, + "skillspector_version": "2.13.3", + "llm_requested": false, + "llm_available": true, + "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": 2, + "scanned_components": 1, + "coverage_percent": 50.0, + "is_complete": false, + "status": "partial", + "execution_successful": true, + "fully_inspected_files": 1, + "partially_inspected_files": 1, + "entirely_uninspected_files": 0, + "ledger_exceptions": [ + { + "outcome": "partial", + "phase": "static", + "reason_code": "static_parse_limit", + "message": "A security-relevant expression exceeded a bounded static parser's span limit.", + "path": "scripts/helper.pl", + "start_line": null, + "end_line": null, + "fatal": false, + "analyzers": [ + "static_patterns_tool_misuse" + ] + } + ], + "scope_exclusions": [], + "analyzer_statuses": [ + { + "analyzer_id": "artifact_integrity", + "status": "completed", + "planned_work": 2, + "completed": 2, + "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": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "mcp_rug_pull", + "status": "completed", + "planned_work": 2, + "completed": 2, + "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": "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": "reference_coverage", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "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": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_anti_refusal", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_data_exfiltration", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_deserialization", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_excessive_agency", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_harmful_content", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_memory_poisoning", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_output_handling", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_privilege_escalation", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_prompt_injection", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_rogue_agent", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_ssrf", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_supply_chain", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_system_prompt_leakage", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_patterns_tool_misuse", + "status": "degraded", + "planned_work": 2, + "completed": 1, + "partial": 1, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + }, + { + "analyzer_id": "static_yara", + "status": "completed", + "planned_work": 2, + "completed": 2, + "partial": 0, + "skipped": 0, + "failed": 0, + "unaccounted": 0 + } + ], + "references": [ + { + "source_path": "SKILL.md", + "line": 6, + "column": 6, + "evidence": "Run `scripts/helper.pl`.", + "target_path": "scripts/helper.pl", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + }, + { + "source_path": "SKILL.md", + "line": 8, + "column": 6, + "evidence": "See `scripts/helper.pl`.", + "target_path": "scripts/helper.pl", + "status": "resolved", + "disposition": "analyzed", + "reference_kind": "quoted_or_code" + } + ], + "limitations": [ + "Analyzer static_patterns_tool_misuse status: degraded." + ], + "findings_before_filtering": 3, + "findings_after_filtering": 3 + } +} diff --git a/tests/validators/test_skillspector_ae1_contract.py b/tests/validators/test_skillspector_ae1_contract.py new file mode 100644 index 000000000..f4c589f0c --- /dev/null +++ b/tests/validators/test_skillspector_ae1_contract.py @@ -0,0 +1,74 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The installed SkillSpector library reports an AE1 finding only for a helper it cannot parse. + +Run explicitly (``-m integration``) with SkillSpector v2.13.1 or later +importable. Earlier releases stop early on the inert help string as well. The +helper scripts are scanned as text and never run. +""" + +import json +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path + +import pytest + +from skillevaluator.validators.base import ValidationResult +from skillevaluator.validators.security import SecurityValidator + +pytestmark = pytest.mark.integration + + +def _installed_version() -> tuple[int, ...]: + try: + return tuple(int(part) for part in version("skillspector").split(".")[:3]) + except (PackageNotFoundError, ValueError): + return () + + +@pytest.mark.parametrize( + ("statement", "expected_rule", "expected_complete"), + [ + ('print "Use rm to remove a project\\n";\n', None, True), + ('system("rm -rf /");\n', "TM1", True), + ('print "Use rm ' + "safe " * 2000 + '-rf *";\n', "AE1", False), + ], + ids=["inert-help-string", "executable-removal", "genuine-parser-limit"], +) +def test_installed_scanner_reference_analysis_contract( + tmp_path: Path, statement: str, expected_rule: str | None, expected_complete: bool +) -> None: + graph = pytest.importorskip("skillspector.graph").graph + if _installed_version() < (2, 13, 1): + pytest.skip("SkillSpector before v2.13.1 stops early on valid Perl helpers") + (tmp_path / "scripts").mkdir() + (tmp_path / "SKILL.md").write_text( + "---\nname: perl-help\ndescription: Inspect a Perl helper.\n---\n\n" + "Run `scripts/helper.pl`.\n\nSee `scripts/helper.pl`.\n", + encoding="utf-8", + ) + (tmp_path / "scripts" / "helper.pl").write_text( + "#!/usr/bin/env perl\nuse strict;\nuse warnings;\n" + statement, encoding="utf-8" + ) + + state = graph.invoke({"input_path": str(tmp_path), "use_llm": False, "output_format": "json"}) + report = json.loads(state["report_body"]) + result = ValidationResult(validator_name="Security Scan") + SecurityValidator(use_llm=False, content_type="skill")._process_skillspector_cli_result( + report, result, source_root=tmp_path + ) + + assert report["analysis_completeness"]["is_complete"] is expected_complete + if expected_rule is None: + assert report["issues"] == [] + assert result.passed + else: + assert any(issue["id"] == expected_rule for issue in report["issues"]) + assert not result.passed + if expected_rule == "AE1": + ae1 = [finding for finding in result.findings if finding.check_name.endswith("(AE1)")] + assert len(ae1) == 2 + assert all("static_parse_limit" in finding.suggestion for finding in ae1) + assert all(finding.check_name == "Incomplete referenced artifact analysis (AE1)" for finding in ae1) + assert result.metadata["skillspector_reference_summary"]["reference_occurrences"] == 2 diff --git a/tests/validators/test_skillspector_reference_diagnostics.py b/tests/validators/test_skillspector_reference_diagnostics.py new file mode 100644 index 000000000..0a0ff4a45 --- /dev/null +++ b/tests/validators/test_skillspector_reference_diagnostics.py @@ -0,0 +1,618 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""SkillSpector AE1 findings name the file it did not completely inspect and why. + +SkillSpector reports a High ``AE1`` (incomplete referenced artifact analysis) +finding at each line that names such a file. The findings keep their severity, +and the scan's completeness and gates are unchanged; only the finding's name, +suggestion and metadata explain it, and the result counts the files and lines. + +The reports are real SkillSpector ``--no-llm`` captures with ``skill.source`` +set to ``/fixture/``: + +- v2.11.2 for a skill whose ``SKILL.md`` names ``scripts/helper.pl`` twice. + That release leaves ``pattern`` and ``evidence`` empty, so the reason is + only in the ledger row for the helper. +- v2.12.0 for a skill that names three helpers, one of them twice, with a + ``static_parse_limit`` or ``obfuscated_instruction_text`` reason each. +- v2.13.3 for a Perl helper with a string of 2,000 words, which SkillSpector + cannot parse within its span limit. +""" + +import json +from pathlib import Path +from unittest.mock import patch + +import pytest +from tests.validators.test_security import _jpeg_bytes, _png_bytes + +from skillevaluator.skillspector_references import ( + AE1_PATTERN, + index_legacy_reference_reasons, + is_reference_summary_message, + issue_diagnostics, + report_path, +) +from skillevaluator.utils.tool_runner import ToolResult +from skillevaluator.validators.base import Severity, ValidationResult +from skillevaluator.validators.security import SecurityValidator, _record_skillspector_reference_summary + +_FIXTURES = Path(__file__).parents[1] / "fixtures" +_LEGACY_REPORT = "skillspector-2.11.2-perl-help-text-ae1-no-llm.json" +_HOST_LANGUAGE_REPORT = "skillspector-2.12.0-host-language-parse-limits-ae1-no-llm.json" +_PARSE_LIMIT_REPORT = "skillspector-2.13.3-perl-parse-limit-ae1-no-llm.json" +_IMAGE_PATH_REPORT = "skillspector-2.12.0-image-path-reference-no-llm.json" +_CHECK_NAME = f"{AE1_PATTERN} (AE1)" +_INCOMPLETE = "skillspector JSON field 'analysis_completeness' reports incomplete analysis (status 'partial')" +_OBFUSCATION_ANALYZERS = [ + f"static_patterns_{name}" + for name in ( + "agent_snooping", + "anti_refusal", + "deserialization", + "excessive_agency", + "harmful_content", + "memory_poisoning", + "privilege_escalation", + "prompt_injection", + "rogue_agent", + "ssrf", + "supply_chain", + "system_prompt_leakage", + "tool_misuse", + ) +] + + +def _report(name: str = _LEGACY_REPORT) -> dict: + return json.loads((_FIXTURES / name).read_text(encoding="utf-8")) + + +def _ae1(result: ValidationResult) -> list: + return [finding for finding in result.findings if finding.check_name.endswith("(AE1)")] + + +def _process(report: dict, source_root: Path | None = None) -> ValidationResult: + result = ValidationResult(validator_name="Security Scan") + SecurityValidator(use_llm=False)._process_skillspector_cli_result(report, result, source_root=source_root) + return result + + +def _helper_skill(root: Path) -> Path: + """The skill of the v2.11.2 report: SKILL.md names scripts/helper.pl on lines 6 and 8.""" + (root / "scripts").mkdir(parents=True) + (root / "SKILL.md").write_text( + "---\nname: perl-test\ndescription: Inspect a Perl helper.\n---\n\nRun `scripts/helper.pl`.\n\n" + "See `scripts/helper.pl`.\n", + encoding="utf-8", + ) + (root / "scripts" / "helper.pl").write_text('print "Use rm to remove a project\\n";\n', encoding="utf-8") + return root + + +def _parse_limit_skill(root: Path) -> Path: + """The skill of the v2.13.3 report, whose helper SkillSpector cannot parse within its span limit.""" + (root / "scripts").mkdir(parents=True) + (root / "SKILL.md").write_text( + "---\nname: parser-limit\ndescription: Inspect a Perl helper.\n---\n\nRun `scripts/helper.pl`.\n\n" + "See `scripts/helper.pl`.\n", + encoding="utf-8", + ) + (root / "scripts" / "helper.pl").write_text( + '#!/usr/bin/env perl\nuse strict;\nuse warnings;\nprint "Use rm ' + "safe " * 2000 + '-rf *";\n', + encoding="utf-8", + ) + return root + + +class TestCapturedReports: + """Real reports from three SkillSpector releases.""" + + def test_legacy_report_is_named_and_explained_from_the_ledger(self) -> None: + report = _report() + assert {issue["pattern"] for issue in report["issues"]} == {None} + assert {json.dumps(issue["evidence"]) for issue in report["issues"]} == {"{}"} + + result = _process(report) + + findings = _ae1(result) + assert [finding.line_number for finding in findings] == [6, 8] + for finding in findings: + assert finding.check_name == _CHECK_NAME + assert finding.severity == Severity.HIGH + assert finding.message == "analysis-evasion: scripts/helper.pl (partial)" + assert finding.suggestion.startswith( + "Referenced artifact scripts/helper.pl was not completely inspected (partial). " + "static_parse_limit (static_patterns_tool_misuse): A security-relevant expression exceeded " + "a bounded static parser's span limit. " + ) + # The generic remediation of this release suggests the file is absent. + assert "locally available" not in finding.suggestion + assert "minimal reproducer" in finding.suggestion + assert finding.metadata["skillspector_evidence"] == { + "target_path": "scripts/helper.pl", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "phase": "static", + "message": "A security-relevant expression exceeded a bounded static parser's span limit.", + "analyzers": ["static_patterns_tool_misuse"], + } + ], + } + assert finding.metadata["skillspector_occurrences"] == [ + {"file": "SKILL.md", "start_line": finding.line_number} + ] + assert finding.metadata["skillspector_confidence"] == 1.0 + assert result.metadata["skillspector_reference_summary"] == { + "affected_artifacts": 1, + "reference_occurrences": 2, + "reference_occurrences_truncated": False, + } + assert [message for message in result.messages if is_reference_summary_message(message)] == [ + "skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); " + "each AE1 finding names the artifact and why its analysis stopped" + ] + + def test_structured_evidence_names_every_reason_and_keeps_the_scanner_remedy(self) -> None: + report = _report(_HOST_LANGUAGE_REPORT) + + result = _process(report) + + by_target = {} + for finding in _ae1(result): + assert finding.check_name == _CHECK_NAME + by_target.setdefault(finding.metadata["skillspector_evidence"]["target_path"], []).append(finding) + assert {target: [f.line_number for f in found] for target, found in by_target.items()} == { + "scripts/render_notes.py": [8, 14], + "scripts/check_labels.py": [10], + "scripts/load_plugins.pl": [12], + } + render_notes = by_target["scripts/render_notes.py"][0].suggestion + assert render_notes.startswith( + "Referenced artifact scripts/render_notes.py was not completely inspected (partial). " + "static_parse_limit (static_patterns_tool_misuse): " + ) + assert render_notes.endswith(report["issues"][0]["remediation"]) + # Thirteen reasons that differ only in the analyzer read as one. + check_labels = by_target["scripts/check_labels.py"][0] + assert len(check_labels.metadata["skillspector_evidence"]["reasons"]) == 13 + assert check_labels.suggestion.count("obfuscated_instruction_text") == 1 + assert ( + f"obfuscated_instruction_text ({', '.join(_OBFUSCATION_ANALYZERS)}): Obfuscated instruction text " + "could not be fully evaluated by the deterministic layer." + ) in check_labels.suggestion + assert result.metadata["skillspector_reference_summary"] == { + "affected_artifacts": 3, + "reference_occurrences": 4, + "reference_occurrences_truncated": False, + } + + @patch("skillevaluator.validators.security.Tools") + def test_scan_stays_incomplete_and_failed(self, mock_tools, tmp_path: Path) -> None: + """The diagnostics change no gate: the partial report keeps the scan INCOMPLETE.""" + root = _parse_limit_skill(tmp_path / "perl-parse-limit") + mock_tools.skillspector.is_available = True + mock_tools.skillspector.run.return_value = ToolResult( + success=True, stdout=json.dumps(_report(_PARSE_LIMIT_REPORT)), stderr="", exit_code=0 + ) + + result = SecurityValidator(use_llm=False).validate_security_only(root) + + assert not result.passed + assert result.incomplete_scans == ["skillspector"] + assert any(error.startswith(_INCOMPLETE) for error in result.errors) + findings = _ae1(result) + assert [(finding.line_number, finding.severity) for finding in findings] == [ + (6, Severity.HIGH), + (8, Severity.HIGH), + ] + assert all("static_parse_limit (static_patterns_tool_misuse)" in finding.suggestion for finding in findings) + assert result.summary.high_count == 2 + assert result.metadata["skillspector_reference_summary"]["reference_occurrences"] == 2 + + @patch("skillevaluator.validators.security.Tools") + def test_llm_stage_counts_each_reference_once(self, mock_tools, tmp_path: Path) -> None: + """Both stages report the AE1 findings of an accepted image gap; the count and message appear once.""" + root = tmp_path / "raster-demo" + (root / "assets").mkdir(parents=True) + (root / "SKILL.md").write_text("See `assets/logo.png` and `assets/photo.jpg`.\n", encoding="utf-8") + (root / "assets" / "logo.png").write_bytes(_png_bytes()) + (root / "assets" / "photo.jpg").write_bytes(_jpeg_bytes()) + static = _report(_IMAGE_PATH_REPORT) + enriched = _report(_IMAGE_PATH_REPORT) + enriched["metadata"].update({"llm_requested": True, "llm_available": True}) + for status in enriched["analysis_completeness"]["analyzer_statuses"]: + if status["status"] == "disabled": + status.update({"status": "completed", "planned_work": 1, "completed": 1, "reason_code": None}) + mock_tools.skillspector.is_available = True + mock_tools.skillspector.run.side_effect = [ + ToolResult(success=True, stdout=json.dumps(report), stderr="", exit_code=0) for report in (static, enriched) + ] + + result = SecurityValidator(use_llm=True).validate_security_only(root) + + assert mock_tools.skillspector.run.call_count == 2 + assert result.incomplete_scans == [] + assert sorted(finding.metadata["skillspector_evidence"]["target_path"] for finding in _ae1(result)) == [ + "assets/logo.png", + "assets/photo.jpg", + ] + # One line names both images: two references, one per artifact. + assert result.metadata["skillspector_reference_summary"] == { + "affected_artifacts": 2, + "reference_occurrences": 2, + "reference_occurrences_truncated": False, + } + assert sum(is_reference_summary_message(message) for message in result.messages) == 1 + + +class TestRuleName: + @pytest.mark.parametrize("pattern", [None, "", " ", [], {"unexpected": "object"}]) + def test_ae1_without_a_pattern_is_named_by_its_rule(self, pattern: object) -> None: + issue = _report()["issues"][0] + issue["pattern"] = pattern + finding, is_error = SecurityValidator._convert_skillspector_issue(issue) + assert finding.check_name == _CHECK_NAME + assert is_error + + def test_ae1_keeps_the_scanner_pattern(self) -> None: + issue = _report()["issues"][0] + issue["pattern"] = "Referenced helper not inspected" + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + assert finding.check_name == "Referenced helper not inspected (AE1)" + + def test_other_rules_keep_their_fallback_name_and_metadata(self) -> None: + issue = { + "id": "SQP1", + "category": "Quality Policy", + "pattern": None, + "severity": "LOW", + "finding": "Trigger description", + "evidence": {"target_path": "scripts/helper.pl", "target_disposition": "partial", "reasons": []}, + "occurrences": [{"file": "SKILL.md", "start_line": 1}], + } + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + assert finding.check_name == "Unknown (SQP1)" + assert finding.metadata == {} + + +class TestEvidenceProjection: + def test_evidence_and_limits_are_bounded_and_sanitized(self) -> None: + issue = _report()["issues"][0] + issue["evidence"] = { + "target_path": "scripts/helper.pl", + "target_disposition": "partial", + "reasons": [ + { + "reason_code": "static_parse_limit", + "phase": "static", + "message": "Expression exceeded parser limit.", + "analyzers": ["static_patterns_tool_misuse", {"arbitrary": "object"}, "bad\x1b[31m"], + "start_line": 3, + "end_line": True, + "limits": { + "observed_characters": 9000, + "limit_characters": 8000, + "observed_seconds": 1.25, + "limit_seconds": float("inf"), + "observed_depth": True, + "limit_bytes": -1, + "token": "not-for-export", + "arbitrary": {"nested": "not-for-export"}, + }, + "unexpected": "not-for-export", + } + ] + * 17, + "arbitrary": {"nested": "not-for-export"}, + } + issue["occurrences"] += [{"file": "../outside", "start_line": 2}, {"file": "SKILL.md", "start_line": True}] + + finding, is_error = SecurityValidator._convert_skillspector_issue(issue) + + evidence = finding.metadata["skillspector_evidence"] + assert is_error + assert evidence["reasons_truncated"] is True + assert evidence["reasons"] == [ + { + "reason_code": "static_parse_limit", + "phase": "static", + "message": "Expression exceeded parser limit.", + "analyzers": ["static_patterns_tool_misuse"], + "start_line": 3, + "limits": {"observed_characters": 9000, "limit_characters": 8000, "observed_seconds": 1.25}, + } + ] + assert "at target line 3" in finding.suggestion + assert "limit_characters=8000, observed_characters=9000, observed_seconds=1.25" in finding.suggestion + assert "not-for-export" not in json.dumps(finding.metadata) + assert "bad" not in json.dumps(finding.metadata) + assert finding.metadata["skillspector_occurrences"] == [ + {"file": "SKILL.md", "start_line": 6}, + {"file": "SKILL.md"}, + ] + + def test_occurrence_list_is_bounded(self) -> None: + issue = _report(_PARSE_LIMIT_REPORT)["issues"][0] + issue["occurrences"] = [{"file": "SKILL.md", "start_line": line} for line in range(1, 130)] + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert len(finding.metadata["skillspector_occurrences"]) == 128 + assert finding.metadata["skillspector_occurrences_truncated"] is True + + def test_secret_shaped_text_is_redacted(self) -> None: + issue = _report()["issues"][0] + secret = "nvapi-" + "examplecredential" * 3 + issue["evidence"] = { + "target_path": "scripts/helper.pl", + "target_disposition": "partial", + "reasons": [{"reason_code": "static_parse_limit", "message": secret, "analyzers": [secret]}], + } + + finding, is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert is_error + assert secret not in json.dumps(finding.metadata) + assert secret not in finding.suggestion + assert "nvapi-" in json.dumps(finding.metadata) + + @pytest.mark.parametrize( + "target", ["/outside.pl", "../outside.pl", "scripts/../../outside.pl", "C:/outside.pl", "scripts/\x00helper.pl"] + ) + def test_structured_target_outside_the_scan_is_dropped(self, target: str) -> None: + issue = _report()["issues"][0] + issue["finding"] = "malformed finding" + issue["evidence"] = {"target_path": target, "target_disposition": "partial", "reasons": []} + + finding, is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert is_error + assert "skillspector_evidence" not in finding.metadata + + @pytest.mark.parametrize("disposition", [None, "analyzed", "PARTIAL", ["partial"]]) + def test_unknown_disposition_is_dropped(self, disposition: object) -> None: + issue = _report(_PARSE_LIMIT_REPORT)["issues"][0] + issue["evidence"]["target_disposition"] = disposition + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert "skillspector_evidence" not in finding.metadata + + def test_absolute_paths_count_only_under_the_scan_root(self, tmp_path: Path) -> None: + root = _helper_skill(tmp_path / "skill") + issue = _report(_PARSE_LIMIT_REPORT)["issues"][0] + issue["evidence"]["target_path"] = f"{root.as_posix()}/scripts/helper.pl" + issue["occurrences"] = [ + {"file": f"{root.as_posix()}/SKILL.md", "start_line": 6}, + {"file": f"{tmp_path.as_posix()}/SKILL.md", "start_line": 8}, + ] + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue, scan_root=root) + + assert finding.metadata["skillspector_evidence"]["target_path"] == "scripts/helper.pl" + assert finding.metadata["skillspector_occurrences"] == [{"file": "SKILL.md", "start_line": 6}] + assert report_path(f"{root.as_posix()}/scripts/helper.pl") is None + + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("scripts/helper.pl", "scripts/helper.pl"), + ("./scripts//helper.pl", "scripts/helper.pl"), + ("scripts\\helper.pl", "scripts/helper.pl"), + ("scripts/../helper.pl", "helper.pl"), + ("..", None), + (".", None), + ("", None), + (["scripts/helper.pl"], None), + ], + ) + def test_report_path_is_lexical_and_contained(self, value: object, expected: str | None) -> None: + assert report_path(value) == expected + + +class TestLegacyLedgerReasons: + """Before v2.12.0 the reasons are only in the target's ledger rows.""" + + @pytest.mark.parametrize("target", ["../outside.pl", "/outside.pl", "scripts/\x00helper.pl", "scripts/other.pl"]) + def test_ledger_rows_must_match_an_in_scope_target(self, target: str) -> None: + report = _report() + issue = report["issues"][0] + issue["finding"] = f"{target} (partial)" + + finding, is_error = SecurityValidator._convert_skillspector_issue( + issue, completeness=report["analysis_completeness"] + ) + + assert is_error + assert "skillspector_evidence" not in finding.metadata + assert finding.suggestion == f"{issue['explanation']} {issue['remediation']}" + + def test_source_location_must_be_in_scope(self) -> None: + report = _report() + issue = report["issues"][0] + issue["location"] = {"file": "../outside.md", "start_line": 5} + + finding, _is_error = SecurityValidator._convert_skillspector_issue( + issue, completeness=report["analysis_completeness"] + ) + + assert "skillspector_evidence" not in finding.metadata + + def test_without_the_ledger_the_legacy_finding_is_unchanged(self) -> None: + issue = _report()["issues"][0] + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert finding.check_name == _CHECK_NAME + assert "skillspector_evidence" not in finding.metadata + assert finding.suggestion == f"{issue['explanation']} {issue['remediation']}" + + @pytest.mark.parametrize("structured", [False, True]) + @pytest.mark.parametrize("reason_code", ["read_error", "file_disappeared"]) + def test_read_failures_get_a_read_remedy(self, structured: bool, reason_code: str) -> None: + report = _report() + issue = report["issues"][0] + row = report["analysis_completeness"]["ledger_exceptions"][0] + row.update({"reason_code": reason_code, "message": "Artifact could not be read."}) + if structured: + issue["evidence"] = {"target_path": "scripts/helper.pl", "target_disposition": "partial", "reasons": [row]} + + finding, is_error = SecurityValidator._convert_skillspector_issue( + issue, completeness=report["analysis_completeness"] + ) + + assert is_error + assert finding.severity == Severity.HIGH + assert f"{reason_code} (static_patterns_tool_misuse): Artifact could not be read." in finding.suggestion + assert "readable where the scan runs" in finding.suggestion + assert "minimal reproducer" not in finding.suggestion + + @pytest.mark.parametrize("target", [["not a string"], {"unexpected": "object"}, True, "bad\npath"]) + @pytest.mark.parametrize("reasons", [[], [{"reason_code": "unverified_reason"}]]) + def test_unreadable_structured_target_needs_the_ledger(self, target: object, reasons: list) -> None: + issue = _report()["issues"][0] + issue["evidence"] = {"target_path": target, "target_disposition": "partial", "reasons": reasons} + + finding, is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert is_error + assert "skillspector_evidence" not in finding.metadata + + def test_unreadable_structured_target_uses_only_the_ledger_reasons(self) -> None: + report = _report() + issue = report["issues"][0] + issue["evidence"] = { + "target_path": ["not a string"], + "target_disposition": "partial", + "reasons": [{"reason_code": "unverified_reason"}], + } + + finding, _is_error = SecurityValidator._convert_skillspector_issue( + issue, completeness=report["analysis_completeness"] + ) + + assert "static_parse_limit" in finding.suggestion + assert "unverified_reason" not in finding.suggestion + + def test_ledger_is_read_once_and_bounded(self) -> None: + issue = _report()["issues"][0] + issues = [issue] * 100 + completeness = { + "ledger_exceptions": [ + {"path": "scripts/helper.pl", "reason_code": "static_parse_limit"}, + {"path": "scripts/unrelated.pl", "reason_code": "read_error"}, + ] + * 1000 + } + calls = 0 + + def normalize(path: object) -> str | None: + nonlocal calls + calls += 1 + return report_path(path) + + index = index_legacy_reference_reasons(issues, completeness=completeness, normalize_path=normalize) + + assert calls == 3 # The source, the target and the unrelated ledger path. + assert set(index) == {"scripts/helper.pl"} + assert len(index["scripts/helper.pl"]) == 17 + for repeated in issues: + evidence = issue_diagnostics( + repeated, completeness=completeness, normalize_path=normalize, legacy_reason_index=index + )["skillspector_evidence"] + assert evidence["reasons"] == [{"reason_code": "static_parse_limit"}] + assert evidence["reasons_truncated"] is True + # Each finding normalizes its own paths, never the ledger again. + assert calls <= 4 * len(issues) + 3 + + +class TestTruncatedReasons: + @pytest.mark.parametrize("structured", [False, True]) + @pytest.mark.parametrize( + ("visible_reason", "hidden_reason"), + [("static_parse_limit", "read_error"), ("read_error", "static_parse_limit")], + ) + def test_no_single_remedy_is_claimed(self, structured: bool, visible_reason: str, hidden_reason: str) -> None: + report = _report() + row = report["analysis_completeness"]["ledger_exceptions"][0] + rows = [ + {**row, "reason_code": visible_reason, "message": "Visible analysis limitation.", "start_line": line} + for line in range(1, 17) + ] + rows.append({**row, "reason_code": hidden_reason, "message": "Hidden analysis limitation.", "start_line": 17}) + report["analysis_completeness"]["ledger_exceptions"] = rows + if structured: + for issue in report["issues"]: + issue["evidence"] = { + "target_path": "scripts/helper.pl", + "target_disposition": "partial", + "reasons": rows[:16], + "reasons_truncated": True, + } + + result = _process(report) + + findings = _ae1(result) + assert len(findings) == 2 + for finding in findings: + assert finding.severity == Severity.HIGH + assert finding.metadata["skillspector_evidence"]["reasons_truncated"] is True + assert visible_reason in finding.suggestion + assert hidden_reason not in finding.suggestion + assert "SkillSpector reported more reasons than are shown here" in finding.suggestion + assert "`analysis_completeness.ledger_exceptions`" in finding.suggestion + assert finding.suggestion.endswith("Resolve the reported analysis limitation and rerun the scan.") + + def test_the_scanner_remedy_is_kept(self) -> None: + issue = _report()["issues"][0] + issue["evidence"] = { + "target_path": "scripts/helper.pl", + "target_disposition": "partial", + "reasons": [{"reason_code": "static_parse_limit"}], + "reasons_truncated": True, + } + issue["remediation"] = "Review the expression boundary and rerun after addressing every ledger exception." + + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert finding.suggestion.endswith(issue["remediation"]) + assert "SkillSpector reported more reasons than are shown here" in finding.suggestion + + +class TestSummaryRecord: + def test_a_later_record_replaces_the_count_and_message(self) -> None: + result = _process(_report(_HOST_LANGUAGE_REPORT)) + result.findings = [ + finding + for finding in result.findings + if finding.metadata.get("skillspector_evidence", {}).get("target_path") == "scripts/render_notes.py" + ] + + _record_skillspector_reference_summary(result) + + assert result.metadata["skillspector_reference_summary"]["affected_artifacts"] == 1 + assert [message for message in result.messages if is_reference_summary_message(message)] == [ + "skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); " + "each AE1 finding names the artifact and why its analysis stopped" + ] + + result.findings = [] + _record_skillspector_reference_summary(result) + + assert "skillspector_reference_summary" not in result.metadata + assert not any(is_reference_summary_message(message) for message in result.messages) + + def test_reports_without_ae1_evidence_have_no_summary(self) -> None: + report = _report() + for issue in report["issues"]: + issue["finding"] = "malformed finding" + + result = _process(report) + + assert len(_ae1(result)) == 2 + assert "skillspector_reference_summary" not in result.metadata + assert not any(is_reference_summary_message(message) for message in result.messages) From 2914b5bb1ca1f63660b691761e78510847598e78 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 12:43:11 -0800 Subject: [PATCH 02/15] feat(reporting): count incompletely inspected referenced files in failed Tier 1 reports When the security check fails, the full and compact terminal output, the Markdown report and the HTML report add one line that counts the files SkillSpector did not completely inspect and the lines that name them. The JSON report records the counts in skillspector_reference_summary, with only its three count fields. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- src/skillevaluator/reporting/cli.py | 11 ++ src/skillevaluator/reporting/console_ui.py | 4 + src/skillevaluator/reporting/html.py | 3 + src/skillevaluator/reporting/json_reporter.py | 7 + src/skillevaluator/reporting/markdown.py | 7 + .../reporting/templates/report.html.j2 | 4 + .../test_skillspector_reference_summary.py | 187 ++++++++++++++++++ 7 files changed, 223 insertions(+) create mode 100644 tests/reporting/test_skillspector_reference_summary.py diff --git a/src/skillevaluator/reporting/cli.py b/src/skillevaluator/reporting/cli.py index c45922af5..2ba1f4cbd 100644 --- a/src/skillevaluator/reporting/cli.py +++ b/src/skillevaluator/reporting/cli.py @@ -53,6 +53,7 @@ from skillevaluator.reporting.presentation import FinalRenderContext, build_final_render_context, trial_coverage from skillevaluator.reporting.run_status import Status, result_status from skillevaluator.reporting.terminal_styles import AMBER, FAINT, GREEN, RED, TEXT, grade_style, lift_style +from skillevaluator.skillspector_references import reference_summary_message from skillevaluator.utils.rich_markup import escape_markup if TYPE_CHECKING: @@ -254,6 +255,7 @@ def render_result(self, result: ValidationResult, console: Console) -> None: elif result_status(result) == Status.INCOMPLETE: tools = ", ".join(result.incomplete_scans) console.print(f"[yellow][INCOMPLETE] {escape_markup(tools)} did not complete[/yellow]\n") + self._print_reference_summary(result, console) self._print_summary_stats(result, console) self._print_findings(result, console) elif result.passed: @@ -264,9 +266,18 @@ def render_result(self, result: ValidationResult, console: Console) -> None: self._print_findings(result, console) else: console.print("[red][FAIL] Validation failed[/red]\n") + self._print_reference_summary(result, console) self._print_summary_stats(result, console) self._print_findings(result, console) + @staticmethod + def _print_reference_summary(result: ValidationResult, console: Console) -> None: + """Print how many referenced artifacts SkillSpector did not completely inspect in a failed result.""" + summary = reference_summary_message(result.metadata.get("skillspector_reference_summary")) + if summary and not result.passed: + console.print(f" {escape_markup(summary)}", soft_wrap=True, highlight=False) + console.print() + @staticmethod def _score_cell(dims: dict, dname: str) -> str: """Format a dimension score cell with color coding.""" diff --git a/src/skillevaluator/reporting/console_ui.py b/src/skillevaluator/reporting/console_ui.py index eed1a27c2..cbc56c7ad 100644 --- a/src/skillevaluator/reporting/console_ui.py +++ b/src/skillevaluator/reporting/console_ui.py @@ -64,6 +64,7 @@ grade_style, lift_style, ) +from skillevaluator.skillspector_references import reference_summary_message from skillevaluator.utils.rich_markup import strip_terminal_controls if TYPE_CHECKING: @@ -1183,6 +1184,9 @@ def summarize_tier1(results: list[ValidationResult], lineup: list[str] | None = [(f"{suppressed_security} scanner {noun} suppressed outside agent control paths", MUTED)], ) ) + for r in failed: + if reference_summary := reference_summary_message((r.metadata or {}).get("skillspector_reference_summary")): + rows.append(TierRow("references", [(reference_summary, MUTED)], fit="wrap")) quality = _quality_stats(results) if quality: diff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.py index 5b69f7db8..8341591ed 100644 --- a/src/skillevaluator/reporting/html.py +++ b/src/skillevaluator/reporting/html.py @@ -1720,6 +1720,8 @@ def _create_environment() -> Environment: reporters with different options can share it. Jinja environments are safe to share between threads once they are configured. """ + from skillevaluator.skillspector_references import reference_summary_message + loader = PackageLoader("skillevaluator.reporting", "templates") environment = Environment(loader=loader, autoescape=True) environment.filters["cleanly_skipped"] = is_cleanly_skipped @@ -1729,6 +1731,7 @@ def _create_environment() -> Environment: environment.filters["adaptive_percent"] = _adaptive_percent environment.filters["adaptive_interval_percent"] = _adaptive_interval_percent environment.filters["skip_reason"] = get_skip_reason + environment.filters["skillspector_reference_summary"] = reference_summary_message return environment @staticmethod diff --git a/src/skillevaluator/reporting/json_reporter.py b/src/skillevaluator/reporting/json_reporter.py index 7ad012e39..8b257d1f6 100644 --- a/src/skillevaluator/reporting/json_reporter.py +++ b/src/skillevaluator/reporting/json_reporter.py @@ -37,6 +37,7 @@ ) from skillevaluator.reporting.run_status import Status, resolve_run_status, result_status from skillevaluator.skillspector_provenance import sanitize_skillspector_provenance_metadata +from skillevaluator.skillspector_references import reference_summary_record from skillevaluator.source_identity import recorded_evaluated_source if TYPE_CHECKING: @@ -345,6 +346,12 @@ def _result_to_dict( if isinstance(skillspector_applicability, dict): data["skillspector_applicability"] = skillspector_applicability + # Tier 1 SkillSpector AE1 counts: referenced artifacts it did not + # completely inspect and the reference lines that name them. + reference_summary = reference_summary_record(result.metadata.get("skillspector_reference_summary")) + if reference_summary is not None: + data["skillspector_reference_summary"] = reference_summary + qs = result.metadata.get("quality_scores") if qs: data["quality"] = qs diff --git a/src/skillevaluator/reporting/markdown.py b/src/skillevaluator/reporting/markdown.py index e52031ad2..e397a8232 100644 --- a/src/skillevaluator/reporting/markdown.py +++ b/src/skillevaluator/reporting/markdown.py @@ -42,6 +42,7 @@ safe_url, ) from skillevaluator.reporting.run_status import Status, resolve_run_status, result_status +from skillevaluator.skillspector_references import reference_summary_message if TYPE_CHECKING: from skillevaluator.models import Finding, ValidationResult @@ -521,6 +522,12 @@ def _render_result(self, result: ValidationResult, lines: list[str]) -> None: lines.append(f"| {dname.title()} | {ddata.get('score', 0):.1f} | {ddata.get('weight', 0) * 100:.0f}% |") lines.append("") + if not result.passed and ( + reference_summary := reference_summary_message(result.metadata.get("skillspector_reference_summary")) + ): + lines.append(f"- {reference_summary}") + lines.append("") + if result.is_incomplete: self._render_incomplete(result, lines) elif clean_skip: diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2 index 7725f6752..42cbe5ed9 100644 --- a/src/skillevaluator/reporting/templates/report.html.j2 +++ b/src/skillevaluator/reporting/templates/report.html.j2 @@ -1673,6 +1673,10 @@ + {% for result in results if not result.passed %} + {% set reference_summary = result.metadata.get('skillspector_reference_summary') | skillspector_reference_summary %} + {% if reference_summary %}

{{ reference_summary }}

{% endif %} + {% endfor %} {# ==================== SKILL-CENTRIC VIEW ==================== #}
diff --git a/tests/reporting/test_skillspector_reference_summary.py b/tests/reporting/test_skillspector_reference_summary.py new file mode 100644 index 000000000..e4ad55ee2 --- /dev/null +++ b/tests/reporting/test_skillspector_reference_summary.py @@ -0,0 +1,187 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""A failed result counts the files SkillSpector did not completely inspect in every report. + +The counts come from the AE1 findings' evidence (see +``tests/validators/test_skillspector_reference_diagnostics.py``). The real +SkillSpector v2.11.2 report names ``scripts/helper.pl`` at two lines of +``SKILL.md``. +""" + +import json +import re +from pathlib import Path + +import pytest + +from skillevaluator.reporting.cli import CLIReporter +from skillevaluator.reporting.console_ui import summarize_tier1 +from skillevaluator.reporting.html import HTMLReporter +from skillevaluator.reporting.json_reporter import JSONReporter +from skillevaluator.reporting.markdown import MarkdownReporter +from skillevaluator.skillspector_references import ( + combine_reference_summaries, + reference_summary_message, + reference_summary_record, +) +from skillevaluator.validators.base import ValidationResult +from skillevaluator.validators.security import SecurityValidator + +_REPORT = Path(__file__).parents[1] / "fixtures" / "skillspector-2.11.2-perl-help-text-ae1-no-llm.json" + + +def _write_skill(root: Path) -> None: + (root / "scripts").mkdir(parents=True) + (root / "SKILL.md").write_text( + "---\nname: perl-test\ndescription: Inspect a Perl helper.\n---\n\nRun `scripts/helper.pl`.\n\n" + "See `scripts/helper.pl`.\n", + encoding="utf-8", + ) + (root / "scripts" / "helper.pl").write_text('print "Use rm to remove a project\\n";\n', encoding="utf-8") + + +def _validate( + root: Path, monkeypatch: pytest.MonkeyPatch, *, skills: tuple[str, ...], lines: int = 0 +) -> ValidationResult: + """Scan *skills* under *root* with the captured report; *lines* lists that many reference lines in one AE1.""" + for name in skills: + _write_skill(root / name) + validator = SecurityValidator(use_llm=False) + + def scan(path: Path) -> ValidationResult: + report = json.loads(_REPORT.read_text(encoding="utf-8")) + if lines: + report["issues"][0]["occurrences"] = [ + {"file": "SKILL.md", "start_line": line} for line in range(1, lines + 1) + ] + result = ValidationResult(validator_name="Security Scan") + validator._process_skillspector_cli_result(report, result, source_root=path) + return result + + monkeypatch.setattr(validator, "_run_skillspector", scan) + return validator.validate_security_only(root) + + +def _rendered(result: ValidationResult) -> dict[str, str]: + passed, rows = summarize_tier1([result], lineup=["security"]) + assert passed == result.passed + return { + "CLI": re.sub(r"\x1b\[[0-9;]*m", "", CLIReporter().render(result)), + "terminal summary": "\n".join("".join(text for text, _style in row.segments) for row in rows), + "Markdown": MarkdownReporter(include_timestamp=False).render(result), + # The visible line; the page's embedded data also carries the result messages. + "HTML": "\n".join( + re.findall( + r'

]*>([^<]*)

', + HTMLReporter(include_timestamp=False).render(result), + ) + ), + } + + +def _phrase(artifacts: int, occurrences: str) -> str: + return ( + f"skillspector could not completely inspect {artifacts} referenced artifact(s) across {occurrences} " + "reference occurrence(s); each AE1 finding names the artifact and why its analysis stopped" + ) + + +@pytest.mark.parametrize("skills", [(".",), ("alpha", "beta")], ids=["skill", "folder"]) +def test_failed_reports_show_the_counts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, skills: tuple) -> None: + result = _validate(tmp_path, monkeypatch, skills=skills) + + expected = { + "affected_artifacts": len(skills), + "reference_occurrences": 2 * len(skills), + "reference_occurrences_truncated": False, + } + assert not result.passed + assert result.metadata["skillspector_reference_summary"] == expected + assert sum(finding.check_name.endswith("(AE1)") for finding in result.findings) == 2 * len(skills) + phrase = _phrase(len(skills), str(2 * len(skills))) + for reporter, rendered in _rendered(result).items(): + assert rendered.count(phrase) == 1, reporter + exported = json.loads(JSONReporter(include_timestamp=False).render(result)) + assert exported["skillspector_reference_summary"] == expected + combined = json.loads(JSONReporter(include_timestamp=False).render_all([result])) + assert combined["results"][0]["skillspector_reference_summary"] == expected + + +def test_a_cut_occurrence_list_is_a_lower_bound(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + result = _validate(tmp_path, monkeypatch, skills=("alpha", "beta"), lines=129) + + # Each skill: 128 kept lines of the first AE1, of which line 8 is the second AE1's. + assert result.metadata["skillspector_reference_summary"] == { + "affected_artifacts": 2, + "reference_occurrences": 256, + "reference_occurrences_truncated": True, + } + for reporter, rendered in _rendered(result).items(): + assert _phrase(2, "at least 256") in rendered, reporter + + +def test_passing_results_do_not_show_the_counts() -> None: + """Only a failed result gets the count line; JSON still records it.""" + result = ValidationResult(validator_name="Security Scan") + result.metadata["skillspector_reference_summary"] = { + "affected_artifacts": 1, + "reference_occurrences": 2, + "reference_occurrences_truncated": False, + } + + assert result.passed + for reporter, rendered in _rendered(result).items(): + assert "referenced artifact(s)" not in rendered, reporter + exported = json.loads(JSONReporter(include_timestamp=False).render(result)) + assert exported["skillspector_reference_summary"]["affected_artifacts"] == 1 + + +@pytest.mark.parametrize( + "summary", + [ + None, + [], + {"affected_artifacts": 0, "reference_occurrences": 2}, + {"affected_artifacts": True, "reference_occurrences": 2}, + {"affected_artifacts": 1, "reference_occurrences": -1}, + {"affected_artifacts": 1, "reference_occurrences": 1 << 63}, + {"affected_artifacts": "1", "reference_occurrences": 2}, + {"affected_artifacts": "", "reference_occurrences": 2}, + ], +) +def test_malformed_counts_are_neither_shown_nor_exported(summary: object) -> None: + result = ValidationResult(validator_name="Security Scan") + result.add_error("failed") + result.metadata["skillspector_reference_summary"] = summary + + assert reference_summary_message(summary) is None + for reporter, rendered in _rendered(result).items(): + assert "referenced artifact(s)" not in rendered, reporter + assert "skillspector_reference_summary" not in json.loads(JSONReporter(include_timestamp=False).render(result)) + + +def test_export_keeps_only_the_count_fields() -> None: + summary = { + "affected_artifacts": 2, + "reference_occurrences": 3, + "reference_occurrences_truncated": "yes", + "paths": ["scripts/helper.pl"], + } + + assert reference_summary_record(summary) == { + "affected_artifacts": 2, + "reference_occurrences": 3, + "reference_occurrences_truncated": False, + } + + +def test_folder_totals_skip_malformed_children() -> None: + assert combine_reference_summaries([]) is None + assert combine_reference_summaries( + [ + {"affected_artifacts": 1, "reference_occurrences": 2, "reference_occurrences_truncated": False}, + {"affected_artifacts": "1", "reference_occurrences": 2}, + {"affected_artifacts": 3, "reference_occurrences": 0, "reference_occurrences_truncated": True}, + ] + ) == {"affected_artifacts": 4, "reference_occurrences": 2, "reference_occurrences_truncated": True} From 6806e31b075b9da5ef6abe78a9a20e9da1d27d3d Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 12:43:11 -0800 Subject: [PATCH 03/15] docs(tier1): describe the reasons and counts of SkillSpector AE1 findings Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 17 +++++++++++++++++ docs/tier1-validation.mdx | 6 +++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d2f93826..54c3a6fe2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,23 @@ All notable changes to SkillEvaluator are documented in this file. Your Agent" docs page shows how to install it in Codex, Claude Code, OpenCode, OpenClaw, and other skill-aware agents. +- Tier 1 **Incomplete referenced artifact analysis (AE1)** findings from + SkillSpector now say why SkillSpector stopped inspecting the file that a skill + names. The suggestion names the file, its disposition and each reason + SkillSpector gives, such as + `static_parse_limit (static_patterns_tool_misuse)`, with any line and limits, + and the finding's metadata records them under `skillspector_evidence` and + `skillspector_occurrences`. Before, the finding said only + `Referenced artifact was not completely inspected`, and its reason had to be + matched by hand against the incomplete-analysis error, which lists at most + three rows. With SkillSpector before v2.12.0 the finding was titled + `Unknown (AE1)` and told the user to make the file available although + SkillSpector had read part of it. It now carries the rule's name and the + reasons from the report's ledger rows for the file. A failed check also counts + the files and the lines that name them in one line of the terminal, Markdown + and HTML reports, and in the JSON field `skillspector_reference_summary`. + Severities, scan completeness and gates are unchanged. + ### Changed - Align terminal grade and lift colors across compact, full, and direct Tier 3 diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx index 1471719d5..1a3f04e88 100644 --- a/docs/tier1-validation.mdx +++ b/docs/tier1-validation.mdx @@ -208,6 +208,10 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice - v2.13.4 reports `observed_records` and `limit_records` on the row. SkillEvaluator accepts the row only when `observed_records` equals the BH1 `declaration_count` and does not exceed `limit_records`. A manifest with more records than SkillSpector reads, or with a hook handler it counted but could not parse, therefore stays `INCOMPLETE`. So does a settings file with permission rules, `env` or other settings beside its hooks, because SkillSpector counts those records too. A part it does not count, such as a hook group that is not an object, is not visible and gets the Critical. - v2.13.3, the release SkillEvaluator installs, does not report them. SkillEvaluator then refuses only a BH1 that counts 2,048 or more declarations, because SkillSpector may have cut that manifest short. A manifest that SkillSpector parsed only in part, such as one with a malformed handler beside a valid one, gets the same Critical as a manifest it read in full, and still fails. + **Incomplete referenced artifacts.** SkillSpector reports a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names a file it did not completely inspect. Releases before v2.12.0 leave the finding's name empty, so SkillEvaluator names it by its rule instead of `Unknown (AE1)`. The finding's suggestion names the file, its disposition (`partial`, `failed`, `out_of_scope` or `uninspected`) and each reason SkillSpector gives: the reason code, such as `static_parse_limit` or `read_error`, the analyzers, the line in the file, the message and any limits, such as `limit_characters=8000`. Reasons that differ only in the analyzer are listed once. SkillSpector's own remedy is kept. Releases before v2.12.0 give no reasons in the finding and a generic remedy that says to make the file available: SkillEvaluator then reads the reasons from the report's `analysis_completeness` rows for that file and gives a remedy for a parse limit, a read error, or any other reason. Without such a row the finding keeps SkillSpector's text. The finding's metadata records the file, its disposition and up to 16 reasons under `skillspector_evidence`, with `reasons_truncated` when SkillSpector gave more, and up to 128 reference lines under `skillspector_occurrences`. Text with control characters is left out, credential-shaped text is masked, and a path outside the scanned target is dropped. + + When the check fails, the terminal output, the `references` row of the terminal summary, and the Markdown and HTML reports add one line, such as `skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); each AE1 finding names the artifact and why its analysis stopped`. The JSON report records the counts in `skillspector_reference_summary`: `affected_artifacts`, `reference_occurrences`, and `reference_occurrences_truncated`, which is `true` when SkillSpector listed more than 128 lines for one finding, so the count is a lower bound. For a folder of skills the counts are totals. None of this changes the finding's severity, whether the scan is complete, or any gate. + **Agent control paths.** SkillSpector rules describe attacks on an agent, so a match is an agent threat only in a file the agent reads or runs. When `validate` or `tier1` detects a skill, rules, workflows, or plugin artifact, the `security` check keeps findings on agent control paths and suppresses the rest: | File role | Tier 1 finding | Examples | @@ -586,7 +590,7 @@ Tier 1 checks always gate the exit code inside `validate`. Tier 2 gates when it Install Bandit and pip-audit with `skillevaluator[security]`. Install Semgrep separately with `brew install semgrep` or `uv tool install semgrep`, and SkillSpector with `uv tool install git+https://github.com/NVIDIA/SkillSpector.git@v2.13.3`. Required scanner failures remain `INCOMPLETE` until the scanner is installed and returns valid evidence. `skillevaluator doctor --tier 1` lists every scanner the selected checks need, with its resolved path and version. - SkillSpector releases before v2.13.1 can stop inspecting a valid Python or Perl helper early and record a `static_parse_limit`, `obfuscated_instruction_text`, or `runtime_limit` ledger exception. The security check is then `INCOMPLETE`, often with a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names the helper. Check the installed release with `skillspector --version` and upgrade with `uv tool install git+https://github.com/NVIDIA/SkillSpector.git@v2.13.3`. If the exception remains after the upgrade, investigate it like any other incomplete scan. + SkillSpector releases before v2.13.1 can stop inspecting a valid Python or Perl helper early and record a `static_parse_limit`, `obfuscated_instruction_text`, or `runtime_limit` ledger exception. The security check is then `INCOMPLETE`, often with a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names the helper. The finding's suggestion names the helper and the reason, such as `static_parse_limit (static_patterns_tool_misuse)`. Check the installed release with `skillspector --version` and upgrade with `uv tool install git+https://github.com/NVIDIA/SkillSpector.git@v2.13.3`. If the exception remains after the upgrade, investigate it like any other incomplete scan. With SkillSpector v2.12.0 and later, a skill, folder or hooks-only plugin From 170456b007305a5d9ca9e0c30cedfc25d963b4bb Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 13:15:25 -0800 Subject: [PATCH 04/15] fix(tier1): drop AE1 reason limits too large for a float A reason's limit that is an integer beyond the float range raised OverflowError in math.isfinite, so the scan returned no result. Check the type and range first and call math.isfinite only for floats, so such a limit is left out like any other out-of-range value. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- src/skillevaluator/skillspector_references.py | 7 ++-- ...test_skillspector_reference_diagnostics.py | 33 +++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/skillevaluator/skillspector_references.py b/src/skillevaluator/skillspector_references.py index 9daa6eebf..921806eb5 100644 --- a/src/skillevaluator/skillspector_references.py +++ b/src/skillevaluator/skillspector_references.py @@ -156,8 +156,11 @@ def _reasons(rows: object) -> list[dict]: limits = {} for key, accepts_float in _LIMIT_FIELDS: value = metrics.get(key) - numeric = type(value) is int or (accepts_float and type(value) is float) - if numeric and math.isfinite(value) and 0 <= value <= _MAX_COUNT: + # The range is checked before any float conversion, so an + # integer too large for a float is dropped, not raised. + if (type(value) is int and 0 <= value <= _MAX_COUNT) or ( + accepts_float and type(value) is float and math.isfinite(value) and 0 <= value <= _MAX_COUNT + ): limits[key] = value if limits: reason["limits"] = limits diff --git a/tests/validators/test_skillspector_reference_diagnostics.py b/tests/validators/test_skillspector_reference_diagnostics.py index 0a0ff4a45..f65d2f5e6 100644 --- a/tests/validators/test_skillspector_reference_diagnostics.py +++ b/tests/validators/test_skillspector_reference_diagnostics.py @@ -335,6 +335,39 @@ def test_evidence_and_limits_are_bounded_and_sanitized(self) -> None: {"file": "SKILL.md"}, ] + @pytest.mark.parametrize("field", ["observed_characters", "observed_seconds"]) + @pytest.mark.parametrize( + "value", + [10**400, -(10**400), 1 << 63, float("nan"), -1.0], + ids=["beyond-float", "below-float", "beyond-count", "nan", "negative"], + ) + def test_out_of_range_limits_are_dropped(self, field: str, value: object) -> None: + """A limit beyond the count range, even an integer too large for a float, is left out.""" + issue = _report(_PARSE_LIMIT_REPORT)["issues"][0] + issue["evidence"]["reasons"][0]["limits"] = {field: value, "limit_characters": 8000} + + finding, is_error = SecurityValidator._convert_skillspector_issue(issue) + + assert is_error + assert finding.metadata["skillspector_evidence"]["reasons"][0]["limits"] == {"limit_characters": 8000} + + @patch("skillevaluator.validators.security.Tools") + def test_an_oversized_limit_does_not_stop_the_scan(self, mock_tools, tmp_path: Path) -> None: + root = _parse_limit_skill(tmp_path / "perl-parse-limit") + report = _report(_PARSE_LIMIT_REPORT) + report["issues"][0]["evidence"]["reasons"][0]["limits"] = {"observed_characters": 10**400} + mock_tools.skillspector.is_available = True + mock_tools.skillspector.run.return_value = ToolResult( + success=True, stdout=json.dumps(report), stderr="", exit_code=0 + ) + + result = SecurityValidator(use_llm=False).validate_security_only(root) + + assert not result.passed + assert result.incomplete_scans == ["skillspector"] + assert result.summary.high_count == 2 + assert result.metadata["skillspector_reference_summary"]["affected_artifacts"] == 1 + def test_occurrence_list_is_bounded(self) -> None: issue = _report(_PARSE_LIMIT_REPORT)["issues"][0] issue["occurrences"] = [{"file": "SKILL.md", "start_line": line} for line in range(1, 130)] From 3fcc2d047888decc87693234f445c5aa3026c330 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 13:16:46 -0800 Subject: [PATCH 05/15] fix(tier1): keep the AE1 count line out of passing results The count of incompletely inspected referenced artifacts was also added to the result's messages. A policy that lowers the AE1 findings, or --verify-llm, can pass a complete scan, and reporters list a passing result's messages as passed checks, so the Markdown, HTML and terminal reports showed the count as a success. Every reporter already renders the line from the skillspector_reference_summary metadata, and only for a failed result, so the message is dropped. JSON still records the counts for every result. Also pin that a severity override for a SkillSpector report before v2.12.0 matches the rule's name, not "Unknown (AE1)". Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- src/skillevaluator/skillspector_references.py | 6 -- src/skillevaluator/validators/security.py | 13 ++-- .../test_skillspector_reference_summary.py | 63 ++++++++++++++++++- ...test_skillspector_reference_diagnostics.py | 32 +++++----- 4 files changed, 83 insertions(+), 31 deletions(-) diff --git a/src/skillevaluator/skillspector_references.py b/src/skillevaluator/skillspector_references.py index 921806eb5..a2fba3454 100644 --- a/src/skillevaluator/skillspector_references.py +++ b/src/skillevaluator/skillspector_references.py @@ -38,7 +38,6 @@ "combine_reference_summaries", "diagnostic_text", "index_legacy_reference_reasons", - "is_reference_summary_message", "issue_diagnostics", "reference_suggestion", "reference_summary", @@ -427,8 +426,3 @@ def reference_summary_message(summary: object) -> str | None: f"{_SUMMARY_MESSAGE_PREFIX}{record['affected_artifacts']} referenced artifact(s) across {count} " "reference occurrence(s); each AE1 finding names the artifact and why its analysis stopped" ) - - -def is_reference_summary_message(message: object) -> bool: - """Whether *message* is a :func:`reference_summary_message`.""" - return isinstance(message, str) and message.startswith(_SUMMARY_MESSAGE_PREFIX) diff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.py index aeb7e5693..d5bb357cd 100644 --- a/src/skillevaluator/validators/security.py +++ b/src/skillevaluator/validators/security.py @@ -62,11 +62,9 @@ REFERENCE_SUMMARY_KEY, combine_reference_summaries, index_legacy_reference_reasons, - is_reference_summary_message, issue_diagnostics, reference_suggestion, reference_summary, - reference_summary_message, report_path, ) from skillevaluator.spdx import is_spdx_only_html_comment @@ -1077,21 +1075,20 @@ def _combine_skillspector_applicability(blocks: list[dict]) -> dict: def _record_skillspector_reference_summary(result: ValidationResult) -> None: - """Count the referenced artifacts behind *result*'s AE1 evidence in its metadata and one message. + """Count the referenced artifacts behind *result*'s AE1 evidence in its metadata. The counts come from the findings (:func:`~skillevaluator.skillspector_references.reference_summary`), so a - second call after the ``--llm`` stage is merged replaces the first count - and its message. + second call after the ``--llm`` stage is merged replaces the first count. + They are not added to the result's messages: reporters list a passing + result's messages as passed checks, and they show the counts only for a + failed result. """ - result.messages = [message for message in result.messages if not is_reference_summary_message(message)] summary = reference_summary(result.findings) if summary is None: result.metadata.pop(REFERENCE_SUMMARY_KEY, None) return result.metadata[REFERENCE_SUMMARY_KEY] = summary - if message := reference_summary_message(summary): - result.add_message(message) def _issue_field(issue: dict): diff --git a/tests/reporting/test_skillspector_reference_summary.py b/tests/reporting/test_skillspector_reference_summary.py index e4ad55ee2..0906d05e2 100644 --- a/tests/reporting/test_skillspector_reference_summary.py +++ b/tests/reporting/test_skillspector_reference_summary.py @@ -12,8 +12,10 @@ import json import re from pathlib import Path +from unittest.mock import patch import pytest +from tests.validators.test_security import _jpeg_bytes, _png_bytes from skillevaluator.reporting.cli import CLIReporter from skillevaluator.reporting.console_ui import summarize_tier1 @@ -25,10 +27,15 @@ reference_summary_message, reference_summary_record, ) -from skillevaluator.validators.base import ValidationResult +from skillevaluator.utils.tool_runner import ToolResult +from skillevaluator.validators.base import Severity, ValidationResult +from skillevaluator.validators.policy import ValidationPolicy, apply_policy from skillevaluator.validators.security import SecurityValidator _REPORT = Path(__file__).parents[1] / "fixtures" / "skillspector-2.11.2-perl-help-text-ae1-no-llm.json" +# A complete v2.12.0 scan whose two AE1 findings name image files it does not analyze. +_IMAGE_REPORT = Path(__file__).parents[1] / "fixtures" / "skillspector-2.12.0-image-path-reference-no-llm.json" +_AE1_OVERRIDE = "SECURITY.Incomplete referenced artifact analysis (AE1)" def _write_skill(root: Path) -> None: @@ -70,7 +77,7 @@ def _rendered(result: ValidationResult) -> dict[str, str]: "CLI": re.sub(r"\x1b\[[0-9;]*m", "", CLIReporter().render(result)), "terminal summary": "\n".join("".join(text for text, _style in row.segments) for row in rows), "Markdown": MarkdownReporter(include_timestamp=False).render(result), - # The visible line; the page's embedded data also carries the result messages. + # The line above the Tier 1 results. "HTML": "\n".join( re.findall( r'

]*>([^<]*)

', @@ -121,6 +128,58 @@ def test_a_cut_occurrence_list_is_a_lower_bound(tmp_path: Path, monkeypatch: pyt assert _phrase(2, "at least 256") in rendered, reporter +@patch("skillevaluator.validators.security.Tools") +def _scan_images(root: Path, mock_tools, *, pattern: object = "keep") -> ValidationResult: + """Scan a skill that names two images with the captured v2.12.0 report; *pattern* replaces each AE1's.""" + (root / "assets").mkdir(parents=True) + (root / "SKILL.md").write_text("See `assets/logo.png` and `assets/photo.jpg`.\n", encoding="utf-8") + (root / "assets" / "logo.png").write_bytes(_png_bytes()) + (root / "assets" / "photo.jpg").write_bytes(_jpeg_bytes()) + report = json.loads(_IMAGE_REPORT.read_text(encoding="utf-8")) + if pattern != "keep": + for issue in report["issues"]: + issue["pattern"] = pattern + mock_tools.skillspector.is_available = True + mock_tools.skillspector.run.return_value = ToolResult( + success=True, stdout=json.dumps(report), stderr="", exit_code=0 + ) + return SecurityValidator(use_llm=False).validate_security_only(root) + + +def test_a_downgraded_passing_scan_does_not_show_the_counts(tmp_path: Path) -> None: + """A policy that lowers the AE1 findings of a complete scan passes it; no report lists the count line.""" + result = _scan_images(tmp_path / "raster-demo") + assert not result.passed + assert result.incomplete_scans == [] + + apply_policy([result], ValidationPolicy(severity_overrides={_AE1_OVERRIDE: Severity.LOW})) + + assert result.passed + for reporter, rendered in _rendered(result).items(): + assert "could not completely inspect" not in rendered, reporter + # A passing result lists its messages as passed checks in the full page. + assert "could not completely inspect" not in HTMLReporter(include_timestamp=False).render(result) + # JSON records the counts for every result, but not as a message. + exported = JSONReporter(include_timestamp=False).render(result) + assert json.loads(exported)["skillspector_reference_summary"] == { + "affected_artifacts": 2, + "reference_occurrences": 2, + "reference_occurrences_truncated": False, + } + assert "could not completely inspect" not in exported + + +@pytest.mark.parametrize(("override", "passes"), [(_AE1_OVERRIDE, True), ("SECURITY.Unknown (AE1)", False)]) +def test_overrides_match_the_rule_name_of_reports_before_v2_12(tmp_path: Path, override: str, passes: bool) -> None: + """Before v2.12.0 an AE1 has no pattern; a severity override uses the rule's name, not ``Unknown``.""" + result = _scan_images(tmp_path / "raster-demo", pattern=None) + assert {finding.check_name for finding in result.findings} == {"Incomplete referenced artifact analysis (AE1)"} + + apply_policy([result], ValidationPolicy(severity_overrides={override: Severity.LOW})) + + assert result.passed is passes + + def test_passing_results_do_not_show_the_counts() -> None: """Only a failed result gets the count line; JSON still records it.""" result = ValidationResult(validator_name="Security Scan") diff --git a/tests/validators/test_skillspector_reference_diagnostics.py b/tests/validators/test_skillspector_reference_diagnostics.py index f65d2f5e6..44754c3c8 100644 --- a/tests/validators/test_skillspector_reference_diagnostics.py +++ b/tests/validators/test_skillspector_reference_diagnostics.py @@ -30,7 +30,6 @@ from skillevaluator.skillspector_references import ( AE1_PATTERN, index_legacy_reference_reasons, - is_reference_summary_message, issue_diagnostics, report_path, ) @@ -73,6 +72,11 @@ def _ae1(result: ValidationResult) -> list: return [finding for finding in result.findings if finding.check_name.endswith("(AE1)")] +def _count_messages(result: ValidationResult) -> list[str]: + """Result messages with the count line, which reporters would list as passed checks.""" + return [message for message in result.messages if "could not completely inspect" in message] + + def _process(report: dict, source_root: Path | None = None) -> ValidationResult: result = ValidationResult(validator_name="Security Scan") SecurityValidator(use_llm=False)._process_skillspector_cli_result(report, result, source_root=source_root) @@ -151,10 +155,8 @@ def test_legacy_report_is_named_and_explained_from_the_ledger(self) -> None: "reference_occurrences": 2, "reference_occurrences_truncated": False, } - assert [message for message in result.messages if is_reference_summary_message(message)] == [ - "skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); " - "each AE1 finding names the artifact and why its analysis stopped" - ] + # Reporters show the count from the metadata, and only for a failed result. + assert _count_messages(result) == [] def test_structured_evidence_names_every_reason_and_keeps_the_scanner_remedy(self) -> None: report = _report(_HOST_LANGUAGE_REPORT) @@ -215,7 +217,7 @@ def test_scan_stays_incomplete_and_failed(self, mock_tools, tmp_path: Path) -> N @patch("skillevaluator.validators.security.Tools") def test_llm_stage_counts_each_reference_once(self, mock_tools, tmp_path: Path) -> None: - """Both stages report the AE1 findings of an accepted image gap; the count and message appear once.""" + """Both stages report the AE1 findings of an accepted image gap; each reference line counts once.""" root = tmp_path / "raster-demo" (root / "assets").mkdir(parents=True) (root / "SKILL.md").write_text("See `assets/logo.png` and `assets/photo.jpg`.\n", encoding="utf-8") @@ -246,7 +248,7 @@ def test_llm_stage_counts_each_reference_once(self, mock_tools, tmp_path: Path) "reference_occurrences": 2, "reference_occurrences_truncated": False, } - assert sum(is_reference_summary_message(message) for message in result.messages) == 1 + assert _count_messages(result) == [] class TestRuleName: @@ -617,7 +619,7 @@ def test_the_scanner_remedy_is_kept(self) -> None: class TestSummaryRecord: - def test_a_later_record_replaces_the_count_and_message(self) -> None: + def test_a_later_record_replaces_the_count(self) -> None: result = _process(_report(_HOST_LANGUAGE_REPORT)) result.findings = [ finding @@ -627,17 +629,17 @@ def test_a_later_record_replaces_the_count_and_message(self) -> None: _record_skillspector_reference_summary(result) - assert result.metadata["skillspector_reference_summary"]["affected_artifacts"] == 1 - assert [message for message in result.messages if is_reference_summary_message(message)] == [ - "skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); " - "each AE1 finding names the artifact and why its analysis stopped" - ] + assert result.metadata["skillspector_reference_summary"] == { + "affected_artifacts": 1, + "reference_occurrences": 2, + "reference_occurrences_truncated": False, + } result.findings = [] _record_skillspector_reference_summary(result) assert "skillspector_reference_summary" not in result.metadata - assert not any(is_reference_summary_message(message) for message in result.messages) + assert _count_messages(result) == [] def test_reports_without_ae1_evidence_have_no_summary(self) -> None: report = _report() @@ -648,4 +650,4 @@ def test_reports_without_ae1_evidence_have_no_summary(self) -> None: assert len(_ae1(result)) == 2 assert "skillspector_reference_summary" not in result.metadata - assert not any(is_reference_summary_message(message) for message in result.messages) + assert _count_messages(result) == [] From 2ca02a808fa9f7f93e6cf31c0eb15bcd5b01f76b Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 13:19:07 -0800 Subject: [PATCH 06/15] perf(tier1): normalize each AE1 path and text once per SkillSpector report Every reference line and reason of every AE1 finding went through redaction, and every absolute path resolved the scan root again. A report with thousands of AE1 findings that repeat the same lines took seconds instead of a fraction of one. ReportNormalizer keeps, for one report, the redacted form of each distinct text and the in-scan form of each distinct path, and resolves the scan root at most once. _process_skillspector_cli_result builds one and passes it to the ledger index and to every issue it converts. report_path keeps its behavior for a single path. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- src/skillevaluator/skillspector_references.py | 113 ++++++++++++------ src/skillevaluator/validators/security.py | 21 ++-- ...test_skillspector_reference_diagnostics.py | 49 ++++++++ 3 files changed, 142 insertions(+), 41 deletions(-) diff --git a/src/skillevaluator/skillspector_references.py b/src/skillevaluator/skillspector_references.py index a2fba3454..70fb2ebbe 100644 --- a/src/skillevaluator/skillspector_references.py +++ b/src/skillevaluator/skillspector_references.py @@ -35,6 +35,7 @@ "AE1_PATTERN", "AE1_RULE_ID", "REFERENCE_SUMMARY_KEY", + "ReportNormalizer", "combine_reference_summaries", "diagnostic_text", "index_legacy_reference_reasons", @@ -96,38 +97,76 @@ def _root_prefixes(scan_root: Path | None) -> list[PurePosixPath]: return prefixes +class ReportNormalizer: + """:func:`diagnostic_text` and :func:`report_path` for one report, each distinct value computed once. + + A report repeats the same paths and reason texts across its AE1 findings + and their reference lines. One normalizer per report redacts each distinct + text once and resolves the scan root at most once, however many findings + repeat them. Its caches hold only the values of that report. + """ + + def __init__(self, scan_root: Path | None = None) -> None: + self._scan_root = scan_root + self._prefixes: list[PurePosixPath] | None = None + self._texts: dict[tuple[str, int], str | None] = {} + self._paths: dict[str, str | None] = {} + + def text(self, value: object, *, max_length: int = 4096) -> str | None: + """:func:`diagnostic_text` of *value*, computed once per distinct text.""" + if not isinstance(value, str): + return None + key = (value, max_length) + if key not in self._texts: + self._texts[key] = diagnostic_text(value, max_length=max_length) + return self._texts[key] + + def path(self, value: object) -> str | None: + """:func:`report_path` of *value* under this report's scan root, computed once per distinct path.""" + if not isinstance(value, str): + return None + if value not in self._paths: + self._paths[value] = self._contained_path(self.text(value)) + return self._paths[value] + + def _contained_path(self, text: str | None) -> str | None: + if text is None: + return None + slash_path = text.replace("\\", "/") + if PurePosixPath(slash_path).is_absolute() or PureWindowsPath(slash_path).drive: + if self._prefixes is None: + self._prefixes = _root_prefixes(self._scan_root) + for prefix in self._prefixes: + try: + slash_path = PurePosixPath(slash_path).relative_to(prefix).as_posix() + break + except ValueError: + continue + else: + return None + normalized = posixpath.normpath(slash_path) + if normalized in {".", ".."} or normalized.startswith(("../", "/")): + return None + return normalized + + def report_path(value: object, *, scan_root: Path | None = None) -> str | None: """A SkillSpector report path as POSIX text relative to the scan, else ``None``. The path is checked lexically and never resolved, because the file an AE1 finding names may be missing or unreadable. An absolute path counts only under *scan_root*. A path with control characters, a Windows drive, or a - ``..`` that leaves the scan, and the scan root itself, are ``None``. + ``..`` that leaves the scan, and the scan root itself, are ``None``. To + normalize the paths of a whole report, use one :class:`ReportNormalizer`. """ - text = diagnostic_text(value) - if text is None: - return None - slash_path = text.replace("\\", "/") - if PurePosixPath(slash_path).is_absolute() or PureWindowsPath(slash_path).drive: - for prefix in _root_prefixes(scan_root): - try: - slash_path = PurePosixPath(slash_path).relative_to(prefix).as_posix() - break - except ValueError: - continue - else: - return None - normalized = posixpath.normpath(slash_path) - if normalized in {".", ".."} or normalized.startswith(("../", "/")): - return None - return normalized + return ReportNormalizer(scan_root).path(value) def _line(value: object) -> int | None: return value if type(value) is int and 0 < value <= _MAX_COUNT else None -def _reasons(rows: object) -> list[dict]: +def _reasons(rows: object, text: Callable[..., str | None]) -> list[dict]: """The first reasons of *rows* with only known, valid fields, without repeats.""" if not isinstance(rows, list): return [] @@ -135,18 +174,16 @@ def _reasons(rows: object) -> list[dict]: for row in rows[:_MAX_REASONS]: if not isinstance(row, dict): continue - reason_code = diagnostic_text(row.get("reason_code"), max_length=128) + reason_code = text(row.get("reason_code"), max_length=128) if not reason_code: continue reason: dict[str, Any] = {"reason_code": reason_code} for field, max_length in (("phase", 128), ("message", 4096)): - if value := diagnostic_text(row.get(field), max_length=max_length): + if value := text(row.get(field), max_length=max_length): reason[field] = value analyzers = row.get("analyzers") if isinstance(analyzers, list): - reason["analyzers"] = [ - text for item in analyzers[:_MAX_ANALYZERS] if (text := diagnostic_text(item, max_length=256)) - ] + reason["analyzers"] = [name for item in analyzers[:_MAX_ANALYZERS] if (name := text(item, max_length=256))] for field in ("start_line", "end_line"): if (line := _line(row.get(field))) is not None: reason[field] = line @@ -168,7 +205,9 @@ def _reasons(rows: object) -> list[dict]: return reasons -def _reference_target(issue: Mapping[str, object], normalize_path: Callable[[object], str | None]): +def _reference_target( + issue: Mapping[str, object], normalize_path: Callable[[object], str | None], text: Callable[..., str | None] +): """``(target, disposition, structured)`` of an AE1 issue, else ``None``. *structured* says whether the target came from ``evidence`` (v2.12.0 and @@ -177,11 +216,11 @@ def _reference_target(issue: Mapping[str, object], normalize_path: Callable[[obj """ evidence = issue.get("evidence") evidence = evidence if isinstance(evidence, dict) else {} - target = diagnostic_text(evidence.get("target_path")) + target = text(evidence.get("target_path")) structured = target is not None disposition = evidence.get("target_disposition") if not structured: - match = _LEGACY_FINDING_RE.fullmatch(diagnostic_text(issue.get("finding")) or "") + match = _LEGACY_FINDING_RE.fullmatch(text(issue.get("finding")) or "") location = issue.get("location") source = location.get("file") if isinstance(location, dict) else None if match and normalize_path(source) is not None: @@ -197,12 +236,14 @@ def index_legacy_reference_reasons( *, normalize_path: Callable[[object], str | None], completeness: object = None, + text: Callable[..., str | None] = diagnostic_text, ) -> dict[str, list[dict]]: """The ledger rows of each AE1 target that has no structured reasons, read once. At most one row more than an AE1 finding keeps is indexed per target, so the extra row still shows that the reasons were cut short. Each path is - normalized once, however often it repeats. + normalized once, however often it repeats. *normalize_path* and *text* + are usually the methods of the report's :class:`ReportNormalizer`. """ if not isinstance(completeness, dict) or not isinstance(completeness.get("ledger_exceptions"), list): return {} @@ -219,7 +260,7 @@ def normalize_once(path: object) -> str | None: for issue in issues: if not isinstance(issue, dict) or issue.get("id") != AE1_RULE_ID: continue - target_info = _reference_target(issue, normalize_once) + target_info = _reference_target(issue, normalize_once, text) if target_info is None: continue target, _disposition, structured = target_info @@ -244,6 +285,7 @@ def issue_diagnostics( normalize_path: Callable[[object], str | None], completeness: object = None, legacy_reason_index: Mapping[str, list[dict]] | None = None, + text: Callable[..., str | None] = diagnostic_text, ) -> dict: """Finding metadata that explains an AE1 *issue*: the target, its reasons and the reference lines. @@ -253,10 +295,11 @@ def issue_diagnostics( target's ledger rows in *completeness* (or *legacy_reason_index*), and the finding gets no evidence without them. ``skillspector_occurrences`` lists up to 128 of the issue's ``occurrences``. Any other issue gets ``{}``. + Paths go through *normalize_path* and other text through *text*. """ if issue.get("id") != AE1_RULE_ID: return {} - target_info = _reference_target(issue, normalize_path) + target_info = _reference_target(issue, normalize_path, text) if target_info is None: return {} target, disposition, structured = target_info @@ -266,10 +309,10 @@ def issue_diagnostics( if not rows: if legacy_reason_index is None: legacy_reason_index = index_legacy_reference_reasons( - [issue], completeness=completeness, normalize_path=normalize_path + [issue], completeness=completeness, normalize_path=normalize_path, text=text ) rows = legacy_reason_index.get(target, []) - reasons = _reasons(rows) + reasons = _reasons(rows, text) # A target named only in the finding text needs matching ledger rows; an # unreadable evidence target must not pass for a structured one. if not reasons and not structured: @@ -318,7 +361,9 @@ def _reason_details(reasons: list[dict]) -> list[str]: return details -def reference_suggestion(evidence: Mapping[str, Any], remediation: object) -> str: +def reference_suggestion( + evidence: Mapping[str, Any], remediation: object, *, text: Callable[..., str | None] = diagnostic_text +) -> str: """The suggestion of an AE1 finding: what was not inspected, why, and what to do. SkillSpector's own remediation is kept unless it is missing or the generic @@ -328,7 +373,7 @@ def reference_suggestion(evidence: Mapping[str, Any], remediation: object) -> st """ reasons = evidence["reasons"] truncated = evidence.get("reasons_truncated") is True - action = diagnostic_text(remediation) + action = text(remediation) if not action or action == _LEGACY_REMEDIATION: codes = set() if truncated else {reason["reason_code"] for reason in reasons} if codes == {"static_parse_limit"}: diff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.py index d5bb357cd..8f17bf853 100644 --- a/src/skillevaluator/validators/security.py +++ b/src/skillevaluator/validators/security.py @@ -32,7 +32,6 @@ import zlib from collections import Counter from collections.abc import Callable, Iterable, Mapping -from functools import partial from pathlib import Path, PurePosixPath from urllib.parse import unquote @@ -60,12 +59,12 @@ AE1_PATTERN, AE1_RULE_ID, REFERENCE_SUMMARY_KEY, + ReportNormalizer, combine_reference_summaries, index_legacy_reference_reasons, issue_diagnostics, reference_suggestion, reference_summary, - report_path, ) from skillevaluator.spdx import is_spdx_only_html_comment from skillevaluator.utils.path_security import matches_filesystem_name @@ -4430,10 +4429,13 @@ def _process_skillspector_cli_result( skipped_by_role: Counter[str] = Counter() has_critical_or_high = False completeness = data.get("analysis_completeness") + # One normalizer per report: each distinct path and text is redacted once. + normalizer = ReportNormalizer(source_root) legacy_reason_index = index_legacy_reference_reasons( candidate_issues, - normalize_path=partial(report_path, scan_root=source_root), + normalize_path=normalizer.path, completeness=completeness, + text=normalizer.text, ) for issue, scope in zip(candidate_issues, scopes, strict=True): if scope is not None and not scope.applicable: @@ -4445,8 +4447,8 @@ def _process_skillspector_cli_result( finding, is_error = self._convert_skillspector_issue( issue, completeness=completeness, - scan_root=source_root, legacy_reason_index=legacy_reason_index, + normalizer=normalizer, ) if scope is not None: finding.metadata.update( @@ -4949,6 +4951,7 @@ def _convert_skillspector_issue( completeness: object = None, scan_root: Path | None = None, legacy_reason_index: Mapping[str, list[dict]] | None = None, + normalizer: ReportNormalizer | None = None, ) -> tuple[Finding, bool]: """Convert a single skillspector issue dict into a Finding. @@ -4960,7 +4963,9 @@ def _convert_skillspector_issue( completely inspect and why, its metadata and suggestion carry that (:func:`~skillevaluator.skillspector_references.issue_diagnostics`), with the reasons of earlier releases read from *completeness* or - *legacy_reason_index*. Paths count only inside *scan_root*. + *legacy_reason_index*. Paths count only inside *scan_root*. A + *normalizer* shared by a report's issues replaces *scan_root*, so each + distinct path and text is redacted once per report. """ g = _issue_field(issue) issue_sev = str(g("severity", "UNKNOWN")).upper() @@ -4975,16 +4980,18 @@ def _convert_skillspector_issue( else: pattern = g("pattern", "Unknown") metadata = SecurityValidator._build_issue_metadata(issue) + normalizer = normalizer or ReportNormalizer(scan_root) metadata.update( issue_diagnostics( issue, - normalize_path=partial(report_path, scan_root=scan_root), + normalize_path=normalizer.path, completeness=completeness, legacy_reason_index=legacy_reason_index, + text=normalizer.text, ) ) if evidence := metadata.get("skillspector_evidence"): - suggestion = reference_suggestion(evidence, remediation) + suggestion = reference_suggestion(evidence, remediation, text=normalizer.text) finding = Finding( category="SECURITY", diff --git a/tests/validators/test_skillspector_reference_diagnostics.py b/tests/validators/test_skillspector_reference_diagnostics.py index 44754c3c8..76db1de81 100644 --- a/tests/validators/test_skillspector_reference_diagnostics.py +++ b/tests/validators/test_skillspector_reference_diagnostics.py @@ -20,13 +20,16 @@ cannot parse within its span limit. """ +import copy import json +from collections import Counter from pathlib import Path from unittest.mock import patch import pytest from tests.validators.test_security import _jpeg_bytes, _png_bytes +from skillevaluator import skillspector_references from skillevaluator.skillspector_references import ( AE1_PATTERN, index_legacy_reference_reasons, @@ -565,6 +568,52 @@ def normalize(path: object) -> str | None: assert calls <= 4 * len(issues) + 3 +class TestLargeReports: + def test_each_distinct_path_and_text_is_normalized_once_per_report( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Findings that repeat the same absolute reference lines and reasons redact each text once.""" + root = _parse_limit_skill(tmp_path / "skill") + report = _report(_PARSE_LIMIT_REPORT) + template = report["issues"][0] + template["occurrences"] = [ + {"file": f"{root.as_posix()}/SKILL.md", "start_line": line} for line in range(1, 129) + ] + reason = template["evidence"]["reasons"][0] + template["evidence"]["reasons"] = [{**reason, "start_line": line} for line in range(1, 17)] + report["issues"] = [] + for index in range(50): + issue = copy.deepcopy(template) + issue["evidence"]["target_path"] = f"scripts/helper{index}.pl" + report["issues"].append(issue) + redacted: list[str] = [] + prefix_lookups = 0 + redact, root_prefixes = skillspector_references.redact_sensitive_text, skillspector_references._root_prefixes + + def counting_redact(value: str) -> str: + redacted.append(value) + return redact(value) + + def counting_root_prefixes(scan_root: Path | None) -> list: + nonlocal prefix_lookups + prefix_lookups += 1 + return root_prefixes(scan_root) + + monkeypatch.setattr(skillspector_references, "redact_sensitive_text", counting_redact) + monkeypatch.setattr(skillspector_references, "_root_prefixes", counting_root_prefixes) + + result = _process(report, source_root=root) + + findings = _ae1(result) + assert len(findings) == 50 + for finding in findings: + assert len(finding.metadata["skillspector_occurrences"]) == 128 + assert len(finding.metadata["skillspector_evidence"]["reasons"]) == 16 + assert result.metadata["skillspector_reference_summary"]["affected_artifacts"] == 50 + assert [text for text, count in Counter(redacted).items() if count > 1] == [] + assert prefix_lookups == 1 + + class TestTruncatedReasons: @pytest.mark.parametrize("structured", [False, True]) @pytest.mark.parametrize( From 3047a47b58427844e517567f77084d29e8d6f91e Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 13:19:41 -0800 Subject: [PATCH 07/15] fix(reporting): prefix AE1 reference lines with their skill in folder results merge_with_prefix put the skill's [name] prefix on each finding's path and on the PII scan's metadata occurrences, but not on the skillspector_occurrences of an AE1 finding. In a folder report a JSON reader could not tell which skill a listed reference line was in without the finding's own path. Prefix those lines the same way; the referenced file's target_path stays relative to the named skill. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- docs/tier1-validation.mdx | 2 +- src/skillevaluator/models/result.py | 13 +++++++---- .../test_skillspector_reference_summary.py | 23 +++++++++++++++++++ 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx index 1a3f04e88..4c951adfc 100644 --- a/docs/tier1-validation.mdx +++ b/docs/tier1-validation.mdx @@ -208,7 +208,7 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice - v2.13.4 reports `observed_records` and `limit_records` on the row. SkillEvaluator accepts the row only when `observed_records` equals the BH1 `declaration_count` and does not exceed `limit_records`. A manifest with more records than SkillSpector reads, or with a hook handler it counted but could not parse, therefore stays `INCOMPLETE`. So does a settings file with permission rules, `env` or other settings beside its hooks, because SkillSpector counts those records too. A part it does not count, such as a hook group that is not an object, is not visible and gets the Critical. - v2.13.3, the release SkillEvaluator installs, does not report them. SkillEvaluator then refuses only a BH1 that counts 2,048 or more declarations, because SkillSpector may have cut that manifest short. A manifest that SkillSpector parsed only in part, such as one with a malformed handler beside a valid one, gets the same Critical as a manifest it read in full, and still fails. - **Incomplete referenced artifacts.** SkillSpector reports a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names a file it did not completely inspect. Releases before v2.12.0 leave the finding's name empty, so SkillEvaluator names it by its rule instead of `Unknown (AE1)`. The finding's suggestion names the file, its disposition (`partial`, `failed`, `out_of_scope` or `uninspected`) and each reason SkillSpector gives: the reason code, such as `static_parse_limit` or `read_error`, the analyzers, the line in the file, the message and any limits, such as `limit_characters=8000`. Reasons that differ only in the analyzer are listed once. SkillSpector's own remedy is kept. Releases before v2.12.0 give no reasons in the finding and a generic remedy that says to make the file available: SkillEvaluator then reads the reasons from the report's `analysis_completeness` rows for that file and gives a remedy for a parse limit, a read error, or any other reason. Without such a row the finding keeps SkillSpector's text. The finding's metadata records the file, its disposition and up to 16 reasons under `skillspector_evidence`, with `reasons_truncated` when SkillSpector gave more, and up to 128 reference lines under `skillspector_occurrences`. Text with control characters is left out, credential-shaped text is masked, and a path outside the scanned target is dropped. + **Incomplete referenced artifacts.** SkillSpector reports a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names a file it did not completely inspect. Releases before v2.12.0 leave the finding's name empty, so SkillEvaluator names it by its rule instead of `Unknown (AE1)`. The finding's suggestion names the file, its disposition (`partial`, `failed`, `out_of_scope` or `uninspected`) and each reason SkillSpector gives: the reason code, such as `static_parse_limit` or `read_error`, the analyzers, the line in the file, the message and any limits, such as `limit_characters=8000`. Reasons that differ only in the analyzer are listed once. SkillSpector's own remedy is kept. Releases before v2.12.0 give no reasons in the finding and a generic remedy that says to make the file available: SkillEvaluator then reads the reasons from the report's `analysis_completeness` rows for that file and gives a remedy for a parse limit, a read error, or any other reason. Without such a row the finding keeps SkillSpector's text. The finding's metadata records the file, its disposition and up to 16 reasons under `skillspector_evidence`, with `reasons_truncated` when SkillSpector gave more, and up to 128 reference lines under `skillspector_occurrences`. In a folder of skills each reference line's `file` starts with the skill's `[name]` prefix, like the finding's own path, and `target_path` stays relative to that skill. Text with control characters is left out, credential-shaped text is masked, and a path outside the scanned target is dropped. When the check fails, the terminal output, the `references` row of the terminal summary, and the Markdown and HTML reports add one line, such as `skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); each AE1 finding names the artifact and why its analysis stopped`. The JSON report records the counts in `skillspector_reference_summary`: `affected_artifacts`, `reference_occurrences`, and `reference_occurrences_truncated`, which is `true` when SkillSpector listed more than 128 lines for one finding, so the count is a lower bound. For a folder of skills the counts are totals. None of this changes the finding's severity, whether the scan is complete, or any gate. diff --git a/src/skillevaluator/models/result.py b/src/skillevaluator/models/result.py index c2fb481b0..d9e3aea03 100644 --- a/src/skillevaluator/models/result.py +++ b/src/skillevaluator/models/result.py @@ -651,14 +651,17 @@ def merge_with_prefix(self, other: ValidationResult, prefix: str) -> None: # Prefix findings with skill name in file_path for finding in other.findings: metadata = finding.metadata - listed = metadata.get("occurrences") if isinstance(metadata, dict) else None - if isinstance(listed, list): + for key in ("occurrences", "skillspector_occurrences"): + listed = metadata.get(key) if isinstance(metadata, dict) else None + if not isinstance(listed, list): + continue # A check that folds repeats (the PII scan) lists each location - # in metadata; prefix those like file_path so the finding's own - # location still matches its first listed one. + # in metadata, and a SkillSpector AE1 finding lists the lines + # that name its file; prefix those like file_path so the + # finding's own location still matches its first listed one. metadata = { **metadata, - "occurrences": [ + key: [ {**item, "file": f"[{prefix}] {item['file']}"} if isinstance(item, dict) and isinstance(item.get("file"), str) else item diff --git a/tests/reporting/test_skillspector_reference_summary.py b/tests/reporting/test_skillspector_reference_summary.py index 0906d05e2..471b90a9b 100644 --- a/tests/reporting/test_skillspector_reference_summary.py +++ b/tests/reporting/test_skillspector_reference_summary.py @@ -115,6 +115,29 @@ def test_failed_reports_show_the_counts(tmp_path: Path, monkeypatch: pytest.Monk assert combined["results"][0]["skillspector_reference_summary"] == expected +def test_folder_reference_lines_name_their_skill(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """In a folder, each exported reference line carries its skill's prefix, like the finding's own path.""" + result = _validate(tmp_path, monkeypatch, skills=("alpha", "beta")) + + exported = json.loads(JSONReporter(include_timestamp=False).render(result)) + located = sorted( + (finding["file_path"], finding["line_number"], finding["metadata"]["skillspector_occurrences"]) + for finding in exported["findings"] + if finding["check_name"].endswith("(AE1)") + ) + assert located == [ + (f"[{skill}] SKILL.md", line, [{"file": f"[{skill}] SKILL.md", "start_line": line}]) + for skill in ("alpha", "beta") + for line in (6, 8) + ] + # The referenced file stays relative to the skill that the prefix names. + assert { + finding["metadata"]["skillspector_evidence"]["target_path"] + for finding in exported["findings"] + if finding["check_name"].endswith("(AE1)") + } == {"scripts/helper.pl"} + + def test_a_cut_occurrence_list_is_a_lower_bound(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: result = _validate(tmp_path, monkeypatch, skills=("alpha", "beta"), lines=129) From d55fb560e270f83ad9cc445753e67ed79751cf61 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 13:20:15 -0800 Subject: [PATCH 08/15] fix(reporting): say the AE1 count line names any reasons SkillSpector gave The count line ended "each AE1 finding names the artifact and why its analysis stopped", but a finding counts whenever SkillSpector names its file, even with an empty reason list and no ledger row for the file. Say instead that each finding names the artifact and any reasons SkillSpector gave. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- docs/tier1-validation.mdx | 2 +- src/skillevaluator/skillspector_references.py | 11 +++++--- .../test_skillspector_reference_summary.py | 2 +- ...test_skillspector_reference_diagnostics.py | 27 +++++++++++++++++++ 4 files changed, 36 insertions(+), 6 deletions(-) diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx index 4c951adfc..1145a257b 100644 --- a/docs/tier1-validation.mdx +++ b/docs/tier1-validation.mdx @@ -210,7 +210,7 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice **Incomplete referenced artifacts.** SkillSpector reports a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names a file it did not completely inspect. Releases before v2.12.0 leave the finding's name empty, so SkillEvaluator names it by its rule instead of `Unknown (AE1)`. The finding's suggestion names the file, its disposition (`partial`, `failed`, `out_of_scope` or `uninspected`) and each reason SkillSpector gives: the reason code, such as `static_parse_limit` or `read_error`, the analyzers, the line in the file, the message and any limits, such as `limit_characters=8000`. Reasons that differ only in the analyzer are listed once. SkillSpector's own remedy is kept. Releases before v2.12.0 give no reasons in the finding and a generic remedy that says to make the file available: SkillEvaluator then reads the reasons from the report's `analysis_completeness` rows for that file and gives a remedy for a parse limit, a read error, or any other reason. Without such a row the finding keeps SkillSpector's text. The finding's metadata records the file, its disposition and up to 16 reasons under `skillspector_evidence`, with `reasons_truncated` when SkillSpector gave more, and up to 128 reference lines under `skillspector_occurrences`. In a folder of skills each reference line's `file` starts with the skill's `[name]` prefix, like the finding's own path, and `target_path` stays relative to that skill. Text with control characters is left out, credential-shaped text is masked, and a path outside the scanned target is dropped. - When the check fails, the terminal output, the `references` row of the terminal summary, and the Markdown and HTML reports add one line, such as `skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); each AE1 finding names the artifact and why its analysis stopped`. The JSON report records the counts in `skillspector_reference_summary`: `affected_artifacts`, `reference_occurrences`, and `reference_occurrences_truncated`, which is `true` when SkillSpector listed more than 128 lines for one finding, so the count is a lower bound. For a folder of skills the counts are totals. None of this changes the finding's severity, whether the scan is complete, or any gate. + When the check fails, the terminal output, the `references` row of the terminal summary, and the Markdown and HTML reports add one line, such as `skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); each AE1 finding names the artifact and any reasons SkillSpector gave`. The JSON report records the counts in `skillspector_reference_summary`: `affected_artifacts`, `reference_occurrences`, and `reference_occurrences_truncated`, which is `true` when SkillSpector listed more than 128 lines for one finding, so the count is a lower bound. For a folder of skills the counts are totals. None of this changes the finding's severity, whether the scan is complete, or any gate. **Agent control paths.** SkillSpector rules describe attacks on an agent, so a match is an agent threat only in a file the agent reads or runs. When `validate` or `tier1` detects a skill, rules, workflows, or plugin artifact, the `security` check keeps findings on agent control paths and suppresses the rest: diff --git a/src/skillevaluator/skillspector_references.py b/src/skillevaluator/skillspector_references.py index 70fb2ebbe..1537bcbd3 100644 --- a/src/skillevaluator/skillspector_references.py +++ b/src/skillevaluator/skillspector_references.py @@ -50,7 +50,6 @@ AE1_RULE_ID = "AE1" AE1_PATTERN = "Incomplete referenced artifact analysis" REFERENCE_SUMMARY_KEY = "skillspector_reference_summary" -_SUMMARY_MESSAGE_PREFIX = "skillspector could not completely inspect " # The generic remediation of SkillSpector releases before v2.12.0. It suggests # that the file is absent, which is wrong for a file the scan read in part. _LEGACY_REMEDIATION = "Make the referenced artifact locally available and fully analyzable, or remove the reference." @@ -461,13 +460,17 @@ def combine_reference_summaries(summaries: Iterable[object]) -> dict | None: def reference_summary_message(summary: object) -> str | None: - """The one-line text of a valid *summary*, the same in every report, else ``None``.""" + """The one-line text of a valid *summary*, the same in every report, else ``None``. + + It says only that each finding names its file and any reasons, because a + finding counts even when SkillSpector gave no reason for its file. + """ record = reference_summary_record(summary) if record is None: return None occurrences = record["reference_occurrences"] count = f"at least {occurrences}" if record["reference_occurrences_truncated"] else str(occurrences) return ( - f"{_SUMMARY_MESSAGE_PREFIX}{record['affected_artifacts']} referenced artifact(s) across {count} " - "reference occurrence(s); each AE1 finding names the artifact and why its analysis stopped" + f"skillspector could not completely inspect {record['affected_artifacts']} referenced artifact(s) across " + f"{count} reference occurrence(s); each AE1 finding names the artifact and any reasons SkillSpector gave" ) diff --git a/tests/reporting/test_skillspector_reference_summary.py b/tests/reporting/test_skillspector_reference_summary.py index 471b90a9b..a2eafc802 100644 --- a/tests/reporting/test_skillspector_reference_summary.py +++ b/tests/reporting/test_skillspector_reference_summary.py @@ -90,7 +90,7 @@ def _rendered(result: ValidationResult) -> dict[str, str]: def _phrase(artifacts: int, occurrences: str) -> str: return ( f"skillspector could not completely inspect {artifacts} referenced artifact(s) across {occurrences} " - "reference occurrence(s); each AE1 finding names the artifact and why its analysis stopped" + "reference occurrence(s); each AE1 finding names the artifact and any reasons SkillSpector gave" ) diff --git a/tests/validators/test_skillspector_reference_diagnostics.py b/tests/validators/test_skillspector_reference_diagnostics.py index 76db1de81..1fd48d20c 100644 --- a/tests/validators/test_skillspector_reference_diagnostics.py +++ b/tests/validators/test_skillspector_reference_diagnostics.py @@ -34,6 +34,7 @@ AE1_PATTERN, index_legacy_reference_reasons, issue_diagnostics, + reference_summary_message, report_path, ) from skillevaluator.utils.tool_runner import ToolResult @@ -690,6 +691,32 @@ def test_a_later_record_replaces_the_count(self) -> None: assert "skillspector_reference_summary" not in result.metadata assert _count_messages(result) == [] + def test_a_finding_without_reasons_counts_without_claiming_one(self) -> None: + """A named file with no reasons and no ledger rows is counted; the line claims no reason for it.""" + report = _report(_PARSE_LIMIT_REPORT) + for issue in report["issues"]: + if issue["id"] == "AE1": + issue["evidence"] = { + "target_path": "scripts/helper.pl", + "target_disposition": "uninspected", + "reasons": [], + } + report["analysis_completeness"]["ledger_exceptions"] = [] + + result = _process(report) + + findings = _ae1(result) + assert len(findings) == 2 + for finding in findings: + assert finding.metadata["skillspector_evidence"]["reasons"] == [] + assert finding.suggestion.startswith( + "Referenced artifact scripts/helper.pl was not completely inspected (uninspected). Review " + ) + assert reference_summary_message(result.metadata["skillspector_reference_summary"]) == ( + "skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); " + "each AE1 finding names the artifact and any reasons SkillSpector gave" + ) + def test_reports_without_ae1_evidence_have_no_summary(self) -> None: report = _report() for issue in report["issues"]: From 6edfa901b2890f097f70221d6cba51a811f766f5 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 13:20:46 -0800 Subject: [PATCH 09/15] refactor(reporting): import the AE1 count formatter where cli and markdown use it The module-level imports in reporting/cli.py and reporting/markdown.py sat in the same import slot that several open pull requests also add to, so each of those merges would conflict on one line. Import reference_summary_message inside the method that uses it, as html.py already does. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- src/skillevaluator/reporting/cli.py | 3 ++- src/skillevaluator/reporting/markdown.py | 17 +++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/skillevaluator/reporting/cli.py b/src/skillevaluator/reporting/cli.py index 2ba1f4cbd..e7dc1967c 100644 --- a/src/skillevaluator/reporting/cli.py +++ b/src/skillevaluator/reporting/cli.py @@ -53,7 +53,6 @@ from skillevaluator.reporting.presentation import FinalRenderContext, build_final_render_context, trial_coverage from skillevaluator.reporting.run_status import Status, result_status from skillevaluator.reporting.terminal_styles import AMBER, FAINT, GREEN, RED, TEXT, grade_style, lift_style -from skillevaluator.skillspector_references import reference_summary_message from skillevaluator.utils.rich_markup import escape_markup if TYPE_CHECKING: @@ -273,6 +272,8 @@ def render_result(self, result: ValidationResult, console: Console) -> None: @staticmethod def _print_reference_summary(result: ValidationResult, console: Console) -> None: """Print how many referenced artifacts SkillSpector did not completely inspect in a failed result.""" + from skillevaluator.skillspector_references import reference_summary_message + summary = reference_summary_message(result.metadata.get("skillspector_reference_summary")) if summary and not result.passed: console.print(f" {escape_markup(summary)}", soft_wrap=True, highlight=False) diff --git a/src/skillevaluator/reporting/markdown.py b/src/skillevaluator/reporting/markdown.py index e397a8232..acd68e183 100644 --- a/src/skillevaluator/reporting/markdown.py +++ b/src/skillevaluator/reporting/markdown.py @@ -42,7 +42,6 @@ safe_url, ) from skillevaluator.reporting.run_status import Status, resolve_run_status, result_status -from skillevaluator.skillspector_references import reference_summary_message if TYPE_CHECKING: from skillevaluator.models import Finding, ValidationResult @@ -522,11 +521,7 @@ def _render_result(self, result: ValidationResult, lines: list[str]) -> None: lines.append(f"| {dname.title()} | {ddata.get('score', 0):.1f} | {ddata.get('weight', 0) * 100:.0f}% |") lines.append("") - if not result.passed and ( - reference_summary := reference_summary_message(result.metadata.get("skillspector_reference_summary")) - ): - lines.append(f"- {reference_summary}") - lines.append("") + self._render_reference_summary(result, lines) if result.is_incomplete: self._render_incomplete(result, lines) @@ -611,6 +606,16 @@ def _render_findings(self, findings: list[Finding], lines: list[str]) -> None: lines.append("") lines.append("") + @staticmethod + def _render_reference_summary(result: ValidationResult, lines: list[str]) -> None: + """List how many referenced artifacts SkillSpector did not completely inspect in a failed result.""" + from skillevaluator.skillspector_references import reference_summary_message + + summary = reference_summary_message(result.metadata.get("skillspector_reference_summary")) + if summary and not result.passed: + lines.append(f"- {summary}") + lines.append("") + def _render_incomplete(self, result: ValidationResult, lines: list[str]) -> None: """Render missing scanner evidence without presenting a failure as a pass.""" lines.append(f"**Incomplete scanners:** {', '.join(result.incomplete_scans)}") From 3342e9d47a06d31d30fff37a9d4739d1d813663c Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 13:21:54 -0800 Subject: [PATCH 10/15] docs(tier1): note the AE1 check-name change for severity overrides With SkillSpector before v2.12.0 the AE1 check name changes from "Unknown (AE1)" to "Incomplete referenced artifact analysis (AE1)", so a severity_overrides entry keyed on the old name no longer matches and the SARIF rule ID changes. Say so in the CHANGELOG and the Tier 1 docs, and soften "gates are unchanged" to the one case where a gate can change. Also say that JSON records the counts for every result, while the other reports show them only for a failed one. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 +++++++++---- docs/tier1-validation.mdx | 4 ++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 54c3a6fe2..ced39ebe6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,10 +25,15 @@ All notable changes to SkillEvaluator are documented in this file. three rows. With SkillSpector before v2.12.0 the finding was titled `Unknown (AE1)` and told the user to make the file available although SkillSpector had read part of it. It now carries the rule's name and the - reasons from the report's ledger rows for the file. A failed check also counts - the files and the lines that name them in one line of the terminal, Markdown - and HTML reports, and in the JSON field `skillspector_reference_summary`. - Severities, scan completeness and gates are unchanged. + reasons from the report's ledger rows for the file. Its check name, and so its + SARIF rule ID, changes: a `severity_overrides` entry keyed on + `SECURITY.Unknown (AE1)` must now use + `SECURITY.Incomplete referenced artifact analysis (AE1)`. The JSON field + `skillspector_reference_summary` counts the files and the lines that name + them for every result, and a failed check shows the counts in one line of + the terminal, Markdown and HTML reports. Severities and scan completeness are + unchanged; a gate changes only where an override of `SECURITY.Unknown (AE1)` + was what let the check pass. ### Changed diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx index 1145a257b..b32b44e42 100644 --- a/docs/tier1-validation.mdx +++ b/docs/tier1-validation.mdx @@ -208,9 +208,9 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice - v2.13.4 reports `observed_records` and `limit_records` on the row. SkillEvaluator accepts the row only when `observed_records` equals the BH1 `declaration_count` and does not exceed `limit_records`. A manifest with more records than SkillSpector reads, or with a hook handler it counted but could not parse, therefore stays `INCOMPLETE`. So does a settings file with permission rules, `env` or other settings beside its hooks, because SkillSpector counts those records too. A part it does not count, such as a hook group that is not an object, is not visible and gets the Critical. - v2.13.3, the release SkillEvaluator installs, does not report them. SkillEvaluator then refuses only a BH1 that counts 2,048 or more declarations, because SkillSpector may have cut that manifest short. A manifest that SkillSpector parsed only in part, such as one with a malformed handler beside a valid one, gets the same Critical as a manifest it read in full, and still fails. - **Incomplete referenced artifacts.** SkillSpector reports a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names a file it did not completely inspect. Releases before v2.12.0 leave the finding's name empty, so SkillEvaluator names it by its rule instead of `Unknown (AE1)`. The finding's suggestion names the file, its disposition (`partial`, `failed`, `out_of_scope` or `uninspected`) and each reason SkillSpector gives: the reason code, such as `static_parse_limit` or `read_error`, the analyzers, the line in the file, the message and any limits, such as `limit_characters=8000`. Reasons that differ only in the analyzer are listed once. SkillSpector's own remedy is kept. Releases before v2.12.0 give no reasons in the finding and a generic remedy that says to make the file available: SkillEvaluator then reads the reasons from the report's `analysis_completeness` rows for that file and gives a remedy for a parse limit, a read error, or any other reason. Without such a row the finding keeps SkillSpector's text. The finding's metadata records the file, its disposition and up to 16 reasons under `skillspector_evidence`, with `reasons_truncated` when SkillSpector gave more, and up to 128 reference lines under `skillspector_occurrences`. In a folder of skills each reference line's `file` starts with the skill's `[name]` prefix, like the finding's own path, and `target_path` stays relative to that skill. Text with control characters is left out, credential-shaped text is masked, and a path outside the scanned target is dropped. + **Incomplete referenced artifacts.** SkillSpector reports a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names a file it did not completely inspect. Releases before v2.12.0 leave the finding's name empty, so SkillEvaluator names it by its rule instead of `Unknown (AE1)`. A `severity_overrides` entry for these findings uses `SECURITY.Incomplete referenced artifact analysis (AE1)`; one keyed on `SECURITY.Unknown (AE1)` no longer matches. The finding's suggestion names the file, its disposition (`partial`, `failed`, `out_of_scope` or `uninspected`) and each reason SkillSpector gives: the reason code, such as `static_parse_limit` or `read_error`, the analyzers, the line in the file, the message and any limits, such as `limit_characters=8000`. Reasons that differ only in the analyzer are listed once. SkillSpector's own remedy is kept. Releases before v2.12.0 give no reasons in the finding and a generic remedy that says to make the file available: SkillEvaluator then reads the reasons from the report's `analysis_completeness` rows for that file and gives a remedy for a parse limit, a read error, or any other reason. Without such a row the finding keeps SkillSpector's text. The finding's metadata records the file, its disposition and up to 16 reasons under `skillspector_evidence`, with `reasons_truncated` when SkillSpector gave more, and up to 128 reference lines under `skillspector_occurrences`. In a folder of skills each reference line's `file` starts with the skill's `[name]` prefix, like the finding's own path, and `target_path` stays relative to that skill. Text with control characters is left out, credential-shaped text is masked, and a path outside the scanned target is dropped. - When the check fails, the terminal output, the `references` row of the terminal summary, and the Markdown and HTML reports add one line, such as `skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); each AE1 finding names the artifact and any reasons SkillSpector gave`. The JSON report records the counts in `skillspector_reference_summary`: `affected_artifacts`, `reference_occurrences`, and `reference_occurrences_truncated`, which is `true` when SkillSpector listed more than 128 lines for one finding, so the count is a lower bound. For a folder of skills the counts are totals. None of this changes the finding's severity, whether the scan is complete, or any gate. + When the check fails, the terminal output, the `references` row of the terminal summary, and the Markdown and HTML reports add one line, such as `skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); each AE1 finding names the artifact and any reasons SkillSpector gave`. The JSON report records the counts for every result, passed or failed, in `skillspector_reference_summary`: `affected_artifacts`, `reference_occurrences`, and `reference_occurrences_truncated`, which is `true` when SkillSpector listed more than 128 lines for one finding, so the count is a lower bound. For a folder of skills the counts are totals. None of this changes the finding's severity or whether the scan is complete. A gate changes only where a policy lowered `SECURITY.Unknown (AE1)` and that was what let the check pass. **Agent control paths.** SkillSpector rules describe attacks on an agent, so a match is an agent threat only in a file the agent reads or runs. When `validate` or `tier1` detects a skill, rules, workflows, or plugin artifact, the `security` check keeps findings on agent control paths and suppresses the rest: From 1153394163b6aaffb62c2c730723c84a88458caa Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 13:27:31 -0800 Subject: [PATCH 11/15] refactor(reporting): register the AE1 count filter first in the HTML environment Two sibling port branches add a filter after skip_reason, where this branch also added one, so each merge conflicted on one line. Register skillspector_reference_summary before the other filters instead. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- src/skillevaluator/reporting/html.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.py index 8341591ed..a5ee44679 100644 --- a/src/skillevaluator/reporting/html.py +++ b/src/skillevaluator/reporting/html.py @@ -1724,6 +1724,7 @@ def _create_environment() -> Environment: loader = PackageLoader("skillevaluator.reporting", "templates") environment = Environment(loader=loader, autoescape=True) + environment.filters["skillspector_reference_summary"] = reference_summary_message environment.filters["cleanly_skipped"] = is_cleanly_skipped environment.filters["execution_status"] = _result_display_status environment.filters["related_paths"] = _related_paths @@ -1731,7 +1732,6 @@ def _create_environment() -> Environment: environment.filters["adaptive_percent"] = _adaptive_percent environment.filters["adaptive_interval_percent"] = _adaptive_interval_percent environment.filters["skip_reason"] = get_skip_reason - environment.filters["skillspector_reference_summary"] = reference_summary_message return environment @staticmethod From 98acca5076020268290214da172069fd08803ccf Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 13:55:05 -0800 Subject: [PATCH 12/15] fix(tier1): keep the measured run time out of AE1 suggestions A finding's suggestion is part of its finding_id, which the docs say stays the same across runs. The AE1 suggestion listed every limit of a reason, including observed_seconds, the wall-clock time SkillSpector records with a runtime_limit reason. Each run of a scan that hit the runtime budget gave the finding a new finding_id, and with --llm the two stages' copies of one reference line counted as two unique findings when the second stage was incomplete. The suggestion now leaves out observed_seconds; the finding's metadata still records it. Reasons that differ only in the run time are described once. The CHANGELOG notes that AE1 finding_id values change once because the suggestion text is new. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 18 ++++---- docs/tier1-validation.mdx | 2 +- src/skillevaluator/skillspector_references.py | 17 +++++-- .../test_skillspector_reference_summary.py | 30 +++++++++++++ ...test_skillspector_reference_diagnostics.py | 44 ++++++++++++++++++- 5 files changed, 98 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ced39ebe6..464418258 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,19 +19,21 @@ All notable changes to SkillEvaluator are documented in this file. SkillSpector gives, such as `static_parse_limit (static_patterns_tool_misuse)`, with any line and limits, and the finding's metadata records them under `skillspector_evidence` and - `skillspector_occurrences`. Before, the finding said only - `Referenced artifact was not completely inspected`, and its reason had to be - matched by hand against the incomplete-analysis error, which lists at most - three rows. With SkillSpector before v2.12.0 the finding was titled - `Unknown (AE1)` and told the user to make the file available although + `skillspector_occurrences`. The suggestion leaves out the measured run time, + so a finding keeps its `finding_id` from run to run; because the suggestion + text is new, each AE1 `finding_id` changes once with this release. Before, the + finding said only `Referenced artifact was not completely inspected`, and its + reason had to be matched by hand against the incomplete-analysis error, which + lists at most three rows. With SkillSpector before v2.12.0 the finding was + titled `Unknown (AE1)` and told the user to make the file available although SkillSpector had read part of it. It now carries the rule's name and the reasons from the report's ledger rows for the file. Its check name, and so its SARIF rule ID, changes: a `severity_overrides` entry keyed on `SECURITY.Unknown (AE1)` must now use `SECURITY.Incomplete referenced artifact analysis (AE1)`. The JSON field - `skillspector_reference_summary` counts the files and the lines that name - them for every result, and a failed check shows the counts in one line of - the terminal, Markdown and HTML reports. Severities and scan completeness are + `skillspector_reference_summary` counts the files and the lines that name them + for every result, and a failed check shows the counts in one line of the + terminal, Markdown and HTML reports. Severities and scan completeness are unchanged; a gate changes only where an override of `SECURITY.Unknown (AE1)` was what let the check pass. diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx index b32b44e42..1bd135041 100644 --- a/docs/tier1-validation.mdx +++ b/docs/tier1-validation.mdx @@ -208,7 +208,7 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice - v2.13.4 reports `observed_records` and `limit_records` on the row. SkillEvaluator accepts the row only when `observed_records` equals the BH1 `declaration_count` and does not exceed `limit_records`. A manifest with more records than SkillSpector reads, or with a hook handler it counted but could not parse, therefore stays `INCOMPLETE`. So does a settings file with permission rules, `env` or other settings beside its hooks, because SkillSpector counts those records too. A part it does not count, such as a hook group that is not an object, is not visible and gets the Critical. - v2.13.3, the release SkillEvaluator installs, does not report them. SkillEvaluator then refuses only a BH1 that counts 2,048 or more declarations, because SkillSpector may have cut that manifest short. A manifest that SkillSpector parsed only in part, such as one with a malformed handler beside a valid one, gets the same Critical as a manifest it read in full, and still fails. - **Incomplete referenced artifacts.** SkillSpector reports a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names a file it did not completely inspect. Releases before v2.12.0 leave the finding's name empty, so SkillEvaluator names it by its rule instead of `Unknown (AE1)`. A `severity_overrides` entry for these findings uses `SECURITY.Incomplete referenced artifact analysis (AE1)`; one keyed on `SECURITY.Unknown (AE1)` no longer matches. The finding's suggestion names the file, its disposition (`partial`, `failed`, `out_of_scope` or `uninspected`) and each reason SkillSpector gives: the reason code, such as `static_parse_limit` or `read_error`, the analyzers, the line in the file, the message and any limits, such as `limit_characters=8000`. Reasons that differ only in the analyzer are listed once. SkillSpector's own remedy is kept. Releases before v2.12.0 give no reasons in the finding and a generic remedy that says to make the file available: SkillEvaluator then reads the reasons from the report's `analysis_completeness` rows for that file and gives a remedy for a parse limit, a read error, or any other reason. Without such a row the finding keeps SkillSpector's text. The finding's metadata records the file, its disposition and up to 16 reasons under `skillspector_evidence`, with `reasons_truncated` when SkillSpector gave more, and up to 128 reference lines under `skillspector_occurrences`. In a folder of skills each reference line's `file` starts with the skill's `[name]` prefix, like the finding's own path, and `target_path` stays relative to that skill. Text with control characters is left out, credential-shaped text is masked, and a path outside the scanned target is dropped. + **Incomplete referenced artifacts.** SkillSpector reports a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names a file it did not completely inspect. Releases before v2.12.0 leave the finding's name empty, so SkillEvaluator names it by its rule instead of `Unknown (AE1)`. A `severity_overrides` entry for these findings uses `SECURITY.Incomplete referenced artifact analysis (AE1)`; one keyed on `SECURITY.Unknown (AE1)` no longer matches. The finding's suggestion names the file, its disposition (`partial`, `failed`, `out_of_scope` or `uninspected`) and each reason SkillSpector gives: the reason code, such as `static_parse_limit` or `read_error`, the analyzers, the line in the file, the message and any limits, such as `limit_characters=8000`. The suggestion is part of the finding's `finding_id`, so it leaves out the measured run time (`observed_seconds`), which differs from run to run; the metadata keeps it. Reasons that differ only in the analyzer or the run time are listed once. SkillSpector's own remedy is kept. Releases before v2.12.0 give no reasons in the finding and a generic remedy that says to make the file available: SkillEvaluator then reads the reasons from the report's `analysis_completeness` rows for that file and gives a remedy for a parse limit, a read error, or any other reason. Without such a row the finding keeps SkillSpector's text. The finding's metadata records the file, its disposition and up to 16 reasons under `skillspector_evidence`, with `reasons_truncated` when SkillSpector gave more, and up to 128 reference lines under `skillspector_occurrences`. In a folder of skills each reference line's `file` starts with the skill's `[name]` prefix, like the finding's own path, and `target_path` stays relative to that skill. Text with control characters is left out, credential-shaped text is masked, and a path outside the scanned target is dropped. When the check fails, the terminal output, the `references` row of the terminal summary, and the Markdown and HTML reports add one line, such as `skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); each AE1 finding names the artifact and any reasons SkillSpector gave`. The JSON report records the counts for every result, passed or failed, in `skillspector_reference_summary`: `affected_artifacts`, `reference_occurrences`, and `reference_occurrences_truncated`, which is `true` when SkillSpector listed more than 128 lines for one finding, so the count is a lower bound. For a folder of skills the counts are totals. None of this changes the finding's severity or whether the scan is complete. A gate changes only where a policy lowered `SECURITY.Unknown (AE1)` and that was what let the check pass. diff --git a/src/skillevaluator/skillspector_references.py b/src/skillevaluator/skillspector_references.py index 1537bcbd3..e939c3448 100644 --- a/src/skillevaluator/skillspector_references.py +++ b/src/skillevaluator/skillspector_references.py @@ -65,6 +65,11 @@ for prefix in ("observed", "limit") for unit in ("artifacts", "bytes", "characters", "depth", "findings", "records", "seconds") ) +# The time a run took differs from run to run. A suggestion is part of its +# finding's ``finding_id``, which must stay the same across runs, so it shows +# only the limits that the file and the configuration fix; the finding's +# metadata keeps every limit. +_RUN_DEPENDENT_LIMITS = frozenset({"observed_seconds"}) def diagnostic_text(value: object, *, max_length: int = 4096) -> str | None: @@ -338,11 +343,17 @@ def issue_diagnostics( def _reason_details(reasons: list[dict]) -> list[str]: - """One text per distinct reason, with the analyzers of rows that differ only in them joined.""" + """One text per distinct reason, with the analyzers of rows that differ only in them joined. + + The measured run time (``observed_seconds``) is left out, so the text, and + the ``finding_id`` that hashes it, is the same in every run of one scan. + """ grouped: dict[tuple, list[str]] = {} for reason in reasons: - limits = reason.get("limits") or {} - key = (reason["reason_code"], reason.get("start_line"), reason.get("message"), tuple(sorted(limits.items()))) + limits = sorted( + (key, value) for key, value in (reason.get("limits") or {}).items() if key not in _RUN_DEPENDENT_LIMITS + ) + key = (reason["reason_code"], reason.get("start_line"), reason.get("message"), tuple(limits)) analyzers = grouped.setdefault(key, []) analyzers.extend(name for name in reason.get("analyzers", []) if name not in analyzers) details = [] diff --git a/tests/reporting/test_skillspector_reference_summary.py b/tests/reporting/test_skillspector_reference_summary.py index a2eafc802..94c789586 100644 --- a/tests/reporting/test_skillspector_reference_summary.py +++ b/tests/reporting/test_skillspector_reference_summary.py @@ -35,6 +35,8 @@ _REPORT = Path(__file__).parents[1] / "fixtures" / "skillspector-2.11.2-perl-help-text-ae1-no-llm.json" # A complete v2.12.0 scan whose two AE1 findings name image files it does not analyze. _IMAGE_REPORT = Path(__file__).parents[1] / "fixtures" / "skillspector-2.12.0-image-path-reference-no-llm.json" +# A failed v2.13.3 scan whose first AE1 finding gives a structured reason. +_PARSE_LIMIT_REPORT = Path(__file__).parents[1] / "fixtures" / "skillspector-2.13.3-perl-parse-limit-ae1-no-llm.json" _AE1_OVERRIDE = "SECURITY.Incomplete referenced artifact analysis (AE1)" @@ -115,6 +117,34 @@ def test_failed_reports_show_the_counts(tmp_path: Path, monkeypatch: pytest.Monk assert combined["results"][0]["skillspector_reference_summary"] == expected +def test_copies_that_differ_only_in_run_time_are_one_unique_finding() -> None: + """Two copies of one reference line whose reasons differ only in the measured run time group as one finding. + + With ``--llm`` both stages report the line, and they are not merged when + the second stage is incomplete. + """ + result = ValidationResult(validator_name="Security Scan") + for seconds in (30.0412, 30.1877): + issue = json.loads(_PARSE_LIMIT_REPORT.read_text(encoding="utf-8"))["issues"][0] + issue["evidence"]["reasons"] = [ + { + "reason_code": "runtime_limit", + "phase": "exclusion_audit", + "message": "Inspection reached its configured runtime limit.", + "analyzers": [], + "limits": {"limit_seconds": 30.0, "observed_seconds": seconds}, + } + ] + finding, _is_error = SecurityValidator._convert_skillspector_issue(issue) + result.add_finding(finding) + + exported = json.loads(JSONReporter(include_timestamp=False).render_all([result])) + + assert exported["finding_counts"]["raw_occurrences"] == 2 + assert exported["finding_counts"]["unique_findings"] == 1 + assert len(exported["finding_groups"]) == 1 + + def test_folder_reference_lines_name_their_skill(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: """In a folder, each exported reference line carries its skill's prefix, like the finding's own path.""" result = _validate(tmp_path, monkeypatch, skills=("alpha", "beta")) diff --git a/tests/validators/test_skillspector_reference_diagnostics.py b/tests/validators/test_skillspector_reference_diagnostics.py index 1fd48d20c..09699de32 100644 --- a/tests/validators/test_skillspector_reference_diagnostics.py +++ b/tests/validators/test_skillspector_reference_diagnostics.py @@ -333,7 +333,9 @@ def test_evidence_and_limits_are_bounded_and_sanitized(self) -> None: } ] assert "at target line 3" in finding.suggestion - assert "limit_characters=8000, observed_characters=9000, observed_seconds=1.25" in finding.suggestion + # The measured run time stays in the metadata, not in the suggestion. + assert "limit_characters=8000, observed_characters=9000." in finding.suggestion + assert "observed_seconds" not in finding.suggestion assert "not-for-export" not in json.dumps(finding.metadata) assert "bad" not in json.dumps(finding.metadata) assert finding.metadata["skillspector_occurrences"] == [ @@ -357,6 +359,46 @@ def test_out_of_range_limits_are_dropped(self, field: str, value: object) -> Non assert is_error assert finding.metadata["skillspector_evidence"]["reasons"][0]["limits"] == {"limit_characters": 8000} + @staticmethod + def _runtime_limit_finding(*elapsed: float): + """The v2.13.3 AE1 finding with one runtime_limit reason per *elapsed* run time.""" + issue = _report(_PARSE_LIMIT_REPORT)["issues"][0] + issue["evidence"]["reasons"] = [ + { + "reason_code": "runtime_limit", + "phase": "exclusion_audit", + "message": "Inspection reached its configured runtime limit.", + "analyzers": [], + "limits": {"limit_seconds": 30.0, "observed_seconds": seconds}, + } + for seconds in elapsed + ] + finding, is_error = SecurityValidator._convert_skillspector_issue(issue) + assert is_error + return finding + + def test_run_time_does_not_change_the_finding_id(self) -> None: + """Two runs that differ only in the measured run time give the same suggestion and ``finding_id``.""" + first = self._runtime_limit_finding(30.0412) + second = self._runtime_limit_finding(30.1877) + + assert first.suggestion == second.suggestion + assert first.finding_id == second.finding_id + assert "runtime_limit: Inspection reached its configured runtime limit; limit_seconds=30.0." in first.suggestion + assert "observed_seconds" not in first.suggestion + # The metadata, which the ID does not hash, keeps what each run measured. + assert [finding.metadata["skillspector_evidence"]["reasons"][0]["limits"] for finding in (first, second)] == [ + {"observed_seconds": 30.0412, "limit_seconds": 30.0}, + {"observed_seconds": 30.1877, "limit_seconds": 30.0}, + ] + + def test_reasons_that_differ_only_in_run_time_are_described_once(self) -> None: + finding = self._runtime_limit_finding(1.5, 2.5) + + assert len(finding.metadata["skillspector_evidence"]["reasons"]) == 2 + assert finding.suggestion.count("runtime_limit") == 1 + assert finding.finding_id == self._runtime_limit_finding(3.5).finding_id + @patch("skillevaluator.validators.security.Tools") def test_an_oversized_limit_does_not_stop_the_scan(self, mock_tools, tmp_path: Path) -> None: root = _parse_limit_skill(tmp_path / "perl-parse-limit") From 28b708736e5832efbb25146b6a35d7d6460d6928 Mon Sep 17 00:00:00 2001 From: Narendran Raghavan Date: Mon, 9 Nov 2026 13:55:32 -0800 Subject: [PATCH 13/15] fix(reporting): keep the AE1 count line in reports rendered from retained JSON CI renders its HTML and Markdown reports again from the JSON report through retained_results, which rebuilds each result's metadata from named fields. skillspector_reference_summary was not one of them, so a failed Tier 1 result lost the count line in every report that CI published, although the docs and the CHANGELOG say the Markdown and HTML reports show it. retained_results now copies the record through reference_summary_record, so only valid counts are kept and a malformed record is dropped. The hunk sits after the scanners block, apart from the lines that open PRs #333 and #349 change in this function. Signed-off-by: Narendran Raghavan Co-Authored-By: Claude Opus 5.5 --- docs/tier1-validation.mdx | 2 +- src/skillevaluator/reporting/retained.py | 5 ++ .../test_skillspector_reference_summary.py | 46 +++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx index 1bd135041..6ec42820c 100644 --- a/docs/tier1-validation.mdx +++ b/docs/tier1-validation.mdx @@ -210,7 +210,7 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice **Incomplete referenced artifacts.** SkillSpector reports a High **Incomplete referenced artifact analysis (AE1)** finding at each line that names a file it did not completely inspect. Releases before v2.12.0 leave the finding's name empty, so SkillEvaluator names it by its rule instead of `Unknown (AE1)`. A `severity_overrides` entry for these findings uses `SECURITY.Incomplete referenced artifact analysis (AE1)`; one keyed on `SECURITY.Unknown (AE1)` no longer matches. The finding's suggestion names the file, its disposition (`partial`, `failed`, `out_of_scope` or `uninspected`) and each reason SkillSpector gives: the reason code, such as `static_parse_limit` or `read_error`, the analyzers, the line in the file, the message and any limits, such as `limit_characters=8000`. The suggestion is part of the finding's `finding_id`, so it leaves out the measured run time (`observed_seconds`), which differs from run to run; the metadata keeps it. Reasons that differ only in the analyzer or the run time are listed once. SkillSpector's own remedy is kept. Releases before v2.12.0 give no reasons in the finding and a generic remedy that says to make the file available: SkillEvaluator then reads the reasons from the report's `analysis_completeness` rows for that file and gives a remedy for a parse limit, a read error, or any other reason. Without such a row the finding keeps SkillSpector's text. The finding's metadata records the file, its disposition and up to 16 reasons under `skillspector_evidence`, with `reasons_truncated` when SkillSpector gave more, and up to 128 reference lines under `skillspector_occurrences`. In a folder of skills each reference line's `file` starts with the skill's `[name]` prefix, like the finding's own path, and `target_path` stays relative to that skill. Text with control characters is left out, credential-shaped text is masked, and a path outside the scanned target is dropped. - When the check fails, the terminal output, the `references` row of the terminal summary, and the Markdown and HTML reports add one line, such as `skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); each AE1 finding names the artifact and any reasons SkillSpector gave`. The JSON report records the counts for every result, passed or failed, in `skillspector_reference_summary`: `affected_artifacts`, `reference_occurrences`, and `reference_occurrences_truncated`, which is `true` when SkillSpector listed more than 128 lines for one finding, so the count is a lower bound. For a folder of skills the counts are totals. None of this changes the finding's severity or whether the scan is complete. A gate changes only where a policy lowered `SECURITY.Unknown (AE1)` and that was what let the check pass. + When the check fails, the terminal output, the `references` row of the terminal summary, and the Markdown and HTML reports add one line, such as `skillspector could not completely inspect 1 referenced artifact(s) across 2 reference occurrence(s); each AE1 finding names the artifact and any reasons SkillSpector gave`. The HTML and Markdown reports that the CI workflow renders again from the JSON report show the same line. The JSON report records the counts for every result, passed or failed, in `skillspector_reference_summary`: `affected_artifacts`, `reference_occurrences`, and `reference_occurrences_truncated`, which is `true` when SkillSpector listed more than 128 lines for one finding, so the count is a lower bound. For a folder of skills the counts are totals. None of this changes the finding's severity or whether the scan is complete. A gate changes only where a policy lowered `SECURITY.Unknown (AE1)` and that was what let the check pass. **Agent control paths.** SkillSpector rules describe attacks on an agent, so a match is an agent threat only in a file the agent reads or runs. When `validate` or `tier1` detects a skill, rules, workflows, or plugin artifact, the `security` check keeps findings on agent control paths and suppresses the rest: diff --git a/src/skillevaluator/reporting/retained.py b/src/skillevaluator/reporting/retained.py index 0038f86cd..9ca562273 100644 --- a/src/skillevaluator/reporting/retained.py +++ b/src/skillevaluator/reporting/retained.py @@ -18,6 +18,7 @@ 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_references import REFERENCE_SUMMARY_KEY, reference_summary_record class RetainedReportError(ValueError): @@ -215,6 +216,10 @@ def retained_results(payload: dict, *, copy_metadata: bool = True) -> list[Valid "scanners must map scanner names to versions", ) metadata["scanners"] = dict(row["scanners"]) + # Only the valid counts are kept; a failed result's reports show them. + reference_summary = reference_summary_record(row.get(REFERENCE_SUMMARY_KEY)) + if reference_summary is not None: + metadata[REFERENCE_SUMMARY_KEY] = reference_summary if "dependency_coverage" in row: _require( isinstance(row["dependency_coverage"], list) diff --git a/tests/reporting/test_skillspector_reference_summary.py b/tests/reporting/test_skillspector_reference_summary.py index 94c789586..0b3840259 100644 --- a/tests/reporting/test_skillspector_reference_summary.py +++ b/tests/reporting/test_skillspector_reference_summary.py @@ -22,6 +22,7 @@ from skillevaluator.reporting.html import HTMLReporter from skillevaluator.reporting.json_reporter import JSONReporter from skillevaluator.reporting.markdown import MarkdownReporter +from skillevaluator.reporting.retained import render_retained_report, retained_results from skillevaluator.skillspector_references import ( combine_reference_summaries, reference_summary_message, @@ -145,6 +146,51 @@ def test_copies_that_differ_only_in_run_time_are_one_unique_finding() -> None: assert len(exported["finding_groups"]) == 1 +def test_reports_rendered_again_from_the_json_show_the_counts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """CI renders its HTML and Markdown reports again from the JSON report; a failed result keeps the line.""" + result = _validate(tmp_path, monkeypatch, skills=(".",)) + payload = json.loads(JSONReporter(include_timestamp=False).render_all([result])) + + [retained] = retained_results(payload) + + assert not retained.passed + assert retained.metadata["skillspector_reference_summary"] == { + "affected_artifacts": 1, + "reference_occurrences": 2, + "reference_occurrences_truncated": False, + } + phrase = _phrase(1, "2") + assert MarkdownReporter(include_timestamp=False).render_all([retained]).count(phrase) == 1 + html = render_retained_report(payload, skill_name="perl-test") + assert re.findall(r'

]*>([^<]*)

', html) == [phrase] + + +@pytest.mark.parametrize( + "summary", + [ + [], + {"affected_artifacts": 0, "reference_occurrences": 2}, + {"affected_artifacts": 1, "reference_occurrences": 10**400}, + {"affected_artifacts": "", "reference_occurrences": 2}, + ], +) +def test_reports_rendered_again_from_the_json_drop_malformed_counts( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, summary: object +) -> None: + result = _validate(tmp_path, monkeypatch, skills=(".",)) + payload = json.loads(JSONReporter(include_timestamp=False).render_all([result])) + payload["results"][0]["skillspector_reference_summary"] = summary + + [retained] = retained_results(payload) + + assert "skillspector_reference_summary" not in retained.metadata + html = render_retained_report(payload, skill_name="perl-test") + assert "referenced artifact(s)" not in html + assert "