stackparity 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. stackparity/__init__.py +17 -0
  2. stackparity/_engine/agents/investigator.py +294 -0
  3. stackparity/_engine/agents/memory_agent.py +37 -0
  4. stackparity/_engine/agents/pipeline_agent.py +152 -0
  5. stackparity/_engine/agents/remediation_agent.py +248 -0
  6. stackparity/_engine/agents/runtime.py +177 -0
  7. stackparity/_engine/agents/specialists.py +709 -0
  8. stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
  9. stackparity/_engine/cli/__init__.py +2 -0
  10. stackparity/_engine/cli/main.py +1252 -0
  11. stackparity/_engine/cli/remediate.py +461 -0
  12. stackparity/_engine/cli/term.py +44 -0
  13. stackparity/_engine/config/__init__.py +0 -0
  14. stackparity/_engine/config/constants.py +88 -0
  15. stackparity/_engine/config/loader.py +155 -0
  16. stackparity/_engine/config/settings.py +108 -0
  17. stackparity/_engine/containers/__init__.py +12 -0
  18. stackparity/_engine/containers/discovery.py +143 -0
  19. stackparity/_engine/containers/models.py +72 -0
  20. stackparity/_engine/containers/trivy_image_scanner.py +165 -0
  21. stackparity/_engine/core/__init__.py +0 -0
  22. stackparity/_engine/core/capabilities.py +107 -0
  23. stackparity/_engine/core/finding_schema.py +305 -0
  24. stackparity/_engine/core/git_manager.py +206 -0
  25. stackparity/_engine/core/http.py +64 -0
  26. stackparity/_engine/core/models.py +109 -0
  27. stackparity/_engine/core/netpolicy.py +242 -0
  28. stackparity/_engine/core/plugins.py +43 -0
  29. stackparity/_engine/core/repository_inspector.py +243 -0
  30. stackparity/_engine/core/safe_env.py +48 -0
  31. stackparity/_engine/core/scan_orchestrator.py +289 -0
  32. stackparity/_engine/core/scan_state.py +58 -0
  33. stackparity/_engine/core/url_validator.py +135 -0
  34. stackparity/_engine/ecosystems/__init__.py +1 -0
  35. stackparity/_engine/ecosystems/registry.py +138 -0
  36. stackparity/_engine/evidence/__init__.py +1 -0
  37. stackparity/_engine/evidence/store.py +65 -0
  38. stackparity/_engine/explainability/__init__.py +0 -0
  39. stackparity/_engine/explainability/evidence_formatter.py +30 -0
  40. stackparity/_engine/explainability/explanation_engine.py +132 -0
  41. stackparity/_engine/explainability/explanation_validator.py +54 -0
  42. stackparity/_engine/explainability/prompt_templates.py +18 -0
  43. stackparity/_engine/graph/__init__.py +0 -0
  44. stackparity/_engine/graph/dependency_tracer.py +86 -0
  45. stackparity/_engine/graph/graph_builder.py +165 -0
  46. stackparity/_engine/graph/graph_diff.py +57 -0
  47. stackparity/_engine/graph/graph_exporter.py +194 -0
  48. stackparity/_engine/graph/graph_validator.py +46 -0
  49. stackparity/_engine/graph/impact_analyzer.py +23 -0
  50. stackparity/_engine/graph/tree_view.py +185 -0
  51. stackparity/_engine/intel/__init__.py +0 -0
  52. stackparity/_engine/intel/epss.py +53 -0
  53. stackparity/_engine/llm/__init__.py +1 -0
  54. stackparity/_engine/llm/client.py +138 -0
  55. stackparity/_engine/monitor/__init__.py +0 -0
  56. stackparity/_engine/monitor/watch.py +171 -0
  57. stackparity/_engine/non_cve/__init__.py +7 -0
  58. stackparity/_engine/non_cve/base.py +62 -0
  59. stackparity/_engine/non_cve/iac.py +144 -0
  60. stackparity/_engine/non_cve/sast.py +272 -0
  61. stackparity/_engine/non_cve/supply_chain.py +147 -0
  62. stackparity/_engine/orchestration/__init__.py +1 -0
  63. stackparity/_engine/orchestration/pipeline.py +279 -0
  64. stackparity/_engine/orchestration/supervisor.py +167 -0
  65. stackparity/_engine/pipeline_analysis/__init__.py +0 -0
  66. stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
  67. stackparity/_engine/pipeline_analysis/ci.py +189 -0
  68. stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
  69. stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
  70. stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
  71. stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
  72. stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
  73. stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
  74. stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
  75. stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
  76. stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
  77. stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
  78. stackparity/_engine/pipeline_analysis/eol.py +62 -0
  79. stackparity/_engine/pipeline_analysis/models.py +37 -0
  80. stackparity/_engine/policy/__init__.py +0 -0
  81. stackparity/_engine/policy/engine.py +216 -0
  82. stackparity/_engine/policy/resources/default.yaml +56 -0
  83. stackparity/_engine/policy/resources/strict.yaml +35 -0
  84. stackparity/_engine/reachability/__init__.py +0 -0
  85. stackparity/_engine/reachability/app_reachability.py +186 -0
  86. stackparity/_engine/reachability/scanners.py +215 -0
  87. stackparity/_engine/remediation/__init__.py +0 -0
  88. stackparity/_engine/remediation/adapters.py +198 -0
  89. stackparity/_engine/remediation/apply_local.py +309 -0
  90. stackparity/_engine/remediation/code_fixes.py +383 -0
  91. stackparity/_engine/remediation/compat.py +156 -0
  92. stackparity/_engine/remediation/container_plan.py +127 -0
  93. stackparity/_engine/remediation/delivery.py +31 -0
  94. stackparity/_engine/remediation/export.py +44 -0
  95. stackparity/_engine/remediation/lifecycle.py +623 -0
  96. stackparity/_engine/remediation/local_trial.py +358 -0
  97. stackparity/_engine/remediation/patchers.py +215 -0
  98. stackparity/_engine/remediation/planner.py +285 -0
  99. stackparity/_engine/remediation/pr_template_engine.py +234 -0
  100. stackparity/_engine/remediation/reachability_impact.py +147 -0
  101. stackparity/_engine/remediation/versions.py +92 -0
  102. stackparity/_engine/remediation/whatif.py +64 -0
  103. stackparity/_engine/remediation/worktree_pr.py +434 -0
  104. stackparity/_engine/reporting/__init__.py +0 -0
  105. stackparity/_engine/reporting/counts.py +63 -0
  106. stackparity/_engine/reporting/fix_pdf.py +343 -0
  107. stackparity/_engine/reporting/fix_report.py +135 -0
  108. stackparity/_engine/reporting/json_exporter.py +61 -0
  109. stackparity/_engine/reporting/report_generator.py +200 -0
  110. stackparity/_engine/reporting/sarif.py +71 -0
  111. stackparity/_engine/reporting/vex.py +57 -0
  112. stackparity/_engine/reporting/view.py +166 -0
  113. stackparity/_engine/risk_analysis/__init__.py +0 -0
  114. stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
  115. stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
  116. stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
  117. stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
  118. stackparity/_engine/risk_analysis/function_impact.py +184 -0
  119. stackparity/_engine/risk_analysis/production_context.py +252 -0
  120. stackparity/_engine/risk_analysis/risk_rules.py +81 -0
  121. stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
  122. stackparity/_engine/sandbox/__init__.py +0 -0
  123. stackparity/_engine/sandbox/runner.py +142 -0
  124. stackparity/_engine/sbom/__init__.py +0 -0
  125. stackparity/_engine/sbom/adapters/__init__.py +19 -0
  126. stackparity/_engine/sbom/adapters/builtin.py +29 -0
  127. stackparity/_engine/sbom/adapters/syft.py +26 -0
  128. stackparity/_engine/sbom/adapters/trivy.py +76 -0
  129. stackparity/_engine/sbom/builtin_generator.py +227 -0
  130. stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
  131. stackparity/_engine/sbom/exporters.py +153 -0
  132. stackparity/_engine/sbom/fusion/__init__.py +5 -0
  133. stackparity/_engine/sbom/fusion/engine.py +315 -0
  134. stackparity/_engine/sbom/fusion/hashes.py +47 -0
  135. stackparity/_engine/sbom/fusion/ledger.py +96 -0
  136. stackparity/_engine/sbom/fusion/registries.py +271 -0
  137. stackparity/_engine/sbom/fusion/resolver.py +143 -0
  138. stackparity/_engine/sbom/fusion/writer.py +114 -0
  139. stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
  140. stackparity/_engine/sbom/merge.py +71 -0
  141. stackparity/_engine/sbom/package_extractors/common.py +104 -0
  142. stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
  143. stackparity/_engine/sbom/package_extractors/npm.py +206 -0
  144. stackparity/_engine/sbom/package_extractors/others.py +267 -0
  145. stackparity/_engine/sbom/package_extractors/python.py +143 -0
  146. stackparity/_engine/sbom/quality_analyzer.py +191 -0
  147. stackparity/_engine/sbom/scanner_engine.py +98 -0
  148. stackparity/_engine/sbom/syft_runner.py +100 -0
  149. stackparity/_engine/sbom/tool_locator.py +69 -0
  150. stackparity/_engine/sbom/trivy_runner.py +82 -0
  151. stackparity/_engine/storage/__init__.py +0 -0
  152. stackparity/_engine/storage/cache.py +56 -0
  153. stackparity/_engine/storage/database.py +295 -0
  154. stackparity/_engine/storage/memory.py +146 -0
  155. stackparity/_engine/suspicious_changes/__init__.py +12 -0
  156. stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
  157. stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
  158. stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
  159. stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
  160. stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
  161. stackparity/_engine/suspicious_changes/package_risk.py +78 -0
  162. stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
  163. stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
  164. stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
  165. stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
  166. stackparity/_engine/tools/__init__.py +1 -0
  167. stackparity/_engine/tools/builtin.py +93 -0
  168. stackparity/_engine/tools/registry.py +66 -0
  169. stackparity/_engine/ui/__init__.py +0 -0
  170. stackparity/_engine/ui/components/__init__.py +0 -0
  171. stackparity/_engine/ui/components/common.py +238 -0
  172. stackparity/_engine/ui/components/live_progress.py +157 -0
  173. stackparity/_engine/ui/components/memory_panel.py +82 -0
  174. stackparity/_engine/ui/pages/__init__.py +0 -0
  175. stackparity/_engine/ui/pages/agents_page.py +76 -0
  176. stackparity/_engine/ui/pages/architecture_page.py +44 -0
  177. stackparity/_engine/ui/pages/fixes_page.py +98 -0
  178. stackparity/_engine/ui/pages/graph_page.py +203 -0
  179. stackparity/_engine/ui/pages/health_page.py +117 -0
  180. stackparity/_engine/ui/pages/monitor_page.py +67 -0
  181. stackparity/_engine/ui/pages/pipeline_page.py +219 -0
  182. stackparity/_engine/ui/pages/remediation_page.py +409 -0
  183. stackparity/_engine/ui/pages/reports_page.py +54 -0
  184. stackparity/_engine/ui/pages/sbom_page.py +210 -0
  185. stackparity/_engine/ui/pages/scan_page.py +131 -0
  186. stackparity/_engine/ui/pages/suspicious_page.py +551 -0
  187. stackparity/_engine/ui/pages/vulns_page.py +201 -0
  188. stackparity/_engine/ui/state.py +116 -0
  189. stackparity/_engine/ui/theme.py +201 -0
  190. stackparity/_engine/ui/visualizations/__init__.py +0 -0
  191. stackparity/_engine/ui/visualizations/graphs.py +373 -0
  192. stackparity/_engine/vulnerability/__init__.py +0 -0
  193. stackparity/_engine/vulnerability/cvss.py +58 -0
  194. stackparity/_engine/vulnerability/kev_client.py +47 -0
  195. stackparity/_engine/vulnerability/nvd_client.py +74 -0
  196. stackparity/_engine/vulnerability/osv_client.py +139 -0
  197. stackparity/_engine/vulnerability/remediation_engine.py +50 -0
  198. stackparity/_engine/vulnerability/verification.py +94 -0
  199. stackparity/_engine/vulnerability/version_matcher.py +299 -0
  200. stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
  201. stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
  202. stackparity/cli.py +30 -0
  203. stackparity/dashboard_app.py +95 -0
  204. stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
  205. stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
  206. stackparity/web_dist/index.html +13 -0
  207. stackparity/web_server.py +533 -0
  208. stackparity-1.0.0.dist-info/METADATA +204 -0
  209. stackparity-1.0.0.dist-info/RECORD +212 -0
  210. stackparity-1.0.0.dist-info/WHEEL +4 -0
  211. stackparity-1.0.0.dist-info/entry_points.txt +2 -0
  212. stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,1252 @@
