From 30e2ef0b18204b7856c4a317972e1898387254b6 Mon Sep 17 00:00:00 2001 From: Rod Boev Date: Fri, 2 Oct 2026 19:31:42 -0400 Subject: [PATCH 1/3] feat(cli): add --min-coverage threshold Signed-off-by: Rod Boev --- docs/ANALYSIS_RESOURCE_BOUNDS.md | 2 + src/skillspector/cli.py | 51 ++++- tests/unit/test_cli.py | 308 ++++++++++++++++++++++++++++++- 3 files changed, 358 insertions(+), 3 deletions(-) diff --git a/docs/ANALYSIS_RESOURCE_BOUNDS.md b/docs/ANALYSIS_RESOURCE_BOUNDS.md index fdea2c8fd3..feeaff4e7a 100644 --- a/docs/ANALYSIS_RESOURCE_BOUNDS.md +++ b/docs/ANALYSIS_RESOURCE_BOUNDS.md @@ -269,6 +269,8 @@ When relevant analysis is incomplete: - `skillspector scan --fail-on-incomplete` exits with status 1. Without this option, the CLI retains its compatibility behavior and still applies its ordinary risk-score exit policy. Execution failures exit with status 2. +- `skillspector scan --min-coverage PERCENT` exits with status 1 when canonical coverage is below + `PERCENT`; equality passes and recursive scans evaluate each child. - MCP responses set `safe_to_install` to `false` when analysis is incomplete, any relevant file is entirely uninspected, execution failed, or the risk score exceeds the installation threshold. diff --git a/src/skillspector/cli.py b/src/skillspector/cli.py index 8aee2fed96..44b2a1d9c2 100644 --- a/src/skillspector/cli.py +++ b/src/skillspector/cli.py @@ -22,6 +22,7 @@ from __future__ import annotations import json +import math import os import sys import warnings @@ -360,6 +361,26 @@ def _write_result( print(report_body) +def _validate_min_coverage(value: float | None) -> float | None: + """Accept only finite percentage thresholds in the CLI's supported range.""" + if value is not None and (not math.isfinite(value) or not 0 <= value <= 100): + raise typer.BadParameter("must be a finite number between 0 and 100") + return value + + +def _coverage_below_threshold(result: dict[str, object], threshold: float | None) -> bool: + """Compare finalized canonical coverage with the requested threshold.""" + if threshold is None: + return False + completeness = result.get("analysis_completeness") + coverage = completeness.get("coverage_percent") if isinstance(completeness, dict) else None + if isinstance(coverage, bool) or not isinstance(coverage, (int, float)): + return True + if not math.isfinite(coverage): + return True + return coverage < threshold + + def _recursive_json_payload(result: dict[str, object]) -> dict[str, object] | None: """Return parsed report_body when it is valid JSON object text.""" raw_report_body = result.get("report_body") @@ -522,6 +543,14 @@ def scan( help="Exit 1 when relevant analysis is partial or incomplete.", ), ] = False, + min_coverage: Annotated[ + float | None, + typer.Option( + "--min-coverage", + help="Exit 1 when canonical analysis coverage is below this percentage (0-100).", + callback=_validate_min_coverage, + ), + ] = None, fail_on_findings: Annotated[ bool, typer.Option( @@ -588,10 +617,17 @@ def scan( authentication session. """ if mcp_registry: - if recursive or baseline is not None or show_suppressed or yara_rules_dir is not None: + if ( + recursive + or baseline is not None + or show_suppressed + or yara_rules_dir is not None + or min_coverage is not None + ): err_console.print( "[red]Error:[/red] --mcp-registry cannot be combined with " - "--recursive, --baseline, --show-suppressed, or --yara-rules-dir" + "--recursive, --baseline, --show-suppressed, --yara-rules-dir, " + "or --min-coverage" ) raise typer.Exit(code=2) if format != FormatChoice.json: @@ -674,6 +710,7 @@ def scan( verbose=verbose, fail_on_incomplete=fail_on_incomplete, fail_on_findings=fail_on_findings, + min_coverage=min_coverage, ) except typer.Exit: raise @@ -761,6 +798,8 @@ def scan( raise typer.Exit(code=1) if fail_on_findings and effective_findings(result): raise typer.Exit(code=1) + if _coverage_below_threshold(result, min_coverage): + raise typer.Exit(code=1) if (result.get("risk_score") or 0) > RISK_THRESHOLD: raise typer.Exit(code=1) except typer.Exit: @@ -2693,6 +2732,7 @@ def _scan_multi_skill( yara_dir: str | None = None, verbose: bool = False, fail_on_incomplete: bool = False, + min_coverage: float | None = None, fail_on_findings: bool = False, **legacy_kwargs: object, ) -> None: @@ -2735,6 +2775,7 @@ def _scan_multi_skill( complete_skill_count = 0 partial_skill_count = 0 failed_skill_count = 0 + coverage_failed = False for i, skill in enumerate(skills, 1): if i > _MULTI_SKILL_MAX_SKILLS: @@ -2781,6 +2822,8 @@ def _scan_multi_skill( source_local_only=skill.local_only, ) child_failed = result.get("execution_successful") is False + if not child_failed and _coverage_below_threshold(result, min_coverage): + coverage_failed = True completeness_value = result.get("analysis_completeness") child_partial = ( not child_failed @@ -2886,6 +2929,8 @@ def _scan_multi_skill( aggregate_limitations.append( f"{unscanned_skill_count} recursive skill(s) unscanned after an aggregate limit" ) + if min_coverage is not None and min_coverage > 0: + coverage_failed = True aggregate_limitations = list(dict.fromkeys(aggregate_limitations))[:256] aggregate_completeness = _multi_skill_analysis_completeness( total_skills=len(skills) + omitted_symlink_entry_count, @@ -3122,6 +3167,8 @@ def _scan_multi_skill( raise typer.Exit(code=1) if fail_on_findings and has_findings: raise typer.Exit(code=1) + if coverage_failed: + raise typer.Exit(code=1) if max_score > RISK_THRESHOLD: raise typer.Exit(code=1) diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index 2bcb85b112..f25d854c03 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -349,6 +349,150 @@ def test_cli_fail_on_incomplete_exits_one_after_writing_report( assert output.exists() +@pytest.mark.parametrize( + ("coverage", "threshold", "exit_code"), + [(86.9, 87.0, 1), (87.0, 87.0, 0)], +) +def test_cli_min_coverage_uses_strict_boundary_and_writes_report( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + coverage: float, + threshold: float, + exit_code: int, +) -> None: + (tmp_path / "SKILL.md").write_text("# Safe", encoding="utf-8") + output = tmp_path / "report.json" + monkeypatch.setattr( + "skillspector.cli.graph.invoke", + lambda state, config: { + "report_body": json.dumps({"analysis_completeness": {"coverage_percent": coverage}}), + "execution_successful": True, + "analysis_completeness": {"coverage_percent": coverage}, + "risk_score": 0, + }, + ) + result = runner.invoke( + app, + [ + "scan", + str(tmp_path), + "-f", + "json", + "-o", + str(output), + "--min-coverage", + str(threshold), + ], + ) + assert result.exit_code == exit_code + assert json.loads(output.read_text())["analysis_completeness"]["coverage_percent"] == coverage + + +@pytest.mark.parametrize( + ("analysis_completeness", "threshold"), + [ + (None, 87), + ({"coverage_percent": None}, 87), + ({"coverage_percent": "unknown"}, 87), + ({"coverage_percent": True}, 0), + ({"coverage_percent": float("nan")}, 0), + ({"coverage_percent": float("inf")}, 0), + ], + ids=["missing", "null", "non-numeric", "boolean", "nan", "infinity"], +) +def test_cli_min_coverage_fails_closed_for_malformed_coverage( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + analysis_completeness: dict[str, object] | None, + threshold: float, +) -> None: + (tmp_path / "SKILL.md").write_text("# Safe", encoding="utf-8") + output = tmp_path / "report.json" + graph_result: dict[str, object] = { + "report_body": json.dumps( + {"analysis_completeness": analysis_completeness} + if analysis_completeness is not None + else {} + ), + "execution_successful": True, + "risk_score": 0, + } + if analysis_completeness is not None: + graph_result["analysis_completeness"] = analysis_completeness + monkeypatch.setattr("skillspector.cli.graph.invoke", lambda state, config: graph_result) + + result = runner.invoke( + app, + [ + "scan", + str(tmp_path), + "-f", + "json", + "-o", + str(output), + "--min-coverage", + str(threshold), + ], + ) + + assert result.exit_code == 1 + assert output.exists() + + +@pytest.mark.parametrize("value", ["-1", "101", "nan", "inf"]) +def test_cli_min_coverage_rejects_invalid_values(tmp_path: Path, value: str) -> None: + (tmp_path / "SKILL.md").write_text("# Safe", encoding="utf-8") + result = runner.invoke(app, ["scan", str(tmp_path), "--min-coverage", value]) + assert result.exit_code == 2 + plain_output = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", result.output) + assert "--min-coverage" in plain_output + + +def test_cli_mcp_registry_rejects_min_coverage(tmp_path: Path) -> None: + payload = tmp_path / "registry.json" + payload.write_text('{"servers": []}', encoding="utf-8") + result = runner.invoke( + app, + ["scan", str(payload), "--mcp-registry", "--min-coverage", "87"], + ) + assert result.exit_code == 2 + assert "--min-coverage" in result.output + + +def test_recursive_min_coverage_checks_each_child_and_writes_report(tmp_path: Path) -> None: + s1 = SkillDirectory(path=tmp_path / "one", name="one", relative_path="one") + s2 = SkillDirectory(path=tmp_path / "two", name="two", relative_path="two") + detection = MultiSkillDetectionResult( + is_multi_skill=True, skills=[s1, s2], has_root_skill=False + ) + output = tmp_path / "combined.json" + with patch( + "skillspector.cli.graph.invoke", + side_effect=[ + { + "report_body": json.dumps({"analysis_completeness": {"coverage_percent": 100}}), + "analysis_completeness": {"coverage_percent": 100}, + "risk_score": 0, + }, + { + "report_body": json.dumps({"analysis_completeness": {"coverage_percent": 80}}), + "analysis_completeness": {"coverage_percent": 80}, + "risk_score": 0, + }, + ], + ): + with pytest.raises(typer.Exit) as exit_info: + _scan_multi_skill( + detection, + FormatChoice.json, + output, + no_llm=True, + min_coverage=87, + ) + assert exit_info.value.exit_code == 1 + assert output.exists() + + def test_cli_fail_on_incomplete_rejects_missing_semantic_telemetry( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: @@ -427,6 +571,168 @@ def test_cli_fail_on_findings_exits_one_below_risk_threshold( assert output.exists() +def test_recursive_min_coverage_passes_when_all_children_meet_threshold( + tmp_path: Path, +) -> None: + skills = [ + SkillDirectory(path=tmp_path / "one", name="one", relative_path="one"), + SkillDirectory(path=tmp_path / "two", name="two", relative_path="two"), + ] + output = tmp_path / "combined.json" + child = { + "report_body": json.dumps({"analysis_completeness": {"coverage_percent": 100}}), + "analysis_completeness": {"coverage_percent": 100}, + "risk_score": 0, + } + with patch("skillspector.cli.graph.invoke", side_effect=[child.copy(), child.copy()]): + _scan_multi_skill( + MultiSkillDetectionResult(is_multi_skill=True, skills=skills, has_root_skill=False), + FormatChoice.json, + output, + no_llm=True, + min_coverage=90, + ) + assert output.exists() + assert ( + json.loads(output.read_text(encoding="utf-8"))["analysis_completeness"]["coverage_percent"] + == 100.0 + ) + + +def test_recursive_min_coverage_fails_when_skills_are_omitted( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + skills = [SkillDirectory(tmp_path / name, name, name) for name in ("one", "two", "three")] + output = tmp_path / "combined.json" + monkeypatch.setattr(cli, "_MULTI_SKILL_MAX_PUBLIC_RECORDS", 1) + monkeypatch.setattr( + cli.graph, "invoke", lambda *_args, **_kwargs: _bounded_recursive_result("one") + ) + + with pytest.raises(typer.Exit) as exit_info: + _scan_multi_skill( + MultiSkillDetectionResult(is_multi_skill=True, skills=skills), + FormatChoice.json, + output, + no_llm=True, + min_coverage=30, + ) + + assert exit_info.value.exit_code == 1 + payload = json.loads(output.read_text(encoding="utf-8")) + assert payload["analysis_completeness"]["coverage_percent"] == pytest.approx(33.33) + assert payload["skills_omitted"] == 2 + assert payload["skills"][-1]["omitted_count"] == 2 + + +def test_recursive_min_coverage_allows_omitted_skills_at_threshold_zero( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + skills = [SkillDirectory(tmp_path / name, name, name) for name in ("one", "two", "three")] + output = tmp_path / "combined.json" + monkeypatch.setattr(cli, "_MULTI_SKILL_MAX_PUBLIC_RECORDS", 1) + monkeypatch.setattr( + cli.graph, "invoke", lambda *_args, **_kwargs: _bounded_recursive_result("one") + ) + + _scan_multi_skill( + MultiSkillDetectionResult(is_multi_skill=True, skills=skills), + FormatChoice.json, + output, + no_llm=True, + min_coverage=0, + ) + + payload = json.loads(output.read_text(encoding="utf-8")) + assert payload["skills_omitted"] == 2 + assert payload["skills"][-1]["omitted_count"] == 2 + + +def test_recursive_min_coverage_ignores_aggregate_completeness_for_partial_children( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + skills = [SkillDirectory(tmp_path / name, name, name) for name in ("one", "two", "three")] + output = tmp_path / "combined.json" + + def partial_result(label: str) -> dict[str, object]: + result = _bounded_recursive_result(label, finding_count=0) + result["analysis_completeness"] = {"is_complete": False, "coverage_percent": 95} + result["report_body"] = json.dumps( + {"analysis_completeness": result["analysis_completeness"]} + ) + return result + + results = iter(partial_result(name) for name in ("one", "two", "three")) + monkeypatch.setattr(cli.graph, "invoke", lambda *_args, **_kwargs: next(results)) + + _scan_multi_skill( + MultiSkillDetectionResult(is_multi_skill=True, skills=skills), + FormatChoice.json, + output, + no_llm=True, + min_coverage=90, + ) + + payload = json.loads(output.read_text(encoding="utf-8")) + assert payload["skills_omitted"] == 0 + assert payload["analysis_completeness"]["coverage_percent"] == 0.0 + + +@pytest.mark.parametrize( + ("analysis_completeness", "threshold"), + [ + (None, 87), + ({"coverage_percent": None}, 87), + ({"coverage_percent": "unknown"}, 87), + ({"coverage_percent": True}, 0), + ({"coverage_percent": float("nan")}, 0), + ({"coverage_percent": float("inf")}, 0), + ], + ids=["missing", "null", "non-numeric", "boolean", "nan", "infinity"], +) +def test_recursive_min_coverage_fails_closed_for_malformed_child_coverage( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + analysis_completeness: dict[str, object] | None, + threshold: float, +) -> None: + skills = [ + SkillDirectory(tmp_path / "one", "one", "one"), + SkillDirectory(tmp_path / "two", "two", "two"), + ] + output = tmp_path / "combined.json" + malformed_child: dict[str, object] = { + "report_body": json.dumps( + {"analysis_completeness": analysis_completeness} + if analysis_completeness is not None + else {} + ), + "execution_successful": True, + "risk_score": 0, + } + if analysis_completeness is not None: + malformed_child["analysis_completeness"] = analysis_completeness + valid_child = _bounded_recursive_result("two", finding_count=0) + results = iter([malformed_child, valid_child]) + + def invoke(*_args: object, **_kwargs: object) -> dict[str, object]: + return next(results) + + monkeypatch.setattr(cli.graph, "invoke", invoke) + + with pytest.raises(typer.Exit) as exit_info: + _scan_multi_skill( + MultiSkillDetectionResult(is_multi_skill=True, skills=skills), + FormatChoice.json, + output, + no_llm=True, + min_coverage=threshold, + ) + + assert exit_info.value.exit_code == 1 + assert output.exists() + + def test_recursive_scan_exits_two_after_writing_all_child_reports(tmp_path: Path) -> None: """Recursive mode aggregates child execution failures after producing output.""" s1 = SkillDirectory(path=tmp_path / "one", name="one", relative_path="one") @@ -1583,7 +1889,7 @@ def _bounded_recursive_result(label: str, *, finding_count: int = 1) -> dict[str "risk_severity": "LOW", "risk_recommendation": "SAFE", "execution_successful": True, - "analysis_completeness": {"is_complete": True}, + "analysis_completeness": {"is_complete": True, "coverage_percent": 100}, "findings": findings, "filtered_findings": findings, "suppressed_findings": [], From 72a5e9a0de966710e67b51fe9810aebc84c480d1 Mon Sep 17 00:00:00 2001 From: Rod Boev Date: Fri, 2 Oct 2026 19:33:55 -0400 Subject: [PATCH 2/3] fix(cli): fail min coverage on symlinked omissions Signed-off-by: Rod Boev --- README.md | 4 +-- docs/ANALYSIS_RESOURCE_BOUNDS.md | 5 ++- src/skillspector/cli.py | 4 +-- tests/unit/test_cli.py | 55 ++++++++++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 03dae54601..f609bf02fd 100644 --- a/README.md +++ b/README.md @@ -682,10 +682,10 @@ SkillSpector is built to be driven by other tools (CI pipelines, install gates, | Code | Meaning | |------|---------| | `0` | Scan completed, `risk_score` ≤ 50 (recommendation `SAFE` or `CAUTION`), and no enabled strict gate fired | -| `1` | Scan completed and either `risk_score` > 50, `--fail-on-findings` found an active finding, or `--fail-on-incomplete` found partial/incomplete analysis | +| `1` | Scan completed and either `risk_score` > 50, `--fail-on-findings` found an active finding, `--fail-on-incomplete` found partial/incomplete analysis, or `--min-coverage` found coverage below its threshold | | `2` | Error (bad input, unreadable source, internal failure) | -> By default, the exit code collapses `SAFE` and `CAUTION` into `0`. Use `--fail-on-findings` to gate on any active finding, `--fail-on-incomplete` to gate on incomplete coverage, or read the JSON `recommendation` field for custom policy. +> By default, the exit code collapses `SAFE` and `CAUTION` into `0`. Use `--fail-on-findings` to gate on any active finding, `--fail-on-incomplete` to gate on incomplete coverage, `--min-coverage PERCENT` to gate on a coverage floor, or read the JSON `recommendation` field for custom policy. ### Machine-readable output diff --git a/docs/ANALYSIS_RESOURCE_BOUNDS.md b/docs/ANALYSIS_RESOURCE_BOUNDS.md index feeaff4e7a..553c5d06c9 100644 --- a/docs/ANALYSIS_RESOURCE_BOUNDS.md +++ b/docs/ANALYSIS_RESOURCE_BOUNDS.md @@ -270,7 +270,10 @@ When relevant analysis is incomplete: its compatibility behavior and still applies its ordinary risk-score exit policy. Execution failures exit with status 2. - `skillspector scan --min-coverage PERCENT` exits with status 1 when canonical coverage is below - `PERCENT`; equality passes and recursive scans evaluate each child. + `PERCENT`; equality passes. Recursive scans check each scanned child's own coverage, not the + aggregate `analysis_completeness.coverage_percent`, and any omitted or unscanned skill fails a + positive threshold. Skills that discovery never found because it stopped early are not counted; + add `--fail-on-incomplete` to catch that case. - MCP responses set `safe_to_install` to `false` when analysis is incomplete, any relevant file is entirely uninspected, execution failed, or the risk score exceeds the installation threshold. diff --git a/src/skillspector/cli.py b/src/skillspector/cli.py index 44b2a1d9c2..190b611efd 100644 --- a/src/skillspector/cli.py +++ b/src/skillspector/cli.py @@ -2929,8 +2929,8 @@ def _scan_multi_skill( aggregate_limitations.append( f"{unscanned_skill_count} recursive skill(s) unscanned after an aggregate limit" ) - if min_coverage is not None and min_coverage > 0: - coverage_failed = True + if skills_omitted_total and min_coverage is not None and min_coverage > 0: + coverage_failed = True aggregate_limitations = list(dict.fromkeys(aggregate_limitations))[:256] aggregate_completeness = _multi_skill_analysis_completeness( total_skills=len(skills) + omitted_symlink_entry_count, diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index f25d854c03..6f2977ed3a 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -648,6 +648,61 @@ def test_recursive_min_coverage_allows_omitted_skills_at_threshold_zero( assert payload["skills"][-1]["omitted_count"] == 2 +@pytest.mark.parametrize(("threshold", "exit_code"), [(90, 1), (0, None)]) +def test_recursive_min_coverage_counts_symlinked_skills_as_omitted( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + threshold: float, + exit_code: int | None, +) -> None: + skills = [SkillDirectory(tmp_path / name, name, name) for name in ("one", "two")] + output = tmp_path / "combined.json" + monkeypatch.setattr( + cli.graph, + "invoke", + lambda *_args, **_kwargs: _bounded_recursive_result("one", finding_count=0), + ) + + expectation = pytest.raises(typer.Exit) if exit_code else nullcontext() + with expectation as exit_info: + _scan_multi_skill( + MultiSkillDetectionResult( + is_multi_skill=True, skills=skills, omitted_symlink_entries=1 + ), + FormatChoice.json, + output, + no_llm=True, + min_coverage=threshold, + ) + + if exit_info is not None: + assert exit_info.value.exit_code == exit_code + assert json.loads(output.read_text(encoding="utf-8"))["skills_omitted"] == 1 + + +def test_recursive_min_coverage_keeps_execution_failure_exit_two(tmp_path: Path) -> None: + skills = [SkillDirectory(tmp_path / name, name, name) for name in ("one", "two")] + output = tmp_path / "combined.json" + with patch( + "skillspector.cli.graph.invoke", + side_effect=[ + _bounded_recursive_result("one", finding_count=0), + {"report_body": "{}", "risk_score": 0, "execution_successful": False}, + ], + ): + with pytest.raises(typer.Exit) as exit_info: + _scan_multi_skill( + MultiSkillDetectionResult(is_multi_skill=True, skills=skills), + FormatChoice.json, + output, + no_llm=True, + min_coverage=90, + ) + + assert exit_info.value.exit_code == 2 + assert output.exists() + + def test_recursive_min_coverage_ignores_aggregate_completeness_for_partial_children( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: From f49f5ac90ec8ce7eb9abf35b0f818e36eddd1793 Mon Sep 17 00:00:00 2001 From: Rod Boev Date: Fri, 2 Oct 2026 19:44:42 -0400 Subject: [PATCH 3/3] fix(cli): gate symlink-only recursive fallback on min coverage Signed-off-by: Rod Boev --- src/skillspector/cli.py | 13 +++++++++++-- tests/unit/test_cli.py | 39 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/skillspector/cli.py b/src/skillspector/cli.py index 190b611efd..26b41980d4 100644 --- a/src/skillspector/cli.py +++ b/src/skillspector/cli.py @@ -381,6 +381,11 @@ def _coverage_below_threshold(result: dict[str, object], threshold: float | None return coverage < threshold +def _omissions_fail_threshold(omitted_skills: int, threshold: float | None) -> bool: + """Known omitted skills leave coverage below any positive threshold.""" + return bool(omitted_skills) and threshold is not None and threshold > 0 + + def _recursive_json_payload(result: dict[str, object]) -> dict[str, object] | None: """Return parsed report_body when it is valid JSON object text.""" raw_report_body = result.get("report_body") @@ -676,8 +681,10 @@ def scan( discovery_console = ( err_console if output is None and format is not FormatChoice.terminal else console ) + recursive_omitted_skills = 0 if recursive and resolved_path.is_dir(): detection = detect_skills(resolved_path) + recursive_omitted_skills = detection.omitted_symlink_entries if not detection.complete: pre_scan_ledger_events = _multi_skill_limitation_events(detection) err_console.print( @@ -798,7 +805,9 @@ def scan( raise typer.Exit(code=1) if fail_on_findings and effective_findings(result): raise typer.Exit(code=1) - if _coverage_below_threshold(result, min_coverage): + if _coverage_below_threshold(result, min_coverage) or _omissions_fail_threshold( + recursive_omitted_skills, min_coverage + ): raise typer.Exit(code=1) if (result.get("risk_score") or 0) > RISK_THRESHOLD: raise typer.Exit(code=1) @@ -2929,7 +2938,7 @@ def _scan_multi_skill( aggregate_limitations.append( f"{unscanned_skill_count} recursive skill(s) unscanned after an aggregate limit" ) - if skills_omitted_total and min_coverage is not None and min_coverage > 0: + if _omissions_fail_threshold(skills_omitted_total, min_coverage): coverage_failed = True aggregate_limitations = list(dict.fromkeys(aggregate_limitations))[:256] aggregate_completeness = _multi_skill_analysis_completeness( diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index 6f2977ed3a..45e8469502 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -445,7 +445,9 @@ def test_cli_min_coverage_rejects_invalid_values(tmp_path: Path, value: str) -> result = runner.invoke(app, ["scan", str(tmp_path), "--min-coverage", value]) assert result.exit_code == 2 plain_output = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", result.output) - assert "--min-coverage" in plain_output + assert "must be a finite number between 0 and 100" in " ".join( + re.sub(r"[│╭╮╰╯─]", " ", plain_output).split() + ) def test_cli_mcp_registry_rejects_min_coverage(tmp_path: Path) -> None: @@ -453,12 +455,45 @@ def test_cli_mcp_registry_rejects_min_coverage(tmp_path: Path) -> None: payload.write_text('{"servers": []}', encoding="utf-8") result = runner.invoke( app, - ["scan", str(payload), "--mcp-registry", "--min-coverage", "87"], + ["scan", str(payload), "--mcp-registry", "--format", "json", "--min-coverage", "87"], ) assert result.exit_code == 2 + assert "cannot be combined with" in result.output assert "--min-coverage" in result.output +@pytest.mark.parametrize(("threshold", "exit_code"), [("90", 1), ("0", 0)]) +def test_recursive_min_coverage_fails_when_only_symlinked_skills_were_found( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, threshold: str, exit_code: int +) -> None: + (tmp_path / "README.md").write_text("# Skills", encoding="utf-8") + output = tmp_path / "report.json" + monkeypatch.setattr( + cli_module, + "detect_skills", + lambda _path: MultiSkillDetectionResult(is_multi_skill=False, omitted_symlink_entries=1), + ) + monkeypatch.setattr( + cli_module, + "_scan_skill", + lambda **_kwargs: { + "report_body": "{}", + "execution_successful": True, + "analysis_completeness": {"is_complete": True, "coverage_percent": 100}, + "risk_score": 0, + }, + ) + + result = runner.invoke( + app, + ["scan", str(tmp_path), "--recursive", "--no-llm", "-f", "json", "-o", str(output)] + + ["--min-coverage", threshold], + ) + + assert result.exit_code == exit_code + assert output.exists() + + def test_recursive_min_coverage_checks_each_child_and_writes_report(tmp_path: Path) -> None: s1 = SkillDirectory(path=tmp_path / "one", name="one", relative_path="one") s2 = SkillDirectory(path=tmp_path / "two", name="two", relative_path="two")