Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions src/skillspector/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ class FormatChoice(StrEnum):
sarif = "sarif"


# Reports that tools parse from stdout, so status text must go to stderr.
_MACHINE_READABLE_FORMATS = frozenset({FormatChoice.json, FormatChoice.sarif})


class TransportChoice(StrEnum):
"""Transport choices for the MCP server."""

Expand Down Expand Up @@ -658,7 +662,7 @@ def scan(
)
return
if detection.complete and not detection.has_root_skill and len(detection.skills) == 0:
(err_console if format == FormatChoice.json else console).print(
(err_console if format in _MACHINE_READABLE_FORMATS else console).print(
"[yellow]Warning:[/yellow] --recursive specified but no sub-skills "
"detected. Scanning as single skill."
)
Expand All @@ -671,7 +675,7 @@ def scan(
"with a bounded scan and reporting partial coverage."
)
if detection.is_multi_skill:
(err_console if format == FormatChoice.json else console).print(
(err_console if format in _MACHINE_READABLE_FORMATS else console).print(
f"[yellow]Warning:[/yellow] Found {len(detection.skills)} skills in "
f"this directory. Use --recursive to scan each independently."
)
Expand Down Expand Up @@ -2018,7 +2022,7 @@ def _scan_transitive(
except Exception:
transitive_sources.add(target)
traversal.note_child_scan_failure(target)
if format == FormatChoice.json:
if format in _MACHINE_READABLE_FORMATS:
logger.warning("Transitive scan failed for %s", target)
else:
console.print(f"[yellow]Warning:[/yellow] Transitive scan failed for {target}")
Expand Down Expand Up @@ -2150,7 +2154,7 @@ def _scan_skill(
yara_dir = str(yara_rules_dir.resolve()) if yara_rules_dir else None
active_visited: set[str] = set()
if verbose:
(err_console if format == FormatChoice.json else console).print(
(err_console if format in _MACHINE_READABLE_FORMATS else console).print(
"[dim]Running scan...[/dim]"
)
logger.debug(
Expand Down Expand Up @@ -2376,7 +2380,9 @@ def _scan_multi_skill(
if yara_dir is None and isinstance(legacy_kwargs.get("yara_rules_dir"), Path):
yara_dir = str(legacy_kwargs["yara_rules_dir"])
skills = detection.skills
status_console = err_console if format == FormatChoice.json and output is None else console
status_console = (
err_console if format in _MACHINE_READABLE_FORMATS and output is None else console
)
status_console.print(
f"[bold]Multi-skill directory detected:[/bold] {len(skills)} skills found\n"
)
Expand Down Expand Up @@ -2654,7 +2660,7 @@ def _scan_multi_skill(
console.print(f"[green]Combined report saved to:[/green] {output}")
else:
print(rendered)
elif output and format == FormatChoice.sarif:
elif format == FormatChoice.sarif:
merged_sarif = _multi_skill_sarif_report(
processed_skills,
results,
Expand All @@ -2669,8 +2675,11 @@ def _scan_multi_skill(
merged_sarif = _multi_skill_sarif_report([], [], aggregate_completeness)
rendered = json.dumps(merged_sarif, indent=2)
_ensure_recursive_output_bound(rendered)
Path(output).write_text(rendered, encoding="utf-8")
console.print(f"[green]Combined report saved to:[/green] {output}")
if output:
Path(output).write_text(rendered, encoding="utf-8")
console.print(f"[green]Combined report saved to:[/green] {output}")
else:
print(rendered)
elif output:
sections: list[str] = []
for skill, result in zip(processed_skills, results, strict=True):
Expand Down
68 changes: 60 additions & 8 deletions tests/unit/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1364,10 +1364,11 @@ def test_scan_multi_skill_json_stdout_survives_child_failure(
assert "Error: boom" in captured.err


def test_recursive_json_single_skill_advisory_does_not_pollute_stdout(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
@pytest.mark.parametrize("output_format", ["json", "sarif"])
def test_recursive_single_skill_advisory_does_not_pollute_stdout(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, output_format: str
) -> None:
"""Recursive fallback advisories stay off stdout when JSON is requested."""
"""Recursive fallback advisories stay off stdout when JSON or SARIF is requested."""
monkeypatch.setattr(
cli,
"detect_skills",
Expand All @@ -1388,7 +1389,7 @@ def test_recursive_json_single_skill_advisory_does_not_pollute_stdout(

result = runner.invoke(
app,
["scan", str(tmp_path), "--recursive", "--format", "json", "--no-llm"],
["scan", str(tmp_path), "--recursive", "--format", output_format, "--no-llm"],
)

assert result.exit_code == 0, result.output
Expand All @@ -1397,10 +1398,11 @@ def test_recursive_json_single_skill_advisory_does_not_pollute_stdout(
assert "Scanning as single" in result.stderr


def test_json_multi_skill_advisory_does_not_pollute_stdout(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
@pytest.mark.parametrize("output_format", ["json", "sarif"])
def test_multi_skill_advisory_does_not_pollute_stdout(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, output_format: str
) -> None:
"""The non-recursive multi-skill advisory stays off JSON stdout."""
"""The non-recursive multi-skill advisory stays off JSON and SARIF stdout."""
skills = [
SkillDirectory(path=tmp_path / name, name=name, relative_path=name)
for name in ("one", "two")
Expand All @@ -1425,7 +1427,7 @@ def test_json_multi_skill_advisory_does_not_pollute_stdout(

result = runner.invoke(
app,
["scan", str(tmp_path), "--format", "json", "--no-llm"],
["scan", str(tmp_path), "--format", output_format, "--no-llm"],
)

assert result.exit_code == 0, result.output
Expand Down Expand Up @@ -1667,6 +1669,30 @@ def test_recursive_sarif_is_valid_and_carries_aggregate_completeness(
assert completeness["is_complete"] is True


def test_recursive_sarif_without_output_writes_only_the_log_to_stdout(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture
) -> None:
"""Recursive SARIF without --output prints the log; status text goes to stderr."""
skills = [SkillDirectory(tmp_path / name, name, name) for name in ("one", "two")]
detection = MultiSkillDetectionResult(is_multi_skill=True, skills=skills)
monkeypatch.setattr(
cli.graph,
"invoke",
lambda *_args, **_kwargs: _bounded_recursive_result("one"),
)

_scan_multi_skill(detection, FormatChoice.sarif, None, no_llm=True, verbose=True)

captured = capsys.readouterr()
payload = json.loads(captured.out)
validate_sarif_report(payload)
assert payload["runs"][-1]["properties"]["kind"] == "recursiveAggregate"
assert "Scanning" not in captured.out
assert "Scanning" in captured.err
assert "Running scan" in captured.err
assert "Multi-Skill Summary" in captured.err


def test_recursive_sarif_bounds_the_final_serialized_document(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
Expand Down Expand Up @@ -2783,6 +2809,32 @@ def fake_run_graph_scan(
assert data["issues"][0]["id"] == "D1"


def test_transitive_failure_warning_stays_off_sarif_stdout(tmp_path: Path, monkeypatch) -> None:
"""A failed transitive child does not print its warning into the SARIF log."""
target = "https://github.com/org/broken.git"

def fake_run_graph_scan(input_path: str, format, no_llm: bool, **_kwargs) -> dict[str, object]:
if input_path == str(tmp_path):
return _mock_graph_result(
findings=[_finding("D1", "direct finding")],
file_cache={"SKILL.md": f"deps {target}"},
output_format=format.value,
)
raise ValueError("resolver failure")

monkeypatch.setattr(cli, "_run_graph_scan", fake_run_graph_scan)
result = runner.invoke(
app,
["scan", str(tmp_path), "--format", "sarif", "--transitive", "--no-llm"],
)

assert result.exit_code == 0, result.output
assert "Transitive scan failed" not in result.stdout
payload = json.loads(result.stdout)
validate_sarif_report(payload)
assert [item["ruleId"] for item in payload["runs"][0]["results"]] == ["D1"]


def test_scan_transitive_does_not_rescan_root_source(monkeypatch) -> None:
"""A root external source is seeded in visited so self-references are not rescanned."""
root_source = "https://github.com/org/root.git"
Expand Down
Loading