1
+ """StackParity CLI — CLI-first, local-first software supply-chain security platform.
2
+
3
+ Exit codes (CI/CD documented):
4
+ 0 = Success / policy gate passed
5
+ 1 = Policy gate failed, or fix validation failed
6
+ 2 = Execution or configuration error, or incomplete coverage with --require-complete
7
+ 130 = Interrupted
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import shutil
14
+ import socket
15
+ import subprocess
16
+ import sys
17
+ import threading
18
+ import webbrowser
19
+ from pathlib import Path
20
+ from typing import Optional
21
+
22
+ import typer
23
+ from rich.panel import Panel
24
+ from rich.table import Table
25
+
26
+ # Ensure src/ is importable even when invoked directly as a script
27
+ _SRC = Path(__file__).resolve().parent.parent
28
+ if str(_SRC) not in sys.path:
29
+ sys.path.insert(0, str(_SRC))
30
+
31
+ from cli.term import SafeConsole # noqa: E402
32
+ from config.settings import ROOT, get_settings # noqa: E402
33
+ from storage.database import Database # noqa: E402
34
+
35
+ app = typer.Typer(
36
+ name="stackparity",
37
+ help="StackParity — CLI-first, local-first software supply-chain security platform.",
38
+ no_args_is_help=True,
39
+ add_completion=False,
40
+ )
41
+ auth_app = typer.Typer(help="Manage GitHub CLI and scanner authentication.")
42
+ app.add_typer(auth_app, name="auth")
43
+
44
+
45
+ def _version(value: bool) -> None:
46
+ if value:
47
+ from stackparity import __version__
48
+ print(f"stackparity {__version__}")
49
+ raise typer.Exit()
50
+
51
+
52
+ @app.callback(epilog=(
53
+ "Typical workflow: stackparity scan -> stackparity findings -> stackparity fix --interactive -> stackparity fix --apply "
54
+ "-> stackparity pr. Or run the whole guided flow with: stackparity run.\n\n"
55
+ "Exit codes: 0 success, 1 policy gate or validation failed, 2 usage/configuration/execution error, 130 interrupted."))
56
+ def _root(version: bool = typer.Option(False, "--version", "-V", callback=_version, is_eager=True, help="Show the version and exit.")) -> None:
57
+ """StackParity: CLI-first software supply-chain security. Scans are read-only; every change needs your explicit approval."""
58
+
59
+ for _stream in (sys.stdout, sys.stderr):
60
+ # pipes and redirected output on Windows default to a legacy code page, which corrupts non-ASCII text
61
+ if hasattr(_stream, "reconfigure") and not _stream.isatty():
62
+ _stream.reconfigure(encoding="utf-8", errors="replace")
63
+
64
+ # Repository content, package metadata and tool output are printed throughout; SafeConsole keeps their control characters
65
+ # (escape sequences, bidi overrides) visible and inert on every code path (see cli/term.py).
66
+ console = SafeConsole(stderr=False)
67
+ err_console = SafeConsole(stderr=True)
68
+
69
+
70
+ def _load_scan(db: Database, which: str = "latest") -> dict:
71
+ """Resolve 'latest' to the newest scan of the repository in the current directory, else the newest scan overall."""
72
+ scans = db.list_scans(200)
73
+ if not scans:
74
+ err_console.print("[red]No persisted scans found. Run 'stackparity scan' in your repository first.[/red]")
75
+ raise typer.Exit(code=2)
76
+ sid = which
77
+ if which == "latest":
78
+ here = {_repo_url_for(Path.cwd()), "local:" + Path.cwd().resolve().as_posix()}
79
+ sid = next((s["scan_id"] for s in scans if s["repo_url"] in here and s["status"] != "failed"), scans[0]["scan_id"])
80
+ res = db.load_scan(sid)
81
+ if not res:
82
+ err_console.print(f"[red]Scan '{sid}' not found in SQLite.[/red]")
83
+ raise typer.Exit(code=2)
84
+ return res
85
+
86
+
87
+ def _repo_url_for(path: Path) -> Optional[str]:
88
+ """The repo_url a local scan of ``path`` (or its Git root) is stored under."""
89
+ from core.git_manager import run_git
90
+ try:
91
+ top = run_git(["rev-parse", "--show-toplevel"], cwd=path, timeout=10, check=False).stdout.strip()
92
+ except Exception:
93
+ top = ""
94
+ root = Path(top) if top else path
95
+ return "local:" + root.resolve().as_posix()
96
+
97
+
98
+ def _port_free(port: int) -> bool:
99
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
100
+ try:
101
+ probe.bind(("127.0.0.1", port))
102
+ return True
103
+ except OSError:
104
+ return False
105
+
106
+
107
+ def _pick_port(preferred: int, strict: bool) -> int:
108
+ """The preferred loopback port, else the next free one (or an OS-assigned one); ``strict`` refuses to move."""
109
+ if _port_free(preferred):
110
+ return preferred
111
+ if strict:
112
+ err_console.print(f"[red]Port {preferred} is already in use. Choose another with --port.[/red]")
113
+ raise typer.Exit(code=2)
114
+ for port in range(preferred + 1, preferred + 50):
115
+ if _port_free(port):
116
+ return port
117
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
118
+ s.bind(("127.0.0.1", 0))
119
+ return s.getsockname()[1]
120
+
121
+
122
+ def _wait_ready(url: str, proc: subprocess.Popen, timeout: float = 45.0) -> bool:
123
+ import time
124
+ import urllib.request
125
+ deadline = time.monotonic() + timeout
126
+ direct = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback probe: never through a configured proxy
127
+ while time.monotonic() < deadline:
128
+ if proc.poll() is not None:
129
+ return False
130
+ try:
131
+ with direct.open(url, timeout=2) as resp: # noqa: S310 - loopback health check
132
+ if resp.status == 200:
133
+ return True
134
+ except OSError:
135
+ pass
136
+ time.sleep(0.3)
137
+ return False
138
+
139
+
140
+ def _stop(proc: subprocess.Popen) -> None:
141
+ if proc.poll() is None:
142
+ proc.terminate()
143
+ try:
144
+ proc.wait(timeout=10)
145
+ except subprocess.TimeoutExpired:
146
+ proc.kill()
147
+ proc.wait(timeout=5)
148
+
149
+
150
+ def _launch_dashboard(scan_id: Optional[str] = None, port: Optional[int] = None, open_browser: bool = True, legacy: bool = False) -> int:
151
+ """Start the dashboard on 127.0.0.1, wait until it answers, print the real URL, and stop it cleanly on Ctrl+C."""
152
+ import secrets
153
+ from urllib.parse import urlencode
154
+ if legacy:
155
+ missing = [m for m in ("streamlit", "pandas") if not _importable(m)]
156
+ extra = "legacy-dashboard"
157
+ else:
158
+ missing = [m for m in ("uvicorn", "starlette") if not _importable(m)]
159
+ extra = "dashboard"
160
+ if missing:
161
+ err_console.print(f"[red]The dashboard dependencies are not installed ({', '.join(missing)} missing).[/red]\n"
162
+ f"Install them with: pip install \"stackparity\\[{extra}]\" (pipx: pipx inject stackparity {' '.join(missing)})")
163
+ raise typer.Exit(code=2)
164
+ from stackparity.web_server import WEB_DIST_DIR
165
+ if not legacy and not (WEB_DIST_DIR / "index.html").exists():
166
+ err_console.print("[yellow]The compiled dashboard UI is missing from this installation; the API will run without the web UI.[/yellow]")
167
+
168
+ port = _pick_port(port or get_settings().dashboard_port, strict=port is not None)
169
+ token = secrets.token_urlsafe(24)
170
+ import stackparity
171
+ pkg_parent = str(Path(stackparity.__file__).resolve().parent.parent)
172
+ env = {**os.environ, "STACKPARITY_DASHBOARD_TOKEN": token, "STACKPARITY_PARENT_PID": str(os.getpid()),
173
+ "PYTHONPATH": os.pathsep.join(p for p in (pkg_parent, os.environ.get("PYTHONPATH")) if p)}
174
+ if legacy:
175
+ import stackparity.dashboard_app as dash_mod
176
+ env["STACKPARITY_INITIAL_SCAN_ID" if scan_id else "STACKPARITY_AUTOLOAD_LATEST"] = scan_id or "1"
177
+ cmd = [sys.executable, "-m", "streamlit", "run", str(Path(dash_mod.__file__).resolve()), "--server.address", "127.0.0.1",
178
+ "--server.port", str(port), "--server.headless", "true", "--browser.gatherUsageStats", "false"]
179
+ health = f"http://127.0.0.1:{port}/_stcore/health"
180
+ else:
181
+ cmd = [sys.executable, "-m", "uvicorn", "stackparity.web_server:app", "--host", "127.0.0.1", "--port", str(port), "--log-level", "warning"]
182
+ health = f"http://127.0.0.1:{port}/api/health"
183
+ url = f"http://127.0.0.1:{port}" + ("/?" + urlencode({"scan": scan_id}) if scan_id and not legacy else "")
184
+
185
+ err_console.print(f"Starting the StackParity dashboard on 127.0.0.1:{port} ...")
186
+ proc = subprocess.Popen(cmd, env=env, shell=False)
187
+ try:
188
+ if not _wait_ready(health, proc):
189
+ err_console.print("[red]The dashboard server did not start.[/red] Run 'stackparity doctor' to check the installation.")
190
+ _stop(proc)
191
+ raise typer.Exit(code=2)
192
+ console.print(Panel.fit(
193
+ f"[bold green]StackParity dashboard is running[/bold green]\n"
194
+ f"URL: [cyan]{url}[/cyan]\n"
195
+ f"Bound to the loopback interface only; changes require this session's token.\n"
196
+ f"Scan: {scan_id or 'latest persisted scan'}\n"
197
+ f"Press [bold]Ctrl+C[/bold] to stop the server.",
198
+ border_style="green"))
199
+ if open_browser:
200
+ try:
201
+ webbrowser.open(url)
202
+ except Exception:
203
+ pass
204
+ code = proc.wait()
205
+ except KeyboardInterrupt:
206
+ err_console.print("Stopping the dashboard ...")
207
+ _stop(proc)
208
+ err_console.print(f"Dashboard stopped; port {port} released." if _port_free(port) else "Dashboard stopped.")
209
+ return 0
210
+ finally:
211
+ _stop(proc) # whatever ends this function, the server process does not outlive it
212
+ return code
213
+
214
+
215
+ def _importable(module: str) -> bool:
216
+ import importlib.util
217
+ return importlib.util.find_spec(module) is not None
218
+
219
+
220
+ def _print_scan_summary(result: dict) -> None:
221
+ from reporting.view import dashboard_view
222
+ repo = result.get("repo") or {}
223
+ view = dashboard_view(result)
224
+ cov, counts = view["coverage"], view["counts"]
225
+ sources = ", ".join(f"{name}: {s.get('state')}" for name, s in (result.get("source_status") or {}).items()) or "no source queried"
226
+
227
+ table = Table(title=f"StackParity Scan Summary: {repo.get('name', 'repo')} ({repo.get('scan_id', '')})")
228
+ table.add_column("Category", style="cyan")
229
+ table.add_column("Count", justify="right", style="bold")
230
+ table.add_column("Notes", style="dim")
231
+ table.add_row("Components", str(counts["components"]), f"inventory {cov['inventory']['state'].replace('_', ' ')} ({cov['inventory']['source']})")
232
+ state = cov["vulnerability"]["state"]
233
+ table.add_row("Known vulnerabilities", "n/a" if state == "not_assessed" else str(counts["vulnerabilities"]),
234
+ f"{state.replace('_', ' ')}; {sources}")
235
+ severe = ", ".join(f"{row['count']} {row['severity'].lower()}" for row in view["severity"] if row["count"])
236
+ if severe:
237
+ table.add_row(" by severity", "", severe)
238
+ for row in view["non_cve"]["by_category"]:
239
+ table.add_row(row["label"], str(row["count"]), "non-CVE findings")
240
+ if not view["non_cve"]["by_category"]:
241
+ table.add_row("Non-CVE findings", "0", "no engine reported a finding")
242
+ table.add_row("Remediation proposals", str(counts["remediations"]), f"{view['remediation']['with_patch']} with a patch")
243
+ policy = result.get("policy_result")
244
+ if policy:
245
+ table.add_row("Policy gate", "PASS" if policy.get("passed") else "FAIL",
246
+ f"{policy.get('policy')}: {policy.get('blocking')} blocking, {policy.get('warnings')} warning(s)")
247
+ console.print(table)
248
+ if not cov["complete"]:
249
+ console.print("[yellow]Incomplete coverage (an absent finding is not proof of safety):[/yellow]")
250
+ for gap in cov["gaps"]:
251
+ console.print(f" - {gap}", markup=False)
252
+ if result.get("from_cache"):
253
+ console.print("[dim]Reused the stored scan of this commit. Use --deep to force a rescan.[/dim]")
254
+
255
+
256
+ def _print_environment(result: dict) -> None:
257
+ import platform
258
+ insp = result.get("inspection") or {}
259
+ repo = result.get("repo") or {}
260
+ techs = insp.get("technologies") or []
261
+ langs = ", ".join(insp.get("headline_languages") or list((insp.get("languages") or {}).keys())[:6]) or "none detected"
262
+ frameworks = ", ".join(f if isinstance(f, str) else str(f.get("name", f)) for f in insp.get("frameworks") or []) or "none detected"
263
+ supported = [t["name"] for t in techs if t.get("support") == "supported"]
264
+ partial = [t["name"] for t in techs if t.get("support") == "partial"]
265
+ unsupported = [t["name"] for t in techs if t.get("support") not in ("supported", "partial")] + [str(u) for u in insp.get("unsupported") or []]
266
+ engines = [f"SBOM: {(result.get('sbom_tool') or {}).get('used') or 'none'}"]
267
+ engines += [f"{k}: {v.get('status')}" for k, v in (result.get("scanner_status") or {}).items()]
268
+ engines += [f"{k}: {v.get('state')}" for k, v in (result.get("source_status") or {}).items()]
269
+ services = insp.get("services") or []
270
+ lines = [f"Repository: [bold]{repo.get('name')}[/bold] {repo.get('local_path') or repo.get('url')} commit {(repo.get('commit_sha') or '')[:12]}",
271
+ f"Environment: {platform.system()} {platform.release()}, Python {platform.python_version()}",
272
+ f"Languages: {langs} Frameworks: {frameworks}",
273
+ f"Ecosystems: supported {', '.join(supported) or 'none'}" + (f"; partial {', '.join(partial)}" if partial else ""),
274
+ f"Manifests and lockfiles: {len(insp.get('manifests') or [])} Services: {len(services)} "
275
+ f"Container/CI files: {len(insp.get('dockerfiles') or []) + len(insp.get('container_files') or []) + len(insp.get('ci_files') or [])}",
276
+ f"Engines: {', '.join(engines)}"]
277
+ if unsupported:
278
+ lines.append(f"[yellow]Detected but not supported: {', '.join(unsupported)}[/yellow]")
279
+ console.print(Panel("\n".join(lines), title="Scan context", border_style="cyan"))
280
+
281
+
282
+ def _print_stages(result: dict) -> None:
283
+ steps = [(a.get("agent"), s) for a in result.get("agents") or [] for s in a.get("steps") or []]
284
+ if not steps:
285
+ return
286
+ counts: dict[str, int] = {}
287
+ for _, s in steps:
288
+ counts[s.get("status") or "unknown"] = counts.get(s.get("status") or "unknown", 0) + 1
289
+ failed = [f"{agent}: {s.get('label')}" for agent, s in steps if s.get("status") in ("failed", "error")]
290
+ console.print("Stages: " + ", ".join(f"{n} {k}" for k, n in sorted(counts.items())) + f" Duration: {result.get('total_seconds', '?')}s")
291
+ for f in failed:
292
+ console.print(f" [red]failed[/red] {f}", markup=True)
293
+
294
+
295
+ def _next_steps(result: dict) -> None:
296
+ rem = len((result.get("remediation") or {}).get("items") or [])
297
+ steps = ["stackparity findings list every finding", "stackparity inspect <FINDING_ID> evidence and dependency paths"]
298
+ if rem or result.get("sast_findings") or result.get("iac_findings"):
299
+ steps.append("stackparity fix --interactive review and approve exact changes")
300
+ steps.append("stackparity dashboard open the localhost dashboard")
301
+ console.print("Next: " + "\n ".join(steps), markup=False)
302
+
303
+
304
+ @app.command()
305
+ def scan(
306
+ target: str = typer.Argument(".", help="Local project directory or public GitHub HTTPS URL."),
307
+ ref: Optional[str] = typer.Option(None, "--ref", help="Git branch or tag (for GitHub URLs)."),
308
+ mode: str = typer.Option("auto", "--mode", help="SBOM scanner mode: auto | builtin | syft | trivy."),
309
+ deep: bool = typer.Option(False, "--deep", help="Enable deep analysis (NVD, KEV, registry checks, investigator, remediation)."),
310
+ dashboard: bool = typer.Option(False, "--dashboard", help="Launch localhost dashboard after scan completes."),
311
+ offline: bool = typer.Option(False, "--offline", help="Offline mode: disable NVD, KEV, and registry network lookups."),
312
+ no_ai: bool = typer.Option(True, "--no-ai/--ai", help="Disable or enable optional grounded LLM reasoning."),
313
+ policy: Optional[str] = typer.Option(None, "--policy", help="Evaluate policy gate (default | strict | path)."),
314
+ fmt: Optional[str] = typer.Option(None, "--format", help="Export format: md | html | json | sarif | vex."),
315
+ out: Optional[Path] = typer.Option(None, "--out", help="Output file path for --format."),
316
+ json_out: bool = typer.Option(False, "--json", help="Print machine-readable JSON summary to stdout."),
317
+ quiet: bool = typer.Option(False, "--quiet", "-q", help="Suppress progress output."),
318
+ require_complete: bool = typer.Option(False, "--require-complete", help="Exit 2 when any part of the analysis was skipped or failed."),
319
+ non_interactive: bool = typer.Option(False, "--non-interactive", help="CI mode: plain log lines on stderr, no prompts or animations."),
320
+ ) -> None:
321
+ """Scan a repository or local folder for CVE and Non-CVE supply-chain risks (read-only).
322
+
323
+ Examples:\n
324
+ stackparity scan scan the current directory\n
325
+ stackparity scan ./service --deep add NVD, CISA KEV and registry checks\n
326
+ stackparity scan --offline no network access; coverage gaps are reported\n
327
+ stackparity scan --non-interactive --format json --out result.json
328
+ """
329
+ if mode not in ("auto", "builtin", "syft", "trivy"):
330
+ raise typer.BadParameter("Choose auto, builtin, syft or trivy", param_hint="--mode")
331
+ if not target.startswith("https://") and not Path(target).expanduser().is_dir():
332
+ err_console.print(f"[red]'{target}' is not a directory or an https:// GitHub URL.[/red]")
333
+ raise typer.Exit(code=2)
334
+ from cli.remediate import is_interactive
335
+ interactive = is_interactive(non_interactive)
336
+ result = _run_scan(target, ref=ref, mode=mode, deep=deep, offline=offline, no_ai=no_ai, policy=policy,
337
+ show_progress=not (quiet or json_out or (fmt and not out)), live=interactive and err_console.is_terminal)
338
+ from storage.memory import Memory
339
+ db = Database(get_settings().db_path)
340
+
341
+ if result.get("status") == "failed":
342
+ err_console.print(f"[red]Scan failed: {result.get('error')}[/red]")
343
+ raise typer.Exit(code=2)
344
+
345
+ exit_code = 0
346
+ if policy:
347
+ pr = result.get("policy_result")
348
+ if not pr:
349
+ err_console.print("Requested policy could not be evaluated.")
350
+ raise typer.Exit(code=2)
351
+ if not pr.get("passed"):
352
+ exit_code = 1
353
+
354
+ from reporting.view import coverage, dashboard_view
355
+ cov = coverage(result)
356
+ if policy and not cov["complete"] and not quiet:
357
+ err_console.print("Warning: the policy gate was evaluated on incomplete coverage: " + " ".join(cov["gaps"]), markup=False, soft_wrap=True)
358
+ if require_complete and not cov["complete"]:
359
+ err_console.print("Incomplete coverage (--require-complete): " + " ".join(cov["gaps"]), markup=False, soft_wrap=True)
360
+ exit_code = exit_code or 2
361
+
362
+ if fmt:
363
+ _export_report(result, fmt, out, Memory(db).decisions(result["repo"]["url"]))
364
+ elif json_out:
365
+ counts = dashboard_view(result)["counts"]
366
+ console.print_json(json.dumps({
367
+ "scan_id": result["repo"]["scan_id"],
368
+ "status": result.get("status"),
369
+ "components": counts["components"],
370
+ "vulnerabilities": counts["vulnerabilities"],
371
+ "non_cve_findings": counts["non_cve"],
372
+ "coverage": cov,
373
+ "standardized_findings": len(result.get("standardized_findings") or []),
374
+ "remediations": len((result.get("remediation") or {}).get("items") or []),
375
+ "policy_result": result.get("policy_result"),
376
+ "limitations": result.get("limitations", []),
377
+ }, default=str))
378
+ elif not quiet:
379
+ _print_environment(result)
380
+ _print_scan_summary(result)
381
+ _print_stages(result)
382
+ _next_steps(result)
383
+
384
+ if dashboard:
385
+ dashboard_code = _launch_dashboard(scan_id=result["repo"]["scan_id"], open_browser=interactive)
386
+ exit_code = exit_code or dashboard_code
387
+
388
+ raise typer.Exit(code=exit_code)
389
+
390
+
391
+ def _run_scan(target: str, *, ref: Optional[str] = None, mode: str = "auto", deep: bool = False, offline: bool = False, no_ai: bool = True,
392
+ policy: Optional[str] = None, show_progress: bool = True, live: bool = False) -> dict:
393
+ """Run the pipeline with progress driven by the pipeline's own events (no timers)."""
394
+ from core.scan_orchestrator import ScanOptions, run_scan
395
+ opts = ScanOptions.for_profile(target, deep=deep, offline=offline, policy=policy or "default", ref=ref,
396
+ use_llm=(not no_ai) and not offline, sbom_scanner=mode)
397
+ s = get_settings()
398
+ db = Database(s.db_path)
399
+ progress = None
400
+ task = None
401
+ if show_progress and live:
402
+ from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
403
+ progress = Progress(SpinnerColumn(), TextColumn("{task.description}"), BarColumn(), TextColumn("{task.percentage:>3.0f}%"),
404
+ TimeElapsedColumn(), console=err_console, transient=True)
405
+ task = progress.add_task("Starting", total=100)
406
+
407
+ def on_event(e: dict) -> None:
408
+ if not show_progress:
409
+ return
410
+ kind = e.get("kind")
411
+ pct = int((e.get("progress") or 0) * 100)
412
+ msg = str(e.get("message", ""))[:110]
413
+ if progress is not None:
414
+ progress.update(task, completed=pct, description=f"[cyan]{e.get('agent')}[/cyan] {msg}")
415
+ if kind in ("done", "warning", "error"):
416
+ mark = {"done": "[green]done[/green]", "warning": "[yellow]warn[/yellow]", "error": "[red]fail[/red]"}[kind]
417
+ progress.console.print(f" {mark} {e.get('agent')}: {msg}")
418
+ elif kind in ("start", "done", "warning", "error"):
419
+ err_console.print(f"[{pct:3d}%] {e.get('agent')}: {kind}: {msg}", markup=False, highlight=False)
420
+
421
+ try:
422
+ if progress is not None:
423
+ with progress:
424
+ result = run_scan(opts, settings=s, db=db, on_event=on_event)
425
+ else:
426
+ result = run_scan(opts, settings=s, db=db, on_event=on_event)
427
+ except KeyboardInterrupt:
428
+ err_console.print("[yellow]Scan interrupted; no result was saved.[/yellow]")
429
+ raise typer.Exit(code=130)
430
+ except Exception as exc:
431
+ err_console.print(f"Scan failed: {exc}", markup=False)
432
+ raise typer.Exit(code=2)
433
+ if result.get("status") == "failed":
434
+ err_console.print(f"Scan failed: {result.get('error')}", markup=False)
435
+ raise typer.Exit(code=2)
436
+ return result
437
+
438
+
439
+ def _candidate_rows(db, res):
440
+ from remediation import lifecycle
441
+ recs = lifecycle.records(db, res["repo"]["scan_id"])
442
+ cands = lifecycle.candidates(res, {k: v["choice"] for k, v in recs.items() if v.get("choice")})
443
+ return [(c, lifecycle.status(db, res, c, recs.get(c.id))) for c in cands]
444
+
445
+
446
+ @app.command()
447
+ def fix(
448
+ scan_id: str = typer.Argument("latest", help="Persisted scan ID (default: latest scan of this repository)."),
449
+ dry_run: bool = typer.Option(False, "--dry-run", help="Show every candidate and its exact diff; change nothing (the default)."),
450
+ interactive_review: bool = typer.Option(False, "--interactive", "-i", help="Review candidates one by one and approve, reject or skip each."),
451
+ apply: bool = typer.Option(False, "--apply", help="Validate the APPROVED changes in an isolated Git worktree, then offer to apply them."),
452
+ approve: list[str] = typer.Option([], "--approve", help="Approve this candidate ID (repeatable). Explicit, scoped authorization for CI."),
453
+ reject: list[str] = typer.Option([], "--reject", help="Reject this candidate ID (repeatable)."),
454
+ choose: list[str] = typer.Option([], "--choose", help="Select an alternative fix: ID=RULE (see the alternatives in --dry-run)."),
455
+ reason: str = typer.Option("", "--reason", help="Reason recorded with --approve/--reject."),
456
+ proposal_id: list[str] = typer.Option([], "--id", help="Limit the view or review to these candidate IDs."),
457
+ export: Optional[Path] = typer.Option(None, "--export", help="Write the approved changes as a patch file."),
458
+ run_tests: bool = typer.Option(False, "--run-tests", help="With --apply: run the project's tests in a network-isolated container (Docker)."),
459
+ lockfiles: bool = typer.Option(False, "--lockfiles", help="With --apply: regenerate and verify lockfiles (npm, pnpm, uv) without running package scripts."),
460
+ to_working_tree: bool = typer.Option(False, "--to-working-tree", help="With --apply: write validated changes into your checkout (asks first)."),
461
+ online: bool = typer.Option(False, "--online", help="Allow network access for this step after an --offline scan (registry metadata, lockfiles, test dependencies)."),
462
+ allow_stale_lockfile: bool = typer.Option(False, "--allow-stale-lockfile", help="Accept writing a manifest whose lockfile could not be regenerated."),
463
+ allow_build_code: bool = typer.Option(False, "--allow-build-code", help="Let Poetry/Pipenv build source distributions while locking (runs package code)."),
464
+ yes: bool = typer.Option(False, "--yes", "-y", help="Answer yes to the confirmation prompts of this command."),
465
+ non_interactive: bool = typer.Option(False, "--non-interactive", help="Never prompt; anything needing consent is declined unless --yes."),
466
+ json_out: bool = typer.Option(False, "--json", help="Print candidates and states as JSON."),
467
+ ) -> None:
468
+ """Review, approve and apply remediations. Nothing in your checkout changes without an explicit confirmation.
469
+
470
+ Examples:\n
471
+ stackparity fix list candidates with their diffs (dry run)\n
472
+ stackparity fix --interactive approve / reject / skip each change\n
473
+ stackparity fix --approve REM-001 --reason "reviewed" record one approval (CI)\n
474
+ stackparity fix --apply validate approved changes in an isolated worktree\n
475
+ stackparity fix --apply --to-working-tree then write them into your checkout
476
+ """
477
+ from cli import remediate as ui
478
+ from remediation import lifecycle
479
+ from remediation.lifecycle import LifecycleError
480
+
481
+ if sum(bool(x) for x in (interactive_review, apply, dry_run)) > 1:
482
+ err_console.print("Choose one of --dry-run, --interactive or --apply.", markup=False)
483
+ raise typer.Exit(code=2)
484
+ interactive = ui.is_interactive(non_interactive)
485
+ if interactive_review and not interactive:
486
+ err_console.print("--interactive needs a terminal. In CI, record decisions with --approve/--reject instead.", markup=False)
487
+ raise typer.Exit(code=2)
488
+ db = Database(get_settings().db_path)
489
+ res = _load_scan(db, scan_id)
490
+ lifecycle.ensure_schema(db)
491
+ wanted = {x.upper() for x in proposal_id}
492
+
493
+ if choose or approve or reject:
494
+ rows = {c.id: c for c, _ in _candidate_rows(db, res)}
495
+ code = 0
496
+ for spec in choose:
497
+ cid, _, rule = spec.partition("=")
498
+ cand = rows.get(cid.upper())
499
+ if not cand or not rule:
500
+ err_console.print(f"--choose expects ID=RULE with a known ID: {spec}", markup=False)
501
+ raise typer.Exit(code=2)
502
+ try:
503
+ rows[cand.id] = lifecycle._rechoose(res, cand, rule) if cand.kind == "code" else cand
504
+ lifecycle.transition(db, res, rows[cand.id], "pending_review", ui.actor(), f"Selected alternative {rule}")
505
+ except (LifecycleError, StopIteration) as exc:
506
+ err_console.print(str(exc) or f"{cid}: unknown alternative", markup=False)
507
+ code = 2
508
+ for decision, ids in (("approved", approve), ("rejected", reject)):
509
+ for cid in ids:
510
+ cand = rows.get(cid.upper())
511
+ if not cand:
512
+ err_console.print(f"Unknown candidate ID: {cid}", markup=False)
513
+ code = 2
514
+ continue
515
+ try:
516
+ st = lifecycle.decide(db, res, cand, decision, ui.actor(), reason or f"{decision} via CLI")
517
+ console.print(f"{cand.id}: {st['state']} ({cand.title})", markup=False)
518
+ except LifecycleError as exc:
519
+ err_console.print(f"{cand.id}: {exc}", markup=False)
520
+ code = 2
521
+ raise typer.Exit(code=code)
522
+
523
+ if interactive_review:
524
+ ui.review(console, db, res, only=sorted(wanted) or None)
525
+ approved = lifecycle.approved(db, res)
526
+ if approved:
527
+ console.print(f"{len(approved)} approved change(s) are ready. Next: stackparity fix --apply (validates in an isolated worktree)")
528
+ raise typer.Exit(code=0)
529
+
530
+ if apply:
531
+ policy = ui.network_policy(console, res, ["compatibility", "package_manager"], "Validation", online=online, interactive=interactive)
532
+ run, files = ui.execute(console, db, res, run_tests=run_tests, lockfiles=lockfiles, policy=policy, allow_build_code=allow_build_code)
533
+ if run is None:
534
+ raise typer.Exit(code=1 if lifecycle.repo_root_of(res) else 2)
535
+ if run.error or run.validation_status == "failed":
536
+ raise typer.Exit(code=1)
537
+ if export:
538
+ ui.export_patch(console, db, res, export, run)
539
+ if to_working_tree:
540
+ if not ui.apply_to_working_tree(console, db, res, run, *files, interactive=interactive, yes=yes, allow_stale=allow_stale_lockfile):
541
+ raise typer.Exit(code=1)
542
+ else:
543
+ console.print("Your checkout was not modified. Next: stackparity pr (open a pull request), "
544
+ "stackparity fix --apply --to-working-tree, or --export PATH.")
545
+ raise typer.Exit(code=0)
546
+
547
+ rows = [(c, st) for c, st in _candidate_rows(db, res) if not wanted or c.id in wanted]
548
+ if export:
549
+ ui.export_patch(console, db, res, export)
550
+ raise typer.Exit(code=0)
551
+ if json_out:
552
+ print(json.dumps([{**c.to_dict(), "status": st} for c, st in rows], indent=2, default=str))
553
+ raise typer.Exit(code=0)
554
+ if not rows:
555
+ console.print("[green]No remediation candidates for this scan.[/green]")
556
+ raise typer.Exit(code=0)
557
+ console.print(ui.candidates_table(rows))
558
+ for cand, st in rows:
559
+ if cand.diff:
560
+ console.print(f"\n[bold cyan]{cand.id}[/bold cyan] {cand.title} [dim]{cand.rationale[:160]}[/dim]")
561
+ ui.show_diff(console, cand.diff)
562
+ if len(cand.alternatives) > 1:
563
+ console.print(" alternatives: " + "; ".join(f"{a['key']} ({a['title']})" for a in cand.alternatives), markup=False)
564
+ manual = [c for c, _ in rows if c.manual]
565
+ if manual:
566
+ console.print(f"\n{len(manual)} finding(s) have manual recommendations only (no safe automatic change). See: stackparity fix --interactive")
567
+ console.print("[dim]Dry run: nothing was changed. Review with 'stackparity fix --interactive'.[/dim]")
568
+
569
+
570
+ @app.command()
571
+ def pr(
572
+ scan_id: str = typer.Argument("latest", help="Persisted scan ID (default: latest scan of this repository)."),
573
+ base: Optional[str] = typer.Option(None, "--base", help="Base branch for the pull request (default: the repository default)."),
574
+ run_tests: bool = typer.Option(False, "--run-tests", help="Run the project's tests in a network-isolated container (Docker)."),
575
+ lockfiles: bool = typer.Option(False, "--lockfiles", help="Regenerate and verify lockfiles (npm, pnpm, uv) without running package scripts."),
576
+ online: bool = typer.Option(False, "--online", help="Allow network access after an --offline scan (needed to push and open the PR)."),
577
+ allow_stale_lockfile: bool = typer.Option(False, "--allow-stale-lockfile", help="Publish even though a lockfile could not be regenerated."),
578
+ allow_build_code: bool = typer.Option(False, "--allow-build-code", help="Let Poetry/Pipenv build source distributions while locking (runs package code)."),
579
+ yes: bool = typer.Option(False, "--yes", "-y", help="Authorize pushing the branch and opening the pull request without a prompt."),
580
+ non_interactive: bool = typer.Option(False, "--non-interactive", help="Never prompt; publishing is declined unless --yes."),
581
+ ) -> None:
582
+ """Open a pull request with the APPROVED changes, validated in an isolated worktree. Never merges.
583
+
584
+ Without GitHub CLI authentication or an 'origin' remote, the validated patch and PR description are exported instead.
585
+ """
586
+ from cli import remediate as ui
587
+ from remediation import lifecycle
588
+
589
+ interactive = ui.is_interactive(non_interactive)
590
+ db = Database(get_settings().db_path)
591
+ res = _load_scan(db, scan_id)
592
+ lifecycle.ensure_schema(db)
593
+ root = lifecycle.repo_root_of(res)
594
+ if not root or not (root / ".git").exists():
595
+ err_console.print("The scanned directory is not a local Git repository; a pull request cannot be prepared.", markup=False)
596
+ raise typer.Exit(code=2)
597
+ if not lifecycle.approved(db, res):
598
+ console.print("No approved changes. Review them with 'stackparity fix --interactive' (or approve with 'stackparity fix --approve ID').")
599
+ raise typer.Exit(code=1)
600
+ policy = ui.network_policy(console, res, ["git_remote", "pr_publish", "compatibility", "package_manager"], "Publishing a pull request",
601
+ online=online, interactive=interactive)
602
+ ctx = ui.git_context(root, check_auth=policy.allows("pr_publish"))
603
+ console.print(f"Repository {root} branch {ctx['branch']} remote {ctx['remote'] or 'none'} provider {ctx['provider'] or 'unknown'} "
604
+ f"GitHub CLI {'authenticated' if ctx['gh_auth'] else ('installed' if ctx['gh'] else 'not installed')}", markup=False)
605
+ can_publish = ctx["provider"] == "github" and ctx["gh_auth"] and policy.allows("git_remote")
606
+
607
+ def publish(run) -> bool:
608
+ ui.preview_publish(console, run, ctx, base)
609
+ if not run.lock_consistent:
610
+ _, allowed = ui.lockfile_review(console, run, interactive, yes, allow_stale_lockfile)
611
+ if not allowed:
612
+ return False
613
+ if run.generated:
614
+ console.print(f"The commit includes {len(run.generated)} regenerated lockfile(s): {', '.join(sorted(run.generated))} (shown in the final diff above).",
615
+ markup=False)
616
+ return ui.confirm(console, f"Push branch {run.branch} to origin and open a pull request", interactive, yes)
617
+
618
+ run, _ = ui.execute(console, db, res, run_tests=run_tests, lockfiles=lockfiles, publish=publish if can_publish else None, base=base,
619
+ policy=policy, allow_build_code=allow_build_code)
620
+ if run is None:
621
+ raise typer.Exit(code=2)
622
+ if not can_publish or not run.published:
623
+ out = ui.default_patch_path(res)
624
+ if run.diff:
625
+ out.write_text(run.diff, encoding="utf-8", newline="")
626
+ out.with_suffix(".md").write_text(f"# {run.pr_title}\n\n{run.pr_body}\n", encoding="utf-8")
627
+ if not can_publish:
628
+ console.print("[yellow]A pull request could not be opened automatically:[/yellow]")
629
+ for p in ctx["problems"]:
630
+ console.print(f" - {p}", markup=False)
631
+ if run.diff:
632
+ console.print(f"Validated patch: {out}\nPull request description: {out.with_suffix('.md')}\n"
633
+ f"To publish manually: git switch -c {run.branch} && git apply \"{out}\" && git add -A && git commit -m \"{run.pr_title}\" "
634
+ f"&& git push -u origin {run.branch} && gh pr create --body-file \"{out.with_suffix('.md')}\"", markup=False, soft_wrap=True)
635
+ raise typer.Exit(code=1 if run.error or run.validation_status == "failed" else 0)
636
+ if run.reused_pr:
637
+ console.print(f"[bold green]A pull request for exactly these changes is already open:[/bold green] {run.pr_url} (nothing was pushed again)")
638
+ else:
639
+ console.print(f"[bold green]Pull request created:[/bold green] {run.pr_url}")
640
+ console.print("It was not merged. Review and merge it on GitHub when you are satisfied.")
641
+ if run.error:
642
+ err_console.print(run.error, markup=False)
643
+ raise typer.Exit(code=1)
644
+
645
+
646
+ @app.command()
647
+ def findings(
648
+ scan_id: str = typer.Argument("latest", help="Persisted scan ID (default: latest scan of this repository)."),
649
+ severity: list[str] = typer.Option([], "--severity", "-s", help="Filter by severity: critical, high, medium, low (repeatable or comma separated)."),
650
+ kind: str = typer.Option("all", "--type", "-t", help="all | cve | non-cve"),
651
+ limit: int = typer.Option(200, "--limit", "-n", min=1, help="Maximum rows to display."),
652
+ json_out: bool = typer.Option(False, "--json", help="Print the findings as JSON."),
653
+ ) -> None:
654
+ """List CVE and non-CVE findings of a scan, highest severity first."""
655
+ from reporting.view import _sev, non_cve_findings
656
+ if kind not in ("all", "cve", "non-cve"):
657
+ raise typer.BadParameter("Choose all, cve or non-cve", param_hint="--type")
658
+ wanted = {x.strip().upper() for s in severity for x in s.split(",") if x.strip()}
659
+ bad = wanted - {"CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO", "UNKNOWN"}
660
+ if bad:
661
+ raise typer.BadParameter(f"Unknown severity: {', '.join(sorted(bad))}", param_hint="--severity")
662
+ db = Database(get_settings().db_path)
663
+ res = _load_scan(db, scan_id)
664
+ rank = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3, "INFO": 4, "UNKNOWN": 5}
665
+ rows = []
666
+ if kind in ("all", "cve"):
667
+ for v in res.get("vulnerabilities") or []:
668
+ rows.append({"id": v.get("finding_id"), "type": "CVE", "severity": _sev(v.get("severity")), "advisory": v.get("primary_id"),
669
+ "where": f"{v.get('package_name')}@{v.get('installed_version')} ({v.get('ecosystem')})",
670
+ "title": (v.get("summary") or "")[:90], "fix": (v.get("fixed_versions") or [None])[0] or "-"})
671
+ if kind in ("all", "non-cve"):
672
+ for f in non_cve_findings(res):
673
+ rows.append({"id": f["finding_id"], "type": f["category_label"], "severity": f["severity"], "advisory": f.get("rule_id") or "-",
674
+ "where": (f"{f.get('file')}:{f.get('line')}" if f.get("line") else f.get("file")) if f.get("file") else (f.get("package") or "-"),
675
+ "title": f["title"][:90], "fix": (f.get("recommendation") or "-")[:60]})
676
+ if wanted:
677
+ rows = [r for r in rows if r["severity"] in wanted]
678
+ rows.sort(key=lambda r: (rank.get(r["severity"], 9), r["type"], str(r["id"])))
679
+ if json_out:
680
+ print(json.dumps({"scan_id": res["repo"]["scan_id"], "total": len(rows), "findings": rows[:limit]}, indent=2, default=str))
681
+ return
682
+ if not rows:
683
+ from reporting.view import coverage
684
+ cov = coverage(res)
685
+ console.print("No findings match." + ("" if cov["complete"] else " Coverage was incomplete, so this is not proof of safety."))
686
+ return
687
+ t = Table(title=f"Findings of scan {res['repo']['scan_id']} ({len(rows)})")
688
+ for col in ("ID", "Type", "Severity", "Advisory/Rule", "Package or location", "Title", "Fix"):
689
+ t.add_column(col, overflow="fold")
690
+ from cli.remediate import _sev as sev_style, safe
691
+ for r in rows[:limit]:
692
+ t.add_row(safe(r["id"]), safe(r["type"]), sev_style(r["severity"]), safe(r["advisory"]), safe(r["where"]), safe(r["title"]), safe(r["fix"]))
693
+ console.print(t)
694
+ if len(rows) > limit:
695
+ console.print(f"[dim]{len(rows) - limit} more; use --limit or --json.[/dim]")
696
+ console.print("[dim]Details: stackparity inspect <ID>[/dim]")
697
+
698
+
699
+ @app.command()
700
+ def inspect(
701
+ finding_id: str = typer.Argument(..., help="Finding ID (e.g. VULN-0001, SAST-AST-001), advisory ID (CVE/GHSA) or candidate ID (REM-001, FIX-...)."),
702
+ scan_id: str = typer.Option("latest", "--scan", help="Persisted scan ID (default: latest scan of this repository)."),
703
+ json_out: bool = typer.Option(False, "--json", help="Print as JSON."),
704
+ ) -> None:
705
+ """Show the evidence, dependency paths and remediation for one finding."""
706
+ from cli import remediate as ui
707
+ from reporting.view import non_cve_findings
708
+ db = Database(get_settings().db_path)
709
+ res = _load_scan(db, scan_id)
710
+ key = finding_id.strip()
711
+ up = key.upper()
712
+ vuln = next((v for v in res.get("vulnerabilities") or [] if up in {str(v.get("finding_id")).upper(), str(v.get("primary_id")).upper(),
713
+ *[str(a).upper() for a in v.get("aliases") or []]}), None)
714
+ other = next((f for f in non_cve_findings(res) if up in (f["finding_id"].upper(), f["uid"].upper())), None)
715
+ cands = {c.id: (c, st) for c, st in _candidate_rows(db, res)}
716
+ if up in cands:
717
+ cand, st = cands[up]
718
+ if json_out:
719
+ print(json.dumps({**cand.to_dict(), "status": st}, indent=2, default=str))
720
+ return
721
+ ui.show_candidate(console, cand, st, 1, 1)
722
+ ui.show_evidence(console, cand)
723
+ return
724
+ if not vuln and not other:
725
+ err_console.print(f"No finding '{key}' in scan {res['repo']['scan_id']}. List them with: stackparity findings", markup=False)
726
+ raise typer.Exit(code=2)
727
+ fid = (vuln or other)["finding_id"]
728
+ related = [(c, st) for c, st in cands.values() if fid in c.finding_ids]
729
+ if vuln:
730
+ paths = _paths_to(res, vuln.get("package_name"), vuln.get("installed_version"))
731
+ if json_out:
732
+ print(json.dumps({"finding": vuln, "dependency_paths": paths, "remediations": [{**c.to_dict(), "status": st} for c, st in related]}, indent=2, default=str))
733
+ return
734
+ s = ui.safe
735
+ lines = [f"[bold]{s(vuln.get('primary_id'))}[/bold] {s(fid)} severity {ui._sev(str(vuln.get('severity') or 'UNKNOWN').upper())} CVSS {s(vuln.get('cvss_score') or '-')}",
736
+ s(f"Package: {vuln.get('package_name')} {vuln.get('installed_version')} ({vuln.get('ecosystem')}) in {vuln.get('service_dir') or '.'}"),
737
+ s(f"Aliases: {', '.join(vuln.get('aliases') or []) or '-'}"),
738
+ s(f"Fixed in: {', '.join(vuln.get('fixed_versions') or []) or 'no fixed version recorded'}"),
739
+ s(f"Known exploited (CISA KEV): {'yes' if vuln.get('kev') else 'no / not checked'} EPSS: {vuln.get('epss') or '-'}"),
740
+ s(f"Reachability: {(vuln.get('reachability') or {}).get('status') or 'not assessed'} Verdict: {vuln.get('verdict') or '-'}"),
741
+ s(f"Summary: {vuln.get('summary') or '-'}")]
742
+ refs = [r for r in vuln.get("references") or [] if isinstance(r, str)][:5]
743
+ if refs:
744
+ lines.append(s("References: " + " ".join(refs)))
745
+ console.print(Panel("\n".join(lines), title="Finding", border_style="red"))
746
+ console.print("Dependency paths:" if paths else "Dependency paths: none recorded in the graph")
747
+ for p in paths[:10]:
748
+ console.print(" " + " > ".join(p), markup=False)
749
+ else:
750
+ if json_out:
751
+ print(json.dumps({"finding": other, "remediations": [{**c.to_dict(), "status": st} for c, st in related]}, indent=2, default=str))
752
+ return
753
+ s = ui.safe
754
+ console.print(Panel("\n".join([f"[bold]{s(other['title'])}[/bold] {s(fid)} {ui._sev(other['severity'])} confidence {s(other.get('confidence'))}",
755
+ s(f"Category: {other['category_label']} Engine: {other['engine']} Rule: {other.get('rule_id') or '-'}"),
756
+ s(f"Location: {other.get('file')}:{other.get('line')}" if other.get("file") else f"Package: {other.get('package') or '-'}"),
757
+ s(f"Classification: {other.get('classification') or '-'}"),
758
+ s(f"Description: {other.get('description') or '-'}"),
759
+ s(f"Recommendation: {other.get('recommendation') or '-'}")]), title="Finding", border_style="yellow"))
760
+ if other.get("snippet"):
761
+ console.print(Syntax_line(other["snippet"], other.get("file") or ""))
762
+ for c, st in related:
763
+ console.print(f"Remediation {c.id}: {c.title} ({st['state'].replace('_', ' ')})", markup=False)
764
+ ui.show_diff(console, c.diff)
765
+ if not related:
766
+ console.print("[dim]No remediation candidate addresses this finding.[/dim]")
767
+
768
+
769
+ def Syntax_line(code: str, path: str):
770
+ from rich.syntax import Syntax
771
+ lexer = Syntax.guess_lexer(path, code=code) if path else "text"
772
+ return Syntax(code, lexer, theme="ansi_dark", background_color="default", word_wrap=True)
773
+
774
+
775
+ def _paths_to(res: dict, name: Optional[str], version: Optional[str], limit: int = 25) -> list[list[str]]:
776
+ import networkx as nx
777
+ from graph.graph_exporter import graph_from_json
778
+ gd = res.get("graph") or {}
779
+ if not gd.get("nodes") or not name:
780
+ return []
781
+ g = graph_from_json(gd)
782
+ targets = [n for n, d in g.nodes(data=True) if str(d.get("name", "")).lower() == name.lower() and (version is None or d.get("version") in (version, None))]
783
+ roots = [n for n, d in g.nodes(data=True) if d.get("kind") == "root"] or [n for n in g.nodes if g.in_degree(n) == 0]
784
+ label = lambda n: g.nodes[n].get("label") or str(n) # noqa: E731
785
+ out: list[list[str]] = []
786
+ for t in targets:
787
+ for r in roots:
788
+ if r == t or not nx.has_path(g, r, t):
789
+ continue
790
+ for p in nx.all_simple_paths(g, r, t, cutoff=12):
791
+ out.append([label(n) for n in p])
792
+ if len(out) >= limit:
793
+ return out
794
+ return out
795
+
796
+
797
+ @app.command()
798
+ def trace(
799
+ package: str = typer.Argument(..., help="Package name, optionally name@version."),
800
+ scan_id: str = typer.Option("latest", "--scan", help="Persisted scan ID (default: latest scan of this repository)."),
801
+ limit: int = typer.Option(25, "--limit", "-n", min=1, help="Maximum number of paths."),
802
+ json_out: bool = typer.Option(False, "--json", help="Print as JSON."),
803
+ ) -> None:
804
+ """Trace how a package enters the dependency graph and which findings it carries."""
805
+ db = Database(get_settings().db_path)
806
+ res = _load_scan(db, scan_id)
807
+ name, _, version = package.rpartition("@") if "@" in package[1:] else (package, "", "")
808
+ paths = _paths_to(res, name, version or None, limit)
809
+ vulns = [v for v in res.get("vulnerabilities") or [] if str(v.get("package_name", "")).lower() == name.lower()
810
+ and (not version or v.get("installed_version") == version)]
811
+ comps = [c for c in res.get("components") or [] if str(c.get("name", "")).lower() == name.lower()]
812
+ if json_out:
813
+ print(json.dumps({"package": package, "versions": sorted({str(c.get("version")) for c in comps}), "paths": paths,
814
+ "findings": [{"id": v.get("finding_id"), "advisory": v.get("primary_id"), "severity": v.get("severity")} for v in vulns]}, indent=2))
815
+ return
816
+ if not comps and not paths:
817
+ err_console.print(f"{package} is not in the inventory of scan {res['repo']['scan_id']}.", markup=False)
818
+ raise typer.Exit(code=2)
819
+ console.print(f"[bold]{package}[/bold]: versions {', '.join(sorted({str(c.get('version')) for c in comps})) or '?'}; "
820
+ f"{len(vulns)} known vulnerabilit{'y' if len(vulns) == 1 else 'ies'}")
821
+ if not paths:
822
+ console.print("No dependency path was recorded (the inventory has no relationship data for it).")
823
+ for p in paths:
824
+ console.print(" " + " > ".join(p), markup=False)
825
+ for v in vulns[:20]:
826
+ console.print(f" {v.get('finding_id')} {v.get('primary_id')} {v.get('severity')} fixed in {', '.join(v.get('fixed_versions') or []) or '-'}", markup=False)
827
+
828
+
829
+ @app.command("run")
830
+ def run_workflow(
831
+ target: str = typer.Argument(".", help="Repository directory (default: current directory)."),
832
+ deep: bool = typer.Option(False, "--deep", help="Deep scan (NVD, CISA KEV, registry checks)."),
833
+ offline: bool = typer.Option(False, "--offline", help="No network access."),
834
+ run_tests: bool = typer.Option(False, "--run-tests", help="Run the project's tests in a network-isolated container during validation."),
835
+ lockfiles: bool = typer.Option(False, "--lockfiles", help="Regenerate npm lockfiles without running scripts."),
836
+ non_interactive: bool = typer.Option(False, "--non-interactive", help="Scan and report only; never prompt or change anything."),
837
+ ) -> None:
838
+ """Scan a local project, review and apply validated fixes, and optionally open the dashboard."""
839
+ from cli import remediate as ui
840
+ from remediation import lifecycle
841
+
842
+ path = Path(target).expanduser().resolve()
843
+ if not path.is_dir():
844
+ err_console.print(f"'{target}' is not a directory.", markup=False)
845
+ raise typer.Exit(code=2)
846
+ interactive = ui.is_interactive(non_interactive)
847
+ console.rule("[bold]Scan[/bold]")
848
+ res = _run_scan(str(path), deep=deep, offline=offline, show_progress=True, live=interactive and err_console.is_terminal)
849
+ _print_environment(res)
850
+ _print_scan_summary(res)
851
+ _print_stages(res)
852
+ db = Database(get_settings().db_path)
853
+ lifecycle.ensure_schema(db)
854
+ scan_id = res["repo"]["scan_id"]
855
+ res = db.load_scan(scan_id) or res
856
+
857
+ console.rule("[bold]Remediation[/bold]")
858
+ rows = _candidate_rows(db, res)
859
+ manual = sum(c.manual for c, _ in rows)
860
+ applied = 0
861
+ outcome = "No applicable fixes"
862
+ exit_code = 0
863
+ if rows:
864
+ console.print(ui.candidates_table(rows))
865
+ if not interactive:
866
+ outcome = "Non-interactive run: nothing was reviewed or changed"
867
+ elif len(rows) > manual:
868
+ if res["repo"].get("commit_sha") in (None, "", "unversioned") or res["repo"]["url"] != _repo_url_for(path):
869
+ outcome = "Local application requires scanning a Git repository root with at least one commit"
870
+ elif ui.ask_yes(console, "Review fixes for local application"):
871
+ ui.review(console, db, res)
872
+ outcome = "No approved fixes"
873
+ if lifecycle.approved(db, res):
874
+ run, files = ui.execute(console, db, res, run_tests=run_tests, lockfiles=lockfiles)
875
+ if run is None or run.error or run.validation_status == "failed":
876
+ outcome = "Validation failed"
877
+ exit_code = 1
878
+ else:
879
+ outcome = run.validation_status.replace("_", " ").capitalize()
880
+ if ui.apply_to_working_tree(console, db, res, run, *files, interactive=True, yes=False):
881
+ applied = len(run.item_ids)
882
+ else:
883
+ outcome = "Review skipped"
884
+
885
+ console.print(f"Scan {scan_id} saved.\n{outcome}.\nApplied {applied} fix(es). {manual} manual recommendation(s).", markup=False)
886
+ if interactive and ui.ask_yes(console, "View insights in the dashboard?"):
887
+ dashboard_code = _launch_dashboard(scan_id=scan_id)
888
+ exit_code = exit_code or dashboard_code
889
+ if exit_code:
890
+ raise typer.Exit(code=exit_code)
891
+
892
+
893
+ @app.command()
894
+ def clean(
895
+ workspaces: bool = typer.Option(False, "--workspaces", help="Remove leftover temporary worktrees and clones."),
896
+ keep: Optional[int] = typer.Option(None, "--keep-scans", min=1, help="Keep only the newest N scans of each repository (with their artifacts)."),
897
+ patches: bool = typer.Option(False, "--patches", help="Remove exported patch files."),
898
+ all_: bool = typer.Option(False, "--all", help="Workspaces and patches, and keep 5 scans per repository."),
899
+ dry_run: bool = typer.Option(False, "--dry-run", help="Only list what would be removed."),
900
+ yes: bool = typer.Option(False, "--yes", "-y", help="Do not ask for confirmation."),
901
+ non_interactive: bool = typer.Option(False, "--non-interactive", help="Never prompt; removal is declined unless --yes."),
902
+ ) -> None:
903
+ """Remove StackParity's own temporary data. Never touches your repositories."""
904
+ from cli import remediate as ui
905
+ from core.git_manager import run_git
906
+ s = get_settings()
907
+ if all_:
908
+ workspaces, patches, keep = True, True, keep or 5
909
+ if not (workspaces or patches or keep):
910
+ console.print(f"Data: {s.data_dir}\nWorkspaces: {s.workspace_dir}\nArtifacts: {s.artifacts_dir}\n"
911
+ "Choose what to remove: --workspaces, --patches, --keep-scans N, or --all (add --dry-run to preview).", markup=False)
912
+ return
913
+ db = Database(s.db_path)
914
+ victims: list[Path] = []
915
+ scans_to_drop: list[tuple[str, int]] = []
916
+ if workspaces and s.workspace_dir.exists():
917
+ victims += [p for p in s.workspace_dir.iterdir()]
918
+ if patches and (s.artifacts_dir / "patches").exists():
919
+ victims += list((s.artifacts_dir / "patches").iterdir())
920
+ if keep:
921
+ repos: dict[str, int] = {}
922
+ for row in db.list_scans(100000):
923
+ repos[row["repo_url"]] = repos.get(row["repo_url"], 0) + 1
924
+ scans_to_drop = [(url, n - keep) for url, n in repos.items() if n > keep]
925
+ total_scans = sum(n for _, n in scans_to_drop)
926
+ console.print(f"Would remove {len(victims)} file(s)/folder(s) and {total_scans} old scan(s).")
927
+ for v in victims[:20]:
928
+ console.print(f" {v}", markup=False)
929
+ if dry_run or (not victims and not total_scans):
930
+ return
931
+ if not ui.confirm(console, "Remove them", ui.is_interactive(non_interactive), yes):
932
+ raise typer.Exit(code=0)
933
+ for v in victims:
934
+ if v.is_dir():
935
+ shutil.rmtree(v, ignore_errors=True)
936
+ else:
937
+ v.unlink(missing_ok=True)
938
+ removed = 0
939
+ for url, _ in scans_to_drop:
940
+ for sid in db.prune_repo(url, keep):
941
+ removed += 1
942
+ for sub in ("sbom", "scans", "reports", "graphs"):
943
+ for f in (s.artifacts_dir / sub).glob(f"*{sid}*"):
944
+ f.unlink(missing_ok=True)
945
+ if workspaces:
946
+ for row in db.list_scans(1000):
947
+ path = (row.get("repo_url") or "").removeprefix("local:")
948
+ if path and (Path(path) / ".git").exists():
949
+ run_git(["worktree", "prune"], cwd=Path(path), check=False)
950
+ console.print(f"Removed {len(victims)} item(s) and {removed} scan(s).")
951
+
952
+
953
+ @app.command()
954
+ def dashboard(
955
+ scan_id: Optional[str] = typer.Argument(None, help="Optional scan ID to preload (defaults to latest persisted scan)."),
956
+ port: Optional[int] = typer.Option(None, "--port", "-p", help="Localhost port (default: dashboard_port setting, 8501)."),
957
+ no_browser: bool = typer.Option(False, "--no-browser", help="Do not automatically open the browser."),
958
+ legacy: bool = typer.Option(False, "--legacy", help="Launch the legacy Streamlit dashboard instead of React."),
959
+ ) -> None:
960
+ """Launch the localhost dashboard bound strictly to 127.0.0.1."""
961
+ raise typer.Exit(code=_launch_dashboard(scan_id=scan_id, port=port, open_browser=not no_browser, legacy=legacy))
962
+
963
+
964
+ @app.command()
965
+ def sbom(scan_id: str = typer.Argument("latest"), out: Optional[Path] = typer.Option(None, "--out")) -> None:
966
+ """Export the original CycloneDX SBOM from a persisted scan."""
967
+ from sbom.exporters import stored_sbom_path
968
+
969
+ settings = get_settings()
970
+ scan = _load_scan(Database(settings.db_path), scan_id)
971
+ try:
972
+ artifact = stored_sbom_path(scan, settings.artifacts_dir)
973
+ if out:
974
+ shutil.copyfile(artifact, out)
975
+ else:
976
+ sys.stdout.buffer.write(artifact.read_bytes())
977
+ except OSError as exc:
978
+ err_console.print(str(exc), markup=False)
979
+ raise typer.Exit(code=2)
980
+
981
+
982
+ @app.command()
983
+ def graph(
984
+ scan_id: str = typer.Argument("latest", help="Persisted scan ID (or 'latest')."),
985
+ out: Optional[Path] = typer.Option(None, "--out", "-o", help="Export complete uncapped dependency graph JSON to file."),
986
+ ) -> None:
987
+ """Inspect or export the complete, uncapped dependency graph."""
988
+ from graph.graph_exporter import dependency_payload, graph_from_json
989
+
990
+ db = Database(get_settings().db_path)
991
+ res = _load_scan(db, scan_id)
992
+ gd = res.get("graph") or {"nodes": [], "edges": [], "relationships": {}}
993
+ g = graph_from_json(gd)
994
+ payload = dependency_payload(g, gd.get("relationships") or {}, {}, {}, {}, {}, cap=None)
995
+
996
+ if out:
997
+ out.parent.mkdir(parents=True, exist_ok=True)
998
+ out.write_text(json.dumps(gd, indent=2), encoding="utf-8")
999
+ console.print(f"[green]Exported complete graph ({len(payload['nodes'])} nodes, {len(payload['edges'])} edges) to {out}[/green]")
1000
+ return
1001
+
1002
+ console.print(Panel.fit(
1003
+ f"Scan ID: [cyan]{res['repo']['scan_id']}[/cyan]\n"
1004
+ f"Total Nodes: [bold]{len(payload['nodes'])}[/bold] (truncated={payload['truncated']})\n"
1005
+ f"Total Edges: [bold]{len(payload['edges'])}[/bold]\n"
1006
+ f"Direct Packages: [bold]{payload['directs']}[/bold]",
1007
+ title="Dependency Graph Topology",
1008
+ ))
1009
+
1010
+
1011
+ def _export_report(result: dict, fmt: str, out: Optional[Path], decisions: Optional[dict] = None) -> None:
1012
+ from reporting import json_exporter, report_generator
1013
+ from reporting.sarif import to_sarif
1014
+ from reporting.vex import to_vex
1015
+
1016
+ builders = {
1017
+ "md": lambda: report_generator.generate_markdown(result),
1018
+ "html": lambda: report_generator.generate_html(result),
1019
+ "json": lambda: json_exporter.dumps(result),
1020
+ "sarif": lambda: json_exporter.dumps(to_sarif(result)),
1021
+ "vex": lambda: json_exporter.dumps(to_vex(result, decisions)),
1022
+ }
1023
+ if fmt not in builders:
1024
+ err_console.print(f"[red]Unsupported format '{fmt}'. Choose from: md, html, json, sarif, vex.[/red]")
1025
+ raise typer.Exit(code=2)
1026
+ text = builders[fmt]()
1027
+ if out:
1028
+ out.parent.mkdir(parents=True, exist_ok=True)
1029
+ out.write_text(text, encoding="utf-8")
1030
+ console.print(f"[green]Wrote {fmt.upper()} report to {out}[/green]")
1031
+ else:
1032
+ print(text)
1033
+
1034
+
1035
+ @app.command()
1036
+ def report(
1037
+ scan_id: str = typer.Argument("latest", help="Persisted scan ID (or 'latest')."),
1038
+ fmt: str = typer.Option("md", "--format", "-f", help="Report format: md | html | json | sarif | vex."),
1039
+ out: Optional[Path] = typer.Option(None, "--out", "-o", help="Write report to file instead of stdout."),
1040
+ ) -> None:
1041
+ """Generate a report from a persisted scan without rescanning."""
1042
+ from storage.memory import Memory
1043
+
1044
+ db = Database(get_settings().db_path)
1045
+ res = _load_scan(db, scan_id)
1046
+ _export_report(res, fmt, out, Memory(db).decisions(res["repo"]["url"]))
1047
+
1048
+
1049
+ @auth_app.command("login")
1050
+ def auth_login(
1051
+ status: bool = typer.Option(False, "--status", help="Check current GitHub CLI and API token status without interactive login."),
1052
+ ) -> None:
1053
+ """Authenticate GitHub CLI ('gh') for PR creation and check API token configuration."""
1054
+ gh = shutil.which("gh")
1055
+ s = get_settings()
1056
+ if status or not gh:
1057
+ table = Table(title="Authentication & Token Status")
1058
+ table.add_column("Integration", style="cyan")
1059
+ table.add_column("Status")
1060
+ gh_ok = False
1061
+ if gh:
1062
+ p = subprocess.run([gh, "auth", "status"], capture_output=True, text=True, shell=False)
1063
+ gh_ok = p.returncode == 0
1064
+ table.add_row("GitHub CLI (gh)", "[green]authenticated[/green]" if gh_ok else ("[yellow]installed, not logged in[/yellow]" if gh else "[red]not installed[/red]"))
1065
+ table.add_row("NVD_API_KEY", "[green]configured[/green]" if s.nvd_api_key else "[dim]not set (public rate limit)[/dim]")
1066
+ table.add_row("LLM_API_KEY", "[green]configured[/green]" if s.llm_api_key else "[dim]not set (deterministic mode)[/dim]")
1067
+ console.print(table)
1068
+ return
1069
+
1070
+ proc = subprocess.run([gh, "auth", "login"], shell=False)
1071
+ raise typer.Exit(code=proc.returncode)
1072
+
1073
+
1074
+ @app.command()
1075
+ def doctor(json_out: bool = typer.Option(False, "--json", help="Print the diagnostics as JSON.")) -> None:
1076
+ """Check environment health, scanner availability, plugins, configuration and optional extras."""
1077
+ from core.capabilities import diagnostics
1078
+ s = get_settings()
1079
+ info = diagnostics(s)
1080
+ broken = _dependency_issues()
1081
+ info["core_dependencies"] = broken
1082
+ if json_out:
1083
+ print(json.dumps(info, indent=2, default=str))
1084
+ return
1085
+
1086
+ table = Table(title=f"StackParity Doctor {info['version']} (Python {info['python']}, {info['platform']})")
1087
+ table.add_column("Component", style="cyan")
1088
+ table.add_column("State")
1089
+ table.add_column("Detail")
1090
+ table.add_row("Built-in SBOM engine", "[green]OK[/green]", "lockfile and manifest parsing")
1091
+ table.add_row("Built-in non-CVE scanners", "[green]OK[/green]", ", ".join(x["name"] for x in info["builtin"]["scanners"]))
1092
+ for t in info["tools"]:
1093
+ table.add_row(t["label"], "[green]OK[/green]" if t["available"] else "[yellow]not found[/yellow]",
1094
+ t["path"] if t["available"] else f"optional; {t['fallback']}")
1095
+ for extra in info["extras"]:
1096
+ table.add_row(f"extra: {extra['extra']}", "[green]OK[/green]" if extra["installed"] else "[yellow]not installed[/yellow]",
1097
+ "installed" if extra["installed"] else "missing " + ", ".join(extra["missing"]))
1098
+ for plugin in info["plugins"]:
1099
+ table.add_row(f"plugin: {plugin['name']}", "[green]OK[/green]" if plugin["status"] == "loaded" else "[red]error[/red]", plugin.get("error", "loaded"))
1100
+ table.add_row("NVD API key", "[green]OK[/green]" if info["credentials"]["nvd_api_key"] else "[dim]unset[/dim]", "optional; public rate limit otherwise")
1101
+ table.add_row("SQLite database", "[green]OK[/green]" if s.db_path.parent.exists() else "[red]missing[/red]", info["storage"]["database"])
1102
+ table.add_row("Core dependencies", "[green]OK[/green]" if not broken else "[red]problem[/red]", "; ".join(broken) or "compatible")
1103
+ for problem in info["configuration_problems"]:
1104
+ table.add_row("Configuration", "[yellow]warning[/yellow]", problem)
1105
+ console.print(table)
1106
+
1107
+
1108
+ def _dependency_issues() -> list[str]:
1109
+ """Installed versions that violate the package metadata (reported, never changed)."""
1110
+ from importlib import metadata
1111
+ try:
1112
+ from packaging.requirements import Requirement
1113
+ requirements = metadata.requires("stackparity") or []
1114
+ except (ImportError, metadata.PackageNotFoundError):
1115
+ return []
1116
+ issues = []
1117
+ for text in requirements:
1118
+ req = Requirement(text)
1119
+ if req.marker and not req.marker.evaluate({"extra": ""}):
1120
+ continue
1121
+ try:
1122
+ version = metadata.version(req.name)
1123
+ if not req.specifier.contains(version, prereleases=True):
1124
+ issues.append(f"{req.name}=={version} violates {req.specifier}")
1125
+ except metadata.PackageNotFoundError:
1126
+ issues.append(f"{req.name} missing")
1127
+ return issues
1128
+
1129
+
1130
+ @app.command()
1131
+ def history(
1132
+ limit: int = typer.Option(20, "--limit", "-n", help="Number of recent scans to display."),
1133
+ json_out: bool = typer.Option(False, "--json", help="Output scan history as JSON."),
1134
+ ) -> None:
1135
+ """List persisted scans stored in local SQLite."""
1136
+ db = Database(get_settings().db_path)
1137
+ rows = db.list_scans(limit)
1138
+ if json_out:
1139
+ console.print_json(json.dumps(rows, default=str))
1140
+ return
1141
+ if not rows:
1142
+ console.print("[dim]No scans recorded yet.[/dim]")
1143
+ return
1144
+ table = Table(title=f"Scan History (latest {len(rows)})")
1145
+ table.add_column("Scan ID", style="cyan")
1146
+ table.add_column("Repository")
1147
+ table.add_column("Timestamp")
1148
+ table.add_column("Status")
1149
+ table.add_column("Vulns", justify="right")
1150
+ for r in rows:
1151
+ summary = r.get("summary") or {}
1152
+ confirmed, unconfirmed = summary.get("vulnerabilities_confirmed"), summary.get("vulnerabilities_unknown")
1153
+ if summary.get("vulnerability_assessment") == "not_assessed":
1154
+ vulns = "not assessed"
1155
+ elif confirmed is None:
1156
+ vulns = "unrecorded"
1157
+ else:
1158
+ vulns = str(confirmed + (unconfirmed or 0))
1159
+ table.add_row(str(r.get("scan_id")), str(r.get("repo_url") or r.get("repo_name")), str(r.get("scan_timestamp")), str(r.get("status")), vulns)
1160
+ console.print(table)
1161
+
1162
+
1163
+ @app.command()
1164
+ def setup(
1165
+ install: Optional[str] = typer.Option(None, "--install", help="Install one optional tool, with authorization."),
1166
+ recommended: bool = typer.Option(False, "--recommended", help="Install the external SBOM scanners (syft, trivy), with authorization."),
1167
+ yes: bool = typer.Option(False, "--yes", "-y", help="Authorize installation without interactive prompt."),
1168
+ ) -> None:
1169
+ """Inspect or install optional external tools from known package managers."""
1170
+ from core.capabilities import TOOLS, detect, install_command
1171
+ from core.plugins import load_plugins
1172
+ load_plugins()
1173
+ s = get_settings()
1174
+
1175
+ if not install and not recommended:
1176
+ table = Table(title="StackParity Optional Scanner Setup")
1177
+ table.add_column("Tool", style="cyan")
1178
+ table.add_column("Installed")
1179
+ table.add_column("Source")
1180
+ for row in detect(s):
1181
+ table.add_row(row["key"], f"[green]{row['path']}[/green]" if row["available"] else "[yellow]not installed[/yellow]", TOOLS[row["key"]].source)
1182
+ console.print(table)
1183
+ console.print("[dim]Run 'stackparity setup --install <tool>' to install an optional tool with explicit authorization.[/dim]")
1184
+ return
1185
+
1186
+ installed = {row["key"] for row in detect(s) if row["available"]}
1187
+ keys = ["syft", "trivy"] if recommended else [install.lower().strip()]
1188
+ for key in keys:
1189
+ if key not in TOOLS:
1190
+ err_console.print(f"Unknown tool '{key}'. Choose from: {', '.join(TOOLS)}", markup=False)
1191
+ raise typer.Exit(code=2)
1192
+ if key in installed:
1193
+ console.print(f"{key} is already installed.", markup=False)
1194
+ continue
1195
+ cmd = install_command(key)
1196
+ if not cmd or not shutil.which(cmd[0]):
1197
+ err_console.print(f"No supported package manager found for {key}; install it manually from {TOOLS[key].source}.", markup=False, soft_wrap=True)
1198
+ if recommended:
1199
+ continue
1200
+ raise typer.Exit(code=2)
1201
+ if not yes and not typer.confirm(f"Authorize running '{' '.join(cmd)}' from {TOOLS[key].source}?"):
1202
+ console.print(f"Skipped {key} (authorization declined).", markup=False)
1203
+ continue
1204
+ proc = subprocess.run(cmd, shell=False)
1205
+ if proc.returncode and not recommended:
1206
+ raise typer.Exit(code=proc.returncode)
1207
+
1208
+
1209
+ @app.command()
1210
+ def init(
1211
+ target: Path = typer.Argument(Path("."), help="Repository directory to initialize."),
1212
+ force: bool = typer.Option(False, "--force", help="Overwrite existing config files."),
1213
+ ) -> None:
1214
+ """Initialize starter stackparity.toml and CI workflow files in a repository."""
1215
+ target = target.resolve()
1216
+ cfg = target / "stackparity.toml"
1217
+ wf = target / ".github" / "workflows" / "stackparity.yml"
1218
+
1219
+ created: list[str] = []
1220
+ if not cfg.exists() or force:
1221
+ cfg.write_text(
1222
+ "# StackParity local configuration\n"
1223
+ "# Select this trusted file explicitly with STACKPARITY_CONFIG.\n"
1224
+ "http_timeout_s = 25\n",
1225
+ encoding="utf-8",
1226
+ )
1227
+ created.append(str(cfg))
1228
+ if not wf.exists() or force:
1229
+ wf.parent.mkdir(parents=True, exist_ok=True)
1230
+ wf.write_text(
1231
+ "name: StackParity Security Gate\n"
1232
+ "on: [pull_request]\n"
1233
+ "jobs:\n"
1234
+ " stackparity:\n"
1235
+ " runs-on: ubuntu-latest\n"
1236
+ " steps:\n"
1237
+ " - uses: actions/checkout@v4\n"
1238
+ " - uses: actions/setup-python@v5\n"
1239
+ " with:\n python-version: '3.11'\n"
1240
+ " - run: pip install stackparity\n"
1241
+ " - run: stackparity scan . --policy default --format sarif --out stackparity.sarif\n",
1242
+ encoding="utf-8",
1243
+ )
1244
+ created.append(str(wf))
1245
+ if created:
1246
+ console.print("[green]Initialized:[/green]\n" + "\n".join(f" - {c}" for c in created))
1247
+ else:
1248
+ console.print("[yellow]Config files already exist (use --force to overwrite).[/yellow]")
1249
+
1250
+
1251
+ if __name__ == "__main__":
1252
+ app()