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.

Add reusable GitLab skill evaluation and repository onboarding (#248)

Narendran Raghavanb63288ce9f96
diff --git a/.github/workflows/evaluate-skills.yml b/.github/workflows/evaluate-skills.yml
index e874b2b0..ff74f3f3 100644
--- a/.github/workflows/evaluate-skills.yml
+++ b/.github/workflows/evaluate-skills.yml
@@ -158,7 +158,7 @@ jobs:
--mount "type=bind,src=$GITHUB_WORKSPACE,dst=/workspace,readonly" \
--mount "type=bind,src=$RUNNER_TEMP/skill-reports,dst=/reports" \
--env SKILL_PATHS --env MIN_SCORE --env LLM_ENABLED --env LLM_PROVIDER --env LLM_MODEL "${llm_secret_args[@]}" \
- --env SCAN_MODE --env DIFF_BASE_SHA --env DIFF_HEAD_SHA \
+ --env SCAN_MODE --env DIFF_BASE_SHA --env DIFF_HEAD_SHA --env SCAN_WORKERS \
--env CALLER_WORKFLOW_SHA \
--env GITHUB_ACTIONS --env REPORT_IMAGE --env REPORT_URL --env REPORT_RUN_URL --env REPORT_COMMIT \
"$IMAGE"
@@ -186,3 +186,14 @@ jobs:
path: ${{ steps.provenance.outputs.directory }}/execution.jwt
if-no-files-found: error
retention-days: 14
+ # The optional report publisher downloads only this JSON evidence, not the full reports.
+ - name: Upload publisher evidence even when validation fails
+ if: always()
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: ${{ inputs.artifact-name }}-evidence-attempt-${{ github.run_attempt }}
+ path: |
+ ${{ runner.temp }}/skill-reports/summary.json
+ ${{ runner.temp }}/skill-reports/skill-*/skillevaluator-tier1.json
+ if-no-files-found: warn
+ retention-days: 14
diff --git a/.github/workflows/publish-skill-reports.yml b/.github/workflows/publish-skill-reports.yml
index d50c5c13..de990a1b 100644
--- a/.github/workflows/publish-skill-reports.yml
+++ b/.github/workflows/publish-skill-reports.yml
@@ -80,8 +80,10 @@ jobs:
# No dependency cache is restored: other default-branch workflows can write
# this job's cache scope, and uv does not recheck files from its cache.
run: |
- python3 -m pip install --require-hashes -r ci/requirements/uv.txt
- uv sync --frozen --no-dev --no-editable --extra publisher
+ python3 -m venv "$RUNNER_TEMP/uv"
+ "$RUNNER_TEMP/uv/bin/python" -m pip install --disable-pip-version-check \
+ --require-hashes --no-deps --only-binary :all: -r ci/requirements/uv.txt
+ "$RUNNER_TEMP/uv/bin/uv" sync --frozen --no-dev --no-editable --extra publisher
- name: Checkout retained report history
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0
with:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0558a287..2c2b1b7c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,42 @@ All notable changes to SkillEvaluator are documented in this file.
- Add reusable GitLab CI onboarding and configurable Tier 1 quality thresholds,
alongside a shared repository integration guide.
+- Opt-in `SKILL_EVAL_JUDGE_CHARACTER_FACTS=1` adds bounded, escaped Unicode
+ character facts to Tier 3 accuracy, goal-accuracy, and behavior-check prompts
+ without normalizing the evidence. The operator setting is verifier-only;
+ enabling it selects the prompt-based goal judge instead of the optional RAGAS
+ route. Metadata uses the same text rendering as the judge prompts, including
+ numeric and nullable fields. Existing prompts remain unchanged when the
+ setting is unset.
+
+- `tier3 evaluate` now leads with a case-first summary: a verdict line and one
+ row per `evals.json` case. With one agent, each row shows, for with and
+ without the skill, the pass count, per-attempt marks (`✓` pass, `✗` fail,
+ `⊘` did not run, `·` skipped after a pass) and mean score, plus an effect
+ column (`helps`, `hurts`, `both fail`, `better score`, `worse score`,
+ `no change`, `inconclusive`). With several agents, each agent gets a column
+ showing without-skill → with-skill marks and the pass-rate change. Success
+ rate, quality score, and dimensions follow. A "How to improve" list follows,
+ ranked by attempts lost and capped at three; each item names the case,
+ agent, issue type (`skill`, `skill not used`, `skill hurts`, `environment`,
+ `run error`, `eval case`, `missing input`, `goal not met`), one action, and an evidence
+ path, and is also written to `what_to_fix.json` in the run directory. When
+ nothing needs fixing it prints a one-line "nothing to fix" instead. The
+ verdict is `inconclusive` when attempts did not run. The per-evaluator and
+ per-dimension tables and metric findings moved behind the new `--verbose`
+ flag and remain in `report.html`.
+- `goal not met` flags with-skill attempts that pass on the aggregate score
+ while the judge scored goal accuracy 0.00 (for example, the agent only asked
+ for details).
+- `report.html` leads with the same case-based findings: "Verdict at a glance"
+ adds the per-case result, the highest-scoring agent versus the biggest skill
+ lift, and the goal-not-met count; "Conclusion & Next Steps" and the Insights
+ recommendations list the `what_to_fix.json` fixes (or "Nothing to fix").
+ Data fixes elsewhere: Pass@K shows attempts passed, a regressed passing
+ dimension reads "PASS · regressed" with its weakest signal, resource totals
+ are formatted with units and percent change, Attempt Details groups each
+ case's with/without rows and marks passes that missed the goal, and Error
+ Recovery lists only trials with faults, retries or warnings.
- Reusable GitHub Actions onboarding for complete Tier 1 checks, with
pinned runtime/workflow consumer templates, affected-skill PR selection,
optional hosted reports and updated PR feedback. The new guide separates
@@ -116,6 +152,9 @@ All notable changes to SkillEvaluator are documented in this file.
### Fixed
+- CI quality thresholds apply to every parallel scan worker. Report overviews
+ and detailed reports surface failed quality gates ahead of advisory findings,
+ with links to the check that needs attention.
- Tier 2 caps every intra-skill embedding chunk at 3,000 characters, preserves
meaningful short tails and actual Python docstring source ranges, and avoids
counting pieces of one original chunk as duplicates of each other. Oversized
diff --git a/ci/gitlab/skill-evaluation.yml b/ci/gitlab/skill-evaluation.yml
index a4b02869..79c0fc46 100644
--- a/ci/gitlab/skill-evaluation.yml
+++ b/ci/gitlab/skill-evaluation.yml
@@ -26,7 +26,11 @@ skill-evaluation:
trap 'rm -rf "$reports_dir"' EXIT
export SKILL_PATHS="$SKILL_EVAL_PATHS"
export MIN_SCORE="$SKILL_EVAL_MIN_SCORE"
- export REPORT_RUN_URL="${CI_JOB_URL:-}"
+ # Report links must be HTTPS; an instance served over HTTP gets no job link.
+ case "${CI_JOB_URL:-}" in
+ https://*) export REPORT_RUN_URL="$CI_JOB_URL" ;;
+ *) export REPORT_RUN_URL="" ;;
+ esac
export REPORT_COMMIT="${CI_COMMIT_SHA:-}"
export REPORT_IMAGE="$SKILL_EVAL_IMAGE"
case "$SKILL_EVAL_SCAN_MODE" in
diff --git a/ci/native_reports.py b/ci/native_reports.py
index 4a8383b2..36f4b3c9 100644
--- a/ci/native_reports.py
+++ b/ci/native_reports.py
@@ -246,7 +246,11 @@ def render_native_reports(reports: Path, summary: dict, context: dict) -> dict[s
f"<title>Skills · SkillEvaluator</title><style>{_STYLE}</style></head><body>",
f'<aside class="rail">{brand_html("se-logo-index")}<p>Evaluation reports</p><a href="#skills" aria-current="page">All skills</a></aside><main>',
'<header class="hero"><div><div class="eyebrow">Evaluation report · Tier 1</div><h1>Skill scan results</h1>',
- f'<span class="status {verdict_class}">{verdict}</span><p class="muted">Review findings, quality dimensions, and scanner evidence for each skill.</p></div>',
+ f'<span class="status {verdict_class}"><span class="sr-only">Verdict: </span>{verdict}</span>',
+ # A no-op run explains itself once, in the skills section below.
+ "</div>"
+ if no_changes
+ else '<p class="muted">Open a skill to see its findings and the evidence for each check.</p></div>',
f'<a class="button" href="{h(run_url)}">View CI run ↗</a>' if run_url else "",
'</header><div class="metrics">',
]
@@ -275,10 +279,9 @@ def render_native_reports(reports: Path, summary: dict, context: dict) -> dict[s
page.append('<section class="attention"><h2>Needs attention</h2>')
if summary.get("error"):
page.append(f"<p>{h(summary['error'])}</p>")
- for row, data, issue, _status, url, _quality in attention:
- reason, _location, _fix = views._first_action(
- {"row": row, "results": data.get("results", []), "issue": issue}
- )
+ for row, _data, issue, _status, url, _quality in attention:
+ fix = first_fixes.get(row["report_dir"]) if not issue else None
+ reason = issue or row.get("error") or (fix or {}).get("message") or "Open the report to inspect the checks."
label = f'<a href="{h(url)}">{h(row["path"])}</a>' if url else h(row["path"])
line = h(str(reason)[:2000])
if fix and url:
diff --git a/ci/publish_reports.py b/ci/publish_reports.py
index f0f7b8b4..8b496912 100644
--- a/ci/publish_reports.py
+++ b/ci/publish_reports.py
@@ -76,41 +76,10 @@ def allowed_download_url(url: str) -> bool:
DOWNLOAD_TOO_LARGE = "The downloaded artifact exceeds its size limit."
-def _bounded_read(response, limit: int) -> bytes:
- declared = response.headers.get("Content-Length")
- if declared and (not declared.isdigit() or int(declared) > limit):
- raise PublicationError("The downloaded artifact or API response exceeds its size limit.")
- payload = response.read(limit + 1)
- if len(payload) > limit:
- raise PublicationError("The downloaded artifact or API response exceeds its size limit.")
- return payload
-
-
-class GitHubAPI:
- def __init__(self, repository: str, token: str):
- self.repository = repository
- self.token = token
- self.opener = urllib.request.build_opener(_NoRedirect())
-
- def _request(self, path: str):
- root = f"/repos/{self.repository}"
- prefix = root + "/"
- if (path != root and not path.startswith(prefix)) or ".." in path or "\\" in path:
- raise PublicationError("Only this repository's GitHub API endpoints are supported.")
- request = urllib.request.Request(
- f"https://api.github.com{path}",
- headers={
- "Authorization": f"Bearer {self.token}",
- "Accept": "application/vnd.github+json",
- "X-GitHub-Api-Version": "2022-11-28",
- "User-Agent": "SkillEvaluator-report-publisher",
- },
- )
- return self.opener.open(request, timeout=60)
-
- def get(self, path: str):
- with self._request(path) as response:
- return _json(_bounded_read(response, MAX_FILE_BYTES))
+class GitHubAPI(github_api.GitHubAPI):
+ error = PublicationError
+ json_error = "A required JSON document is invalid."
+ user_agent = "SkillEvaluator-report-publisher"
def download_artifact(self, artifact_id: int) -> bytes:
try:
@@ -579,17 +548,17 @@ def _select_artifact(api, repository: str, run: dict, *, provenance=False) -> di
finished = _timestamp(run.get("updated_at"))
if finished < started:
raise PublicationError("The selected run attempt has an invalid time interval.")
- names = (
- {f"{ARTIFACT_NAME}-provenance-attempt-{run['run_attempt']}"}
+ name = (
+ f"{ARTIFACT_NAME}-provenance-attempt-{run['run_attempt']}"
if provenance
- else {ARTIFACT_NAME, f"{ARTIFACT_NAME}-attempt-{run['run_attempt']}"}
+ else f"{EVIDENCE_ARTIFACT}-attempt-{run['run_attempt']}"
)
size_limit = 64 * 1024 if provenance else MAX_TOTAL_BYTES
candidates = []
for artifact in listing["artifacts"]:
if not isinstance(artifact, dict):
raise PublicationError("The selected run has malformed artifact metadata.")
- if artifact.get("name") not in names or artifact.get("expired") is not False:
+ if artifact.get("name") != name or artifact.get("expired") is not False:
continue
identity = artifact.get("workflow_run", {})
if identity.get("id") != run["id"] or identity.get("head_sha") != run["head_sha"]:
@@ -611,7 +580,11 @@ def _select_artifact(api, repository: str, run: dict, *, provenance=False) -> di
"approve its updated caller blob, then trigger a new scan. "
"Downloadable scan reports remain in Actions."
)
- raise PublicationError("The selected run attempt has no current report artifact.")
+ raise PublicationError(
+ f"The selected run attempt has no current report evidence artifact named {name}. "
+ "The scan may have stopped before writing reports, the artifact may have expired, "
+ "or the scan used an evaluator revision that does not upload it."
+ )
if len(candidates) != 1:
raise PublicationError("The selected run attempt has ambiguous report artifacts.")
return candidates[0]
diff --git a/ci/run_tier1.py b/ci/run_tier1.py
index 1562e129..b24207df 100644
--- a/ci/run_tier1.py
+++ b/ci/run_tier1.py
@@ -392,6 +392,7 @@ def evaluate_skill(
workspace: Path,
env: dict[str, str],
llm: bool,
+ min_score: str,
timeout: float,
execute,
tokens: set[str],
@@ -423,6 +424,8 @@ def evaluate_skill(
"--llm" if llm else "--no-llm",
"--profile",
"external",
+ "--min-score",
+ min_score,
# native_reports renders each skill's HTML from the retained JSON
# and replaces any CLI copy, so the CLI does not render it.
"-r",
@@ -518,6 +521,7 @@ def run(workspace: Path, reports: Path, environ: dict[str, str], *, execute=None
if not score.isascii() or not score.isdigit() or len(score) > 3 or int(score) > 100:
raise ConfigurationError("MIN_SCORE must be an integer between 0 and 100.")
min_score = str(int(score))
+ workers = scan_workers(environ)
mode = environ.get("SCAN_MODE", "all")
if mode not in {"all", "changed"}:
raise ConfigurationError("SCAN_MODE must be all or changed.")
@@ -641,6 +645,7 @@ def run(workspace: Path, reports: Path, environ: dict[str, str], *, execute=None
workspace=workspace,
env=worker_env,
llm=llm,
+ min_score=min_score,
timeout=remaining,
execute=execute,
tokens=tokens,
@@ -761,79 +766,6 @@ def run(workspace: Path, reports: Path, environ: dict[str, str], *, execute=None
f"SkillEvaluator: scan time limit reached; {len(rows) - len(started)} skills were not started.",
flush=True,
)
- output = reports / f"skill-{index:03d}"
- output.mkdir()
- row["error"] = "Evaluation interrupted before complete evidence was retained."
- data = None
- try:
- remaining = deadline - clock()
- if remaining <= 0:
- raise subprocess.TimeoutExpired("skillevaluator", SCAN_TIMEOUT_SECONDS)
- # Raw scanner files and logs live only in a private temporary
- # directory, never in the upload directory. Docker mounts /audit-tmp
- # as tmpfs, so cancellation cannot upload half-written secrets.
- with tempfile.TemporaryDirectory(prefix="skillevaluator-private-", dir=env.get("TMPDIR")) as temporary:
- raw = Path(temporary).resolve(strict=True)
- if raw.is_relative_to(workspace) or raw.is_relative_to(reports):
- raise ValueError("A private scanner directory must be outside the workspace and reports.")
- argv = [
- "skillevaluator",
- "tier1",
- str(target),
- "--llm" if llm else "--no-llm",
- "--profile",
- "external",
- "--min-score",
- min_score,
- "-r",
- "json,html,markdown,sarif",
- "-o",
- str(raw),
- ]
- with (raw / "stdout.log").open("xb") as stdout, (raw / "stderr.log").open("xb") as stderr:
- process = execute(
- argv, cwd=workspace, env=env, stdout=stdout, stderr=stderr, check=False, timeout=remaining
- )
- safe = sanitized_outputs(raw, tokens)
- for name, content in safe.items():
- (output / name).write_bytes(content)
- row["exit_code"] = process.returncode
- data = _load_report(output / "skillevaluator-tier1.json")
- for key in (
- "overall_status",
- "incomplete_scans",
- "total_validators",
- "total_errors",
- "total_warnings",
- "severity_counts",
- ):
- row[key] = data[key]
- row["passed"] = (
- process.returncode == 0
- and data["overall_passed"] is True
- and data["overall_status"] == "passed"
- and not data["incomplete_scans"]
- and all(
- result.get("passed") is True
- and result.get("status") not in {"incomplete", "failed"}
- and not result.get("incomplete_scans")
- for result in data["results"]
- )
- )
- if not row["passed"] and row["overall_status"] == "passed":
- row["overall_status"] = "error"
- row["incomplete_scans"] = []
- row["error"] = "Process exit or validator results contradict the report verdict."
- else:
- row.pop("error", None)
- except subprocess.TimeoutExpired:
- row["error"] = "Scan time limit reached; this skill did not finish."
- checkpoint()
- break
- except (OSError, ValueError, UnicodeError, RecursionError):
- row["error"] = "Evaluator execution failed or its JSON report was missing, unreadable, or invalid."
- log_result(row, data, annotations=environ.get("GITHUB_ACTIONS") == "true", budget=annotation_budget)
- checkpoint()
summary = _summary(rows)
summary["selection"] = selection
summary["execution"] = context
diff --git a/docs/github-actions.mdx b/docs/github-actions.mdx
index a03a1997..8ad0a881 100644
--- a/docs/github-actions.mdx
+++ b/docs/github-actions.mdx
@@ -73,7 +73,13 @@ jobs:
Open **Actions → Skill checks** for the result and suggested next step. Download
`skill-evaluator-tier1-attempt-N` for `index.html`, per-skill HTML and JSON,
-Markdown, SARIF and available scanner logs.
+Markdown, SARIF and available scanner logs. Failed and incomplete scans retain
+their available reports. The smaller `skill-evaluator-tier1-evidence-attempt-N`
+artifact contains only the JSON used by the optional report publisher.
+
+The HTML index and reports use four verdicts: **Passed**, **Changes required**,
+**Incomplete** and **Skipped**. A quality score below your minimum fails the
+Quality score check and blocks the verdict.
<Frame caption="Example: a Tier 1 report shows the verdict and quality score separately. This example was captured from a GitLab demo using the same report renderer.">
<img src="./assets/repository-ci-results-example.png" alt="Example results table showing a failed skill, its quality score, and a link to its report" />
@@ -200,7 +206,10 @@ For history initialization, permission details and troubleshooting, follow the
while leaving tracked files is an error. Shared files outside skill roots are
not inferred dependencies; use `all` when they should trigger a full scan.
The 100-skill cap is a selection limit, not a runtime guarantee. Timed-out
- scans retain completed results and mark the remainder incomplete.
+ scans retain completed results and mark the remainder incomplete. The workflow
+ scans up to four skills at once. Set `scan-workers` from 1 to 16 to change
+ this; `1` scans one skill at a time. Results and logs keep the same skill
+ order either way.
</Accordion>
<Accordion title="Control whether it blocks merging">
The workflow runs independently of existing workflows; it does not wait for
@@ -223,8 +232,10 @@ For history initialization, permission details and troubleshooting, follow the
vulnerability services and submit package metadata. Dependencies are audited
without installing packages or running build scripts; unpinned or unresolved
requirements are incomplete. Known credential values detected by the PII
- patterns are redacted, but not every secret or transformation is detectable.
- Raw scanner logs are withheld when a credential or LLM key is present.
+ patterns, NVIDIA API keys, and unquoted `KEY=value` and `Bearer` credentials
+ are redacted from CI reports, including parts that scanners cut or escape.
+ Not every credential or transformed value is detectable. Raw scanner logs
+ are withheld when a credential or LLM key is present.
Remove and rotate exposed credentials; old reports and Git history are not
rewritten. Optional model-backed checks use the separate trusted manual
[LLM template](https://github.com/NVIDIA/SkillEvaluator/blob/main/ci/templates/skill-checks-llm.yml),
diff --git a/docs/gitlab-ci.mdx b/docs/gitlab-ci.mdx
index d0cdf9d7..308f7754 100644
--- a/docs/gitlab-ci.mdx
+++ b/docs/gitlab-ci.mdx
@@ -124,8 +124,10 @@ Skill result: "skills/glossary-builder" — FAILED
The threshold applies to the quality score; security, schema and other
required checks remain independent gates. The first version runs Tier 1
only. This integration does not host reports or post merge-request comments
- automatically. Known values detected by credential patterns are redacted,
- but not every secret or transformation is detectable. Raw scanner logs are
+ automatically. Known values detected by credential patterns, NVIDIA API
+ keys, and unquoted `KEY=value` and `Bearer` credentials are redacted,
+ including parts of them that a scanner cuts or escapes, but not every
+ secret or transformation is detectable. Raw scanner logs are
withheld when a credential is present. Remove and rotate exposed
credentials; previous artifacts and Git history are not rewritten.
</Accordion>
diff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.py
index 0e97e4d5..9d461c71 100644
--- a/src/skillevaluator/reporting/html.py
+++ b/src/skillevaluator/reporting/html.py
@@ -1395,8 +1395,9 @@ def _fix_first(
A check that could not finish comes first, with the scanner's own reason,
because no pass can be claimed until it runs. Findings then rank by severity, then blocking before
- advisory, then occurrences. A failed check with no located finding is
- listed as a high, blocking item so its reason is not lost. Two findings at
+ advisory, then occurrences. A failed check's independent error, or its
+ failure without a located finding, is listed as a high, blocking item so
+ its reason is not lost. Two findings at
the same file and line (for example one secret reported by two scanners)
take one slot.
"""
@@ -1407,6 +1408,7 @@ def _fix_first(
label = plain_check_name(check_name)
status = check.get("status") or ("pass" if check.get("passed") else "fail")
findings = check.get("findings") or []
+ independent_errors = [str(error) for error in check.get("additional_errors") or [] if str(error).strip()]
blocking = not check.get("passed", True)
item = {"check": label, "skill": skill_name, "location": "", "blocking": True}
check_key = (skill_name, "check", check_name)
@@ -1416,8 +1418,8 @@ def _fix_first(
message = f"{label} did not finish" + (f": {reason}" if reason else f" ({scans})" if scans else "")
item |= {"kind": "incomplete", "severity": "incomplete", "message": message}
candidates.append(((2, 0, 1, 0), check_key, item | {"anchor": check_anchors[skill_name][check_name]}))
- elif status == "fail" and not findings:
- errors = [str(error) for error in check.get("errors") or [] if str(error).strip()]
+ elif status == "fail" and (independent_errors or not findings):
+ errors = independent_errors or [str(error) for error in check.get("errors") or [] if str(error).strip()]
message = errors[0] if errors else f"{label} failed without a located finding"
item |= {"kind": "check", "severity": "high", "message": message}
rank = (1, _SEVERITY_RANK["high"], 1, 1)
diff --git a/tests/ci/test_evaluate_workflow.py b/tests/ci/test_evaluate_workflow.py
index f01e8f3e..c1bfd664 100644
--- a/tests/ci/test_evaluate_workflow.py
+++ b/tests/ci/test_evaluate_workflow.py
@@ -70,7 +70,7 @@ def test_real_workflow_shell_preserves_container_boundary_and_secret_selection(t
subprocess.run(["bash", "-e", "-o", "pipefail", "-c", scan["run"]], env=env, check=True, capture_output=True)
args = json.loads(captured.read_text())
passed_environment = [args[index + 1] for index, arg in enumerate(args) if arg == "--env"]
- assert {"SCAN_MODE", "DIFF_BASE_SHA", "DIFF_HEAD_SHA"}.issubset(passed_environment)
+ assert {"SCAN_MODE", "DIFF_BASE_SHA", "DIFF_HEAD_SHA", "MIN_SCORE", "SCAN_WORKERS"}.issubset(passed_environment)
assert ("LLM_API_KEY" in args) is (llm == "true")
for flag in ("--read-only", "--user", "--cap-drop", "--security-opt"):
assert flag in args
@@ -160,3 +160,8 @@ def test_signed_receipt_is_separate_and_retained_after_a_failed_scan():
scan = next(step for step in steps if step.get("name") == "Evaluate selected skills")
assert "provenance" not in scan["run"]
assert "ID_TOKEN" not in scan["run"]
+
+
+def test_scan_worker_input_defaults_to_four_parallel_scans():
+ workers = _workflow()["on"]["workflow_call"]["inputs"]["scan-workers"]
+ assert (workers["type"], workers["default"]) == ("number", "4")
diff --git a/tests/ci/test_gitlab_template.py b/tests/ci/test_gitlab_template.py
index 6dd95381..b7f5fc70 100644
--- a/tests/ci/test_gitlab_template.py
+++ b/tests/ci/test_gitlab_template.py
@@ -1,6 +1,7 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""Contracts for the reusable GitLab job and consumer overrides."""
+
from pathlib import Path
import yaml
@@ -37,12 +38,15 @@ def _run_template(tmp_path, extra_env, *, scanner_exit=0, existing_report=False)
' if [ "$1" = --reports ]; then shift; report_dir=$1; fi\n'
" shift\n"
"done\n"
- "printf '%s\\n%s\\n%s\\n%s\\n' \"$SCAN_MODE\" \"${DIFF_BASE_SHA:-}\" \"${DIFF_HEAD_SHA:-}\" \"$MIN_SCORE\" > \"$report_dir/evidence.txt\"\n"
+ 'printf \'%s\\n%s\\n%s\\n%s\\n\' "$SCAN_MODE" "${DIFF_BASE_SHA:-}" "${DIFF_HEAD_SHA:-}" "$MIN_SCORE" > "$report_dir/evidence.txt"\n'
+ 'printf \'%s\' "${REPORT_RUN_URL:-}" > "$report_dir/run_url.txt"\n'
f"exit {scanner_exit}\n"
)
stub.chmod(0o755)
+ # Start from a clean environment so a suite run inside GitLab CI cannot leak its own job variables.
+ outer = {key: value for key, value in os.environ.items() if not key.startswith(("CI_", "GITLAB_", "SKILL_EVAL_"))}
env = {
- **os.environ,
+ **outer,
"PATH": str(bin_dir) + os.pathsep + os.environ["PATH"],
"CI_PROJECT_DIR": str(workspace),
"CI_PIPELINE_SOURCE": "push",
@@ -102,3 +106,27 @@ def test_gitlab_job_does_not_overwrite_existing_report_directory(tmp_path):
assert result.returncode != 0
assert evidence is None
assert "already exists" in result.stderr
+
+
+def test_gitlab_job_passes_only_https_job_links(tmp_path):
+ for job_url, expected in (
+ ("http://gitlab.example.com/g/p/-/jobs/1", ""),
+ ("https://gitlab.example.com/g/p/-/jobs/1", "https://gitlab.example.com/g/p/-/jobs/1"),
+ ):
+ case = tmp_path / ("https" if expected else "http")
+ case.mkdir()
+ result, evidence = _run_template(case, {"CI_JOB_URL": job_url})
+ assert result.returncode == 0
+ assert evidence == ["all", "", "", "80"]
+ assert (case / "workspace/skill-evaluator-report/run_url.txt").read_text() == expected
+
+
+def test_gitlab_template_ignores_the_outer_ci_environment(tmp_path, monkeypatch):
+ monkeypatch.setenv("CI_MERGE_REQUEST_EVENT_TYPE", "merged_result")
+ monkeypatch.setenv("SKILL_EVAL_SCAN_MODE", "all")
+ result, evidence = _run_template(
+ tmp_path,
+ {"CI_PIPELINE_SOURCE": "merge_request_event", "CI_MERGE_REQUEST_DIFF_BASE_SHA": "a" * 40},
+ )
+ assert result.returncode == 0
+ assert evidence == ["changed", "a" * 40, "b" * 40, "80"]
diff --git a/tests/ci/test_native_reports.py b/tests/ci/test_native_reports.py
index 314a7361..7d9d75b3 100644
--- a/tests/ci/test_native_reports.py
+++ b/tests/ci/test_native_reports.py
@@ -290,3 +290,65 @@ def test_native_overview_displays_quality_threshold_failure_not_an_advisory(tmp_
attention = index.split('<section class="attention">', 1)[1].split("</section>", 1)[0]
assert "below the required 100/100" in attention
assert "Optional version missing" not in attention
+
+
+def test_index_uses_the_report_vocabulary_logo_and_first_fix(tmp_path):
+ summary, _ = _write_fixture(tmp_path, failed=True)
+ render_native_reports(tmp_path, summary, {})
+ page = (tmp_path / "index.html").read_text()
+ report = (tmp_path / "skill-001/skillevaluator-tier1.html").read_text()
+
+ assert '<span class="status fail"><span class="sr-only">Verdict: </span>Changes required</span>' in page
+ assert '<span class="status fail">Changes required</span>' in page
+ assert 'class="mark"' not in page
+ assert re.search(r'<aside class="rail"><div class="brand"><svg class="se-logo"[^>]*aria-hidden="true"', page)
+ assert "most severe first" not in page
+ # "Needs attention" names the skill report's first fix and links to its card.
+ anchor = re.search(r'href="#(f-[^"]+)" class="fix-link"', report).group(1)
+ assert f'href="skill-001/skillevaluator-tier1.html#{anchor}"' in page
+ assert f'id="{anchor}"' in report
+
+
+def test_repository_root_skill_lists_each_fix_first_location_once(tmp_path):
+ """Code Risk Analysis records absolute scan paths; other scanners record skill-relative ones."""
+ risk = ValidationResult(validator_name="Code Risk Analysis", validator_description="Static analysis")
+ risk.add_finding(
+ Finding(
+ category="BANDIT",
+ severity="high",
+ check_name="B602",
+ message="subprocess call with shell=True",
+ file_path="/workspace/scripts/fetch.py",
+ line_number=21,
+ )
+ )
+ scan = ValidationResult(validator_name="Security Scan", validator_description="Detect vulnerabilities")
+ scan.add_finding(
+ Finding(
+ category="SECURITY",
+ severity="high",
+ check_name="tool_misuse",
+ message="Tool Misuse: subprocess.run(command, shell=True",
+ file_path="scripts/fetch.py",
+ line_number=21,
+ )
+ )
+ summary, _ = _write_fixture(tmp_path)
+ payload = json.loads(JSONReporter(include_timestamp=False).render_all([risk, scan]))
+ (tmp_path / "skill-001/skillevaluator-tier1.json").write_text(json.dumps(payload))
+ summary["skills"][0].update(path=".", passed=False, overall_status="failed")
+
+ render_native_reports(tmp_path, summary, {})
+ report = (tmp_path / "skill-001/skillevaluator-tier1.html").read_text()
+ fix_first = report.split('class="fix-first"', 1)[1].split("</section>", 1)[0]
+
+ assert re.findall(r"<code>([^<]+)</code>", fix_first) == ["scripts/fetch.py:21"]
+ assert "/workspace/" not in fix_first
+
+
+def test_index_dark_theme_never_applies_to_print():
+ from ci.native_reports import _STYLE
+
+ assert "@media screen and (prefers-color-scheme:dark)" in _STYLE
+ assert "@media(prefers-color-scheme:dark)" not in _STYLE
+ assert all(int(size) >= 11 for size in re.findall(r"font-size:(\d+)px", _STYLE))
diff --git a/tests/ci/test_publish_reports.py b/tests/ci/test_publish_reports.py
index 2f77ec7c..a1771f84 100644
--- a/tests/ci/test_publish_reports.py
+++ b/tests/ci/test_publish_reports.py
@@ -13,6 +13,7 @@ import zipfile
from pathlib import Path
import pytest
+import yaml
from test_verify_provenance import JWKS, signed_receipt
ROOT = Path(__file__).parents[2]
@@ -533,7 +534,7 @@ def test_publication_uses_triggering_attempt_even_after_a_rerun(tmp_path, latest
result = super().get(path)
if path.endswith("/artifacts?per_page=100"):
result["artifacts"].append({**result["artifacts"][0], "id": 789, "created_at": "2026-10-21T13:01:00Z"})
- result["total_count"] = 2
+ result["total_count"] = len(result["artifacts"])
return result
metadata = publisher.publish(
@@ -681,7 +682,9 @@ def test_scan_evidence_upload_holds_exactly_what_the_publisher_reads(tmp_path):
"tier1"
]["steps"]
uploads = [step for step in steps if step.get("uses", "").startswith("actions/upload-artifact@")]
- full, evidence = uploads
+ assert len(uploads) == 3
+ full = next(step for step in uploads if step["with"]["name"] == "${{ inputs.artifact-name }}-attempt-${{ github.run_attempt }}")
+ evidence = next(step for step in uploads if step["with"]["name"] == "${{ inputs.artifact-name }}-evidence-attempt-${{ github.run_attempt }}")
assert evidence["uses"] == full["uses"] and evidence["if"] == full["if"] == "always()"
assert evidence["with"]["name"] == "${{ inputs.artifact-name }}-evidence-attempt-${{ github.run_attempt }}"
assert evidence["with"]["retention-days"] == full["with"]["retention-days"]
diff --git a/tests/ci/test_publisher_workflow.py b/tests/ci/test_publisher_workflow.py
index dc23fb4b..9aa62bb8 100644
--- a/tests/ci/test_publisher_workflow.py
+++ b/tests/ci/test_publisher_workflow.py
@@ -72,5 +72,245 @@ def test_privileged_publisher_installs_the_reviewed_hash_locked_bootstrap():
steps = load(".github/workflows/publish-skill-reports.yml")["jobs"]["prepare"]["steps"]
install = next(step for step in steps if step.get("name") == "Install the trusted native report renderer")
assert install["working-directory"] == "publisher"
- assert "python3 -m pip install --require-hashes -r ci/requirements/uv.txt" in install["run"]
- assert "uv sync --frozen --no-dev --no-editable --extra publisher" in install["run"]
+ lines = [line.strip() for line in install["run"].replace("\\\n", " ").splitlines()]
+ # uv comes from its hash-locked requirement, installed into a private environment.
+ assert lines[0] == 'python3 -m venv "$RUNNER_TEMP/uv"'
+ assert lines[1].startswith('"$RUNNER_TEMP/uv/bin/python" -m pip install ')
+ for flag in ("--require-hashes", "--no-deps", "--only-binary :all:", "-r ci/requirements/uv.txt"):
+ assert flag in lines[1]
+ assert lines[2] == '"$RUNNER_TEMP/uv/bin/uv" sync --frozen --no-dev --no-editable --extra publisher'
+ assert len(lines) == 3
+ # The runner's system Python and pip are never modified.
+ assert "python3 -m pip" not in install["run"]
+ # This job can push to gh-pages, so it never restores a dependency cache that
+ # other default-branch workflows could have written.
+ for step in steps:
+ assert "actions/cache" not in step.get("uses", "")
+ assert "setup-uv" not in step.get("uses", "")
+
+
+def expression(text: str, context: dict) -> bool:
+ """Evaluate the small GitHub expression subset these job conditions use."""
+ tokens = re.findall(r"'[^']*'|==|!=|&&|\|\||!|\(|\)|always\(\)|[A-Za-z_][\w.-]*", text)
+ assert "".join(tokens) == re.sub(r"\s+", "", text)
+ translated = {"&&": " and ", "||": " or ", "!": " not ", "always()": "True"}
+ python = []
+ for token in tokens:
+ if token.startswith("'"):
+ python.append(repr(token[1:-1]))
+ elif token in translated:
+ python.append(translated[token])
+ elif token in {"==", "!=", "(", ")"}:
+ python.append(token)
+ else:
+ python.append(repr(context[token]))
+ # The input is a workflow file from this repository, translated token by token.
+ return eval("".join(python), {"__builtins__": {}})
+
+
+def job_context(committed, event="workflow_run", attempt="1", deploy="success", skipped=""):
+ return {
+ "needs.prepare.result": "success",
+ "needs.prepare.outputs.skipped": skipped,
+ "needs.prepare.outputs.committed": committed,
+ "needs.prepare.outputs.pr_number": "1",
+ "needs.prepare.outputs.is_current": "true",
+ "needs.deploy.result": deploy,
+ "github.event_name": event,
+ "github.run_attempt": attempt,
+ }
+
+
+ ("committed", "event", "attempt", "deploys"),
+ [
+ ("true", "workflow_run", "1", True),
+ ("false", "workflow_run", "1", False),
+ ("false", "workflow_dispatch", "1", True),
+ ("false", "workflow_run", "2", True),
+ ("true", "workflow_run", "3", True),
+ ],
+)
+def test_deploy_is_skipped_only_when_an_automatic_first_attempt_committed_nothing(committed, event, attempt, deploys):
+ deploy = load(".github/workflows/publish-skill-reports.yml")["jobs"]["deploy"]
+ assert deploy["needs"] == "prepare"
+ # No status function, so GitHub also requires prepare to succeed.
+ assert "always()" not in deploy["if"]
+ assert expression(deploy["if"], job_context(committed, event, attempt)) is deploys
+
+
+ ("committed", "deploy", "comments"),
+ [
+ ("true", "success", True),
+ ("false", "success", True),
+ # The run that pushed this content owns its deploy and its comment.
+ ("false", "skipped", False),
+ ("true", "skipped", False),
+ ("true", "failure", False),
+ ("false", "failure", False),
+ ("true", "cancelled", False),
+ ],
+)
+def test_comment_waits_for_this_runs_own_successful_deploy(committed, deploy, comments):
+ job = load(".github/workflows/publish-skill-reports.yml")["jobs"]["comment"]
+ assert expression(job["if"], job_context(committed, deploy=deploy)) is comments
+ assert not expression(job["if"], {**job_context(committed, deploy=deploy), "needs.prepare.result": "failure"})
+
+
[email protected]("committed", ["true", "false"])
+ ("event", "attempt"), [("workflow_run", "1"), ("workflow_dispatch", "1"), ("workflow_run", "2")]
+)
+def test_skipped_stale_publication_never_deploys_or_comments(committed, event, attempt):
+ # A stale run can follow an earlier attempt that already wrote pr_number and is_current.
+ jobs = load(".github/workflows/publish-skill-reports.yml")["jobs"]
+ for deploy in ("success", "skipped"):
+ context = job_context(committed, event, attempt, deploy, skipped="true")
+ assert not expression(jobs["deploy"]["if"], context)
+ assert not expression(jobs["comment"]["if"], context)
+
+
+def run_publish_loop(tmp_path, *, diffs, pushes):
+ """Run the real publish step shell with stand-ins for git and the publisher."""
+ step = next(
+ step
+ for step in load(".github/workflows/publish-skill-reports.yml")["jobs"]["prepare"]["steps"]
+ if step.get("id") == "publish"
+ )
+ workspace, temp, bin_dir = tmp_path / "workspace", tmp_path / "temp", tmp_path / "bin"
+ python = workspace / "publisher/.venv/bin/python"
+ for directory in (workspace / "site", python.parent, temp, bin_dir):
+ directory.mkdir(parents=True, exist_ok=True)
+ python.write_text('#!/bin/sh\nmkdir -p "$OUTPUT_DIR"\necho summary > "$OUTPUT_DIR/summary.md"\n')
+ git = bin_dir / "git"
+ # Each `diff --cached --quiet` and `push` pops its exit code from a queue file.
+ git.write_text(
+ "#!/bin/sh\n"
+ 'echo "$*" >> "$CALLS"\n'
+ 'pop() { code=$(head -n 1 "$1"); tail -n +2 "$1" > "$1.next"; mv "$1.next" "$1"; exit "$code"; }\n'
+ 'case "$3" in diff) pop "$DIFFS";; push) pop "$PUSHES";; esac\n'
+ )
+ for script in (python, git):
+ script.chmod(0o755)
+ (tmp_path / "diffs").write_text("".join(f"{code}\n" for code in diffs))
+ (tmp_path / "pushes").write_text("".join(f"{code}\n" for code in pushes))
+ output = tmp_path / "github-output"
+ env = {
+ "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}",
+ "GITHUB_WORKSPACE": str(workspace),
+ "RUNNER_TEMP": str(temp),
+ "GITHUB_OUTPUT": str(output),
+ "GITHUB_STEP_SUMMARY": str(tmp_path / "step-summary"),
+ "REPORT_RUN_ID": "123",
+ "CALLS": str(tmp_path / "calls"),
+ "DIFFS": str(tmp_path / "diffs"),
+ "PUSHES": str(tmp_path / "pushes"),
+ }
+ subprocess.run(
+ ["bash", "--noprofile", "--norc", "-eo", "pipefail", "-c", step["run"]],
+ cwd=workspace,
+ env=env,
+ check=True,
+ capture_output=True,
+ )
+ calls = (tmp_path / "calls").read_text().splitlines()
+ return output.read_text().splitlines(), calls
+
+
+ ("diffs", "pushes", "committed", "commits"),
+ [
+ ([0], [], "false", 0),
+ ([1], [0], "true", 1),
+ ([1, 1], [1, 0], "true", 2),
+ # A concurrent writer already published this exact run attempt.
+ ([1, 0], [1], "false", 1),
+ ],
+)
+def test_publish_step_reports_whether_it_pushed_new_content(tmp_path, diffs, pushes, committed, commits):
+ output, calls = run_publish_loop(tmp_path, diffs=diffs, pushes=pushes)
+ assert output == [f"committed={committed}"]
+ assert sum(call.startswith("-C site commit") for call in calls) == commits
+ assert load(".github/workflows/publish-skill-reports.yml")["jobs"]["prepare"]["outputs"]["committed"] == (
+ "${{ steps.publish.outputs.committed }}"
+ )
+
+
+ ("event", "attempt", "deploys"),
+ [("workflow_run", "1", False), ("workflow_dispatch", "1", True), ("workflow_run", "2", True)],
+)
+def test_losing_a_push_race_to_the_same_attempt_never_comments_before_a_deploy(tmp_path, event, attempt, deploys):
+ # Attempt 1's push is rejected because another publisher run pushed this scan
+ # attempt first. After the reset, attempt 2 has nothing left to commit.
+ output, _calls = run_publish_loop(tmp_path, diffs=[1, 0], pushes=[1])
+ assert output == ["committed=false"]
+ jobs = load(".github/workflows/publish-skill-reports.yml")["jobs"]
+ context = job_context("false", event, attempt)
+ assert expression(jobs["deploy"]["if"], context) is deploys
+ deploy = "success" if deploys else "skipped"
+ assert expression(jobs["comment"]["if"], {**context, "needs.deploy.result": deploy}) is deploys
+
+
+def checkout(job: str) -> dict:
+ steps = load(".github/workflows/publish-skill-reports.yml")["jobs"][job]["steps"]
+ return next(
+ step for step in steps if step.get("uses", "").startswith("actions/checkout@") and "repository" in step["with"]
+ )
+
+
+def tracked_files() -> list[str]:
+ listing = subprocess.run(["git", "ls-files", "-z"], cwd=ROOT, capture_output=True, check=True).stdout
+ return [name for name in listing.decode().split("\0") if name and (ROOT / name).is_file()]
+
+
+def test_prepare_sparse_checkout_has_the_build_inputs_and_tools(tmp_path):
+ options = checkout("prepare")["with"]
+ assert options.get("sparse-checkout-cone-mode", "true") == "true"
+ directories = options["sparse-checkout"].split()
+ assert directories == ["ci", "src"]
+ # Cone mode checks out every root file plus the listed directories.
+ selected = [name for name in tracked_files() if "/" not in name or name.split("/", 1)[0] in directories]
+ for name in selected:
+ (tmp_path / name).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(ROOT / name, tmp_path / name)
+ project = tomllib.loads((tmp_path / "pyproject.toml").read_text())
+ build_inputs = [project["project"]["readme"], *project["project"]["license-files"], "uv.lock"]
+ build_inputs.append("ci/requirements/uv.txt")
+ for name in build_inputs:
+ assert (tmp_path / name).is_file(), name
+ for package, data in project["tool"]["setuptools"]["package-data"].items():
+ assert (tmp_path / "src" / package.replace(".", "/")).is_dir(), package
+ assert data
+ code = (
+ "import sys; sys.path[:0] = [sys.argv[1] + '/src', sys.argv[1] + '/ci'];"
+ "import publish_reports, native_reports, report_views, github_api, skillevaluator.reporting.retained as r;"
+ "mods = (publish_reports, native_reports, report_views, github_api, r);"
+ "assert all(m.__file__.startswith(sys.argv[1]) for m in mods), [m.__file__ for m in mods]"
+ )
+ subprocess.run([sys.executable, "-c", code, str(tmp_path)], check=True, capture_output=True, cwd=tmp_path)
+
+
+def test_comment_sparse_checkout_runs_with_only_the_standard_library(tmp_path):
+ options = checkout("comment")["with"]
+ assert options["sparse-checkout-cone-mode"] == "false"
+ names = options["sparse-checkout"].split()
+ assert names == ["ci/comment_report.py", "ci/github_api.py"]
+ for name in names:
+ (tmp_path / name).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(ROOT / name, tmp_path / name)
+ run = load(".github/workflows/publish-skill-reports.yml")["jobs"]["comment"]["steps"][-1]["run"]
+ assert run == "python3 publisher/ci/comment_report.py"
+ # No site-packages, user site or PYTHON* variables, like the runner's bare system Python.
+ result = subprocess.run(
+ [sys.executable, "-S", "-s", "-E", str(tmp_path / "ci/comment_report.py")],
+ cwd=tmp_path,
+ env={"REPORT_RUN_ID": "invalid"},
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode == 1
+ assert "PR feedback rejected" in result.stderr
+ assert "Traceback" not in result.stderr
diff --git a/tests/ci/test_run_tier1.py b/tests/ci/test_run_tier1.py
index d586cd7a..093e4c93 100644
--- a/tests/ci/test_run_tier1.py
+++ b/tests/ci/test_run_tier1.py
@@ -733,18 +733,21 @@ def test_relative_annotation_location_is_confined_to_skill(capsys, path, expecte
@pytest.mark.parametrize("score", ["0", "75", "100"])
-def test_quality_threshold_is_forwarded_to_evaluator(tmp_path, score):
[email protected]("workers", ["1", "4"])
+def test_quality_threshold_is_forwarded_to_evaluator(tmp_path, score, workers):
workspace = tmp_path / "workspace"
skill(workspace, "skills/a")
+ skill(workspace, "skills/b")
calls = []
assert runner.run(
workspace,
tmp_path / "reports",
- {"SKILL_PATHS": "skills", "MIN_SCORE": score},
- execute=fake_cli([(0, payload())], calls),
+ {"SKILL_PATHS": "skills", "MIN_SCORE": score, "SCAN_WORKERS": workers},
+ execute=fake_cli([(0, payload()), (0, payload())], calls),
) == 0
- argv = calls[0][0]
- assert argv[argv.index("--min-score") + 1] == score
+ assert len(calls) == 2
+ for argv, _env in calls:
+ assert argv[argv.index("--min-score") + 1] == score
@pytest.mark.parametrize("score", ["-1", "101", "12.5", "abc", "\uff17\uff10", ""])
@@ -761,3 +764,590 @@ def test_invalid_quality_threshold_fails_without_running_scanner(tmp_path, score
assert not calls
summary = json.loads((tmp_path / "reports/summary.json").read_text())
assert summary["overall_status"] == "error"
+
+
+def parallel_cli(responses, calls, *, before=None):
+ """Fake CLI for concurrent runs; ``before(name)`` runs inside the call."""
+ lock = threading.Lock()
+
+ def invoke(argv, **kwargs):
+ output = Path(argv[argv.index("-o") + 1])
+ name = report_dir(output)
+ with lock:
+ calls.append((name, dict(kwargs["env"])))
+ if before:
+ before(name)
+ exit_code, report = responses[name]
+ kwargs["stdout"].write(b"::error::untrusted scanner text\n")
+ (output / "skillevaluator-tier1.json").write_text(json.dumps(report), encoding="utf-8")
+ return CompletedProcess(argv, exit_code)
+
+ return invoke
+
+
+def scan_outputs(reports):
+ names = ["summary.json", "summary.md", "details.md", "pr-comment.md", "index.html"]
+ names += sorted(path.relative_to(reports).as_posix() for path in reports.glob("skill-*/skillevaluator-tier1.html"))
+ return {name: (reports / name).read_text() for name in names}
+
+
+def test_parallel_scan_matches_sequential_rows_logs_annotations_and_reports(tmp_path, capsys):
+ workspace = tmp_path / "workspace"
+ names = [f"skills/s{index}" for index in range(1, 7)]
+ for name in names:
+ skill(workspace, name)
+ failing = {"skill-002", "skill-003", "skill-005"}
+ # Three failing skills with four findings each exceed the 10-annotation budget.
+ responses = {
+ f"skill-{index:03d}": (1, payload(False, "failed", findings=4))
+ if f"skill-{index:03d}" in failing
+ else (0, payload())
+ for index in range(1, 7)
+ }
+ environment = {"SKILL_PATHS": "skills", "GITHUB_ACTIONS": "true"}
+ outputs, logs, finished = {}, {}, {}
+ for workers in ("1", "4"):
+ order = finished[workers] = []
+ done = {name: threading.Event() for name in responses}
+
+ def before(name, workers=workers, order=order, done=done):
+ if workers != "1" and name == "skill-001":
+ # Finish skill 1 last so completion order differs from skill order.
+ assert done["skill-002"].wait(WAIT)
+ order.append(name)
+ done[name].set()
+
+ reports = tmp_path / f"reports-{workers}"
+ result = runner.run(
+ workspace,
+ reports,
+ {**environment, "SCAN_WORKERS": workers},
+ execute=parallel_cli(responses, [], before=before),
+ )
+ assert result == 1
+ outputs[workers] = scan_outputs(reports)
+ logs[workers] = [line for line in capsys.readouterr().out.splitlines() if "at a time" not in line]
+ assert finished["1"] == sorted(responses)
+ assert finished["4"].index("skill-002") < finished["4"].index("skill-001")
+ assert logs["1"] == logs["4"]
+ assert outputs["1"] == outputs["4"]
+ annotations = [line for line in logs["4"] if line.startswith("::error")]
+ assert len(annotations) == 10
+ assert all("file=skills/s2/SKILL.md" in line or "file=skills/s3/SKILL.md" in line for line in annotations[:8])
+ headers = [line for line in logs["4"] if line.startswith("SkillEvaluator: evaluating skill")]
+ assert headers == [
+ f"SkillEvaluator: evaluating skill {index} of 6: {json.dumps(name)}" for index, name in enumerate(names, 1)
+ ]
+
+
+def test_default_scan_runs_four_skills_at_once(tmp_path, capsys):
+ workspace = tmp_path / "workspace"
+ for index in range(5):
+ skill(workspace, f"skills/s{index}")
+ responses = {f"skill-{index:03d}": (0, payload()) for index in range(1, 6)}
+ barrier = threading.Barrier(4, timeout=WAIT)
+ lock = threading.Lock()
+ state = {"active": 0, "peak": 0, "calls": 0}
+
+ def before(name):
+ with lock:
+ state["calls"] += 1
+ state["active"] += 1
+ state["peak"] = max(state["peak"], state["active"])
+ first_wave = state["calls"] <= 4
+ if first_wave:
+ barrier.wait()
+ with lock:
+ state["active"] -= 1
+
+ calls = []
+ assert runner.run(workspace, tmp_path / "reports", {}, execute=parallel_cli(responses, calls, before=before)) == 0
+ assert state["peak"] == 4 and len(calls) == 5
+ assert "SkillEvaluator: scanning 5 skills, up to 4 at a time." in capsys.readouterr().out
+
+
+def test_one_worker_runs_skills_strictly_one_at_a_time(tmp_path):
+ workspace = tmp_path / "workspace"
+ for index in range(3):
+ skill(workspace, f"skills/s{index}")
+ reports = tmp_path / "reports"
+ responses = {f"skill-{index:03d}": (0, payload()) for index in range(1, 4)}
+ seen = []
+
+ def before(name):
+ # The previous skill's result is saved before this one starts.
+ seen.append(json.loads((reports / "summary.json").read_text())["passed"])
+
+ assert (
+ runner.run(workspace, reports, {"SCAN_WORKERS": "1"}, execute=parallel_cli(responses, [], before=before)) == 0
+ )
+ assert seen == [0, 1, 2]
+
+
+def test_each_worker_gets_its_own_home_and_temporary_directory(tmp_path):
+ workspace = tmp_path / "workspace"
+ for index in range(4):
+ skill(workspace, f"skills/s{index}")
+ audit = tmp_path / "audit-tmp"
+ audit.mkdir()
+ responses = {f"skill-{index:03d}": (0, payload()) for index in range(1, 5)}
+ barrier = threading.Barrier(2, timeout=WAIT)
+ pairs = []
+
+ def before(name):
+ barrier.wait()
+ pairs.append(name)
+
+ calls = []
+ environment = {"SCAN_WORKERS": "2", "TMPDIR": str(audit)}
+ assert (
+ runner.run(workspace, tmp_path / "reports", environment, execute=parallel_cli(responses, calls, before=before))
+ == 0
+ )
+ assert len(calls) == 4
+ homes = {env["HOME"] for _, env in calls}
+ assert homes == {"/tmp/evaluator-home/worker-1", "/tmp/evaluator-home/worker-2"}
+ for _, env in calls:
+ worker = env["HOME"].rsplit("-", 1)[1]
+ assert env["TMPDIR"] == str(audit / f"skillevaluator-worker-{worker}")
+ assert Path(env["HOME"]).is_dir() and Path(env["TMPDIR"]).is_dir()
+ # Calls 1-2 and 3-4 ran together, each pair on two different workers.
+ assert calls[0][1]["HOME"] != calls[1][1]["HOME"] and calls[2][1]["HOME"] != calls[3][1]["HOME"]
+
+
+def test_concurrent_timeout_keeps_finished_results_and_starts_no_more_skills(tmp_path, capsys):
+ workspace = tmp_path / "workspace"
+ for name in "abcde":
+ skill(workspace, f"skills/{name}")
+ reports = tmp_path / "reports"
+ now = [0.0]
+ second_started, first_timed_out = threading.Event(), threading.Event()
+ calls = []
+
+ def execute(argv, **kwargs):
+ output = Path(argv[argv.index("-o") + 1])
+ calls.append(report_dir(output))
+ if report_dir(output) == "skill-001":
+ assert second_started.wait(WAIT)
+ now[0] = runner.SCAN_TIMEOUT_SECONDS + 1
+ first_timed_out.set()
+ raise subprocess.TimeoutExpired(argv, kwargs["timeout"])
+ second_started.set()
+ # Skill 2 was already running when the budget ran out; its result counts.
+ assert first_timed_out.wait(WAIT)
+ (output / "skillevaluator-tier1.json").write_text(json.dumps(payload()), encoding="utf-8")
+ return CompletedProcess(argv, 0)
+
+ environment = {"SCAN_WORKERS": "2"}
+ assert runner.run(workspace, reports, environment, execute=execute, clock=lambda: now[0]) == 1
+ assert sorted(calls) == ["skill-001", "skill-002"]
+ summary = json.loads((reports / "summary.json").read_text())
+ assert (summary["passed"], summary["incomplete"]) == (1, 4)
+ rows = summary["skills"]
+ assert "time limit" in rows[0]["error"] and rows[1]["passed"] is True
+ assert all("Not evaluated" in row["error"] for row in rows[2:])
+ output = capsys.readouterr().out
+ assert 'evaluating skill 2 of 5: "skills/b"' in output and "evaluating skill 3" not in output
+ assert "Scan time limit reached; this skill did not finish." in output
+ assert "3 skills were not started" in output
+
+
+def test_checkpoint_saves_a_later_skill_before_an_earlier_one_finishes(tmp_path):
+ workspace = tmp_path / "workspace"
+ skill(workspace, "skills/a")
+ skill(workspace, "skills/b")
+ reports = tmp_path / "reports"
+ responses = {"skill-001": (0, payload()), "skill-002": (0, payload())}
+ snapshots = []
+
+ def before(name):
+ if name != "skill-001":
+ return
+ deadline = time.monotonic() + WAIT
+ while time.monotonic() < deadline:
+ rows = json.loads((reports / "summary.json").read_text())["skills"]
+ if rows[1]["passed"]:
+ snapshots.append(rows)
+ return
+ time.sleep(0.01)
+
+ assert (
+ runner.run(workspace, reports, {"SCAN_WORKERS": "2"}, execute=parallel_cli(responses, [], before=before)) == 0
+ )
+ assert len(snapshots) == 1 and snapshots[0][0]["passed"] is False
+
+
[email protected]("value", ["0", "17", "four", "-1", "2.5", "٣"])
+def test_invalid_scan_worker_count_fails_before_scanning(tmp_path, value):
+ workspace = tmp_path / "workspace"
+ skill(workspace, "skills/a")
+ reports, calls = tmp_path / "reports", []
+ assert runner.run(workspace, reports, {"SCAN_WORKERS": value}, execute=fake_cli([], calls)) == 1
+ assert not calls
+ assert "SCAN_WORKERS" in json.loads((reports / "summary.json").read_text())["error"]
+
+
+posix_only = pytest.mark.skipif(os.name != "posix", reason="uses a shell script as the evaluator")
+
+
+def scan_shim(tmp_path, *, fast=(), ignore_term=False):
+ """Put a fake ``skillevaluator`` on a PATH and return that PATH.
+
+ A scan records its PID and its background tool's PID in ``scan.pids``,
+ then runs for five minutes. Skills named in ``fast`` pass at once instead.
+ """
+ tool = tmp_path / "bin"
+ tool.mkdir()
+ report = tmp_path / "passing-report.json"
+ report.write_text(json.dumps(payload()), encoding="utf-8")
+ cases = "".join(f'*/{name}) cp "{report}" "$out/skillevaluator-tier1.json"; exit 0 ;;\n' for name in fast)
+ script = tool / "skillevaluator"
+ script.write_text(
+ "#!/bin/sh\n"
+ + ("trap '' TERM\n" if ignore_term else "")
+ + "for out; do :; done\n"
+ + f'case "$2" in\n{cases}*) ;;\nesac\n'
+ + "sleep 300 &\n"
+ + 'echo "$$ $!" > "$out/scan.tmp" && mv "$out/scan.tmp" "$out/scan.pids"\n'
+ + "exec sleep 300\n",
+ encoding="utf-8",
+ )
+ script.chmod(0o755)
+ return f"{tool}{os.pathsep}/usr/bin{os.pathsep}/bin"
+
+
+def scan_pids(output, deadline):
+ pids = output / "scan.pids"
+ while not pids.exists():
+ assert time.monotonic() < deadline, "the scan did not start"
+ time.sleep(0.02)
+ return [int(pid) for pid in pids.read_text().split()]
+
+
+def private_scan_pids(temporary, name, deadline):
+ """Read the PIDs of the scan for report directory ``name`` from its private directory under TMPDIR."""
+ while not (found := sorted(temporary.rglob(f"skillevaluator-private-{name}-*/scan.pids"))):
+ assert time.monotonic() < deadline, "the scan did not start"
+ time.sleep(0.02)
+ return scan_pids(found[0].parent, deadline)
+
+
+def still_running(pids):
+ """Wait up to WAIT for the processes to end; return those still running."""
+ deadline = time.monotonic() + WAIT
+ running = [pid for pid in pids if not ended(pid)]
+ while running and time.monotonic() < deadline:
+ time.sleep(0.05)
+ running = [pid for pid in running if not ended(pid)]
+ return running
+
+
+def ended(pid):
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return True
+ return False
+
+
+def kill_quietly(pids):
+ # Only for processes not seen to end: a PID that ended may be reused.
+ for pid in pids:
+ with contextlib.suppress(OSError):
+ os.kill(pid, signal.SIGKILL)
+
+
+@posix_only
+def test_scan_timeout_also_ends_the_scanner_tools(tmp_path, monkeypatch):
+ path = scan_shim(tmp_path)
+ output = tmp_path / "out"
+ output.mkdir()
+ clock = types.SimpleNamespace(offset=0.0)
+ clock.monotonic = lambda: time.monotonic() + clock.offset
+ monkeypatch.setattr(runner, "time", clock)
+ outcome = {}
+
+ def scan():
+ try:
+ runner.run_scan(
+ ["skillevaluator", "tier1", "skills/a", "-o", str(output)],
+ abort=threading.Event(),
+ timeout=WAIT,
+ env={"PATH": path},
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ except subprocess.TimeoutExpired as exc:
+ outcome["error"] = exc
+
+ thread = threading.Thread(target=scan, daemon=True)
+ thread.start()
+ pids = survivors = scan_pids(output, time.monotonic() + WAIT)
+ try:
+ clock.offset = WAIT
+ thread.join(WAIT)
+ assert not thread.is_alive() and "error" in outcome
+ survivors = still_running(pids)
+ assert not survivors
+ finally:
+ kill_quietly(survivors)
+
+
+@posix_only
+def test_aborted_scan_is_killed_after_the_grace_period(tmp_path, monkeypatch):
+ monkeypatch.setattr(runner, "STOP_GRACE_SECONDS", 0.5)
+ path = scan_shim(tmp_path, ignore_term=True)
+ output = tmp_path / "out"
+ output.mkdir()
+ abort, outcome = threading.Event(), {}
+
+ def scan():
+ outcome["process"] = runner.run_scan(
+ ["skillevaluator", "tier1", "skills/a", "-o", str(output)],
+ abort=abort,
+ timeout=WAIT,
+ env={"PATH": path},
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+
+ thread = threading.Thread(target=scan, daemon=True)
+ thread.start()
+ pids = survivors = scan_pids(output, time.monotonic() + WAIT)
+ try:
+ abort.set()
+ thread.join(WAIT)
+ assert not thread.is_alive()
+ # The scan and its tool ignore SIGTERM, so only SIGKILL ends them.
+ assert outcome["process"].returncode == -signal.SIGKILL
+ survivors = still_running(pids)
+ assert not survivors
+ finally:
+ kill_quietly(survivors)
+
+
+@posix_only
+def test_checkpoint_error_ends_running_scans_at_once(tmp_path, monkeypatch):
+ workspace = tmp_path / "workspace"
+ skill(workspace, "skills/fast")
+ skill(workspace, "skills/slow")
+ audit = tmp_path / "audit-tmp"
+ audit.mkdir()
+ reports = tmp_path / "reports"
+ environment = {"PATH": scan_shim(tmp_path, fast=["fast"]), "TMPDIR": str(audit)}
+ render, pids, outcome = runner.render_reports, [], {}
+ survivors = pids
+
+ def render_reports(*args):
+ if (reports / "skill-001" / "skillevaluator-tier1.json").exists():
+ # The slow scan is running when saving the fast result fails.
+ pids.extend(private_scan_pids(audit, "skill-002", time.monotonic() + WAIT))
+ raise OSError(errno.ENOSPC, "No space left on device")
+ render(*args)
+
+ monkeypatch.setattr(runner, "render_reports", render_reports)
+
+ def scan():
+ try:
+ runner.run(workspace, reports, environment)
+ except BaseException as exc:
+ outcome["error"] = exc
+
+ thread = threading.Thread(target=scan, daemon=True)
+ thread.start()
+ try:
+ thread.join(WAIT)
+ assert not thread.is_alive(), "the run waited for a running scan"
+ assert isinstance(outcome["error"], OSError)
+ survivors = still_running(pids)
+ assert pids and not survivors
+ finally:
+ kill_quietly(survivors)
+
+
+def start_runner_with_endless_scans(tmp_path, *, ignore_term=False):
+ """Start the runner alone in its session, as Docker runs it, and wait for two endless scans."""
+ workspace = tmp_path / "workspace"
+ for name in ("a", "b"):
+ skill(workspace, f"skills/{name}")
+ audit = tmp_path / "audit-tmp"
+ audit.mkdir()
+ reports = tmp_path / "reports"
+ environment = {"PATH": scan_shim(tmp_path, ignore_term=ignore_term), "TMPDIR": str(audit)}
+ environment.update(
+ (name, os.environ[name]) for name in ("PYTHONPATH", "PYTHONDONTWRITEBYTECODE") if name in os.environ
+ )
+ with (tmp_path / "runner.log").open("wb") as log:
+ process = subprocess.Popen(
+ [sys.executable, str(MODULE_PATH), "--workspace", str(workspace), "--reports", str(reports)],
+ env=environment,
+ stdout=log,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ pids = []
+ try:
+ deadline = time.monotonic() + WAIT
+ for name in ("skill-001", "skill-002"):
+ pids += private_scan_pids(audit, name, deadline)
+ except BaseException:
+ process.kill()
+ process.wait()
+ kill_quietly(pids)
+ raise
+ return process, pids
+
+
+@posix_only
+def test_ctrl_c_ends_running_scans_and_their_tools(tmp_path):
+ process, pids = start_runner_with_endless_scans(tmp_path)
+ survivors = pids
+ try:
+ # Docker sends Ctrl-C to the runner (PID 1) only, not to its scans.
+ os.kill(process.pid, signal.SIGINT)
+ assert process.wait(WAIT) == -signal.SIGINT
+ survivors = still_running(pids)
+ assert not survivors
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait()
+ kill_quietly(survivors)
+
+
+@posix_only
+def test_second_ctrl_c_does_not_leave_the_runner_waiting(tmp_path):
+ # The scans ignore SIGTERM, so the second Ctrl-C arrives while the
+ # runner is still waiting for them to end.
+ process, pids = start_runner_with_endless_scans(tmp_path, ignore_term=True)
+ survivors = pids
+ try:
+ os.kill(process.pid, signal.SIGINT)
+ time.sleep(1)
+ os.kill(process.pid, signal.SIGINT)
+ assert process.wait(WAIT) == -signal.SIGINT
+ survivors = still_running(pids)
+ assert not survivors
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait()
+ kill_quietly(survivors)
+
+
+def test_each_report_is_released_once_its_result_is_logged(tmp_path, monkeypatch):
+ # Reports can be 32 MiB each; 100 of them must not stay in memory.
+ workspace = tmp_path / "workspace"
+ for index in range(5):
+ skill(workspace, f"skills/s{index}")
+ responses = {f"skill-{index:03d}": (0, payload()) for index in range(1, 6)}
+ load, reports, alive = runner._load_report, [], []
+
+ class Report(dict):
+ pass
+
+ def tracked(path):
+ report = Report(load(path))
+ reports.append(weakref.ref(report))
+ return report
+
+ def before(name):
+ gc.collect()
+ alive.append(sum(report() is not None for report in reports))
+
+ monkeypatch.setattr(runner, "_load_report", tracked)
+ environment = {"SCAN_WORKERS": "1"}
+ assert (
+ runner.run(workspace, tmp_path / "reports", environment, execute=parallel_cli(responses, [], before=before))
+ == 0
+ )
+ # Only the latest result may still be referenced when the next scan starts.
+ assert alive == [0, 1, 1, 1, 1]
+
+
+def worker_directory(env, name):
+ return Path(env[name]) / ("worker-1" if name == "HOME" else "skillevaluator-worker-1")
+
+
[email protected]("name", ["HOME", "TMPDIR"])
+def test_symlinked_worker_directory_is_rejected(tmp_path, name):
+ env = {"HOME": str(tmp_path / "home"), "TMPDIR": str(tmp_path / "tmp")}
+ directory = worker_directory(env, name)
+ directory.parent.mkdir()
+ (tmp_path / "elsewhere").mkdir(mode=0o700)
+ directory.symlink_to(tmp_path / "elsewhere", target_is_directory=True)
+ with pytest.raises(runner.ConfigurationError):
+ runner.worker_environment(env, 1)
+
+
+@posix_only
[email protected]("name", ["HOME", "TMPDIR"])
+def test_existing_worker_directory_open_to_others_is_rejected(tmp_path, name):
+ env = {"HOME": str(tmp_path / "home"), "TMPDIR": str(tmp_path / "tmp")}
+ directory = worker_directory(env, name)
+ directory.mkdir(parents=True)
+ directory.chmod(0o777)
+ with pytest.raises(runner.ConfigurationError):
+ runner.worker_environment(env, 1)
+ assert stat.S_IMODE(directory.stat().st_mode) == 0o777
+
+
+@posix_only
+def test_worker_directory_owned_by_another_user_is_rejected(tmp_path, monkeypatch):
+ env = {"HOME": str(tmp_path / "home"), "TMPDIR": str(tmp_path / "tmp")}
+ uid = os.getuid()
+ monkeypatch.setattr(runner.os, "getuid", lambda: uid + 1)
+ with pytest.raises(runner.ConfigurationError):
+ runner.worker_environment(env, 1)
+
+
+@posix_only
+def test_existing_private_worker_directories_are_reused(tmp_path):
+ env = {"HOME": str(tmp_path / "home"), "TMPDIR": str(tmp_path / "tmp")}
+ for name in ("HOME", "TMPDIR"):
+ worker_directory(env, name).mkdir(mode=0o700, parents=True)
+ (worker_directory(env, name) / "kept").write_text("", encoding="utf-8")
+ isolated = runner.worker_environment(env, 1)
+ for name in ("HOME", "TMPDIR"):
+ assert isolated[name] == str(worker_directory(env, name))
+ assert (worker_directory(env, name) / "kept").is_file()
+
+
+def test_symlinked_worker_directory_fails_before_scanning(tmp_path):
+ workspace = tmp_path / "workspace"
+ skill(workspace, "skills/a")
+ audit = tmp_path / "audit-tmp"
+ audit.mkdir()
+ (tmp_path / "elsewhere").mkdir(mode=0o700)
+ (audit / "skillevaluator-worker-1").symlink_to(tmp_path / "elsewhere", target_is_directory=True)
+ reports, calls = tmp_path / "reports", []
+ assert runner.run(workspace, reports, {"TMPDIR": str(audit)}, execute=fake_cli([], calls)) == 1
+ assert not calls
+ summary = json.loads((reports / "summary.json").read_text())
+ assert summary["overall_status"] == "error"
+ assert summary["error"] == "Scan worker directories must be private directories owned by this user."
+
+
[email protected]("workers", ["1", "4"])
+def test_unexpected_worker_error_is_a_row_error_and_later_skills_still_run(tmp_path, capsys, workers):
+ workspace = tmp_path / "workspace"
+ for name in ("a", "b", "c"):
+ skill(workspace, f"skills/{name}")
+ reports, calls = tmp_path / "reports", []
+ passing = parallel_cli({"skill-002": (0, payload()), "skill-003": (0, payload())}, calls)
+
+ def execute(argv, **kwargs):
+ if report_dir(Path(argv[argv.index("-o") + 1])) == "skill-001":
+ raise RuntimeError("untrusted worker text")
+ return passing(argv, **kwargs)
+
+ assert runner.run(workspace, reports, {"SCAN_WORKERS": workers}, execute=execute) == 1
+ assert sorted(name for name, _ in calls) == ["skill-002", "skill-003"]
+ rows = json.loads((reports / "summary.json").read_text())["skills"]
+ assert rows[0]["error"] == "Evaluator execution failed unexpectedly; no result is claimed."
+ assert [row["passed"] for row in rows] == [False, True, True]
+ captured = capsys.readouterr()
+ for name in ("a", "b", "c"):
+ assert f'Skill result: "skills/{name}"' in captured.out
+ assert "untrusted worker text" not in captured.out + captured.err
+ assert all("untrusted worker text" not in text for text in scan_outputs(reports).values())
diff --git a/tests/reporting/test_report_redesign.py b/tests/reporting/test_report_redesign.py
index 78d73be6..eb8f2307 100644
--- a/tests/reporting/test_report_redesign.py
+++ b/tests/reporting/test_report_redesign.py
@@ -98,6 +98,23 @@ def test_fix_first_ranks_by_severity_and_lists_each_location_once() -> None:
assert items[-1]["blocking"] is False
+def test_quality_gate_stays_actionable_with_advisory_findings() -> None:
+ quality = ValidationResult(validator_name="QUALITY", validator_description="Quality dimensions")
+ quality.add_finding(_finding("medium", "Optional version missing", "SKILL.md"))
+ reason = "Quality score 98.2/100 is below the required 100/100"
+ quality.fail_gate(reason)
+
+ items = fix_first_for_results([quality], skill_name="demo")
+ assert items[0]["kind"] == "check"
+ assert items[0]["message"] == reason
+ assert items[0]["anchor"].startswith("c-")
+ html = _render([quality])
+ fix_first = html.split('class="fix-first"', 1)[1].split("</section>", 1)[0]
+ assert reason in fix_first
+ assert f'href="#{items[0]["anchor"]}"' in fix_first
+ assert f'id="{items[0]["anchor"]}"' in html
+
+
def test_fix_first_puts_an_unfinished_scan_first_when_incomplete() -> None:
results = _results()
secrets = results[1]