From e16dcf70e7d74cc353633053dca6dc1a11195098 Mon Sep 17 00:00:00 2001 From: Farzam Fallahy <61787362+farzamfallahi@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:50:12 +0100 Subject: [PATCH 1/2] fix(cli): render error text literally instead of as Rich markup CLI error lines interpolated exception text into Rich markup strings, so bracketed text such as skills[old]/demo lost its brackets, nope[/x] raised MarkupError, and the MCP install hint dropped [mcp]. Build the error line from a Rich Text object and pass each line through the shared visible_terminal_text helper, matching the approach in #725 and #734. Closes #885. Signed-off-by: Farzam Fallahy <61787362+farzamfallahi@users.noreply.github.com> --- src/skillspector/cli.py | 32 ++++++++++++++++---------- tests/unit/test_cli.py | 50 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 12 deletions(-) diff --git a/src/skillspector/cli.py b/src/skillspector/cli.py index 4149f55a9..1c896984c 100644 --- a/src/skillspector/cli.py +++ b/src/skillspector/cli.py @@ -122,6 +122,14 @@ def _ensure_utf8_streams() -> None: console = Console() err_console = Console(stderr=True) + +def _error_line(message: object) -> Text: + """Render an error line literally: no Rich markup, emoji or control characters.""" + lines = str(message).split("\n") + body = "\n".join(_visible_terminal_text(line) for line in lines) + return Text.assemble(("Error:", "red"), " ", body) + + _PROGRESS_TREE_MAX_PATHS = 200 _PROGRESS_TREE_MAX_NODES = 1_000 _TRANSITIVE_MAX_TARGETS = 32 @@ -394,7 +402,7 @@ def _exit_on_unsupported_llm_controls(no_llm: bool) -> None: return error = unsupported_control_error() if error is not None: - err_console.print(f"[red]Error:[/red] {error}") + err_console.print(_error_line(error)) raise typer.Exit(code=2) @@ -699,7 +707,7 @@ def scan( try: require_secure_file_output() except ValueError as exc: - err_console.print(f"[red]Error:[/red] {exc}") + err_console.print(_error_line(exc)) raise typer.Exit(code=2) from exc if mcp_registry: @@ -750,7 +758,7 @@ def scan( except typer.Exit: raise except Exception as e: - err_console.print(f"[red]Error:[/red] {e}") + err_console.print(_error_line(e)) raise typer.Exit(code=2) from e return @@ -763,14 +771,14 @@ def scan( resolved_path = validate_local_input_path(resolved_path) _validate_report_destination(resolved_path, output) except (OSError, ValueError) as e: - err_console.print(f"[red]Error:[/red] {e}") + err_console.print(_error_line(e)) raise typer.Exit(code=2) from e try: transitive_allow_prefix, transitive_deny_prefix = transitive.normalize_prefixes( transitive_allow_prefix, transitive_deny_prefix ) except ValueError as exc: - err_console.print(f"[red]Error:[/red] invalid transitive prefix: {exc}") + err_console.print(_error_line(f"invalid transitive prefix: {exc}")) raise typer.Exit(code=2) from exc _exit_on_unsupported_llm_controls(no_llm) yara_dir = str(yara_rules_dir.resolve()) if yara_rules_dir else None @@ -825,13 +833,13 @@ def scan( except typer.Exit: raise except (FileNotFoundError, ValueError) as e: - err_console.print(f"[red]Error:[/red] {e}") + err_console.print(_error_line(e)) raise typer.Exit(code=2) from e except Exception as e: if verbose: err_console.print_exception() else: - err_console.print(f"[red]Error:[/red] {e}") + err_console.print(_error_line(e)) raise typer.Exit(code=2) from e return if detection.complete and not detection.has_root_skill and len(detection.skills) == 0: @@ -921,13 +929,13 @@ def scan( except typer.Exit: raise except (FileNotFoundError, ValueError) as e: - err_console.print(f"[red]Error:[/red] {e}") + err_console.print(_error_line(e)) raise typer.Exit(code=2) from e except Exception as e: if verbose: err_console.print_exception() else: - err_console.print(f"[red]Error:[/red] {e}") + err_console.print(_error_line(e)) raise typer.Exit(code=2) from e finally: if result is not None: @@ -3416,7 +3424,7 @@ def mcp( run_mcp(transport=transport.value, host=host, port=port) except (ModuleNotFoundError, ValueError) as e: - err_console.print(f"[red]Error:[/red] {e}") + err_console.print(_error_line(e)) raise typer.Exit(code=2) from e @@ -3520,13 +3528,13 @@ def baseline( except typer.Exit: raise except (FileNotFoundError, ValueError) as e: - err_console.print(f"[red]Error:[/red] {e}") + err_console.print(_error_line(e)) raise typer.Exit(code=2) from e except Exception as e: if verbose: err_console.print_exception() else: - err_console.print(f"[red]Error:[/red] {e}") + err_console.print(_error_line(e)) raise typer.Exit(code=2) from e finally: if result is not None: diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index d1b106ca0..8fcbd51f0 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -7841,3 +7841,53 @@ def test_cli_baseline_rejects_failed_scan_before_writing( assert output.read_bytes() == previous build.assert_not_called() cleanup.assert_called_once_with(result) + + +@pytest.mark.parametrize( + ("message", "expected"), + [ + ("plain message", "Error: plain message"), + ("skills[old]/demo", "Error: skills[old]/demo"), + ("nope[/x]", "Error: nope[/x]"), + ("[bold]x[/bold]", "Error: [bold]x[/bold]"), + ( + "Install it with: pip install 'skillspector[mcp]'", + "Error: Install it with: pip install 'skillspector[mcp]'", + ), + ("emoji :smile: here", "Error: emoji :smile: here"), + ("C:\\Users\\", "Error: C:\\Users\\"), + ("first\nsecond", "Error: first\nsecond"), + ("esc \x1b[2J", "Error: esc \\x1b[2J"), + ], +) +def test_error_line_renders_message_literally(message: str, expected: str) -> None: + assert cli_module._error_line(message).plain == expected + + +def test_error_line_survives_console_print() -> None: + buffer = StringIO() + Console(file=buffer, width=120).print(cli_module._error_line("a :smile: [bold]b[/bold] C:\\")) + assert buffer.getvalue() == "Error: a :smile: [bold]b[/bold] C:\\\n" + + +@pytest.mark.parametrize("bad_input", ["skills[old]/demo", "nope[/x]"]) +def test_scan_input_error_shows_bracketed_path_literally(bad_input: str) -> None: + result = runner.invoke(app, ["scan", bad_input]) + assert result.exit_code == 2 + assert bad_input in result.output + assert "MarkupError" not in result.output + + +def test_mcp_missing_extra_install_hint_keeps_extra_name( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fake_run(**_kwargs: object) -> None: + raise ModuleNotFoundError( + "The MCP server requires the optional 'mcp' dependency. " + "Install it with: pip install 'skillspector[mcp]'" + ) + + monkeypatch.setattr("skillspector.mcp_server.run", fake_run) + result = runner.invoke(app, ["mcp"]) + assert result.exit_code != 0 + assert "skillspector[mcp]" in result.output From cdb13bee1f39c27d3d3eb29f585488a64e0f7650 Mon Sep 17 00:00:00 2001 From: Farzam Fallahy <61787362+farzamfallahi@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:59:47 +0100 Subject: [PATCH 2/2] fix(cli): render remaining interpolated console output literally Several other console lines still interpolated user-controlled values into Rich markup strings: report and baseline output paths, shipped-baseline paths, transitive scan warnings, and recursive progress and summary lines. Bracketed paths or URLs lost their brackets or raised MarkupError. Route them through a shared _literal_line helper (with _error_line and a new _warning_line built on it) or plain Text objects, passing values through visible_terminal_text. Signed-off-by: Farzam Fallahy <61787362+farzamfallahi@users.noreply.github.com> --- src/skillspector/cli.py | 60 ++++++++++++++++++--------- tests/unit/test_cli.py | 90 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+), 18 deletions(-) diff --git a/src/skillspector/cli.py b/src/skillspector/cli.py index 1c896984c..2ae715dde 100644 --- a/src/skillspector/cli.py +++ b/src/skillspector/cli.py @@ -123,11 +123,21 @@ def _ensure_utf8_streams() -> None: err_console = Console(stderr=True) -def _error_line(message: object) -> Text: - """Render an error line literally: no Rich markup, emoji or control characters.""" +def _literal_line(label: str, style: str, message: object) -> Text: + """Render a labelled line literally: no Rich markup, emoji or control characters.""" lines = str(message).split("\n") body = "\n".join(_visible_terminal_text(line) for line in lines) - return Text.assemble(("Error:", "red"), " ", body) + return Text.assemble((f"{label}:", style), " ", body) + + +def _error_line(message: object) -> Text: + """Render an error line literally.""" + return _literal_line("Error", "red", message) + + +def _warning_line(message: object) -> Text: + """Render a warning line literally.""" + return _literal_line("Warning", "yellow", message) _PROGRESS_TREE_MAX_PATHS = 200 @@ -386,9 +396,9 @@ def _write_result( if output: write_text_no_follow(output, report_body) if format == FormatChoice.terminal: - console.print(f"\n[green]Report saved to:[/green] {output}") + console.print(Text.assemble("\n", _literal_line("Report saved to", "green", output))) else: - console.print(f"Report saved to: {output}") + console.print(_literal_line("Report saved to", "", output)) else: if format == FormatChoice.terminal: console.print(report_body, markup=False, emoji=False) @@ -748,7 +758,7 @@ def scan( report = json.dumps(result, indent=2) if output: write_text_no_follow(output, report) - console.print(f"Report saved to: {output}") + console.print(_literal_line("Report saved to", "", output)) else: print(report) if fail_on_findings and result["findings"]: @@ -870,14 +880,14 @@ def scan( if shipped is not None: if use_shipped_baseline: baseline = shipped - err_console.print(f"[yellow]Applying author-shipped baseline:[/yellow] {shipped}") + err_console.print(_literal_line("Applying author-shipped baseline", "yellow", shipped)) err_console.print( "[dim]Suppressed findings do not count toward the risk score; " "use --show-suppressed to list them.[/dim]" ) else: err_console.print( - f"[yellow]Shipped baseline detected (not applied):[/yellow] {shipped}" + _literal_line("Shipped baseline detected (not applied)", "yellow", shipped) ) err_console.print( "[dim]Review it, then re-run with --use-shipped-baseline to apply its " @@ -885,8 +895,12 @@ def scan( ) elif use_shipped_baseline and baseline is None: err_console.print( - f"[dim]--use-shipped-baseline: no shipped baseline found in {resolved_path}; " - "scanning without a baseline.[/dim]" + Text( + _visible_terminal_text( + f"--use-shipped-baseline: no shipped baseline found in {resolved_path}; scanning without a baseline." + ), + style="dim", + ) ) result = None @@ -2413,7 +2427,7 @@ def _scan_transitive( if format in _MACHINE_READABLE_FORMATS or format is FormatChoice.markdown: logger.warning("Transitive scan failed for %s", target) else: - console.print(f"[yellow]Warning:[/yellow] Transitive scan failed for {target}") + console.print(_warning_line(f"Transitive scan failed for {target}")) finally: if child_result is not None: cleanup_result(child_result) @@ -3010,7 +3024,11 @@ def _scan_multi_skill( aggregate_limitations.extend(shared_transitive_traversal.truncation_reasons) break progress_console.print( - f" [{i}/{len(skills)}] Scanning [bold]{skill.name}[/bold] ({skill.relative_path}/)" + Text.assemble( + f" [{i}/{len(skills)}] Scanning ", + (_visible_terminal_text(str(skill.name)), "bold"), + f" ({_visible_terminal_text(str(skill.relative_path))}/)", + ) ) result: dict[str, object] | None = None try: @@ -3165,7 +3183,9 @@ def _scan_multi_skill( for skill, result in zip(processed_skills, results, strict=True): if "error" in result: progress_console.print( - f" {skill.name:<30} {'ERROR':<8} {'—':<12} {'—':<10} {'error':<10}" + Text( + f" {_visible_terminal_text(str(skill.name)):<30} {'ERROR':<8} {'—':<12} {'—':<10} {'error':<10}" + ) ) continue score = result.get("risk_score", 0) @@ -3173,7 +3193,9 @@ def _scan_multi_skill( finding_count = len(effective_findings(result)) execution = "failed" if result.get("execution_successful") is False else "successful" progress_console.print( - f" {skill.name:<30} {score:<8} {severity:<12} {finding_count:<10} {execution:<10}" + Text( + f" {_visible_terminal_text(str(skill.name)):<30} {score:<8} {severity:<12} {finding_count:<10} {execution:<10}" + ) ) if output_omitted_skill_count: progress_console.print( @@ -3300,7 +3322,7 @@ def _scan_multi_skill( _ensure_recursive_output_bound(rendered) if output is not None: write_text_no_follow(output, rendered) - progress_console.print(f"[green]Combined report saved to:[/green] {output}") + progress_console.print(_literal_line("Combined report saved to", "green", output)) else: sys.stdout.write(rendered) elif format == FormatChoice.sarif: @@ -3328,7 +3350,7 @@ def _scan_multi_skill( _ensure_recursive_output_bound(rendered) if output is not None: write_text_no_follow(output, rendered) - progress_console.print(f"[green]Combined report saved to:[/green] {output}") + progress_console.print(_literal_line("Combined report saved to", "green", output)) else: sys.stdout.write(rendered) else: @@ -3361,7 +3383,7 @@ def _scan_multi_skill( _ensure_recursive_output_bound(rendered) if output is not None: write_text_no_follow(output, rendered) - progress_console.print(f"[green]Combined report saved to:[/green] {output}") + progress_console.print(_literal_line("Combined report saved to", "green", output)) elif format is FormatChoice.terminal: console.print(rendered, markup=False, emoji=False) else: @@ -3523,7 +3545,9 @@ def baseline( else: dump_baseline(data, output) console.print( - f"[green]Wrote baseline with {len(findings)} suppressed finding(s) to:[/green] {output}" + _literal_line( + f"Wrote baseline with {len(findings)} suppressed finding(s) to", "green", output + ) ) except typer.Exit: raise diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index 8fcbd51f0..042092a2b 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -7891,3 +7891,93 @@ def fake_run(**_kwargs: object) -> None: result = runner.invoke(app, ["mcp"]) assert result.exit_code != 0 assert "skillspector[mcp]" in result.output + + +def test_warning_line_renders_message_literally() -> None: + message = ( + "Transitive scan failed for https://raw.githubusercontent.com/acme/tools/main/setup[/x].sh" + ) + assert cli_module._warning_line(message).plain == f"Warning: {message}" + + +def test_literal_line_keeps_label_style_and_literal_path() -> None: + line = cli_module._literal_line("Report saved to", "green", Path("out[b].json")) + assert line.plain == "Report saved to: out[b].json" + assert line.spans[0].style == "green" + + +def test_transitive_child_failure_warning_shows_bracketed_url_literally( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + skill = tmp_path / "skill" + skill.mkdir() + (skill / "SKILL.md").write_text( + "---\nname: demo\ndescription: d\n---\n# Demo\n\n" + "Run https://raw.githubusercontent.com/acme/tools/main/setup[/x].sh first.\n" + ) + real_scan_for_source = cli._run_graph_scan_for_source + child_inputs: list[str] = [] + + def scan_for_source(**kwargs: Any) -> dict[str, object]: + if kwargs["input_path"] == str(skill): + return real_scan_for_source(**kwargs) + child_inputs.append(kwargs["input_path"]) + raise RuntimeError("child scan failed") + + monkeypatch.setattr(cli, "_run_graph_scan_for_source", scan_for_source) + cli._scan_skill( + input_path=str(skill), + format=FormatChoice.terminal, + no_llm=True, + baseline=None, + yara_rules_dir=None, + verbose=False, + show_suppressed=False, + transitive_enabled=True, + transitive_depth=1, + transitive_allow_prefix=None, + transitive_deny_prefix=None, + ) + assert child_inputs, "the root should have reached a transitive child scan" + shown = "".join(capsys.readouterr().out.split()) + assert "Transitivescanfailedfor" in shown + assert "setup[/x].sh" in shown + + +def test_recursive_scan_shows_bracketed_skill_names_literally( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Detection sanitizes names, so build the directories directly to exercise the print path. + skills = [] + for name in ("one[bold]x", "two"): + skill = tmp_path / name + skill.mkdir() + (skill / "SKILL.md").write_text( + "---\nname: demo\ndescription: d\n---\n# Demo\n\nSummarize the supplied text.\n" + ) + skills.append(SkillDirectory(skill, name, name)) + + _scan_multi_skill( + MultiSkillDetectionResult(is_multi_skill=True, skills=skills), + FormatChoice.terminal, + None, + no_llm=True, + ) + + captured = capsys.readouterr() + shown = "".join((captured.out + captured.err).split()) + assert "Scanningone[bold]x(one[bold]x/)" in shown + + +def test_scan_report_saved_message_shows_bracketed_path_literally(tmp_path: Path) -> None: + skill = tmp_path / "skill" + skill.mkdir() + (skill / "SKILL.md").write_text( + "---\nname: demo\ndescription: d\n---\n# Demo\n\nSummarize the supplied text.\n" + ) + report = tmp_path / "out[b].json" + result = runner.invoke( + app, ["scan", str(skill), "--format", "json", "--no-llm", "-o", str(report)] + ) + assert "out[b].json" in "".join(result.output.split()) + assert report.exists()