diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index b037a91..a8c39c7 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -729,6 +729,10 @@ SARIF upload) is covered in [CI.md](CI.md). ## Usage ```bash +# Check installed version and environment details +secfoo --version +secfoo version --json + # Run a skill against the current directory with Claude Code secfoo run --skill security-architecture-review --agent claude diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 08a9d82..bbeaefb 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -2,6 +2,7 @@ import json import os +import platform import shutil import sys from datetime import date, datetime, timezone @@ -18,16 +19,22 @@ from secfoo import cloud as cloud_module from secfoo import mcp as mcp_module from secfoo import memory as memory_module +from secfoo.__about__ import __version__ from secfoo.agents.registry import ADAPTERS, get_adapter from secfoo.aibom import AIBOMParseError, parse_ai_bom from secfoo.attachments import infer_attachment_kind from secfoo.cloud import CloudConfig, CloudError -from secfoo.config import CLOUD_CONFIG_PATH, attachment_dir +from secfoo.config import CLOUD_CONFIG_PATH, STORE_DIR, attachment_dir from secfoo.cost import format_cost, format_tokens, sum_optional from secfoo.report.sarif import findings_to_sarif from secfoo.runner import _project_display_name, already_scanned_skills, execute_runs from secfoo.settings import CONFIG_PATH, ConfigError, load_config -from secfoo.skills.loader import SkillLoadError, load_all_skills, load_skill, register_skill_file +from secfoo.skills.loader import ( + SkillLoadError, + load_all_skills, + load_skill, + register_skill_file, +) from secfoo.skills.renderer import merge_excludes as _merge_excludes from secfoo.storage.repository import RunRepository from secfoo.targets.resolver import TargetResolutionError, resolve_target @@ -60,6 +67,46 @@ console = Console() err_console = Console(stderr=True) + +def _version_callback(value: bool) -> None: + if value: + console.print(f"secfoo {__version__}") + raise typer.Exit() + + +@app.callback() +def app_callback( + version: Annotated[ + bool | None, + typer.Option( + "--version", + "-v", + help="Show the version and exit.", + callback=_version_callback, + is_eager=True, + ), + ] = None, +) -> None: + """Context-based security architectural assessment.""" + + +@app.command(name="version") +def version_cmd( + json_output: Annotated[bool, typer.Option("--json", help="Print version details as JSON.")] = False, +) -> None: + """Print the secfoo version and environment details.""" + if json_output: + info = { + "version": __version__, + "python": platform.python_version(), + "platform": platform.platform(), + "store_path": str(STORE_DIR), + "config_path": str(CONFIG_PATH), + } + print(json.dumps(info, indent=2)) + else: + console.print(f"secfoo {__version__}") + CONFIG_EXAMPLE_PATH = Path(__file__).parent / "config.example.toml" @@ -172,6 +219,18 @@ def _is_interactive() -> bool: return sys.stdin.isatty() +def _is_stdout_tty() -> bool: + """False when stdout is redirected to a file or pipe (and under CliRunner) -- + gates the animated Progress spinner so non-TTY captures are never flooded + with redraw escape sequences, regardless of FORCE_COLOR. + """ + target = getattr(console, "file", sys.stdout) + try: + return bool(target.isatty()) + except (AttributeError, ValueError): + return False + + def _confirm_untrusted_skills(skill_ids: list[str], *, yes: bool, json_output: bool) -> None: """#93: a skill's text becomes agent instructions, so the first time a run would use one secfoo didn't author -- anything but a built-in or a @@ -457,29 +516,42 @@ def run( raise typer.Exit(code=0) task_ids: dict[str, int] = {} + is_tty = _is_stdout_tty() # In --json mode nothing but the final document may reach stdout, so # the spinner is disabled and human-facing notes go to stderr. + # In non-TTY mode (captured logs, CI file redirects), the live spinner + # is also disabled so redraw escape sequences do not flood output. progress = Progress( SpinnerColumn(finished_text=" "), TextColumn("{task.description}"), console=console, - disable=json_output, + disable=json_output or not is_tty, ) def handle_start(skill_name: str) -> None: - task_ids[skill_name] = progress.add_task(f"Running [bold]{skill_name}[/] via {agent.value}...", total=None) + if json_output: + return + if not is_tty: + console.print(f"Running [bold]{skill_name}[/] via {agent.value}...") + else: + task_ids[skill_name] = progress.add_task(f"Running [bold]{skill_name}[/] via {agent.value}...", total=None) def handle_complete(skill_name: str, result_status: str) -> None: + if json_output: + return style = _STATUS_STYLE.get(result_status, "white") - task_id = task_ids.get(skill_name) - if task_id is not None: - progress.update( - task_id, - description=f"[{style}]{result_status}[/] — {skill_name}", - total=1, - completed=1, - ) - progress.stop_task(task_id) + if not is_tty: + console.print(f"[{style}]{result_status}[/] — {skill_name}") + else: + task_id = task_ids.get(skill_name) + if task_id is not None: + progress.update( + task_id, + description=f"[{style}]{result_status}[/] — {skill_name}", + total=1, + completed=1, + ) + progress.stop_task(task_id) with progress: try: diff --git a/tests/test_cli.py b/tests/test_cli.py index e929064..4699ba9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -690,3 +690,93 @@ def test_run_configured_agent_wins_over_detection(monkeypatch): assert result.exit_code == 0, result.output assert captured["agent_id"] == "codex" assert "Using agent" not in result.output + + +def test_version_flag(): + result = runner.invoke(app, ["--version"]) + assert result.exit_code == 0 + assert "secfoo 0.3.0" in result.output + + result_short = runner.invoke(app, ["-v"]) + assert result_short.exit_code == 0 + assert "secfoo 0.3.0" in result_short.output + + +def test_version_command(): + result = runner.invoke(app, ["version"]) + assert result.exit_code == 0 + assert "secfoo 0.3.0" in result.output + + +def test_version_command_json(): + result = runner.invoke(app, ["version", "--json"]) + assert result.exit_code == 0 + data = json.loads(result.output) + assert data["version"] == "0.3.0" + assert "python" in data and len(data["python"]) > 0 + assert "platform" in data and len(data["platform"]) > 0 + assert "store_path" in data and ".secfoo" in data["store_path"] + assert "config_path" in data and "config.toml" in data["config_path"] + + +def test_non_tty_run_no_spinner_flooding_and_no_duplicate_completion(monkeypatch): + """#119: when stdout is not a TTY (captured to file/CI log), Progress + spinner must not flood redraw frames even with FORCE_COLOR=1, and each + skill's start and completion must be printed exactly once. + """ + monkeypatch.setenv("FORCE_COLOR", "1") + + def fake_execute_runs(**kwargs): + on_start = kwargs.get("on_skill_start") + on_complete = kwargs.get("on_skill_complete") + if on_start: + on_start("Secret Scanning") + on_start("SAST") + if on_complete: + on_complete("Secret Scanning", "success") + on_complete("SAST", "success") + return [ + RunOutcome("u1", "secret-scanning", "Secret Scanning", "claude", "success", 0, 1.0, "/tmp/1.md"), + RunOutcome("u2", "sast", "SAST", "claude", "success", 0, 1.0, "/tmp/2.md"), + ] + + monkeypatch.setattr("secfoo.cli.execute_runs", fake_execute_runs) + result = runner.invoke(app, ["run", "--skill", "secret-scanning", "--skill", "sast"]) + assert result.exit_code == 0, result.output + + # No spinner cursor movement escapes in non-TTY output + assert "\x1b[2K" not in result.output + assert "\x1b[1A" not in result.output + assert "\x1b[?25" not in result.output + + # Total byte count should be compact (< 2500 bytes) instead of 96+ KB + assert len(result.output) < 2500 + + # Start and completion lines must appear exactly once + assert result.output.count("Running Secret Scanning via claude...") == 1 + assert result.output.count("Running SAST via claude...") == 1 + assert result.output.count("success — Secret Scanning") == 1 + assert result.output.count("success — SAST") == 1 + + +def test_json_run_suppresses_progress_lines(monkeypatch): + """In --json mode, neither start nor completion messages reach stdout, + so the output remains pure byte-exact JSON. + """ + def fake_execute_runs(**kwargs): + on_start = kwargs.get("on_skill_start") + on_complete = kwargs.get("on_skill_complete") + if on_start: + on_start("SAST") + if on_complete: + on_complete("SAST", "success") + return [_outcome("success")] + + monkeypatch.setattr("secfoo.cli.execute_runs", fake_execute_runs) + result = runner.invoke(app, ["run", "--skill", "sast", "--agent", "claude", "--json"]) + assert result.exit_code == 0, result.output + assert "Running SAST" not in result.output + assert "success — SAST" not in result.output + doc = json.loads(result.output) + assert doc["exit_code"] == 0 + assert len(doc["runs"]) == 1