diff --git a/CHANGELOG.md b/CHANGELOG.md index 43c56495e..6088167bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,40 @@ All notable changes to SkillEvaluator are documented in this file. - The all-tier CI bootstrap rejects an unsupported `SKILL_EVAL_ENV_MODE` without first loading the Tier 3 runtime (Harbor), so the rejection is faster; its message and exit code are unchanged. +- The Tier 1 summary line counts every check without complete evidence, + including one whose scanner is not installed, as `N incomplete` instead of + `N didn't run`. The quiet verdict headline uses the same statuses as the + summary row and verdict box: several such checks read `Tier 1: 2 incomplete` + instead of `Tier 1: 2 didn't run`, and a check with a blocking finding beside + an incomplete scan reads `failed`. Incomplete Tier 2 checks, and Tier 3 runs + that the run budget left incomplete, read `was incomplete` or `N incomplete` + instead of `didn't run`; with a fail verdict, such a Tier 3 run reads + `failed`. Under `--block-on-agent-eval`, an `inconclusive` agent evaluation + reads `was incomplete` instead of `failed`. A single check reads + `didn't run` only when none of its scanners ran; when another scanner in the + same check completed, it reads `was incomplete` and the setup item names the + missing scanner. +- The Tier 1 panel lists a check whose only evidence is not applicable (no code + files, no `scripts/` or `tools/` directory, no dependency files, or no + semantic version label) on its `n/a` row, with the first such check's reason, + and the check ticker no longer shows a ✓ for it. When another member of the + same check ran, the row uses the validator's short name instead, so Code Risk + Analysis reads `code` beside a `✓ code-integrity` ticker entry. A skill with no code + and no `scripts/` or `tools/` directory now shows `n/a code, lint`. +- Harness Compatibility records a `harness_profile_evaluation` success detail + when it evaluates at least one skill. The Tier 1 summary counts one more + sub-check (a count of one reads `1 sub-check`), JSON `checks_performed` goes + from 0 to 1 with a matching `legacy.messages` line, the `-r cli` table reads + `1 checks passed` instead of `OK`, and the HTML and Markdown reports show the + detail instead of `All checks passed`. JUnit gains a passing + `harness_profile_evaluation` testcase, which replaces the + `Harness Compatibility` placeholder testcase when the check has no findings. +- When Harness Compatibility has no findings, that success detail counts as + Tier 1 execution evidence: `publication.reasons`, the HTML eligibility + reasons and `BENCHMARK.md` no longer list + `Tier 1 lacks trustworthy execution evidence.`, and `BENCHMARK.md`'s Tier 1 + row no longer blames Harness Compatibility. Publication still needs every + other required check and the Tier 2 and Tier 3 evidence. ### Documentation @@ -281,6 +315,12 @@ All notable changes to SkillEvaluator are documented in this file. or `.git`, such as `webapp-testing` or `.github/skills/`, left no file to scan and the check passed. Only real test and artifact folders and test files inside the skill are skipped now, and the Tier 1 reference says which. +- Partial scanner results retain their actual diagnostics and recorded versions + instead of being described as missing installations. The general console fix + item quotes the first three diagnostics, each shortened to one bounded line, + and counts the rest. If a check has mixed scanner outcomes, its setup item + reads ` incomplete: not installed`, beside any check that + `didn't run`, and analysis diagnostics appear in a separate item. - Git repository-root lookups preserve trailing whitespace in directory names instead of resolving a different path, keeping report links, repository context, and generated-results ignore entries tied to the actual checkout. diff --git a/docs/harness-check.mdx b/docs/harness-check.mdx index b097c108b..eb8b3ef49 100644 --- a/docs/harness-check.mdx +++ b/docs/harness-check.mdx @@ -231,7 +231,7 @@ These are the findings you are most likely to meet: ```text ╭─ Tier 1 · Static & Security ─────────────────────────────────────────────────────╮ │ checks ! harness │ - │ summary 1/1 checks passed │ + │ summary 1/1 checks passed (1 sub-check) │ │ harness 4 not loaded · 1 degraded (see below) │ ╰────────────────────────────────────────────────────────────────── ✓ pass · 0.1s ─╯ ╭─ Harness compatibility ──────────────────────────────────────────────────────────╮ diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.py index dec7384bb..4d6c5254d 100644 --- a/src/skillevaluator/cli.py +++ b/src/skillevaluator/cli.py @@ -2053,8 +2053,11 @@ def _finish_pipeline_view( if len(failed) == 1: only = failed[0] tier_no = (only.metadata.get("gating") or {}).get("tier") - ran = all(scan.removesuffix("-llm") in only.scanners for scan in only.incomplete_scans) - state = ("was incomplete" if ran else "didn't run") if only.is_incomplete else "failed" + from skillevaluator.reporting.console_ui import _scanner_setup_issue + + state = "failed" + if context.result_statuses[id(only)] == "incomplete": + state = "didn't run" if _scanner_setup_issue(only) else "was incomplete" headline = f"{only.validator_name or 'validation'} {state}" + ( f" in Tier {tier_no}" if tier_no is not None else "" ) @@ -2064,10 +2067,10 @@ def _finish_pipeline_view( by_tier.setdefault((result.metadata.get("gating") or {}).get("tier"), []).append(result) parts = [] for tier_no, results in by_tier.items(): - broken = sum(1 for r in results if not r.is_incomplete) + broken = sum(1 for r in results if context.result_statuses[id(r)] != "incomplete") counts = [ f"{broken} failed" if broken else "", - f"{len(results) - broken} didn't run" if broken < len(results) else "", + f"{len(results) - broken} incomplete" if broken < len(results) else "", ] parts.append((f"Tier {tier_no}: " if tier_no is not None else "") + ", ".join(c for c in counts if c)) headline = " · ".join(parts) or "validation failed" diff --git a/src/skillevaluator/reporting/console_ui.py b/src/skillevaluator/reporting/console_ui.py index 9351d35a6..c4931ad9a 100644 --- a/src/skillevaluator/reporting/console_ui.py +++ b/src/skillevaluator/reporting/console_ui.py @@ -917,26 +917,42 @@ def stage_hint_row(label: str, hint: str, *, lead: str = "") -> TierRow: def _scanners_row(results: list[ValidationResult]) -> list[TierRow]: - """The external scanners behind the Tier 1 checks, with their versions or why they did not run.""" - states: dict[str, tuple[str, str]] = {} + """Scanner versions and incomplete evidence, retaining every member's scan state.""" + versions: dict[str, str] = {} + states: dict[str, set[str]] = {} for r in results: if _is_user_skipped(r): if scanner := _CHECK_SCANNERS.get(r.validator_name): - states.setdefault(scanner, ("skipped", MUTED)) + states.setdefault(scanner, set()).add("skipped") continue for scanner, version in r.scanners.items(): - states[scanner] = (version, MUTED) + if scanner == "skillspector" and version == "unknown": + runtime_version = (r.metadata or {}).get("skillspector_version") + if isinstance(runtime_version, str) and runtime_version: + version = runtime_version + if versions.get(scanner, "unknown") == "unknown": + versions[scanner] = version + states.setdefault(scanner, set()).add("ran") + setup = _scanner_setup_diagnostics(r) for scan in r.incomplete_scans: if (scanner := scan.removesuffix("-llm")) in _SCANNER_NAMES: - version = r.scanners.get(scanner) - if not version: - state = "didn't run" + if scan != scanner and scanner in r.scanners: + state = "llm" else: - state = f"{version}, LLM didn't run" if scan != scanner else f"{version}, scan incomplete" - states[scanner] = (state, f"bold {RED}") + state = "missing" if scan in setup else "incomplete" + states.setdefault(scanner, set()).add(state) segments: list[tuple[str, str]] = [] for scanner in [name for name in _SCANNER_NAMES if name in states]: - state, style = states[scanner] + version, observed = versions.get(scanner), states[scanner] + style = f"bold {RED}" + if "incomplete" in observed or ("missing" in observed and version): + state = f"{version}, scan incomplete" if version else "incomplete" + elif "llm" in observed: + state = f"{version}, LLM didn't run" if version else "LLM incomplete" + elif "missing" in observed: + state = "didn't run" + else: + state, style = version or "skipped", MUTED segments += [*([(" · ", FAINT)] if segments else []), (_SCANNER_NAMES[scanner], TEXT), (f" {state}", style)] return [TierRow("scanners", segments)] if segments else [] @@ -948,8 +964,9 @@ def _is_user_skipped(result: ValidationResult) -> bool: def _is_not_applicable(result: ValidationResult) -> bool: """True when a check was recorded as not applicable to the target instead of run.""" - return ( - _is_skipped(result) and not _is_user_skipped(result) and "not applicable" in get_skip_reason(result).casefold() + return not _is_user_skipped(result) and ( + result_execution_status(result) == "not_applicable" + or (_is_skipped(result) and "not applicable" in get_skip_reason(result).casefold()) ) @@ -1208,11 +1225,11 @@ def summarize_tier1( if sub_checks := sum( r.summary.checks_performed for r in results if outcome[id(r)] in {"pass", "fail", "incomplete"} ): - checks_segments.append((f" ({sub_checks} sub-checks)", MUTED)) + checks_segments.append((f" ({sub_checks} sub-check{'s' if sub_checks != 1 else ''})", MUTED)) if count["fail"]: checks_segments += [(" · ", FAINT), (f"{count['fail']} failed", f"bold {RED}")] if count["incomplete"]: - checks_segments += [(" · ", FAINT), (f"{count['incomplete']} didn't run", f"bold {RED}")] + checks_segments += [(" · ", FAINT), (f"{count['incomplete']} incomplete", f"bold {RED}")] if count["skipped"]: checks_segments += [(" · ", FAINT), (f"{count['skipped']} skipped", MUTED)] if warnings: @@ -1224,10 +1241,21 @@ def summarize_tier1( names = ", ".join(dict.fromkeys(_short_name(r.validator_name) for r in user_skipped)) rows.append(TierRow("skipped", [(names, MUTED), (" with --skip, not checked", FAINT)])) if not_applicable: + # A check key names every member of that check, so use it only when no other member ran; otherwise + # the row would list a check that the ticker marks as passed or failed. + ran = {_check_key(r.validator_name) for r in results if not _is_skipped(r)} names = ", ".join( - dict.fromkeys(_check_key(r.validator_name) or _short_name(r.validator_name) for r in not_applicable) + dict.fromkeys( + key if (key := _check_key(r.validator_name)) and key not in ran else _short_name(r.validator_name) + for r in not_applicable + ) + ) + first = not_applicable[0] + reason = _bounded_console_line( + first.success_details[0].message + if first.success_details and not _is_skipped(first) + else get_skip_reason(first) ) - reason = _bounded_console_line(get_skip_reason(not_applicable[0])) rows += [TierRow("n/a", [(names, MUTED)]), TierRow("", [(reason, FAINT)], fit="wrap")] if advisory: @@ -1289,17 +1317,19 @@ def summarize_tier1( items = [item for r in broken for item in _tier1_fixes(r)] items += [item for r in failed for item in _unresolved_reference_fixes(r)] items += [item for r in broken for item in _later_gate_fixes(r)] - setup = [] + setup_diagnostics = [] for r in incomplete: if _only_llm_stages_missing(r) or _unresolved_reference_fixes(r): continue # A rejected scanner report has a concrete error; installation help is misleading. - report_error = next((str(e) for e in r.errors if str(e).endswith("security scan did not complete")), None) + report_error = next((e for e in map(str, r.errors) if e.endswith("security scan did not complete")), None) if set(r.incomplete_scans) == {"skillspector"} and report_error: items.append(FixItem(_short_name(r.validator_name), report_error, ["or skip it: --skip security"])) else: - setup.append(r) - if setup: + setup_diagnostics.append((r, _scanner_setup_diagnostics(r))) + if partial := [r for r, setup in setup_diagnostics if not setup or set(r.incomplete_scans) - setup.keys()]: + items.append(_incomplete_fix(partial)) + if setup := [r for r, diagnostics in setup_diagnostics if diagnostics]: items.append(_setup_fix(setup)) if llm := [r for r in incomplete if _only_llm_stages_missing(r)]: items.append(_llm_fix(llm)) @@ -1368,30 +1398,109 @@ def _tier1_fix(result: ValidationResult, problem: str = "") -> FixItem: _DOWNLOAD_FAILED = re.compile(r"couldn't (?:download|set up) .+? \((?:[^()]|\([^()]*\))*\)") +_SETUP_SCANNER = re.compile( + r"(?P[\w-]+) (?:not installed|(?:binary )?not found in PATH)\b" + r"|couldn't (?:download|set up) (?P[\w-]+)\b", + re.IGNORECASE, +) +# A file label such as ``pyproject.toml: ``; ``[^\s:]`` keeps the match linear. +_FILE_LABEL = re.compile(r"[^\s:]+: ") + + +def _scanner_setup_diagnostics(result: ValidationResult) -> dict[str, list[str]]: + """Attribute explicit setup diagnostics to the scan they prevented.""" + scans = set(result.incomplete_scans) + if not scans: + return {} + diagnostics: dict[str, list[str]] = {} + for text in map(str, [*result.independent_warnings(), *result.independent_errors()]): + # Merged results can have several bracketed labels. Consume each + # delimiter once and retain the original diagnostic for display. + start = 0 + while text.startswith("[", start): + end = text.find("] ", start + 1) + if end < 0 or text.find("\n", start, end) >= 0: + break + start = end + 2 + if (label := _FILE_LABEL.match(text, start)) and "." in label.group(0): + start = label.end() + if match := _SETUP_SCANNER.match(text, start): + scanner = (match["missing"] or match["download"]).lower() + scan = scanner if scanner in scans else f"{scanner}-llm" + if scan in scans: + diagnostics.setdefault(scan, []).append(text) + return diagnostics + + +def _scanner_setup_issue(result: ValidationResult) -> bool: + """True when setup issues prevented the entire check from running.""" + return ( + bool(result.incomplete_scans) + and not result.scanners + and set(result.incomplete_scans) == _scanner_setup_diagnostics(result).keys() + ) + + +_INCOMPLETE_DIAGNOSTICS_SHOWN = 3 + + +def _analysis_diagnostics(result: ValidationResult) -> list[str]: + setup = _scanner_setup_diagnostics(result) + setup_messages = {message for messages in setup.values() for message in messages} + for messages in (result.gate_failures, result.independent_errors(), result.independent_warnings()): + if diagnostics := [str(message) for message in messages if str(message) not in setup_messages]: + return diagnostics + scans = ", ".join(scan for scan in result.incomplete_scans if scan not in setup) + return [f"{scans} did not produce complete evidence"] + + +def _incomplete_fix(results: list[ValidationResult]) -> FixItem: + """Keep partial, malformed and failed analyses separate from installation failures. + + Some checks report one diagnostic per scanned item, so the item quotes only the first few, + each bounded, and counts the rest; the detailed reports keep every diagnostic. + """ + checks = ", ".join(dict.fromkeys(_short_name(r.validator_name) for r in results)) + diagnostics = list(dict.fromkeys(message for result in results for message in _analysis_diagnostics(result))) + shown = [ + _bounded_console_line(message, limit=_FIX_TEXT_LIMIT) for message in diagnostics[:_INCOMPLETE_DIAGNOSTICS_SHOWN] + ] + more = len(diagnostics) - len(shown) + return FixItem( + "scan", + f"{checks} incomplete: {'; '.join(shown)}" + (f"; and {more} more" if more else ""), + ["resolve the reported scanner or input issues, then rerun; see detailed reports for full diagnostics"], + ) def _setup_fix(results: list[ValidationResult]) -> FixItem: - """One item for checks that could not run because a scanner is missing or failed to download.""" - scanners = list(dict.fromkeys(name for r in results for name in r.incomplete_scans)) + """One item for checks with a scanner that is missing or failed to download.""" + setup = [(result, _scanner_setup_diagnostics(result)) for result in results] + scanners = list(dict.fromkeys(scan for _, diagnostics in setup for scan in diagnostics)) hints: list[str] = [] failed_downloads: list[str] = [] - for r in results: - for text in map(str, [*r.warnings, *r.errors]): + for _, diagnostics in setup: + for text in (message for messages in diagnostics.values() for message in messages): if (download := _DOWNLOAD_FAILED.search(text)) and download.group(0) not in failed_downloads: failed_downloads.append(download.group(0)) match = _INSTALL_HINT.search(text) if match and match.group(1) not in hints: hints.append(match.group(1)) - checks = ", ".join(dict.fromkeys(_short_name(r.validator_name) for r in results)) + # The subject names checks; a check whose other scanners ran is incomplete, not unrun. + states: dict[str, list[str]] = {"didn't run": [], "incomplete": []} + for result, _ in setup: + state = "didn't run" if _scanner_setup_issue(result) else "incomplete" + states[state].append(_short_name(result.validator_name)) + checks = ", ".join(f"{', '.join(dict.fromkeys(names))} {state}" for state, names in states.items() if names) skip = ",".join(dict.fromkeys(_skip_name(r.validator_name) for r in results)) if failed_downloads: hosts = "github.com and pypi.org" if any("set up" in d for d in failed_downloads) else "github.com" actions = [f"check network access to {hosts}, then rerun"] actions += [f"or install it yourself: {hint}" for hint in hints] - problem = f"{checks} didn't run: {'; '.join(failed_downloads)}" + problem = f"{checks}: {'; '.join(failed_downloads)}" else: actions = list(hints) - problem = f"{checks} didn't run: {', '.join(scanners) or 'a required scanner'} not installed" + problem = f"{checks}: {', '.join(scanners) or 'a required scanner'} not installed" return FixItem("setup", problem, [*actions, f"or skip it: --skip {skip}"]) diff --git a/src/skillevaluator/validators/harness.py b/src/skillevaluator/validators/harness.py index 713a94b25..9c95fb51e 100644 --- a/src/skillevaluator/validators/harness.py +++ b/src/skillevaluator/validators/harness.py @@ -61,4 +61,15 @@ def validate(self, skill_path: Path) -> ValidationResult: ) ) result.metadata[HARNESS_METADATA_KEY] = block + harnesses = [row["harness"] for row in next(iter(block.values()), [])] + if harnesses: + evaluations = sum(len(rows) for rows in block.values()) + result.add_success( + "harness_profile_evaluation", + f"Completed {evaluations} harness profile evaluation(s) across {len(block)} skill(s).", + harnesses=harnesses, + profiles_evaluated=len(harnesses), + skills_evaluated=len(block), + evaluations_performed=evaluations, + ) return result diff --git a/tests/harness/test_execution_evidence.py b/tests/harness/test_execution_evidence.py new file mode 100644 index 000000000..4b6725716 --- /dev/null +++ b/tests/harness/test_execution_evidence.py @@ -0,0 +1,148 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Completed harness evaluations must carry truthful execution evidence.""" + +from pathlib import Path + +import pytest + +from skillevaluator.models.result import ValidationResult +from skillevaluator.publication_evidence import tier1_required_checks +from skillevaluator.reporting.base import assess_publication, result_has_execution_evidence +from skillevaluator.tier1.commands import _as_result, run_validation +from skillevaluator.validators.harness import HarnessValidator + + +@pytest.fixture +def clean_profiles(tmp_path: Path) -> Path: + profiles = tmp_path / "clean-profiles" + profiles.mkdir() + (profiles / "clean-fixture.yaml").write_text( + "harness: clean-fixture\n" + "listing: {cut: 1024}\n" + "rules:\n" + " - id: FIXTURE-DESCRIPTION\n" + " when: description_missing\n" + " effect: not_loaded\n" + " message: A description is required.\n", + encoding="utf-8", + ) + return profiles + + +def _skill(root: Path) -> Path: + skill = root / "demo" + skill.mkdir(parents=True) + (skill / "SKILL.md").write_text( + "---\nname: demo\ndescription: Use when reviewing a project.\nlicense: MIT\n" + "metadata:\n author: Demo Author\n---\n# Demo\n\n## Instructions\n\nRead the project.\n" + "\n## Examples\n\nExplain its workflow.\n", + encoding="utf-8", + ) + return skill + + +def test_clean_harness_records_completed_profile_evaluations(tmp_path: Path, clean_profiles: Path) -> None: + skill = _skill(tmp_path) + + result = HarnessValidator(profiles_dir=clean_profiles).validate(skill) + + assert result.findings == [] + assert result_has_execution_evidence(result) + detail = result.success_details[0] + assert detail.check_name == "harness_profile_evaluation" + assert detail.metadata == { + "harnesses": ["clean-fixture"], + "profiles_evaluated": 1, + "skills_evaluated": 1, + "evaluations_performed": 1, + } + + +def test_completed_harness_evidence_keeps_advisory_findings(tmp_path: Path) -> None: + skill = _skill(tmp_path / ".claude" / "skills") + + result = HarnessValidator("claude-code,codex").validate(skill) + + assert any(finding.check_name == "CX-ROOT" for finding in result.findings) + assert result.success_details[0].metadata["harnesses"] == ["claude-code", "codex"] + assert result.success_details[0].metadata["evaluations_performed"] == 2 + assert {row["harness"]: row["status"] for row in result.metadata["harness_compatibility"][str(skill)]} == { + "claude-code": "loads", + "codex": "not_loaded", + } + + +@pytest.mark.parametrize("missing", [False, True], ids=["empty-directory", "missing-target"]) +def test_no_skills_does_not_claim_completed_harness_evaluations(tmp_path: Path, missing: bool) -> None: + target = tmp_path / "missing" if missing else tmp_path + + result = HarnessValidator().validate(target) + + assert result.success_details == [] + assert not result_has_execution_evidence(result) + + +def test_no_profiles_does_not_claim_completed_harness_evaluations(tmp_path: Path) -> None: + skill = _skill(tmp_path) + profiles = tmp_path / "profiles" + profiles.mkdir() + + result = HarnessValidator(profiles_dir=profiles).validate(skill) + + assert result.success_details == [] + assert not result_has_execution_evidence(result) + + +@pytest.mark.parametrize("actual_harness", [True, False], ids=["completed-harness", "empty-harness"]) +def test_harness_publication_requires_actual_execution_evidence( + tmp_path: Path, actual_harness: bool, clean_profiles: Path +) -> None: + skill = _skill(tmp_path) + + def successful(_target: Path) -> ValidationResult: + result = ValidationResult() + result.add_success("completed", "Required check completed") + return result + + required = [ + _as_result(check, check, successful, skill, publication_check_id=check) + for check in sorted(tier1_required_checks(skill_like=True)) + ] + for result in required: + result.metadata["benchmark_policy"] = {"tier2_required": False, "tier3_required": False} + assert assess_publication(required, expected_skill_name="demo").status == "pass" + + if actual_harness: + harness = run_validation( + skill, checks="harness", harness_profiles=clean_profiles, on_check=lambda _check: None + )[0] + assert harness.findings == [] + assert harness.success_details[0].metadata["harnesses"] == ["clean-fixture"] + assert harness.success_details[0].metadata["evaluations_performed"] == 1 + else: + harness = _as_result( + "Harness Compatibility", + "Harness", + lambda _target: ValidationResult(), + skill, + publication_check_id="harness", + ) + harness.metadata["benchmark_policy"] = {"tier2_required": False, "tier3_required": False} + assessment = assess_publication([*required, harness], expected_skill_name="demo") + + assert assessment.status == ("pass" if actual_harness else "incomplete") + assert assessment.reasons == (() if actual_harness else ("Tier 1 lacks trustworthy execution evidence.",)) + + +def test_harness_only_summary_counts_its_single_sub_check(tmp_path: Path, clean_profiles: Path) -> None: + from skillevaluator.reporting.console_ui import summarize_tier1 + + results = run_validation( + _skill(tmp_path), checks="harness", harness_profiles=clean_profiles, on_check=lambda _check: None + ) + + _passed, rows = summarize_tier1(results, lineup=["harness"]) + summary = next("".join(chunk for chunk, _ in row.segments) for row in rows if row.label == "summary") + + assert summary == "1/1 checks passed (1 sub-check)" diff --git a/tests/reporting/test_incomplete_scanner_console.py b/tests/reporting/test_incomplete_scanner_console.py new file mode 100644 index 000000000..5d9881a0a --- /dev/null +++ b/tests/reporting/test_incomplete_scanner_console.py @@ -0,0 +1,376 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Incomplete scanner evidence must not be diagnosed as a missing installation. + +The Tier 1 panel also lists checks with not-applicable evidence apart from the checks that ran. +""" + +import io + +import pytest +from rich.console import Console + +from skillevaluator.models.result import Finding, Severity, ValidationResult +from skillevaluator.reporting.console_ui import ValidateView, summarize_tier1 + + +def _text(rows): + return "\n".join("".join(chunk for chunk, _ in row.segments) for row in rows) + + +def _headline(tmp_path, results): + """The quiet-mode verdict text for blocking *results*.""" + from skillevaluator.cli import _finish_pipeline_view + + stream = io.StringIO() + view = ValidateView("demo", [(1, "Static", "static")], console=Console(file=stream, width=180, color_system=None)) + _finish_pipeline_view( + view, + tier_gate_results=results, + tier3_result=None, + gate_failed=True, + output_dir=tmp_path, + basename="partial", + report_formats=(), + target_path=tmp_path, + agent_eval=False, + ) + return stream.getvalue() + + +@pytest.mark.parametrize( + ("diagnostic", "gate", "runtime_version"), + [ + ( + "skillspector JSON field 'analysis_completeness.analyzer_statuses' has a status that contradicts " + "its work accounting; security scan did not complete", + False, + None, + ), + ( + "skillspector reports incomplete analysis (status 'partial'): SKILL.md:4 " + "[reference_resolution; reference_unresolved]; and 11 more. Missing references require " + "a standalone target with complete, matching reference and scan evidence.", + True, + "2.11.2", + ), + ], +) +def test_partial_analysis_keeps_its_diagnostic_and_version(diagnostic, gate, runtime_version): + # An incomplete marker is not evidence that the installed scanner never ran. + result = ValidationResult(validator_name="Security Scan") + result.record_scanner("skillspector", None if runtime_version else "2.11.2") + if runtime_version: + result.metadata["skillspector_version"] = runtime_version + result.mark_scan_incomplete("skillspector") + if gate: + result.fail_gate(diagnostic) + else: + result.add_error(diagnostic) + result.add_finding(Finding("SECURITY", Severity.MEDIUM, "rug-pull", "Advisory issue", "SKILL.md")) + + passed, rows = summarize_tier1([result], lineup=["security"]) + text = _text(rows) + + assert not passed + assert diagnostic in text + assert "SkillSpector 2.11.2, scan incomplete" in text + assert "0/1 checks passed · 1 incomplete" in text + assert "not installed" not in text + assert "didn't run" not in text + if gate: + assert "security incomplete:" in text + assert "rerun" in text + assert "--skip" not in text + else: + assert "or skip it: --skip security" in text + assert "security incomplete:" not in text + + +@pytest.mark.parametrize("diagnostic", [None, "skillspector timed out after 300 seconds; partial results only"]) +def test_unrecorded_scanner_version_does_not_imply_an_installation_failure(diagnostic): + result = ValidationResult(validator_name="Security Scan") + result.mark_scan_incomplete("skillspector") + if diagnostic: + result.add_error(diagnostic) + + _passed, rows = summarize_tier1([result]) + text = _text(rows) + + assert "SkillSpector incomplete" in text + assert (diagnostic or "skillspector did not produce complete evidence") in text + assert "not installed" not in text + assert "didn't run" not in text + assert "--skip" not in text + + +def test_partial_analysis_and_missing_scanner_keep_their_separate_recoveries(): + security = ValidationResult(validator_name="Security Scan") + security.record_scanner("skillspector", "2.11.2") + security.mark_scan_incomplete("skillspector") + security.fail_gate("skillspector reports incomplete analysis: reference_unresolved at SKILL.md:4") + secrets = ValidationResult(validator_name="Secrets Detection") + secrets.mark_scan_incomplete("gitleaks") + secrets.add_warning("couldn't download Gitleaks 8.30.0 (connection refused). Install with: brew install gitleaks") + + _passed, rows = summarize_tier1([security, secrets]) + text = _text(rows) + + assert "security incomplete: skillspector reports incomplete analysis: reference_unresolved at SKILL.md:4" in text + assert "secrets didn't run: couldn't download Gitleaks 8.30.0 (connection refused)" in text + assert "check network access to github.com, then rerun" in text + assert "brew install gitleaks" in text + assert "--skip security" not in text + + +@pytest.mark.parametrize("merged", [False, True]) +def test_partial_and_missing_scanners_in_the_same_check_keep_separate_recoveries(tmp_path, merged): + result = ValidationResult(validator_name="Code Risk Analysis", metadata={"gating": {"tier": 1, "blocking": True}}) + evidence = ValidationResult() if merged else result + evidence.record_scanner("bandit", "1.9.4") + evidence.mark_scan_incomplete("bandit") + evidence.add_error("Bandit scan error: syntax error while parsing") + evidence.mark_scan_incomplete("semgrep") + evidence.add_warning("semgrep not installed. Install with: uv tool install semgrep") + if merged: + result.merge_with_prefix(evidence, "demo") + + _passed, rows = summarize_tier1([result], lineup=["code-integrity"]) + text = _text(rows) + + assert "Bandit 1.9.4, scan incomplete · Semgrep didn't run" in text + assert "code incomplete:" in text + assert "Bandit scan error: syntax error while parsing" in text + assert "code incomplete: semgrep not installed" in text + assert "bandit, semgrep not installed" not in text + assert "code didn't run" not in text + assert "uv tool install semgrep" in text + assert "Code Risk Analysis was incomplete in Tier 1" in _headline(tmp_path, [result]) + + +def test_setup_item_names_each_check_with_its_own_state(): + security = _missing_skillspector() + code = ValidationResult(validator_name="Code Risk Analysis") + code.record_scanner("semgrep", "1.150.0") + code.mark_scan_incomplete("bandit") + code.add_warning("bandit not installed. Install with: pipx install bandit") + + _passed, rows = summarize_tier1([security, code], lineup=["security", "code-integrity"]) + text = _text(rows) + + assert "security didn't run, code incomplete: skillspector, bandit not installed" in text + assert "or skip it: --skip security,code-integrity" in text + assert "code incomplete: Bandit" not in text + + +def test_missing_dependency_auditor_after_a_file_label_reads_as_setup(tmp_path, monkeypatch): + from skillevaluator.utils.tool_runner import Tools + from skillevaluator.validators.dependencies import DependencySecurityValidator + + monkeypatch.setattr(type(Tools.pip_audit), "is_available", property(lambda _self: False)) + (tmp_path / "pyproject.toml").write_text('[project]\nname = "demo"\ndependencies = ["idna==3.10"]\n') + result = DependencySecurityValidator(use_safety=False).validate(tmp_path) + result.validator_name = "Dependency Vulnerability Audit" + result.metadata["gating"] = {"tier": 1, "blocking": True} + assert any(str(w).startswith("pyproject.toml: pip-audit not installed") for w in result.independent_warnings()) + + _passed, rows = summarize_tier1([result], lineup=["dependency"]) + text = _text(rows) + + assert "dependency vulnerability audit didn't run: pip-audit not installed" in text + assert "or skip it: --skip dependency" in text + assert "incomplete: pyproject.toml" not in text + assert "Dependency Vulnerability Audit didn't run in Tier 1" in _headline(tmp_path, [result]) + + +@pytest.mark.parametrize( + ("last_label", "diagnostic", "scanner_row"), + [ + ("", "semgrep not installed.", "Semgrep didn't run"), + ("", "pyproject.toml: semgrep not installed.", "Semgrep didn't run"), + ("", "Semgrep scan: semgrep not installed.", "Semgrep incomplete"), + ("", "Semgrep scan error: dependency not installed.", "Semgrep incomplete"), + ("[invalid\nlabel] ", "semgrep not installed.", "Semgrep incomplete"), + ], +) +def test_scanner_setup_diagnostics_after_repeated_labels(last_label, diagnostic, scanner_row): + result = ValidationResult(validator_name="Code Risk Analysis") + result.mark_scan_incomplete("semgrep") + result.add_warning("[collection] [member[1]] " * 4096 + last_label + diagnostic) + + _passed, rows = summarize_tier1([result]) + + assert _text([row for row in rows if row.label == "scanners"]) == scanner_row + + +def test_an_advisory_about_a_missing_package_cannot_become_a_scanner_installation_error(): + result = ValidationResult(validator_name="Security Scan") + result.record_scanner("skillspector", "2.11.2") + result.mark_scan_incomplete("skillspector") + result.add_error("skillspector reports partial analysis: reference_unresolved") + result.add_finding(Finding("SECURITY", Severity.MEDIUM, "dependency", "Optional client not installed", "run.py")) + + _passed, rows = summarize_tier1([result]) + text = _text(rows) + + assert "security incomplete: skillspector reports partial analysis: reference_unresolved" in text + assert "skillspector not installed" not in text + assert "--skip security" not in text + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_completed_member_cannot_hide_an_incomplete_scanner_run(reverse): + partial = ValidationResult(validator_name="Security Scan") + partial.record_scanner("skillspector", None) + partial.mark_scan_incomplete("skillspector") + partial.add_error("skillspector returned malformed analysis accounting") + complete = ValidationResult(validator_name="Security Scan") + complete.record_scanner("skillspector", "2.11.2") + results = [partial, complete] + + _passed, rows = summarize_tier1(results[::-1] if reverse else results) + scanner = next(row for row in rows if row.label == "scanners") + + assert _text([scanner]) == "SkillSpector 2.11.2, scan incomplete" + + +@pytest.mark.parametrize("count", [1, 2]) +@pytest.mark.parametrize("blocking", [False, True]) +def test_final_verdict_distinguishes_incomplete_scans_from_known_failures(tmp_path, count, blocking): + results = [] + for _ in range(count): + result = ValidationResult(validator_name="Security Scan", metadata={"gating": {"tier": 1, "blocking": True}}) + result.record_scanner("skillspector", "2.11.2") + result.mark_scan_incomplete("skillspector") + result.fail_gate("skillspector reports incomplete analysis: reference_unresolved") + results.append(result) + if blocking: + results[0].add_finding(Finding("SECURITY", Severity.HIGH, "known-risk", "Known risk", "run.py")) + + text = _headline(tmp_path, results) + + if count == 1: + assert f"Security Scan {'failed' if blocking else 'was incomplete'} in Tier 1" in text + else: + assert ("Tier 1: 1 failed, 1 incomplete" if blocking else "Tier 1: 2 incomplete") in text + assert "didn't run" not in text + + +def _missing_skillspector(): + result = ValidationResult(validator_name="Security Scan", metadata={"gating": {"tier": 1, "blocking": True}}) + result.add_warning("skillspector not installed - skipping security scan. Install with: pipx install skillspector") + result.mark_scan_incomplete("skillspector") + return result + + +def _agent_eval(verdict, *, run_budget=False): + result = ValidationResult( + validator_name="AGENT_EVAL", + passed=False, + metadata={"gating": {"tier": 3, "blocking": True}, "agent_eval": {"verdict": verdict}}, + ) + if run_budget: + result.mark_scan_incomplete("Tier 3 run budget") + return result + + +def _context_dedup(): + result = ValidationResult(validator_name="Context Deduplication", metadata={"gating": {"tier": 2}}) + result.mark_scan_incomplete("embedding-provider") + return result + + +@pytest.mark.parametrize( + ("make", "count", "headline"), + [ + (_missing_skillspector, 1, "Security Scan didn't run in Tier 1"), + (_missing_skillspector, 2, "Tier 1: 2 incomplete"), + (lambda: _agent_eval("inconclusive"), 1, "AGENT_EVAL was incomplete in Tier 3"), + (lambda: _agent_eval("inconclusive", run_budget=True), 1, "AGENT_EVAL was incomplete in Tier 3"), + (lambda: _agent_eval("fail", run_budget=True), 1, "AGENT_EVAL failed in Tier 3"), + (_context_dedup, 1, "Context Deduplication was incomplete in Tier 2"), + (_context_dedup, 2, "Tier 2: 2 incomplete"), + ], + ids=[ + "missing-install", + "two-missing-installs", + "inconclusive-agent-eval", + "run-budget-inconclusive", + "run-budget-fail", + "tier2-provider-error", + "two-tier2-provider-errors", + ], +) +def test_final_verdict_keeps_setup_issues_apart_from_incomplete_and_failed_checks(tmp_path, make, count, headline): + text = _headline(tmp_path, [make() for _ in range(count)]) + + assert headline in text + for other in ("didn't run", "was incomplete", "failed in"): + if other not in headline: + assert other not in text + + +def test_incomplete_fix_quotes_only_the_first_bounded_diagnostics(): + # The dependency audit reports one warning per loosely pinned requirement, so there can be thousands. + result = ValidationResult(validator_name="Dependency Vulnerability Audit") + result.mark_scan_incomplete("pip-audit") + result.add_warning("requirements.txt: " + "a" * 2000) + for line in range(2, 201): + result.add_warning(f"requirements.txt: line {line} requires an exact package version") + + _passed, rows = summarize_tier1([result]) + item = next(row for row in rows if row.label == "scan") + problem = _text([item]) + + assert problem.startswith("dependency vulnerability audit incomplete: requirements.txt: aaa") + assert "a" * 300 not in problem + assert "…; requirements.txt: line 2 requires" in problem + assert "line 3 requires an exact package version; and 197 more" in problem + assert "line 4 requires" not in problem + assert len(problem) < 700 + assert "see detailed reports for full diagnostics" in _text(rows) + + +def test_incomplete_fix_counts_diagnostics_with_a_common_truncated_prefix(): + result = ValidationResult(validator_name="Dependency Vulnerability Audit") + result.mark_scan_incomplete("pip-audit") + prefix = "pyproject.toml: " + "a" * 2000 + for declaration in (1, 2, 2, 3, 4): + result.add_warning(f"{prefix}: declaration {declaration} requires an exact pin") + + _passed, rows = summarize_tier1([result]) + problem = _text([row for row in rows if row.label == "scan"]) + + assert problem.count("pyproject.toml:") == 3 + assert problem.endswith("; and 1 more") + + +def _not_applicable(validator_name, check, message): + result = ValidationResult(validator_name=validator_name) + result.add_success(check, message) + return result + + +@pytest.mark.parametrize("hygiene_ran", [False, True]) +def test_not_applicable_row_never_names_a_check_the_ticker_shows_as_run(hygiene_ran): + code_risk = _not_applicable( + "Code Risk Analysis", "code_file_discovery", "No code files found - code risk analysis is not applicable" + ) + lint = _not_applicable("SCRIPT_LINT", "lint", "No scripts/ or tools/ directory found") + schema = ValidationResult(validator_name="Schema & Repository Governance") + schema.add_success("frontmatter", "Frontmatter is valid") + results = [code_risk, lint, schema] + if hygiene_ran: + hygiene = ValidationResult(validator_name="Code Integrity & Hygiene") + hygiene.add_success("hygiene", "No hygiene issues found") + results.append(hygiene) + + _passed, rows = summarize_tier1(results, lineup=["code-integrity", "lint", "schema"]) + labels = [row.label for row in rows] + texts = [_text([row]) for row in rows] + not_applicable = labels.index("n/a") + + assert texts[not_applicable] == ("code, lint" if hygiene_ran else "code-integrity, lint") + assert texts[not_applicable + 1] == "No code files found - code risk analysis is not applicable" + ticker = texts[labels.index("checks")] + assert ticker == ("✓ code-integrity" if hygiene_ran else "code-integrity") + " · lint · ✓ schema" + assert f"{2 if hygiene_ran else 1}/{2 if hygiene_ran else 1} checks passed" in texts[labels.index("summary")] diff --git a/tests/reporting/test_tier3_validate_cases.py b/tests/reporting/test_tier3_validate_cases.py index 81f68cc21..431d3ac99 100644 --- a/tests/reporting/test_tier3_validate_cases.py +++ b/tests/reporting/test_tier3_validate_cases.py @@ -133,7 +133,7 @@ def test_fix_section_for_tier1_and_tier2(): clean = ValidationResult(validator_name="Version Check", passed=True) _ok, rows = summarize_tier1([schema, secrets, clean]) text = _text(rows) - assert "1/3 checks passed · 1 failed · 1 didn't run" in text + assert "1/3 checks passed · 1 failed · 1 incomplete" in text assert "Author not specified in metadata\n" + " " * 12 + "→ Add 'metadata.author'" in text assert "secrets didn't run: gitleaks not installed\n" + " " * 12 + "→ brew install gitleaks" in text assert [r.label for r in rows if r.glyph in {"1", "2"}][1] == "setup" @@ -432,8 +432,14 @@ def test_llm_scan_that_never_started_gets_the_scanner_fix_not_a_provider_fix(mon assert result.incomplete_scans == ["skillspector-llm"] assert "skillspector" not in result.scanners text = _text(summarize_tier1([result])[1]) - assert "security didn't run" in text - assert "→ or skip it: --skip security" in text + if how == "bad-baseline": + assert "security incomplete:" in text + assert "baseline" in text + assert "not installed" not in text + assert "--skip security" not in text + else: + assert "security didn't run" in text + assert "→ or skip it: --skip security" in text for provider_advice in ("LLM review", "No provider is configured", "provider call failed", "doctor --tier 2"): assert provider_advice not in text @@ -541,6 +547,10 @@ def test_scanners_row_keeps_the_version_when_only_the_llm_stage_failed(): assert not _only_llm_stages_missing(security) assert "SkillSpector 2.13.3, scan incomplete" in _text(_scanners_row([security])) security.metadata["scanners"] = {} + text = _text(_scanners_row([security])) + assert "SkillSpector incomplete" in text + assert "didn't run" not in text + security.add_error("SkillSpector not installed") assert "SkillSpector didn't run" in _text(_scanners_row([security])) @@ -633,7 +643,7 @@ def test_tier1_summary_counts_validators_and_their_sub_checks(): secrets.errors.append("leaked token") results.append(secrets) _ok, rows = summarize_tier1(results, lineup=["code-integrity", "schema", "security"]) - assert "2/4 checks passed (13 sub-checks) · 1 failed · 1 didn't run" in _text(rows) + assert "2/4 checks passed (13 sub-checks) · 1 failed · 1 incomplete" in _text(rows) def test_live_view_draws_the_header_and_finished_tiers_once(monkeypatch): @@ -677,7 +687,7 @@ def test_tier1_summary_row_agrees_with_the_verdict_line(): assert (tier.passed, tier.failed, tier.incomplete, tier.skipped, tier.not_applicable) == (1, 1, 1, 1, 1) text = _text(summarize_tier1(results, lineup=["schema", "version", "unicode"])[1]) assert f"{tier.passed}/{tier.executed} checks passed" in text - assert f"{tier.failed} failed · {tier.incomplete} didn't run · {tier.skipped} skipped" in text + assert f"{tier.failed} failed · {tier.incomplete} incomplete · {tier.skipped} skipped" in text assert tier.summary.startswith(f"{tier.passed} of {tier.executed} checks passed; {tier.failed} failed, ") diff --git a/tests/test_harbor_runner_status.py b/tests/test_harbor_runner_status.py index 95ae948ce..c4528a2d3 100644 --- a/tests/test_harbor_runner_status.py +++ b/tests/test_harbor_runner_status.py @@ -692,11 +692,17 @@ def launch_when_ready(command: list[str], **kwargs: object) -> subprocess.Popen[ # the assertion checks the original process even if its PID is reused. deadline = time.monotonic() + 10 try: - while not ready_path.is_file(): - if process.poll() is not None or time.monotonic() >= deadline: - raise RuntimeError("Windows process-tree fixture did not become ready") - time.sleep(0.01) - parent_pid, child_pid = map(int, ready_path.read_text(encoding="ascii").split()) + while True: + try: + process_ids = ready_path.read_text(encoding="ascii") + except (FileNotFoundError, PermissionError) as exc: + # The renamed file can be visible before Windows lets us open it. + if process.poll() is not None or time.monotonic() >= deadline: + raise RuntimeError("Windows process-tree fixture did not become ready") from exc + time.sleep(0.01) + else: + break + parent_pid, child_pid = map(int, process_ids.split()) child_handle = kernel32.OpenProcess(synchronize_and_terminate, False, child_pid) if not child_handle: raise ctypes.WinError(ctypes.get_last_error()) diff --git a/tests/test_model_catalog.py b/tests/test_model_catalog.py index 0df8a4548..5a50827dd 100644 --- a/tests/test_model_catalog.py +++ b/tests/test_model_catalog.py @@ -856,11 +856,12 @@ def revoke_allowlist(*args, **kwargs): thread.start() try: config = _provider("openai-compatible", base_url=f"http://gateway.test:{catalog.server_port}/v1") + # Use the normal bounded catalog timeout for the live loopback request. if revoke_before_policy_check: with pytest.raises(ModelCatalogError, match="plain HTTP is no longer authorized"): - fetch_model_records(config, timeout_seconds=1.0) + fetch_model_records(config) else: - assert fetch_model_records(config, timeout_seconds=1.0) == (ModelRecord("model-a"),) + assert fetch_model_records(config) == (ModelRecord("model-a"),) finally: catalog.shutdown() proxy.shutdown() diff --git a/tests/test_skip_checks.py b/tests/test_skip_checks.py index 1d5d7773f..ea5bd1ce4 100644 --- a/tests/test_skip_checks.py +++ b/tests/test_skip_checks.py @@ -119,7 +119,7 @@ def test_tier1_summary_names_scanners_and_versions(): _ok, rows = summarize_tier1([security, code_risk, secrets]) row = next(row for row in rows if row.label == "scanners") assert "".join(seg for seg, _style in row.segments) == ( - "SkillSpector 2.13.3 · Bandit 1.9.4 · Semgrep unknown · Gitleaks didn't run" + "SkillSpector 2.13.3 · Bandit 1.9.4 · Semgrep unknown · Gitleaks incomplete" ) assert code_risk.to_dict()["scanners"] == {"bandit": "1.9.4", "semgrep": "unknown"}