Skip to content

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

fix(tier1): keep the missing-reference line check and its warning accurate (#564)

Narendran Raghavan96f03c1abf0e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5ae74edb..e392fcac 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1157,6 +1157,21 @@ All notable changes to SkillEvaluator are documented in this file.
received a `workflow-rules.mdc` file itself; it now receives the workflow
folder, as it already did for a `SKILL.md`. With `--no-dedup`, this also holds
when the file is a symlink to a file with another name.
+- The Tier 1 SkillSpector missing-reference check no longer reads a bold or
+ italic label such as `**Note:**`, `*Tip:*` or `**Step 1:**`, or a `$` shell
+ prompt such as `$ python run.py`, as a wildcard for every file left out of
+ the scan, which kept such a line `INCOMPLETE` whenever anything, even `.git`,
+ was left out. A wildcard elsewhere in the line, or a label inside code, still
+ counts. So do such a label and `$` on a line with a space or shell delimiter
+ between two of the same quote or after a backslash, as written or decoded,
+ such as `setup' 'helper.sh` or `setup\ h*.sh`, where a shell may join words
+ that the check reads apart. With `validate --workers` above 1, a skill of a
+ folder that is also a plugin is judged against the folder, as with one
+ worker, so a line naming a file elsewhere in the folder keeps it
+ `INCOMPLETE`. An `--llm-verify` downgrade no longer drops the accepted
+ missing-reference warning, or the error that says why a scan is
+ `INCOMPLETE`. A severity override from `--policy` or `--profile` no longer
+ drops that error either.
- With `--progress rich` when standard error is not a terminal, such as when
it is redirected to a file or piped to another program, the Tier 3 progress
diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx
index 7530d19c..49ebeeab 100644
--- a/docs/tier1-validation.mdx
+++ b/docs/tier1-validation.mdx
@@ -203,7 +203,8 @@ Precedence, highest to lowest: `--policy` overlay, `--profile` flag, `SKILLEVALU
Severity overrides change how findings gate a run; they do not change the
quality score or waive its `--min-score` requirement. Even an override of
- `QUALITY.*: info` leaves a below-minimum quality score failing.
+ `QUALITY.*: info` leaves a below-minimum quality score failing. Nor do they
+ complete an `INCOMPLETE` scan, whose report keeps the error that says why.
</Accordion>
<Accordion title="Permit reviewed ownership contacts without allowing other email addresses">
@@ -322,13 +323,25 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice
- It is a nonfatal `reference_resolution` row for one line of a file that the report lists once as a component and that is a regular, single-link file of at most 1,000,000 bytes inside the skill, not reached through a symlink.
- The report's complete `references` list records a `missing` reference on that line and quotes part of the line. Every `missing` entry must have an accepted ledger row at the same source path and line; an `ambiguous` entry anywhere, a truncation marker, or an unknown completeness field leaves the scan `INCOMPLETE`.
- The line, at most 10,000 characters long, names nothing in the skill that SkillSpector did not inspect: a symlink, a file the report does not list, a directory that holds no listed file, such as `versions/`, `node_modules/` or `evals/results/`, which SkillEvaluator leaves out of the scanned copy, anything inside such a directory, or a directory that holds any of these, even beside listed files. A `.git` directory counts by its own name, by its Git hooks other than `*.sample` templates, and by every other entry in it that is not part of Git's own layout, such as a script placed there, with everything inside that entry. Git's own files, such as `HEAD`, `config`, `index`, `packed-refs` or `ORIG_HEAD`, and what its `objects`, `refs`, `logs` and `info` directories hold, such as branch names, do not count. Names are compared without regard to case or Unicode normalization, in the line as written and as a Markdown renderer or a reader of file paths may read it: with backslash escapes of ASCII punctuation (such as `node\_modules`) removed, HTML character references (such as `&#118;`) resolved and percent-escapes decoded, up to three of these steps in any order. A skill with more than 50,000 files and directories, or nested more than 64 directories deep, is not checked, and its scan stays `INCOMPLETE`. The work of checking a report's lines is also bounded: when it would take longer, such as for many long lines beside thousands of files left out of the scan, the scan stays `INCOMPLETE`.
- - A word in the line that a shell, cmd.exe, PowerShell or Windows would expand or unquote is read as a pattern, and none of those names may match it. In the pattern, quotes and escapes are removed, a group such as `(v)` stands for what it holds, also right after `]` as in `[v](e)rsions`, each expansion, set of alternatives, extended glob or numeric range may stand for any text, and each bracket expression for any one character. The word is read the way POSIX shells read globs, brace and parameter expansions, `$(...)` and quotes (`v*/*.sh`, `vers?ons`, `v[e]rsions`, `v{e,x}rsions`, `$DIR/run.sh`, `ver""sions`); the way zsh reads groups (`(v)ersions`, `(v|x)ersions`), numeric ranges (`run<1-9>.sh`), the `EXTENDED_GLOB` operators `^`, `#` and `~` (`ver^x`, `verr#sions`, and `v*~x`, read as `v*`), where `x#` as a whole part, such as `C#`, matches only names made of `x`, and globbing flags such as `(#a2)` or `(#c1)`, which make the whole word stand for any text (`(#a2)virsions/x`); the way bash and ksh read extended globs (`@(v)ersions`, `!(x)`); the way cmd.exe reads the `^` escape (`ver^sions`), variables (`%DIR%`, `!DIR!`) and batch parameters (`%1`, `%~dp0`); the way PowerShell reads backtick escapes; with `\` as a directory separator (`v*\i*.sh`); and with a Windows short (8.3) name or a Samba mangled name, a path part with text after a `~` such as `NODE_M~1/BOOTST~1.SH`, standing for any name that holds the part's first character, such as any name with an `n` for `NODE_M~1`. So `3~5` is read as written, as `3`, and as any name with a `3`. A span between backticks is read as Markdown code, as written and with its backticks removed, not as a command, so a plural written as `` `topic`s `` is read as `topics`. Only a leading Markdown `* ` list marker is ignored; a standalone shell wildcard elsewhere, such as `bash *`, still counts. Prose with this syntax is read the same way: a price such as `$5`, a list such as `{a,b}`, `%APPDATA%` or a lone `^` stands for any text, so a line with one stays `INCOMPLETE` whenever anything is left out of the scan, and `approx~10` stays `INCOMPLETE` when a name left out holds an `a`.
- - The check reads names that are written in the reported line, in the spellings above. It does not read other lines and does not run commands, so it does not detect a name on another line, such as `DIR=node_modules` set on one line and used as `sh $DIR/run.sh` on the next, or a name that a command prints or builds, such as `printf` output in backticks, a list piped into `xargs sh`, `find -exec`, or a PowerShell string joined with `+`. It is meant to keep an instruction that names a left-out file `INCOMPLETE`, not to catch a skill written to hide one. Without this check, such a skill passes whenever SkillSpector reports no missing reference in it; with it, the skill also passes when every line SkillSpector reports is another missing reference, such as `output/notes.md`. SkillSpector's own analyzers, not this check, assess the instructions it scanned.
+ - A word in the line that a shell, cmd.exe, PowerShell or Windows would expand or unquote is read as a pattern, and none of those names may match it. In the pattern, quotes and escapes are removed, a group such as `(v)` stands for what it holds, also right after `]` as in `[v](e)rsions`, each expansion, set of alternatives, extended glob or numeric range may stand for any text, and each bracket expression for any one character. The word is read as follows:
+ - The way POSIX shells read globs, brace and parameter expansions, `$(...)` and quotes (`v*/*.sh`, `vers?ons`, `v[e]rsions`, `v{e,x}rsions`, `$DIR/run.sh`, `ver""sions`).
+ - The way zsh reads groups (`(v)ersions`, `(v|x)ersions`), numeric ranges (`run<1-9>.sh`), the `EXTENDED_GLOB` operators `^`, `#` and `~` (`ver^x`, `verr#sions`, and `v*~x`, read as `v*`), where `x#` as a whole part, such as `C#`, matches only names made of `x`, and globbing flags such as `(#a2)` or `(#c1)`, which make the whole word stand for any text (`(#a2)virsions/x`).
+ - The way bash and ksh read extended globs (`@(v)ersions`, `!(x)`).
+ - The way cmd.exe reads the `^` escape (`ver^sions`), variables (`%DIR%`, `!DIR!`) and batch parameters (`%1`, `%~dp0`).
+ - The way PowerShell reads backtick escapes.
+ - With `\` as a directory separator (`v*\i*.sh`).
+ - With a Windows short (8.3) name or a Samba mangled name, a path part with text after a `~` such as `NODE_M~1/BOOTST~1.SH`, standing for any name that holds the part's first character, such as any name with an `n` for `NODE_M~1`. So `3~5` is read as written, as `3`, and as any name with a `3`.
+ - A span between backticks is read as Markdown code, as written and with its backticks removed, not as a command, so a plural written as `` `topic`s `` is read as `topics`. A leading Markdown `* ` list marker is ignored.
+ - A `$` before a space or the end of the line is read as a literal `$`, as a shell reads it, not as an expansion, so a shell prompt `$ python run.py` adds no pattern, and `sh *a$` matches only names that end in `a$`.
+ - A bold or italic label outside code, such as `**Note:**`, `*Tip:*` or `**Step 1:**`, is read as its text, and each of its words, with its `*`, as a pattern that is not split at `:`, `=` or `,`. So as a pattern, `**Note:**` matches only names that hold `note:`, and `**Step 1:**` only names that end in `step` or start with `1:`. A standalone shell wildcard elsewhere, such as `bash *`, still counts, and so does a label inside code.
+ - On a line with a space or shell delimiter between two of the same quote or after a backslash, as written or decoded as above, such as `setup' 'helper.sh`, `"hi there"` or `setup\ h*.sh`, a `$` before a space and a label are read like any other word, so they still stand for any text: a shell may join words there, which the check does not. A PowerShell backtick before a space does not count, as a backtick also ends Markdown code, so ``$ sh setup` h*.ps1`` does not name `setup helper.ps1`.
+ - Prose with this syntax is read the same way: a price such as `$5`, a list such as `{a,b}`, `%APPDATA%` or a lone `^` stands for any text, so a line with one stays `INCOMPLETE` whenever anything is left out of the scan, and `approx~10` stays `INCOMPLETE` when a name left out holds an `a`.
+ - The check reads names that are written in the reported line, in the spellings above. It does not read other lines and does not run commands, so it does not detect a name on another line, such as `DIR=node_modules` set on one line and used as `sh $DIR/run.sh` on the next, or a name that a command prints or builds, such as `printf` output in backticks, a list piped into `xargs sh`, `find -exec`, or a PowerShell string joined with `+`. Nor does it join words at a quoted or escaped space as a shell does, so `setup' 'helper.sh` or `setup\ h*.sh` does not name `setup helper.sh`. It is meant to keep an instruction that names a left-out file `INCOMPLETE`, not to catch a skill written to hide one. Without this check, such a skill passes whenever SkillSpector reports no missing reference in it; with it, the skill also passes when every line SkillSpector reports is another missing reference, such as `output/notes.md`. SkillSpector's own analyzers, not this check, assess the instructions it scanned.
- When the target is a single file, such as `skillevaluator security-scan path/to/SKILL.md`, SkillSpector scans that file alone, so every other file and directory beside it counts as not inspected. A line in it that names a file beside it, such as `scripts/install.sh`, keeps the scan `INCOMPLETE`.
- Tier 3 output in its default location, `<skill>/evals/results`, is left out of the scanned copy too, so it counts as not inspected. The rest of `evals/`, such as `evals/evals.json` and input fixtures in `evals/files`, is scanned. After a Tier 3 run, a line that names `results`, a file the run leaves there, such as `report.html` or `summary.json`, or, when the run used `--harbor-keep-jobs`, any bundled file (the kept Harbor tasks hold a copy of the skill) keeps the scan `INCOMPLETE`, although the same line passed before the run. Writing Tier 3 results outside the skill, with `--results-dir` or `SKILLEVALUATOR_RESULTS_DIR`, keeps a run from changing the result.
- - The scan covers the whole target. When the target is a folder or a plugin that holds skills, such as `skillevaluator security-scan path/to/skills/`, `skillevaluator validate path/to/skills/` (which checks each skill as its own job) or `validate` on a plugin, each skill in it is scanned on its own, and a line may name a file elsewhere in the target that the skill's scan did not inspect, so those skills' missing references keep their scans `INCOMPLETE`.
+ - The scan covers the whole target. When the target is a folder or a plugin that holds skills, such as `skillevaluator security-scan path/to/skills/`, `skillevaluator validate path/to/skills/` (which checks each skill as its own job) or `validate` on a plugin, each skill in it is scanned on its own, and a line may name a file elsewhere in the target that the skill's scan did not inspect, so those skills' missing references keep their scans `INCOMPLETE`, also when a skill in a folder is a plugin of its own.
- Every nonfatal scope exclusion must name an actual uninspected entry under the target. Accepted missing-reference warnings remain visible after the static and LLM stages deduplicate their findings. Any other gap must be a referenced image that SkillEvaluator accepts as described above, and the scan then carries both warnings. Without such images, the report must also show no partially or entirely uninspected file, no limitation and no fatal scope exclusion, and every analyzer must have completed or be not applicable or disabled. In either case the report must count as many findings after filtering as before it, and a `missing` reference without an accepted ledger row, an `ambiguous` reference or a truncation marker leaves the scan `INCOMPLETE` even when a referenced image is its only listed gap. The warning names the file and line of up to three of the references; it does not quote the referenced path. Files not in the scan, including any outside the scanned path, are not inspected.
+ Every nonfatal scope exclusion must name an actual uninspected entry under the target. Accepted missing-reference warnings remain visible after the static and LLM stages deduplicate their findings, and after `--llm-verify` downgrades a finding. Any other gap must be a referenced image that SkillEvaluator accepts as described above, and the scan then carries both warnings. Without such images, the report must also show no partially or entirely uninspected file, no limitation and no fatal scope exclusion, and every analyzer must have completed or be not applicable or disabled. In either case the report must count as many findings after filtering as before it, and a `missing` reference without an accepted ledger row, an `ambiguous` reference or a truncation marker leaves the scan `INCOMPLETE` even when a referenced image is its only listed gap. The warning names the file and line of up to three of the references; it does not quote the referenced path. Files not in the scan, including any outside the scanned path, are not inspected.
SkillSpector v2.12.0 to v2.13.3 report these references as `reference_missing`, and v2.10 and v2.11 as `reference_unresolved`, which SkillEvaluator accepts under the same conditions. A v2.13.3 report whose only gaps are such references is also accepted from the report alone as a missing-reference caveat: an INFO finding that keeps SkillSpector's `partial` status and is recorded as `skillspector_reference_caveats` in the JSON report. It replaces the warning above, and whenever the scan has a known target, as through `validate`, `tier1` or `security-scan`, it is accepted only when the conditions above hold too. A reference that matches several bundled files (`reference_unresolved` from v2.12.0, `ambiguous` in the `references` list before it) still leaves the scan `INCOMPLETE`.
diff --git a/src/skillevaluator/models/result.py b/src/skillevaluator/models/result.py
index 78a56eb6..06f0be39 100644
--- a/src/skillevaluator/models/result.py
+++ b/src/skillevaluator/models/result.py
@@ -597,6 +597,44 @@ class ValidationResult:
self.warnings.append(legacy_msg)
self.summary.warnings += 1
+ def recalculate_keeping_independent(
+ self,
+ errors: list[str],
+ warnings: list[str],
+ *,
+ keep_all_errors: bool = False,
+ keep_repeated_warnings: bool = False,
+ ) -> None:
+ """Rebuild from findings, then put back the errors and warnings that no finding repeats.
+
+ :meth:`recalculate_from_findings` drops every error and warning that no
+ finding repeats. Pass what :meth:`independent_errors` and
+ :meth:`independent_warnings` returned *before* the finding severities
+ changed, because a line that a finding repeats names its old severity.
+
+ Warnings that no finding repeats, such as why a scanner did not
+ complete, always go back, each once. Errors that no finding repeats go
+ back only for an incomplete scan, which fails anyway and whose errors
+ say why. Any other such error, such as the note on a stale SkillSpector
+ baseline, may explain a blocker that the change has just lowered.
+
+ Args:
+ errors: Independent errors read before the change.
+ warnings: Independent warnings read before the change.
+ keep_all_errors: Put every error back, for a change that lowers
+ nothing, such as dropping a repeated finding.
+ keep_repeated_warnings: Put a warning back as often as it was
+ recorded, not once.
+ """
+ self.recalculate_from_findings()
+ if keep_all_errors or self.is_incomplete:
+ for error in errors:
+ if error not in self.errors:
+ self.add_error(error)
+ for warning in warnings:
+ if keep_repeated_warnings or warning not in self.warnings:
+ self.add_warning(warning)
+
def _finding_legacy_lines(self) -> set[str]:
"""Return the legacy error and warning lines that only repeat a structured finding."""
represented = {finding.to_legacy_string() for finding in self.findings}
diff --git a/src/skillevaluator/validators/policy.py b/src/skillevaluator/validators/policy.py
index b6202576..2b3dbe7b 100644
--- a/src/skillevaluator/validators/policy.py
+++ b/src/skillevaluator/validators/policy.py
@@ -382,6 +382,7 @@ def apply_policy(
if policy is None:
return results
for result in results:
+ independent_errors: list[str] = []
independent_warnings: list[str] | None = None
for finding in result.findings:
current = (
@@ -391,14 +392,16 @@ def apply_policy(
if new_severity != current:
if independent_warnings is None:
# Read before any change: a mirrored line names the old severity.
+ independent_errors = result.independent_errors()
independent_warnings = result.independent_warnings()
finding.severity = new_severity
if independent_warnings is not None:
- result.recalculate_from_findings()
- # Rebuilding from findings drops every warning. Keep those no
- # finding mirrors, such as why a scanner did not complete.
- for warning in independent_warnings:
- result.add_warning(warning)
+ # Rebuilding from findings drops every error and warning that no finding
+ # mirrors, such as why a scanner did not complete. An error that explains
+ # blockers the policy has just lowered stays only for an incomplete scan.
+ result.recalculate_keeping_independent(
+ independent_errors, independent_warnings, keep_repeated_warnings=True
+ )
if isinstance(result.metadata, dict):
result.metadata["policy"] = policy.to_dict()
return results
diff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.py
index 6c1a624b..0ab86919 100644
--- a/src/skillevaluator/validators/security.py
+++ b/src/skillevaluator/validators/security.py
@@ -1632,6 +1632,11 @@ _SKILLSPECTOR_NAME_RUN_RE = re.compile(r"[\w.-]+")
# A word of a reference's line: text between whitespace and the Markdown or
# shell delimiters around a path.
_SKILLSPECTOR_LINE_WORD_RE = re.compile(r"[^\s`()<>|;&]+")
+# The private-use code points, from which the stand-in for a literal ``$`` is
+# taken while a line is read (:func:`_skillspector_stand_in`). Neither
+# whitespace nor a word character, it splits no word and joins no parameter
+# name.
+_SKILLSPECTOR_STAND_IN_RANGES = ((0xE000, 0xF8FF), (0xF0000, 0xFFFFD), (0x100000, 0x10FFFD))
# Stands for any text where a shell group or range was read in a line
# (:func:`_skillspector_shell_groups`); unlike ``*``, a word made of it is
# never taken for a list marker.
@@ -1666,6 +1671,26 @@ _SKILLSPECTOR_ZSH_FLAGS_RE = re.compile(r"\(#(?:q|[se]\)|c\d*(?:,\d*)?\)|(?:[ilI
_SKILLSPECTOR_NON_SPACE_RUN_RE = re.compile(r"\S+")
_SKILLSPECTOR_GLOB_SYNTAX = frozenset("*?[" + _SKILLSPECTOR_ZSH_REPEAT)
_SKILLSPECTOR_PATH_PART_SEPARATOR_RE = re.compile(r"[=:,]")
+# A leading Markdown list marker ``*``.
+_SKILLSPECTOR_LIST_MARKER_RE = re.compile(r"^[ \t]*\*(?=[ \t])")
+# A bold or italic label in Markdown, such as ``**Note:**``, ``*Tip:*`` or
+# ``**Step 1:**``: one to three ``*`` at the start of the line or after
+# whitespace, text that starts with a letter or digit, holds no ``*`` or
+# backtick and ends with ``:``, and the same ``*`` before whitespace or the
+# end of the line.
+_SKILLSPECTOR_MARKDOWN_LABEL_RE = re.compile(r"(?<!\S)(\*{1,3})([^\W_][^*`]*?:)\1(?!\S)")
+_SKILLSPECTOR_BACKTICK_RUN_RE = re.compile(r"`+")
+# A ``$`` before whitespace or the end of the line, which a shell keeps as
+# written, as in a prompt such as ``$ python run.py``; one after another ``$``
+# may end the parameter ``$$``.
+_SKILLSPECTOR_LITERAL_DOLLAR_RE = re.compile(r"(?<!\$)\$(?=\s|\Z)")
+# A quoted or escaped character that would otherwise end a word: one between
+# two of the same quote, as in ``setup' 'helper.sh`` or ``"a$ b*"``, or after
+# a backslash, as in ``setup\ h*.sh``. A shell may join words there, which the
+# words of a line are not (:func:`_skillspector_shell_patterns`).
+_SKILLSPECTOR_QUOTED_SPLIT_RE = re.compile(
+ r"""\\[\s`()<>|;&]|'[^'\s`()<>|;&]*[\s`()<>|;&][^']*'|"[^"\s`()<>|;&]*[\s`()<>|;&][^"]*\""""
+)
# Work that checking the lines of one report's missing references may take, in
# units of about one character compared: decoding a line and reading its shell
# groups and words costs 9,000 per character, each search of a decoded line
@@ -2074,6 +2099,22 @@ def _skillspector_shell_expansions(word: str) -> str:
return _SKILLSPECTOR_SHELL_PARAMETER_RE.sub("*", word)
+def _skillspector_stand_in(texts: Iterable[str]) -> str | None:
+ """The first code point of :data:`_SKILLSPECTOR_STAND_IN_RANGES` that no text of *texts* holds.
+
+ So a stand-in for syntax in the texts being read is never also a
+ character of them, such as one that a percent-escape or a character
+ reference decodes to. Returns ``None`` when none is left. The work is
+ linear in the length of the texts.
+ """
+ held: set[str] = set().union(*texts)
+ for first, last in _SKILLSPECTOR_STAND_IN_RANGES:
+ for code in range(first, last + 1):
+ if chr(code) not in held:
+ return chr(code)
+ return None
+
+
def _skillspector_shell_word(word: str) -> tuple[str, str]:
"""*word* as glob patterns for what a POSIX shell, and cmd.exe or PowerShell, may expand it to.
@@ -2171,32 +2212,108 @@ def _skillspector_zsh_pattern(pattern: str) -> str:
return "".join(elements)
+def _skillspector_markdown_labels(text: str) -> tuple[str, list[str]]:
+ """*text* with each bold or italic label outside a code span read as its text, and those labels as written.
+
+ A label (:data:`_SKILLSPECTOR_MARKDOWN_LABEL_RE`), such as ``**Note:**``,
+ is Markdown emphasis. Read as a shell word that is split at its ``:``, its
+ closing ``*`` would be a piece of its own and match every name. A code
+ span, from a run of backticks to the next run of the same length, is read
+ as written, so ``**Run:**`` in one is not a label. The work is linear in
+ the length of *text*.
+ """
+ if "*" not in text:
+ return text, []
+ runs = [match.span() for match in _SKILLSPECTOR_BACKTICK_RUN_RE.finditer(text)]
+ # The next run of the same length after each run, which closes the code span it opens.
+ closes: list[int | None] = [None] * len(runs)
+ latest: dict[int, int] = {}
+ for index in range(len(runs) - 1, -1, -1):
+ size = runs[index][1] - runs[index][0]
+ closes[index] = latest.get(size)
+ latest[size] = index
+ starts: list[int] = []
+ ends: list[int] = []
+ index = 0
+ while index < len(runs):
+ close = closes[index]
+ if close is None:
+ index += 1
+ continue
+ starts.append(runs[index][0])
+ ends.append(runs[close][1])
+ index = close + 1
+ labels: list[str] = []
+
+ def read(match: re.Match[str]) -> str:
+ span = bisect.bisect_right(starts, match.start()) - 1
+ if span >= 0 and match.start() < ends[span]:
+ return match.group()
+ labels.append(match.group())
+ return match.group(2)
+
+ return _SKILLSPECTOR_MARKDOWN_LABEL_RE.sub(read, text), labels
+
+
def _skillspector_shell_patterns(texts: Iterable[str]) -> set[str]:
"""Glob patterns for the path parts of the words in *texts* that a shell or Windows expands or unquotes.
- A word with ``*``, ``?``, ``[``, ``{``, ``$``, ``%``, ``!``, ``^``, ``#``,
- ``~``, a quote, a backslash or a group read in the line is read as a POSIX shell and as
- cmd.exe or PowerShell would (:func:`_skillspector_shell_word`). Each part
- between ``/`` is a pattern, and so is each piece of it between ``=``,
- ``:`` and ``,``, as written and without the dots and punctuation that end
- a sentence after it, with what a ``~`` in it may stand for
- (:func:`_skillspector_tilde_forms`), each read with the zsh
- ``EXTENDED_GLOB`` operators (:func:`_skillspector_zsh_pattern`).
+ The words are split at whitespace and the Markdown or shell delimiters
+ around a path. A word with ``*``, ``?``, ``[``, ``{``, ``$``, ``%``,
+ ``!``, ``^``, ``#``, ``~``, a quote, a backslash or a group read in the
+ line is read as a POSIX shell and as cmd.exe or PowerShell would
+ (:func:`_skillspector_shell_word`). Each part between ``/`` is a pattern,
+ and so is each piece of it between ``=``, ``:`` and ``,``, as written and
+ without the dots and punctuation that end a sentence after it, with what a
+ ``~`` in it may stand for (:func:`_skillspector_tilde_forms`), each read
+ with the zsh ``EXTENDED_GLOB`` operators (:func:`_skillspector_zsh_pattern`).
+
+ Markdown and a shell prompt are read first. A leading list marker ``*``
+ is skipped. A ``$`` before whitespace or the end of the line, which a
+ shell keeps as written, is read as a literal ``$``, not as an expansion
+ (:data:`_SKILLSPECTOR_LITERAL_DOLLAR_RE`). So ``$ python run.py`` adds no
+ pattern, and ``*a$`` stands for names that end in ``a$``. While the words
+ are read, such a ``$`` is a stand-in that no text of *texts* holds
+ (:func:`_skillspector_stand_in`). A bold or italic label outside code,
+ such as ``**Note:**``, is read as its text, and each of its words, with
+ its ``*``, is also a pattern that is not split at ``=``, ``:`` or ``,``
+ (:func:`_skillspector_markdown_labels`). So ``**Note:**`` stands only for
+ names that hold ``note:``, and ``**Step 1:**`` for names that end in
+ ``step`` or start with ``1:``. When any text of *texts* has a quoted or
+ escaped space or delimiter (:data:`_SKILLSPECTOR_QUOTED_SPLIT_RE`), such
+ as ``setup' 'helper.sh``, every text is read without these two steps: a
+ shell may join its words, which these words do not, so the labels and
+ ``$`` of each keep their meaning as globs and expansions, also where
+ decoding removed that escape or showed that label or ``$``, and the texts
+ are read no more narrowly than before. Any other wildcard keeps its
+ meaning, so ``bash *`` or ``--include=*`` may name every uninspected file.
"""
- # Ignore only a leading Markdown bullet. A standalone wildcard elsewhere
- # (for example ``bash *``) can name every uninspected file.
- words = {
- word
- for text in texts
- for word in _SKILLSPECTOR_LINE_WORD_RE.findall(re.sub(r"^[ \t]*\*(?=[ \t])", "", text, count=1))
- }
+ split_words: set[str] = set()
+ label_words: set[str] = set()
+ texts = tuple(texts)
+ # Without a free stand-in, such a "$" is read as an expansion.
+ literal_dollar = _skillspector_stand_in(texts)
+ narrow = all(_SKILLSPECTOR_QUOTED_SPLIT_RE.search(text) is None for text in texts)
+ for text in texts:
+ text = _SKILLSPECTOR_LIST_MARKER_RE.sub("", text, count=1)
+ labels: list[str] = []
+ if narrow:
+ if literal_dollar is not None:
+ text = _SKILLSPECTOR_LITERAL_DOLLAR_RE.sub(literal_dollar, text)
+ text, labels = _skillspector_markdown_labels(text)
+ split_words.update(_SKILLSPECTOR_LINE_WORD_RE.findall(text))
+ for label in labels:
+ label_words.update(_SKILLSPECTOR_LINE_WORD_RE.findall(label))
patterns: set[str] = set()
- for word in words:
+ for word in split_words | label_words:
if _SKILLSPECTOR_SHELL_SYNTAX.isdisjoint(word):
continue
+ split = word in split_words
for reading in _skillspector_shell_word(word):
+ if literal_dollar is not None:
+ reading = reading.replace(literal_dollar, "$")
for index, part in enumerate(reading.split("/")):
- for piece in {part, *_SKILLSPECTOR_PATH_PART_SEPARATOR_RE.split(part)}:
+ for piece in {part, *_SKILLSPECTOR_PATH_PART_SEPARATOR_RE.split(part)} if split else {part}:
patterns.update(
_skillspector_zsh_pattern(form)
for candidate in (piece, piece.rstrip(".,;:!?"))
@@ -2892,11 +3009,11 @@ class SecurityValidator(ValidatorBase):
References written relative to it still count as agent
references. Defaults to the scanned directory.
:func:`_skillspector_missing_reference_notes` accepts missing
- references only in a scan of this root, or without it, of
- *target_root* or else the whole target of :meth:`validate` or
- :meth:`validate_security_only`. A scan outside those methods
- without this root has no reference root, so that rule accepts
- none there; a 2.13.3 report that
+ references only in a scan of *target_root* when it is given,
+ else of this root, or else of the whole target of
+ :meth:`validate` or :meth:`validate_security_only`. A scan
+ outside those methods without either root has no reference
+ root, so that rule accepts none there; a 2.13.3 report that
:func:`reference_caveat_metadata` accepts still passes as its
caveat.
skillspector_baseline: Audited SkillSpector YAML/JSON suppression
@@ -2906,9 +3023,11 @@ class SecurityValidator(ValidatorBase):
target_root: Root of the whole target when this validator is given
only part of it, such as one skill of a folder that
``validate`` checks skill by skill. It replaces the target of
- :meth:`validate` or :meth:`validate_security_only` as the root
- that missing references are judged against, so a skill inside
- it accepts none. Finding scoping is unchanged.
+ :meth:`validate` or :meth:`validate_security_only`, and
+ *skillspector_reference_root*, as the root that missing
+ references are judged against, so a skill inside it accepts
+ none, also when that skill is a plugin of its own. Finding
+ scoping is unchanged.
"""
self._pii_patterns: dict | None = None
self._submitter_override: set[str] | None = (
@@ -3133,11 +3252,12 @@ class SecurityValidator(ValidatorBase):
directory but not a skill, each skill found in it is scanned on its
own, and its instructions may name files elsewhere in the folder that
its scan does not inspect, so their missing references are not
- accepted. A configured ``target_root`` replaces the target, such as
- the folder of skills that a skill passed here belongs to. In a scan
- run outside this walk, :func:`_skillspector_missing_reference_notes`
- accepts missing references only when the configured
- ``skillspector_reference_root`` is the scanned root. Otherwise, as for
+ accepted. A configured ``target_root`` replaces the target and the
+ configured ``skillspector_reference_root``, such as the folder of
+ skills that a skill passed here belongs to. In a scan run outside this
+ walk, :func:`_skillspector_missing_reference_notes` accepts missing
+ references only when the configured ``target_root``, or else the
+ configured ``skillspector_reference_root``, is the scanned root. Otherwise, as for
the per-partition scans of ``tier1/plugin_checks.py``, that rule
accepts none. Such a scan without a configured root has no known
target, so a 2.13.3 report that :func:`reference_caveat_metadata`
@@ -3410,7 +3530,9 @@ class SecurityValidator(ValidatorBase):
result,
baseline_requested=baseline is not None,
scanned_root=original_root if original_root is not None else scan_root,
- reference_root=self.skillspector_reference_root or self._scan_target_root,
+ # The whole target comes first: a skill of a folder that is typed as
+ # a plugin is still only part of the folder.
+ reference_root=self.target_root or self.skillspector_reference_root or self._scan_target_root,
):
result.mark_scan_incomplete(stage_name)
return result
@@ -3440,13 +3562,8 @@ class SecurityValidator(ValidatorBase):
errors = result.independent_errors()
warnings = result.independent_warnings()
result.findings = unique
- result.recalculate_from_findings()
- for error in errors:
- if error not in result.errors:
- result.add_error(error)
- for warning in warnings:
- if warning not in result.warnings:
- result.add_warning(warning)
+ # Dropping a repeated finding lowers nothing, so every error stays.
+ result.recalculate_keeping_independent(errors, warnings, keep_all_errors=True)
@staticmethod
def _drop_repeated_hook_reports(result: ValidationResult, enrichment: ValidationResult) -> None:
@@ -3516,7 +3633,7 @@ class SecurityValidator(ValidatorBase):
inspected or that the scanner reported SAFE. *scanned_root* is the
directory the report's relative paths start from. *reference_root* is
the root of the artifact that contains it: the validator's
- ``skillspector_reference_root``, or else its ``target_root`` or the
+ ``target_root``, or else its ``skillspector_reference_root`` or the
target of the scan in progress. Missing references are accepted by
:func:`_skillspector_missing_reference_notes` only when it is
*scanned_root*. When *reference_root* is given, a caveat that
@@ -6587,7 +6704,12 @@ class SecurityValidator(ValidatorBase):
Findings the LLM classifies as false_positive with high confidence
are downgraded to INFO severity and annotated in metadata. Findings of
checks in :data:`_LLM_VERIFY_EXEMPT_CHECKS` are not sent to the
- verifier: they keep their severity and get no verdict.
+ verifier: they keep their severity and get no verdict. Warnings that no
+ finding repeats, such as an accepted missing-reference warning, are
+ kept when the result is rebuilt. Errors that no finding repeats are
+ kept only when the scan is incomplete, where they say why. Otherwise
+ they are dropped: such an error, such as the note on a stale SkillSpector
+ baseline, explains blockers that the downgrade may have removed.
"""
findings = [finding for finding in result.findings if finding.check_name not in _LLM_VERIFY_EXEMPT_CHECKS]
if not findings:
@@ -6615,6 +6737,9 @@ class SecurityValidator(ValidatorBase):
suppressed = 0
verified = 0
+ # Read before any change: a mirrored line names the old severity.
+ errors = result.independent_errors()
+ warnings = result.independent_warnings()
for idx, finding in enumerate(findings):
verdict_data = verdicts.get(idx)
if not isinstance(verdict_data, dict) or not verdict_data:
@@ -6646,7 +6771,9 @@ class SecurityValidator(ValidatorBase):
suppressed += 1
if suppressed:
- result.recalculate_from_findings()
+ # An error that no finding repeats stays only for an incomplete scan: any other
+ # such error, such as a stale-baseline note, explains blockers that may be gone.
+ result.recalculate_keeping_independent(errors, warnings)
target_severity = finding_verification_policy.DOWNGRADE_SEVERITY.value.upper()
verdict_label = finding_verification_policy.DOWNGRADE_VERDICT.replace("_", " ")
result.add_message(
diff --git a/tests/models/test_result.py b/tests/models/test_result.py
index 34031d64..5d373213 100644
--- a/tests/models/test_result.py
+++ b/tests/models/test_result.py
@@ -202,6 +202,67 @@ class TestRecalculateFromFindings:
assert before[key] == after[key]
+class TestRecalculateKeepingIndependent:
+ """The rebuild that a severity change needs, with the lines no finding repeats put back."""
+
+ @staticmethod
+ def _result(*, incomplete: bool) -> ValidationResult:
+ result = ValidationResult()
+ result.add_finding(_finding(Severity.HIGH))
+ result.add_error("scanner report was cut short")
+ result.fail_gate("scanner status is unknown")
+ result.add_warning("scanner skipped one file")
+ result.add_warning("scanner skipped one file")
+ if incomplete:
+ result.mark_scan_incomplete("scanner")
+ return result
+
+ @staticmethod
+ def _lower(result: ValidationResult, **options: bool) -> tuple[list[str], list[str]]:
+ errors, warnings = result.independent_errors(), result.independent_warnings()
+ result.findings[0].severity = Severity.INFO
+ result.recalculate_keeping_independent(errors, warnings, **options)
+ return errors, warnings
+
+ @pytest.mark.parametrize("incomplete", [True, False])
+ def test_errors_stay_only_for_an_incomplete_scan_and_a_gate_failure_stays_once(self, incomplete: bool):
+ result = self._result(incomplete=incomplete)
+
+ self._lower(result)
+
+ expected = ["scanner status is unknown"]
+ if incomplete:
+ expected.append("scanner report was cut short")
+ assert result.errors == expected
+ assert result.summary.errors == len(expected)
+ assert result.passed is False
+
+ def test_every_error_stays_when_asked(self):
+ result = self._result(incomplete=False)
+
+ self._lower(result, keep_all_errors=True)
+
+ assert result.errors == ["scanner status is unknown", "scanner report was cut short"]
+ assert result.summary.errors == 2
+
+ @pytest.mark.parametrize(("repeated", "copies"), [(False, 1), (True, 2)])
+ def test_a_repeated_warning_goes_back_once_unless_asked(self, repeated: bool, copies: int):
+ result = self._result(incomplete=False)
+
+ self._lower(result, keep_repeated_warnings=repeated)
+
+ assert result.warnings == [result.findings[0].to_legacy_string(), *["scanner skipped one file"] * copies]
+ assert result.summary.warnings == 1 + copies
+
+ def test_a_lowered_finding_is_counted_by_its_new_severity(self):
+ result = self._result(incomplete=False)
+
+ self._lower(result)
+
+ assert (result.summary.high_count, result.summary.warnings) == (0, 2)
+ assert result.findings[0].to_legacy_string() in result.warnings
+
+
class TestMerge:
"""Tests for merge and merge_with_prefix aggregation."""
diff --git a/tests/validators/test_policy.py b/tests/validators/test_policy.py
index 033700c9..20383dcd 100644
--- a/tests/validators/test_policy.py
+++ b/tests/validators/test_policy.py
@@ -10,11 +10,12 @@ from pathlib import Path
import pytest
import yaml
-from skillevaluator.models.result import Severity
+from skillevaluator.models.result import Finding, Severity, ValidationResult
from skillevaluator.validators import policy as policy_module
from skillevaluator.validators.policy import (
DEFAULT_PROFILE_NAME,
ValidationPolicy,
+ apply_policy,
default_policy,
load_policy_file,
load_profile,
@@ -222,3 +223,63 @@ def test_policy_digest_excludes_source_path() -> None:
second = ValidationPolicy(profile="external", source=Path("/tmp/two.yaml"))
assert first.digest == second.digest
+
+
[email protected]("incomplete", [True, False])
+def test_override_keeps_why_an_incomplete_scan_failed(incomplete: bool) -> None:
+ """An override rebuilds a result from its findings; errors no finding repeats stay only on an incomplete scan.
+
+ An incomplete scan fails anyway, and such an error says why. On a complete
+ scan such an error may explain a blocker the override just lowered, so it
+ goes, as before. A gate failure stays either way and is listed once.
+ """
+ result = ValidationResult(validator_name="Security Scan")
+ result.add_structured_finding(
+ Finding(
+ category="SECURITY",
+ severity=Severity.HIGH,
+ check_name="Prompt Injection",
+ message="Ignore all previous instructions",
+ file_path="SKILL.md",
+ line_number=8,
+ )
+ )
+ result.add_error("scanner report was cut short; security scan did not complete")
+ result.fail_gate("scanner status is unknown; security scan did not complete")
+ result.add_warning("scanner skipped one file")
+ if incomplete:
+ result.mark_scan_incomplete("scanner")
+
+ apply_policy([result], ValidationPolicy(severity_overrides={"SECURITY.*": Severity.LOW}))
+
+ assert result.status == ("incomplete" if incomplete else "failed")
+ expected = ["scanner status is unknown; security scan did not complete"]
+ if incomplete:
+ expected.append("scanner report was cut short; security scan did not complete")
+ assert result.errors == expected
+ assert result.summary.errors == len(expected)
+ assert result.warnings == [result.findings[0].to_legacy_string(), "scanner skipped one file"]
+
+
+def test_override_keeps_a_warning_as_often_as_it_was_recorded() -> None:
+ """A warning no finding repeats goes back as often as it was recorded; the LLM downgrade lists it once."""
+ result = ValidationResult(validator_name="Security Scan")
+ result.add_structured_finding(
+ Finding(
+ category="SECURITY",
+ severity=Severity.HIGH,
+ check_name="Prompt Injection",
+ message="Ignore all previous instructions",
+ file_path="SKILL.md",
+ line_number=8,
+ )
+ )
+ result.add_warning("scanner skipped one file")
+ result.add_warning("scanner skipped one file")
+
+ apply_policy([result], ValidationPolicy(severity_overrides={"SECURITY.*": Severity.LOW}))
+
+ assert result.warnings == [result.findings[0].to_legacy_string(), *["scanner skipped one file"] * 2]
+ assert result.summary.warnings == 3
+ assert result.errors == []
+ assert result.passed
diff --git a/tests/validators/test_security.py b/tests/validators/test_security.py
index ed453c04..9808aad7 100644
--- a/tests/validators/test_security.py
+++ b/tests/validators/test_security.py
@@ -23,6 +23,7 @@ from skillevaluator.reporting import CLIReporter, HTMLReporter, JSONReporter, Ma
from skillevaluator.utils.secure_fs import stat_is_link_or_reparse
from skillevaluator.utils.tool_runner import ToolResult, Tools
from skillevaluator.validators.base import Finding, Severity, ValidationResult
+from skillevaluator.validators.policy import ValidationPolicy, apply_policy
from skillevaluator.validators.schema import SchemaValidator
from skillevaluator.validators.security import (
SecurityValidator,
@@ -2097,6 +2098,83 @@ print(json.dumps([finding.metadata["matched_value"] for finding in result.findin
assert any("fingerprints were ignored" in line and "SkillSpector 2.10.0" in line for line in reported)
assert not any("fingerprints were ignored" in finding.message for finding in result.findings)
+ @patch("skillevaluator.validators.security.Tools")
+ def test_llm_verify_downgrade_drops_the_stale_baseline_blocker_error(
+ self, mock_tools, sample_skill_dir: Path, tmp_path: Path
+ ) -> None:
+ """The stale-fingerprint error explains a remaining blocker, so a downgrade of the last one passes the scan."""
+ baseline = tmp_path / "baseline.yaml"
+ baseline.write_text(
+ 'version: 2\nscanner_version: "2.9.0"\nrules: []\nfingerprints:\n'
+ f' - hash: "sha256:{"0" * 64}"\n reason: "Reviewed"\n',
+ encoding="utf-8",
+ )
+ issue = {
+ "id": "PI-1",
+ "category": "Prompt Injection",
+ "pattern": "Instruction override",
+ "severity": "HIGH",
+ "finding": "Ignore prior instructions",
+ "location": {"file": "SKILL.md", "start_line": 8},
+ }
+ verdict = {"verdict": "false_positive", "confidence": "high", "rationale": "Example rationale."}
+
+ with patch("skillevaluator.inference.FindingVerifier") as verifier_cls:
+ verifier_cls.return_value.verify.side_effect = lambda findings, _path: dict.fromkeys(
+ range(len(findings)), verdict
+ )
+ result = _validate_skillspector_payload(
+ mock_tools,
+ sample_skill_dir,
+ _skillspector_json_report([issue]),
+ exit_code=1,
+ validator=SecurityValidator(use_llm=False, verify_llm=True, skillspector_baseline=baseline),
+ )
+
+ assert result.metadata["skillspector_baseline"]["status"] == "fingerprint_version_mismatch"
+ assert any("downgraded 1 finding(s)" in message for message in result.messages)
+ assert not any(finding.severity in (Severity.HIGH, Severity.CRITICAL) for finding in result.findings)
+ assert result.status == "passed"
+ assert result.errors == []
+
+ @pytest.mark.parametrize("incomplete", [True, False])
+ def test_llm_verify_downgrade_keeps_independent_errors_only_for_an_incomplete_scan(
+ self, incomplete: bool, tmp_path: Path
+ ) -> None:
+ """A downgrade rebuilds the result: a gate failure stays, other errors only when incomplete, a warning once."""
+ result = ValidationResult(validator_name="Security Scan")
+ result.add_structured_finding(
+ Finding(
+ category="SECURITY",
+ severity=Severity.HIGH,
+ check_name="Prompt Injection",
+ message="Ignore prior instructions",
+ file_path="SKILL.md",
+ line_number=8,
+ )
+ )
+ result.add_error("scanner report was cut short")
+ result.fail_gate("scanner status is unknown")
+ result.add_warning("scanner skipped one file")
+ result.add_warning("scanner skipped one file")
+ if incomplete:
+ result.mark_scan_incomplete("skillspector")
+
+ with patch("skillevaluator.inference.FindingVerifier") as verifier_cls:
+ verifier_cls.return_value.verify.return_value = {
+ 0: {"verdict": "false_positive", "confidence": "high", "rationale": "Example rationale."}
+ }
+ SecurityValidator(verify_llm=True)._verify_findings_with_llm(result, tmp_path)
+
+ assert result.findings[0].metadata["downgraded"] is True
+ expected = ["scanner status is unknown"]
+ if incomplete:
+ expected.append("scanner report was cut short")
+ assert result.errors == expected
+ assert result.summary.errors == len(expected)
+ assert result.warnings == [result.findings[0].to_legacy_string(), "scanner skipped one file"]
+ assert result.summary.warnings == 2
+
@patch("skillevaluator.validators.security.Tools")
def test_rule_only_skillspector_baseline_ignores_scanner_version(
self, mock_tools, sample_skill_dir: Path, tmp_path: Path
@@ -9356,6 +9434,32 @@ class TestSkillspectorMissingReferences:
assert result.is_incomplete
assert not result.passed
+ @pytest.mark.parametrize("incomplete", [True, False])
+ def test_finding_deduplication_keeps_every_independent_error_and_lists_a_warning_once(
+ self, incomplete: bool
+ ) -> None:
+ """Dropping a repeated finding lowers nothing, so every error stays, complete scan or not."""
+ result = ValidationResult()
+ finding = Finding(
+ category="SECURITY", severity=Severity.LOW, check_name="advisory", message="Repeated", file_path="SKILL.md"
+ )
+ result.add_structured_finding(finding, is_error=False)
+ result.add_structured_finding(finding, is_error=False)
+ result.add_error("Scanner omitted evidence")
+ result.add_warning("Scanner skipped one file")
+ result.add_warning("Scanner skipped one file")
+ if incomplete:
+ result.mark_scan_incomplete("skillspector")
+
+ SecurityValidator._deduplicate_skillspector_findings(result)
+
+ assert len(result.findings) == 1
+ assert result.errors == ["Scanner omitted evidence"]
+ assert result.summary.errors == 1
+ assert result.warnings == [finding.to_legacy_string(), "Scanner skipped one file"]
+ assert result.summary.warnings == 2
+ assert result.is_incomplete is incomplete
+
@pytest.mark.parametrize("version", ["2.12.0", "2.13.3", "2.13.4"])
@pytest.mark.parametrize(
"gap",
@@ -9532,6 +9636,43 @@ class TestSkillspectorMissingReferences:
if not complete:
assert "skillspector_reference_caveats" not in result.metadata
+ @pytest.mark.parametrize("version", ["2.12.0", "2.13.3", "2.13.4"])
+ @pytest.mark.parametrize("left_out", ["helper.sh", ".git/HEAD"])
+ @pytest.mark.parametrize(
+ ("line", "complete"),
+ [
+ # A bold or italic label is Markdown, and a "$" before a space is a shell prompt.
+ ("**Note:** Write the summary to `output/notes.md` and keep it short.", True),
+ ("*Tip:* Write the summary to `output/notes.md` and keep it short.", True),
+ ("**Step 1:** Write the summary to `output/notes.md` and keep it short.", True),
+ ("$ python scripts/summarize.py > output/notes.md", True),
+ # A zero-padded format, whose "%05" decodes to a control character, is no exception.
+ ("$ printf '%05d' 7 > output/notes.md", True),
+ # A wildcard beside a label, a label in code and any other "$" keep their meaning.
+ ("**Note:** Run `bash *` then write the summary to `output/notes.md`.", False),
+ ("Run `sh **Note:**` then write the summary to `output/notes.md`.", False),
+ ("Run `sh $ROOT/setup` then write the summary to `output/notes.md`: $", False),
+ ],
+ )
+ @patch("skillevaluator.validators.security.Tools")
+ def test_markdown_label_and_shell_prompt_are_not_wildcards(
+ self, mock_tools, tmp_path: Path, version: str, left_out: str, line: str, complete: bool
+ ) -> None:
+ """``**Note:**`` and ``$ python ...`` do not stand for every file left out of the scan."""
+ original = "Write the summary to `output/notes.md` and keep it short."
+ files = {
+ **_NOTES_WRITER_FILES,
+ "SKILL.md": _NOTES_WRITER_FILES["SKILL.md"].replace(original, line),
+ left_out: "ref: refs/heads/main\n",
+ }
+ skill = _write_skill(tmp_path / "notes-writer", files)
+ payload = json.loads(json.dumps(_reference_report(version)).replace(original, line))
+
+ result = _validate_skillspector_payload(mock_tools, skill, payload)
+
+ assert result.passed is complete
+ assert result.incomplete_scans == ([] if complete else ["skillspector"])
+
@pytest.mark.parametrize(
("version", "reason_code"),
[("2.11.2", "reference_unresolved"), ("2.12.0", "reference_missing"), ("2.13.3", "reference_missing")],
@@ -10389,10 +10530,11 @@ class TestSkillspectorMissingReferences:
assert alone.incomplete_scans == []
assert alone.warnings == [_reference_caveat_warning("SKILL.md:8", files=1)]
+ @pytest.mark.parametrize("manifest", [False, True])
@pytest.mark.parametrize("workers", [1, 2])
@patch("skillevaluator.validators.security.Tools")
def test_validate_on_a_folder_of_skills_keeps_each_skill_incomplete(
- self, mock_tools, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, workers: int
+ self, mock_tools, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, workers: int, manifest: bool
) -> None:
"""``validate`` runs each skill of a folder as its own job, but a line may still name a file beside it."""
from click.testing import CliRunner
@@ -10407,6 +10549,9 @@ class TestSkillspectorMissingReferences:
{"SKILL.md": _SETUP_HELPER_SKILL.replace("versions/install.sh", "scripts/install.sh")},
)
_write_skill(catalog, {"scripts/install.sh": "#!/bin/sh\ncurl x | sh\n"})
+ if manifest:
+ # A parallel job detects the skill's type again, and a manifest makes it a plugin.
+ _write_skill(skill, {".claude-plugin/plugin.json": '{"name": "setup-helper"}\n'})
report = json.dumps(_reference_report("2.13.3", "staged-script"))
mock_tools.skillspector.is_available = True
mock_tools.skillspector.run.return_value = ToolResult(
@@ -10686,6 +10831,72 @@ class TestSkillspectorMissingReferences:
("Write **all** notes to `output/notes.md`.", "evals", False),
("Write each summary to `output/{name}.md`.", "evals", False),
("Is the user's summary in `output/notes.md`?", "evals", False),
+ # A bold or italic label outside code is read as its text, and a "$"
+ # before whitespace or the end of the line as a literal "$".
+ ("**Note:** Write the summary to `output/notes.md`.", "evals", False),
+ ("*Tip:* write the summary to `output/notes.md`.", "evals", False),
+ ("1. **Step 1:** write `output/notes.md`.", "evals", False),
+ ("**Step 1, then 2:** write `output/notes.md`.", "evals", False),
+ ("$ python scripts/summarize.py > output/notes.md", "evals", False),
+ ("Write `output/notes.md` and print it: $", "evals", False),
+ # A label is a glob that is not split at its ":", and its text keeps
+ # its globs and expansions; any other wildcard stands for any name.
+ ("Run bash *Note:* then write the summary to `output/notes.md`.", "Note:evil.sh", True),
+ ("*Tools: export DIR=$PWD:* then write the summary to `output/notes.md`.", "evals", True),
+ ("**Run v[e]rsions/setup:** now.", "versions", True),
+ ("**Note:** run `bash *` and write `output/notes.md`.", "install.sh", True),
+ ("Run `sh **Run:**` and write `output/notes.md`.", "install.sh", True),
+ ("Run tool --include=* and write `output/notes.md`.", "install.sh", True),
+ ("Run *:* and write `output/notes.md`.", "install.sh", True),
+ ("Run $ROOT/setup now: $", "versions", True),
+ # That "$" stays part of a word with other shell syntax, which may
+ # then name a file whose name ends in "$"; after another "$" it ends
+ # the parameter "$$". Control and private-use characters in the line,
+ # as written or decoded, do not change how it is read.
+ ("Run sh *a$ now.", "xa$", True),
+ ("Run sh setup?$ now.", "setupx$", True),
+ ("Run `sh *a$ now` and write `output/notes.md`.", "xa$", True),
+ ("Run sh 'a'$ now.", "a$", True),
+ ('Run sh "a$ b*" now.', "a$ bc", True),
+ ("Run sh *a$ now.", "xab", False),
+ ("Run sh $$ now.", "x", True),
+ ("Run sh *a\x05$ now.", "xa\x05$", True),
+ ("Run sh *a\x05$ now.", "xa\x05b", False),
+ ("Run sh *a%05$ now.", "xa\x05b", False),
+ ("Run sh *a\ue000$ now.", "xa\ue000b", False),
+ ("$ printf '%05d' 7 > output/notes.md", ".git", False),
+ ("$ printf '%05d' 7 > output/notes.md", "evals", False),
+ ("$ echo %02 %03 %04 %05 \ue000 > output/notes.md", ".git", False),
+ ("$ printf '%05d' $X > output/notes.md", ".git", True),
+ ("$ sh v*/i*.sh %05 > output/notes.md", "install.sh", True),
+ # Each word of a label is a pattern of its own.
+ ("**Step 1:** write `output/notes.md`.", "steps", False),
+ ("**Step 1:** write `output/notes.md`.", "1x", False),
+ ("**Step 1:** write `output/notes.md`.", "nextstep", True),
+ ("**Step 1:** write `output/notes.md`.", "1:x", True),
+ ("**Run the tests:** write `output/notes.md`.", "xrun", True),
+ # A shell may join words at a quoted or escaped space or delimiter,
+ # which this check does not. On such a line a label and a "$" keep
+ # their meaning as a glob and an expansion, as before, also when the
+ # joined name is elsewhere in the line.
+ ("*a' 'b c:* then write `output/notes.md`.", "xa b", True),
+ ("Run sh *setup' 'h:* now.", "xsetup h:y", True),
+ ("*a\\ b c:* then write `output/notes.md`.", "xa b", True),
+ ("**Note:** run sh setup' 'helper.sh now.", "setup helper.sh", True),
+ ("**Note:** run sh setup\\ h*.sh now.", "evals", True),
+ ('**Say "hi there":** in `output/notes.md`.', "evals", True),
+ ('Run sh "a$ b*" now.', "ab", True),
+ ('$ sh "setup h"*.sh > output/notes.md', "evals", True),
+ # So also when the label or "$" shows only once the line is decoded
+ # and the escaped space only as written, or the reverse.
+ ("Run &\\#36; sh setup\\ h*.sh now.", "setup helper.sh", True),
+ ("&\\#42;&\\#42;Note:&\\#42;&\\#42; sh setup\\ h*.sh", "setup helper.sh", True),
+ ("Run $ sh setup&#39; &#39;h*.sh now.", "setup helper.sh", True),
+ # Quotes around no space or delimiter, or a lone apostrophe, join no words.
+ ("**What's new:** write `output/notes.md`.", "evals", False),
+ ('**Say "hi":** in `output/notes.md`.', "evals", False),
+ ("Run sh 'a'$ now.", "ab", False),
+ ("$ printf 'done' > output/notes.md", "evals", False),
# zsh groups and ranges, bash extended globs, cmd.exe escapes and
# variables, PowerShell escapes, Windows 8.3 short names and
# separators, and zsh EXTENDED_GLOB operators.
@@ -10760,6 +10971,22 @@ class TestSkillspectorMissingReferences:
assert avoids is not named
+ def test_stand_in_is_a_private_use_character_that_the_texts_do_not_hold(self) -> None:
+ """Without a free stand-in, a ``$`` before a space is read as an expansion, as before."""
+ from skillevaluator.validators.security import _skillspector_shell_patterns, _skillspector_stand_in
+
+ assert _skillspector_stand_in(["a\x02\x03\x04\x05", ""]) == "\ue000"
+ assert _skillspector_stand_in(["\ue000x", "\ue002"]) == "\ue001"
+ every = "".join(
+ chr(code)
+ for first, last in ((0xE000, 0xF8FF), (0xF0000, 0xFFFFD), (0x100000, 0x10FFFD))
+ for code in range(first, last + 1)
+ )
+ assert _skillspector_stand_in([every[:-1]]) == every[-1]
+ assert _skillspector_stand_in([every[:5000], every[5000:]]) is None
+ assert "*" not in _skillspector_shell_patterns([f"{every[:-1]} $ x"])
+ assert "*" in _skillspector_shell_patterns([f"{every} $ x"])
+
@pytest.mark.parametrize(
("pattern", "name", "matches"),
[
@@ -10940,6 +11167,26 @@ def _high_checks(result: ValidationResult) -> list[str]:
return sorted(finding.check_name for finding in result.findings if finding.severity == Severity.HIGH)
+def _override_notes_report(version: str) -> dict:
+ """The captured 2.13.4 report of the override notes skill; other versions report it as ``partial``."""
+ payload = _reference_report("2.13.4", "instruction-override-and-missing")
+ if version != "2.13.4":
+ payload["metadata"]["skillspector_version"] = version
+ payload["analysis_completeness"].update({"status": "partial", "is_complete": False})
+ return payload
+
+
+def _override_notes_folder_error(version: str) -> str:
+ """The error that says why the override notes skill in a folder is ``INCOMPLETE``."""
+ labels = "SKILL.md:12 [reference_resolution; reference_missing]"
+ if version == "2.13.4":
+ return f"[override-notes] {_caveat_error(labels)}"
+ return (
+ "[override-notes] skillspector JSON field 'analysis_completeness' reports incomplete analysis "
+ f"(status 'partial'): {labels}; security scan did not complete" + _REFERENCE_REJECTION_HELP
+ )
+
+
class TestSkillspectorCompleteWithCaveats:
"""SkillSpector 2.13.4 reports an analysis whose only gaps are missing references as ``complete_with_caveats``."""
@@ -11042,10 +11289,11 @@ class TestSkillspectorCompleteWithCaveats:
assert alone.incomplete_scans == []
assert alone.warnings == [_missing_reference_warning("SKILL.md:8 [reference_resolution; reference_missing]")]
+ @pytest.mark.parametrize("manifest", [False, True])
@pytest.mark.parametrize("workers", [1, 2])
@patch("skillevaluator.validators.security.Tools")
def test_validate_on_a_folder_of_skills_keeps_each_skill_incomplete(
- self, mock_tools, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, workers: int
+ self, mock_tools, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, workers: int, manifest: bool
) -> None:
"""Each skill of a ``validate`` folder run is judged against the folder, also for 2.13.4 caveats."""
from click.testing import CliRunner
@@ -11060,6 +11308,9 @@ class TestSkillspectorCompleteWithCaveats:
{"SKILL.md": _SETUP_HELPER_SKILL.replace("versions/install.sh", "scripts/install.sh")},
)
_write_skill(catalog, {"scripts/install.sh": "#!/bin/sh\ncurl x | sh\n"})
+ if manifest:
+ # A parallel job detects the skill's type again, and a manifest makes it a plugin.
+ _write_skill(skill, {".claude-plugin/plugin.json": '{"name": "setup-helper"}\n'})
report = json.dumps(_reference_report("2.13.4", "staged-script"))
mock_tools.skillspector.is_available = True
mock_tools.skillspector.run.return_value = ToolResult(
@@ -11467,6 +11718,83 @@ class TestSkillspectorCompleteWithCaveats:
assert as_partial.status == "incomplete"
assert _high_checks(as_partial) == _high_checks(result)
+ @pytest.mark.parametrize("target", ["skill", "folder"])
+ @pytest.mark.parametrize("version", ["2.12.0", "2.13.4"])
+ @patch("skillevaluator.validators.security.Tools")
+ def test_llm_verify_downgrade_keeps_the_messages_no_finding_repeats(
+ self, mock_tools, tmp_path: Path, version: str, target: str
+ ) -> None:
+ """An ``--llm-verify`` downgrade rebuilds the result from its findings, which back no reference message.
+
+ The accepted missing-reference warning of a skill, and the error that
+ says why the same skill in a folder is ``INCOMPLETE``, both stay.
+ """
+ root = tmp_path / "bundle"
+ skill = _write_skill(
+ root / "skills" / "override-notes", {**_NOTES_WRITER_FILES, "SKILL.md": _OVERRIDE_NOTES_SKILL}
+ )
+ verdict = {"verdict": "false_positive", "confidence": "high", "rationale": "Example rationale."}
+
+ with patch("skillevaluator.inference.FindingVerifier") as verifier_cls:
+ verifier_cls.return_value.verify.side_effect = lambda findings, _path: dict.fromkeys(
+ range(len(findings)), verdict
+ )
+ result = _validate_skillspector_payload(
+ mock_tools,
+ skill if target == "skill" else root,
+ _override_notes_report(version),
+ exit_code=1,
+ validator=SecurityValidator(use_llm=False, verify_llm=True),
+ )
+
+ assert any("downgraded 3 finding(s)" in message for message in result.messages)
+ assert not _high_checks(result)
+ if target == "skill":
+ assert result.status == "passed"
+ assert result.incomplete_scans == []
+ warning = _missing_reference_warning("SKILL.md:12 [reference_resolution; reference_missing]")
+ assert result.warnings.count(warning) == 1
+ else:
+ assert result.status == "incomplete"
+ assert result.incomplete_scans == ["skillspector"]
+ assert result.errors == [_override_notes_folder_error(version)]
+
+ @pytest.mark.parametrize("target", ["skill", "folder"])
+ @pytest.mark.parametrize("version", ["2.12.0", "2.13.4"])
+ @patch("skillevaluator.validators.security.Tools")
+ def test_policy_override_keeps_the_messages_no_finding_repeats(
+ self, mock_tools, tmp_path: Path, version: str, target: str
+ ) -> None:
+ """A severity override rebuilds the result from its findings, as an ``--llm-verify`` downgrade does.
+
+ The accepted missing-reference warning of a skill, and the error that
+ says why the same skill in a folder is ``INCOMPLETE``, both stay. The
+ ``partial`` error of 2.12.0 is a gate failure, which the rebuild keeps
+ on its own; it is still listed once.
+ """
+ root = tmp_path / "bundle"
+ skill = _write_skill(
+ root / "skills" / "override-notes", {**_NOTES_WRITER_FILES, "SKILL.md": _OVERRIDE_NOTES_SKILL}
+ )
+ result = _validate_skillspector_payload(
+ mock_tools, skill if target == "skill" else root, _override_notes_report(version), exit_code=1
+ )
+ assert len(_high_checks(result)) == 3
+
+ apply_policy([result], ValidationPolicy(severity_overrides={"SECURITY.*": Severity.LOW}))
+
+ assert not _high_checks(result)
+ if target == "skill":
+ assert result.status == "passed"
+ assert result.errors == []
+ warning = _missing_reference_warning("SKILL.md:12 [reference_resolution; reference_missing]")
+ assert result.warnings.count(warning) == 1
+ else:
+ assert result.status == "incomplete"
+ assert result.incomplete_scans == ["skillspector"]
+ assert result.errors == [_override_notes_folder_error(version)]
+ assert result.summary.errors == 1
+
@pytest.mark.parametrize(
("case", "labels"),
[