secguard-cli 1.1.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.
secguard/cli.py ADDED
@@ -0,0 +1,875 @@
1
+ from contextlib import redirect_stdout
2
+ import os
3
+ from pathlib import Path
4
+ import re
5
+ import subprocess
6
+ import sys
7
+ import time
8
+ import typer
9
+ from rich.console import Console
10
+ from rich.panel import Panel
11
+ from rich.syntax import Syntax
12
+ from secguard.scanner import scan_directory, scan_git_history
13
+ from secguard.patcher import apply_patches, preview_patches
14
+ from secguard.config import detect_provider_from_key, save_config, load_config
15
+ from secguard.ai_engine import analyze_finding, analyze_findings
16
+ from secguard.reporter import (
17
+ render_json_report,
18
+ render_markdown_report,
19
+ render_sarif_report,
20
+ render_table_report,
21
+ render_text_report,
22
+ )
23
+ from secguard.dependency_scanner import scan_dependencies
24
+
25
+ app = typer.Typer(
26
+ add_completion=False,
27
+ no_args_is_help=True,
28
+ help="SecGuard - AI-assisted static application security testing (SAST) CLI.",
29
+ )
30
+
31
+ from importlib.metadata import version as _pkg_version
32
+
33
+ def _version_cb(v: bool) -> None:
34
+ if v:
35
+ typer.echo("SecGuard v" + _pkg_version("secguard"))
36
+ raise typer.Exit()
37
+
38
+ @app.callback()
39
+ def _main_cb(
40
+ version: bool = typer.Option(
41
+ False,
42
+ "--version",
43
+ "-V",
44
+ callback=_version_cb,
45
+ is_eager=True,
46
+ help="Show version information.",
47
+ ),
48
+ ) -> None:
49
+ pass
50
+
51
+ console = Console()
52
+ diagnostic_console = Console(stderr=True)
53
+ SEVERITY_ORDER = {"LOW": 1, "MEDIUM": 2, "HIGH": 3, "CRITICAL": 4}
54
+
55
+
56
+ def _normalize_fix_text(value: str) -> str:
57
+ return value.replace("\\n", "\n")
58
+
59
+
60
+ def _git_changed_lines(target: Path) -> dict[Path, set[int]]:
61
+ target_path = target.resolve()
62
+ search_path = target_path if target_path.is_dir() else target_path.parent
63
+ try:
64
+ repository_root = Path(
65
+ subprocess.run(
66
+ ["git", "rev-parse", "--show-toplevel"],
67
+ cwd=search_path,
68
+ check=True,
69
+ capture_output=True,
70
+ text=True,
71
+ ).stdout.strip()
72
+ ).resolve()
73
+ has_head = subprocess.run(
74
+ ["git", "rev-parse", "--verify", "HEAD"],
75
+ cwd=repository_root,
76
+ capture_output=True,
77
+ text=True,
78
+ ).returncode == 0
79
+ diff_args = ["git", "diff", "--no-ext-diff", "--no-renames", "--unified=0"]
80
+ if has_head:
81
+ diff = subprocess.run(
82
+ [*diff_args, "HEAD", "--"],
83
+ cwd=repository_root,
84
+ check=True,
85
+ capture_output=True,
86
+ text=True,
87
+ ).stdout
88
+ else:
89
+ unstaged = subprocess.run(
90
+ [*diff_args, "--"],
91
+ cwd=repository_root,
92
+ check=True,
93
+ capture_output=True,
94
+ text=True,
95
+ ).stdout
96
+ staged = subprocess.run(
97
+ [*diff_args, "--cached", "--"],
98
+ cwd=repository_root,
99
+ check=True,
100
+ capture_output=True,
101
+ text=True,
102
+ ).stdout
103
+ diff = f"{staged}\n{unstaged}"
104
+ untracked = subprocess.run(
105
+ ["git", "ls-files", "--others", "--exclude-standard"],
106
+ cwd=repository_root,
107
+ check=True,
108
+ capture_output=True,
109
+ text=True,
110
+ ).stdout.splitlines()
111
+ except (OSError, subprocess.CalledProcessError) as error:
112
+ raise ValueError(
113
+ f"Could not read the Git working tree for --diff: {error}"
114
+ ) from error
115
+
116
+ changes: dict[Path, set[int]] = {}
117
+ current_file: Path | None = None
118
+ for line in diff.splitlines():
119
+ if line.startswith("+++ "):
120
+ current_file = None
121
+ if line.startswith("+++ b/"):
122
+ candidate = (repository_root / line[6:]).resolve()
123
+ if _is_within_target(candidate, target_path):
124
+ current_file = candidate
125
+ continue
126
+ if current_file is None:
127
+ continue
128
+ hunk = re.match(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line)
129
+ if not hunk:
130
+ continue
131
+ start = int(hunk.group(1))
132
+ count = int(hunk.group(2) or 1)
133
+ if count:
134
+ changes.setdefault(current_file, set()).update(range(start, start + count))
135
+
136
+ for relative_path in untracked:
137
+ path = (repository_root / relative_path).resolve()
138
+ if not _is_within_target(path, target_path) or not path.is_file():
139
+ continue
140
+ try:
141
+ line_count = len(path.read_text(encoding="utf-8", errors="ignore").splitlines())
142
+ except OSError:
143
+ continue
144
+ if line_count:
145
+ changes[path] = set(range(1, line_count + 1))
146
+
147
+ if target_path.is_file():
148
+ return {path: lines for path, lines in changes.items() if path == target_path}
149
+ return changes
150
+
151
+
152
+ def _is_within_target(path: Path, target: Path) -> bool:
153
+ if target.is_file():
154
+ return path == target
155
+ try:
156
+ path.relative_to(target)
157
+ except ValueError:
158
+ return False
159
+ return True
160
+
161
+
162
+ def _validate_fail_on(fail_on: str | None) -> str | None:
163
+ if fail_on is None:
164
+ return None
165
+ normalized = fail_on.upper()
166
+ if normalized not in SEVERITY_ORDER:
167
+ raise typer.BadParameter(
168
+ "Must be one of: critical, high, medium, low.",
169
+ param_hint="'--fail-on'",
170
+ )
171
+ return normalized
172
+
173
+
174
+ def _fail_if_required(findings: list[dict], fail_on: str | None) -> None:
175
+ threshold = _validate_fail_on(fail_on)
176
+ if threshold is None:
177
+ return
178
+ if any(
179
+ not finding.get("suppressed")
180
+ and SEVERITY_ORDER.get(str(finding.get("severity", "")).upper(), 0)
181
+ >= SEVERITY_ORDER[threshold]
182
+ for finding in findings
183
+ ):
184
+ console.print(
185
+ "[bold red]CI threshold exceeded:[/bold red] "
186
+ f"unsuppressed findings meet or exceed severity {threshold}."
187
+ )
188
+ raise typer.Exit(code=1)
189
+
190
+
191
+ def _pytest_working_directory(target: str) -> Path:
192
+ path = Path(target).resolve()
193
+ if path.is_file():
194
+ path = path.parent
195
+ for candidate in (path, *path.parents):
196
+ if (candidate / "pyproject.toml").is_file():
197
+ return candidate
198
+ return Path.cwd()
199
+
200
+
201
+ def _verify_pytest(target: str) -> subprocess.CompletedProcess:
202
+ return subprocess.run(
203
+ [sys.executable, "-m", "pytest"],
204
+ cwd=_pytest_working_directory(target),
205
+ capture_output=True,
206
+ text=True,
207
+ check=False,
208
+ )
209
+
210
+
211
+ def _isolate_failed_test_patches(
212
+ target: str,
213
+ originals: dict[Path, str],
214
+ patches_by_file: dict[Path, list[dict]],
215
+ ) -> list[str]:
216
+ for file_path, content in originals.items():
217
+ file_path.write_text(content, encoding="utf-8")
218
+
219
+ rejected = []
220
+ for file_path, patches in patches_by_file.items():
221
+ for patch in sorted(
222
+ patches,
223
+ key=lambda item: int(item.get("line", 0) or 0),
224
+ reverse=True,
225
+ ):
226
+ before_patch = file_path.read_text(encoding="utf-8")
227
+ applied, status = apply_patches(
228
+ str(file_path),
229
+ [patch],
230
+ backup=False,
231
+ )
232
+ if not applied:
233
+ rejected.append(f"{file_path.name}: {status}")
234
+ continue
235
+ try:
236
+ result = _verify_pytest(target)
237
+ except OSError as error:
238
+ result = None
239
+ reason = f"Could not run pytest: {error}"
240
+ else:
241
+ reason = (
242
+ (result.stdout + "\n" + result.stderr).strip()[-1000:]
243
+ if result is not None
244
+ else "No pytest result was available."
245
+ )
246
+ if result is None or result.returncode != 0:
247
+ file_path.write_text(before_patch, encoding="utf-8")
248
+ rejected.append(f"{file_path.name}: {reason}")
249
+ return rejected
250
+
251
+
252
+ @app.command(help="Configure the API key and AI provider.")
253
+ def config(
254
+ model: str | None = typer.Option(
255
+ None,
256
+ "--model",
257
+ "-m",
258
+ help="Optional custom model name.",
259
+ )
260
+ ):
261
+ """Configure the API key and AI provider."""
262
+ console.print("[bold cyan]\nSecGuard Quick Setup[/bold cyan]")
263
+ api_key = typer.prompt(
264
+ "Paste a Groq, Gemini, or OpenRouter API key (leave empty and press Enter for local Ollama)",
265
+ default="",
266
+ hide_input=True,
267
+ show_default=False,
268
+ )
269
+
270
+ try:
271
+ detected = detect_provider_from_key(api_key)
272
+ except ValueError as e:
273
+ console.print(f"[bold red]Error:[/bold red] {e}")
274
+ raise typer.Exit(code=1)
275
+
276
+ selected_model = model if model else detected["model"]
277
+ if not model and detected["provider"] == "groq":
278
+ groq_models = detected.get("models", [])
279
+ default_model = detected["model"]
280
+ for index, available_model in enumerate(groq_models, start=1):
281
+ console.print(f" {index}) {available_model}")
282
+ model_choice = typer.prompt(
283
+ "Choose an active Groq model by number or model name",
284
+ default=default_model,
285
+ show_default=True,
286
+ )
287
+ if model_choice.isdigit():
288
+ model_index = int(model_choice) - 1
289
+ selected_model = (
290
+ groq_models[model_index]
291
+ if 0 <= model_index < len(groq_models)
292
+ else ""
293
+ )
294
+ elif model_choice in groq_models:
295
+ selected_model = model_choice
296
+ else:
297
+ selected_model = ""
298
+ if not selected_model:
299
+ console.print("Selected model is not in the active model list.")
300
+ raise typer.Exit(code=1)
301
+ save_config(detected["provider"], detected["base_url"], detected["api_key"], selected_model)
302
+
303
+ console.print(
304
+ f"\nSettings saved! Provider: [bold]{detected['provider'].upper()}[/bold] "
305
+ f"| Model: [cyan]{selected_model}[/cyan]"
306
+ )
307
+
308
+
309
+ app.command("setup", hidden=True)(config)
310
+
311
+
312
+ @app.command(help="Scan source code and dependencies for security vulnerabilities.")
313
+ def scan(
314
+ target: str = typer.Argument(".", help="File or directory to scan."),
315
+ ai: bool = typer.Option(True, "--ai/--no-ai", help="Enable or disable AI verification."),
316
+ fix: bool = typer.Option(False, "--fix", help="Automatically fix detected vulnerabilities in files."),
317
+ local: bool = typer.Option(False, "--local", help="Use local Ollama for analysis."),
318
+ report_format: str = typer.Option(
319
+ "table",
320
+ "--format",
321
+ help="Report format: table, json, sarif, text, or md.",
322
+ ),
323
+ output: Path | None = typer.Option(
324
+ None,
325
+ "--output",
326
+ "-o",
327
+ help="Path to write the report to.",
328
+ ),
329
+ no_deps: bool = typer.Option(
330
+ False,
331
+ "--no-deps",
332
+ help="Disable third-party dependency scanning.",
333
+ ),
334
+ diff: bool = typer.Option(
335
+ False,
336
+ "--diff",
337
+ help="Scan only files and lines changed in Git.",
338
+ ),
339
+ history: bool = typer.Option(
340
+ False,
341
+ "--history",
342
+ help="Scan Git commit history for added secrets.",
343
+ ),
344
+ max_commits: int = typer.Option(
345
+ 50,
346
+ "--max-commits",
347
+ min=1,
348
+ help="Maximum commits to inspect with --history.",
349
+ ),
350
+ fail_on: str | None = typer.Option(
351
+ None,
352
+ "--fail-on",
353
+ help="Exit with status 1 when a finding meets or exceeds this severity.",
354
+ ),
355
+ ):
356
+ """Scan source code and dependencies for security vulnerabilities."""
357
+ if report_format not in {"table", "json", "sarif", "text", "md"}:
358
+ raise typer.BadParameter(
359
+ "Must be one of: table, json, sarif, text, md.",
360
+ param_hint="'--format'",
361
+ )
362
+ fail_on = _validate_fail_on(fail_on)
363
+ if history and max_commits < 1:
364
+ raise typer.BadParameter(
365
+ "--max-commits must be at least 1.",
366
+ param_hint="'--max-commits'",
367
+ )
368
+
369
+ table_mode = report_format in {"table", "text"}
370
+ show_progress = table_mode or output is not None
371
+ if show_progress:
372
+ console.print(f"[bold cyan]Starting scan:[/bold cyan] {target}\n")
373
+
374
+ def display_dependency_finding(finding: dict, destination: Console) -> None:
375
+ version = str(finding["version"])
376
+ version_spec = str(finding.get("version_spec", version))
377
+ if version_spec != version:
378
+ version = (
379
+ f"{version_spec}"
380
+ f" (queried: {version})"
381
+ )
382
+ destination.print(
383
+ f"[bold red][{finding['severity']}][/bold red] {finding['issue']} — "
384
+ f"{finding['package']} {version} ({finding['ecosystem']}) "
385
+ + f"at {finding['file']}:{finding['line']}"
386
+ )
387
+ destination.print(finding["explanation"])
388
+ if finding.get("fixed_version"):
389
+ destination.print(
390
+ f"Recommended safe version: {finding['fixed_version']}"
391
+ )
392
+
393
+ def emit_report(findings: list[dict]) -> None:
394
+ if report_format == "json":
395
+ report = render_json_report(findings, target)
396
+ elif report_format == "sarif":
397
+ report = render_sarif_report(findings)
398
+ elif report_format == "md":
399
+ report = render_markdown_report(findings)
400
+ elif report_format == "table":
401
+ report = render_table_report(findings)
402
+ else:
403
+ report = render_text_report(findings)
404
+
405
+ if output is not None:
406
+ try:
407
+ output.write_text(report, encoding="utf-8")
408
+ except OSError as e:
409
+ console.print(f"[bold red]Could not write report:[/bold red] {e}")
410
+ raise typer.Exit(code=1)
411
+ console.print(f"[bold green]Report saved as UTF-8:[/bold green] {output}")
412
+ elif report_format in {"json", "sarif"}:
413
+ sys.stdout.write(report)
414
+ elif report_format != "text":
415
+ console.print(report, markup=False, highlight=False)
416
+
417
+ static_started = time.perf_counter()
418
+ try:
419
+ if diff:
420
+ try:
421
+ changed_lines = _git_changed_lines(Path(target))
422
+ except ValueError as error:
423
+ raise typer.BadParameter(
424
+ str(error),
425
+ param_hint="'--diff'",
426
+ ) from error
427
+ candidates = []
428
+ scan_root = Path(target).resolve()
429
+ for changed_file, changed_line_numbers in changed_lines.items():
430
+ for finding in scan_directory(str(changed_file)):
431
+ if finding.get("line") not in changed_line_numbers:
432
+ continue
433
+ if scan_root.is_dir():
434
+ finding["file"] = str(changed_file.relative_to(scan_root))
435
+ candidates.append(finding)
436
+ else:
437
+ candidates = scan_directory(target)
438
+ except FileNotFoundError as e:
439
+ console.print(f"[bold red]Error:[/bold red] {e}")
440
+ raise typer.Exit(code=1)
441
+
442
+ history_findings = []
443
+ if history:
444
+ try:
445
+ history_findings = scan_git_history(target, max_commits=max_commits)
446
+ except ValueError as error:
447
+ console.print(f"[bold red]Could not scan Git history:[/bold red] {error}")
448
+ raise typer.Exit(code=1)
449
+ candidates.extend(history_findings)
450
+
451
+ dependency_findings = [] if no_deps or diff else scan_dependencies(target)
452
+ static_elapsed = time.perf_counter() - static_started
453
+ candidates.extend(dependency_findings)
454
+ code_candidates = [
455
+ item for item in candidates
456
+ if not item.get("is_dependency")
457
+ and not item.get("is_history")
458
+ and not item.get("suppressed")
459
+ ]
460
+ settings = None if local else load_config()
461
+ if local:
462
+ ai_provider = "ollama"
463
+ ai_model = os.environ.get("SECGUARD_LOCAL_MODEL", "auto")
464
+ elif settings:
465
+ ai_provider = str(settings.get("provider", "unknown"))
466
+ ai_model = str(settings.get("model", "unknown"))
467
+ else:
468
+ ai_provider, ai_model = "unconfigured", "none"
469
+
470
+ def print_timing_summary(ai_elapsed: float = 0.0) -> None:
471
+ destination = (
472
+ console
473
+ if table_mode or output is not None
474
+ else diagnostic_console
475
+ )
476
+ destination.print(
477
+ f"Static: {static_elapsed:.1f}s | "
478
+ f"AI ({ai_provider}/{ai_model}): {ai_elapsed:.1f}s",
479
+ markup=False,
480
+ )
481
+
482
+ if not candidates:
483
+ if output is not None or report_format in {"json", "sarif", "md"}:
484
+ emit_report([])
485
+ else:
486
+ console.print("[bold green]Clean! No suspicious findings were detected.[/bold green]")
487
+ print_timing_summary()
488
+ return
489
+
490
+ if not ai:
491
+ for item in candidates:
492
+ if item.get("suppressed"):
493
+ destination = console if show_progress else diagnostic_console
494
+ destination.print(
495
+ "[dim][Suppressed][/dim] "
496
+ f"{item.get('file', '?')}:{item.get('line', '?')} - "
497
+ f"{item.get('issue', 'Security finding')}"
498
+ )
499
+ continue
500
+ if item.get("is_dependency"):
501
+ display_dependency_finding(item, console if show_progress else diagnostic_console)
502
+ else:
503
+ destination = console if show_progress else diagnostic_console
504
+ history_commit = (
505
+ f" (commit {item['commit']})"
506
+ if item.get("commit")
507
+ else ""
508
+ )
509
+ destination.print(
510
+ f"[yellow][Preliminary finding][/yellow] {item['file']}:{item['line']}"
511
+ f"{history_commit} - {item['issue']}"
512
+ )
513
+ if output is not None or report_format in {"json", "sarif", "md"}:
514
+ if code_candidates and output is not None:
515
+ console.print(
516
+ "[yellow]AI verification is disabled; the report contains only verified dependency findings.[/yellow]"
517
+ )
518
+ emit_report([
519
+ *dependency_findings,
520
+ *history_findings,
521
+ *(item for item in candidates if item.get("suppressed")),
522
+ ])
523
+ _fail_if_required(candidates, fail_on)
524
+ print_timing_summary()
525
+ return
526
+
527
+ if code_candidates and not local and not settings:
528
+ if not dependency_findings:
529
+ console.print(
530
+ "[bold yellow]Warning:[/bold yellow] AI is not configured. "
531
+ "Run [bold]secguard config[/bold] first."
532
+ )
533
+ raise typer.Exit(code=1)
534
+ destination = console if show_progress else diagnostic_console
535
+ destination.print(
536
+ "[yellow]AI is not configured; code findings remain unverified while "
537
+ "OSV dependency findings are still reported.[/yellow]"
538
+ )
539
+ for item in code_candidates:
540
+ destination.print(
541
+ "[yellow][Preliminary finding][/yellow] "
542
+ f"{item['file']}:{item['line']} - {item['issue']}"
543
+ )
544
+ candidates = list(dependency_findings)
545
+ code_candidates = []
546
+
547
+ if show_progress and code_candidates:
548
+ console.print(
549
+ f"[dim]{len(code_candidates)} preliminary findings are being analyzed "
550
+ "with AI...[/dim]\n"
551
+ )
552
+
553
+ verified_count = 0
554
+ verified_findings = []
555
+ patches_by_file: dict[Path, list[dict]] = {}
556
+ ai_verdicts = {}
557
+ ai_elapsed = 0.0
558
+
559
+ if code_candidates:
560
+ ai_started = time.perf_counter()
561
+ try:
562
+ if show_progress:
563
+ with console.status("Running file-based AI analysis..."):
564
+ batch_verdicts = analyze_findings(
565
+ code_candidates,
566
+ local=local,
567
+ )
568
+ else:
569
+ with redirect_stdout(sys.stderr):
570
+ batch_verdicts = analyze_findings(
571
+ code_candidates,
572
+ local=local,
573
+ )
574
+ ai_verdicts = {
575
+ id(item): verdict
576
+ for item, verdict in zip(code_candidates, batch_verdicts)
577
+ }
578
+ ai_elapsed = time.perf_counter() - ai_started
579
+ except Exception as e:
580
+ console.print(f"[bold red]AI connection error:[/bold red] {e}")
581
+ raise typer.Exit(code=1)
582
+
583
+ for item in candidates:
584
+ if item.get("suppressed"):
585
+ verified_findings.append({**item, "suppressed": True})
586
+ continue
587
+ is_dependency = item.get("is_dependency", False)
588
+ is_history = item.get("is_history", False)
589
+ if is_dependency or is_history:
590
+ verdict = item
591
+ else:
592
+ verdict = ai_verdicts.get(id(item))
593
+
594
+ if verdict and not is_dependency:
595
+ verdict = dict(verdict)
596
+ if not verdict.get("fixed_code") and verdict.get("suggested_fix"):
597
+ verdict["fixed_code"] = verdict["suggested_fix"]
598
+ for code_key in ("fix", "fixed_code"):
599
+ code = verdict.get(code_key)
600
+ if isinstance(code, str):
601
+ verdict[code_key] = _normalize_fix_text(code)
602
+
603
+ if verdict and verdict.get("is_vulnerable"):
604
+ verified_count += 1
605
+ verified_findings.append({
606
+ **item,
607
+ **verdict,
608
+ })
609
+ ext = Path(item["file"]).suffix.lstrip(".")
610
+ lexer = ext if ext in {"py", "js", "php", "json"} else "python"
611
+ destination = console if show_progress else diagnostic_console
612
+
613
+ history_commit = f" (commit {item['commit']})" if item.get("commit") else ""
614
+ header = (
615
+ f"[{verdict['severity']}] {item['issue']} — "
616
+ f"{item['file']}:{item['line']}{history_commit}"
617
+ )
618
+ if is_dependency:
619
+ display_dependency_finding(item, destination)
620
+ elif table_mode:
621
+ console.print(
622
+ Panel(
623
+ f"[bold]Description:[/bold] {verdict['explanation']}",
624
+ title=header,
625
+ border_style="red",
626
+ )
627
+ )
628
+
629
+ if (
630
+ table_mode
631
+ and not is_dependency
632
+ and not item.get("is_binary")
633
+ and verdict.get("fixed_code")
634
+ ):
635
+ console.print("[bold green]Recommended safe code:[/bold green]")
636
+ console.print(Syntax(verdict["fixed_code"], lexer, theme="monokai", line_numbers=False, word_wrap=True))
637
+
638
+ if fix:
639
+ if is_dependency:
640
+ destination.print(
641
+ "[yellow]Dependency updates are not applied automatically; "
642
+ "update the manifest manually.[/yellow]"
643
+ )
644
+ elif is_history:
645
+ destination.print(
646
+ "[yellow]Secrets in Git history are not patched automatically; "
647
+ "revoke the key and clean the history.[/yellow]"
648
+ )
649
+ elif item.get("is_binary"):
650
+ console.print(
651
+ "[dim]Automatic source-code patching is not available for "
652
+ "binary/APK files.[/dim]"
653
+ )
654
+ elif typer.confirm(
655
+ f"\nApply this fix to {item['file']}?"
656
+ ):
657
+ if (
658
+ isinstance(verdict.get("fixed_code"), str)
659
+ and verdict["fixed_code"].strip()
660
+ and verdict.get("patch_applicable") is not False
661
+ ):
662
+ target_file = Path(item["abs_path"])
663
+ patches_by_file.setdefault(target_file, []).append({
664
+ "line": item.get("line", 0),
665
+ "vulnerable_code": verdict.get("vulnerable_code") or item.get("code", ""),
666
+ "fixed_code": verdict.get("fixed_code", ""),
667
+ })
668
+ if table_mode:
669
+ console.print()
670
+
671
+ for target_file, patches in patches_by_file.items():
672
+ applied_indexes, status_msg = apply_patches(
673
+ str(target_file),
674
+ patches,
675
+ )
676
+ if applied_indexes:
677
+ console.print(
678
+ f"[bold green]{target_file.name}: {status_msg} "
679
+ f"({len(applied_indexes)}/{len(patches)} patches)[/bold green]"
680
+ )
681
+ else:
682
+ console.print(
683
+ f"[bold yellow]{target_file.name}: {status_msg}[/bold yellow]"
684
+ )
685
+
686
+ if verified_count == 0 and table_mode:
687
+ console.print(
688
+ "[bold green]AI review complete: no real vulnerabilities found "
689
+ "(false positives were removed).[/bold green]"
690
+ )
691
+
692
+ if output is not None or report_format in {"json", "sarif", "md"}:
693
+ emit_report(verified_findings)
694
+ _fail_if_required(verified_findings, fail_on)
695
+ print_timing_summary(ai_elapsed)
696
+
697
+
698
+ @app.command(
699
+ "fix",
700
+ help="Generate security patches, show diffs, and optionally apply them.",
701
+ )
702
+ def fix_command(
703
+ target: str = typer.Argument(".", help="File or directory to patch."),
704
+ apply: bool = typer.Option(
705
+ False,
706
+ "--apply",
707
+ help="Apply the previewed patches to files.",
708
+ ),
709
+ verify_tests: bool = typer.Option(
710
+ False,
711
+ "--verify-tests",
712
+ help="Run pytest after applying patches and roll back if it fails.",
713
+ ),
714
+ local: bool = typer.Option(False, "--local", help="Use local Ollama for analysis."),
715
+ fail_on: str | None = typer.Option(
716
+ None,
717
+ "--fail-on",
718
+ help="Exit with status 1 when a finding meets or exceeds this severity.",
719
+ ),
720
+ ):
721
+ """Generate security patches, display diffs, and optionally apply them."""
722
+ fail_on = _validate_fail_on(fail_on)
723
+ if verify_tests and not apply:
724
+ raise typer.BadParameter("--verify-tests requires --apply.")
725
+ try:
726
+ candidates = scan_directory(target)
727
+ except FileNotFoundError as error:
728
+ console.print(f"[bold red]Error:[/bold red] {error}")
729
+ raise typer.Exit(code=1)
730
+
731
+ candidates = [
732
+ item for item in candidates
733
+ if not item.get("suppressed")
734
+ and not item.get("is_binary")
735
+ ]
736
+ if not candidates:
737
+ console.print("[green]No findings to patch.[/green]")
738
+ return
739
+
740
+ verdicts: list[dict | None] = [None] * len(candidates)
741
+ missing_indexes = []
742
+ for index, finding in enumerate(candidates):
743
+ fixed_code = finding.get("fixed_code") or finding.get("suggested_fix")
744
+ if type(finding.get("is_vulnerable")) is bool and (
745
+ not finding["is_vulnerable"]
746
+ or (
747
+ isinstance(fixed_code, str)
748
+ and fixed_code.strip()
749
+ and finding.get("patch_applicable") is not False
750
+ )
751
+ ):
752
+ cached = dict(finding)
753
+ cached["fixed_code"] = fixed_code or ""
754
+ cached["suggested_fix"] = fixed_code or ""
755
+ verdicts[index] = cached
756
+ else:
757
+ missing_indexes.append(index)
758
+
759
+ if missing_indexes:
760
+ try:
761
+ new_verdicts = analyze_findings(
762
+ [candidates[index] for index in missing_indexes],
763
+ local=local,
764
+ )
765
+ except Exception as error:
766
+ console.print(f"[bold red]AI analysis error:[/bold red] {error}")
767
+ raise typer.Exit(code=1)
768
+ for index, verdict in zip(missing_indexes, new_verdicts):
769
+ verdicts[index] = verdict
770
+
771
+ verified = []
772
+ patches_applied: dict[Path, str] = {}
773
+ patches_by_file: dict[Path, list[dict]] = {}
774
+ patch_failed = False
775
+ for finding, verdict in zip(candidates, verdicts):
776
+ if not verdict or verdict.get("is_vulnerable") is not True:
777
+ continue
778
+ item = {**finding, **verdict}
779
+ verified.append(item)
780
+ fixed_code = item.get("fixed_code") or item.get("suggested_fix")
781
+ vulnerable_code = item.get("vulnerable_code") or finding.get("code", "")
782
+ if (
783
+ not isinstance(fixed_code, str)
784
+ or not fixed_code.strip()
785
+ or item.get("patch_applicable") is False
786
+ ):
787
+ console.print(
788
+ f"[yellow]No applicable patch:[/yellow] "
789
+ f"{finding.get('file')}:{finding.get('line')}"
790
+ )
791
+ continue
792
+
793
+ file_path = Path(str(finding.get("abs_path", "")))
794
+ if not file_path.is_file():
795
+ console.print(
796
+ f"[yellow]Target file not found:[/yellow] {finding.get('file')}"
797
+ )
798
+ patch_failed = patch_failed or apply
799
+ continue
800
+ patches_by_file.setdefault(file_path, []).append({
801
+ "line": finding.get("line", 0),
802
+ "vulnerable_code": str(vulnerable_code),
803
+ "fixed_code": fixed_code,
804
+ })
805
+
806
+ for file_path, patches in patches_by_file.items():
807
+ preview_indexes, diff = preview_patches(
808
+ str(file_path),
809
+ patches,
810
+ validate=not apply,
811
+ )
812
+ if not preview_indexes:
813
+ console.print(f"[yellow]Could not create patch preview:[/yellow] {diff}")
814
+ patch_failed = patch_failed or apply
815
+ continue
816
+ if diff:
817
+ console.print(diff, markup=False, highlight=False)
818
+ if not apply:
819
+ continue
820
+
821
+ original_content = file_path.read_text(encoding="utf-8")
822
+ applied_indexes, status = apply_patches(
823
+ str(file_path),
824
+ patches,
825
+ backup=False,
826
+ )
827
+ if applied_indexes:
828
+ patches_applied.setdefault(file_path, original_content)
829
+ console.print(
830
+ f"[green]{file_path.name}: {status} "
831
+ f"({len(applied_indexes)}/{len(patches)} patches)[/green]"
832
+ )
833
+ else:
834
+ patch_failed = True
835
+ console.print(f"[yellow]Patch was not applied:[/yellow] {status}")
836
+
837
+ if verify_tests and patches_applied:
838
+ try:
839
+ test_result = _verify_pytest(target)
840
+ except OSError as error:
841
+ test_result = None
842
+ console.print(f"[red]Could not run pytest:[/red] {error}")
843
+ if test_result is None or test_result.returncode != 0:
844
+ rejected = _isolate_failed_test_patches(
845
+ target,
846
+ patches_applied,
847
+ patches_by_file,
848
+ )
849
+ console.print(
850
+ "[bold yellow]Batch pytest verification failed; patches were "
851
+ "tested individually and failing changes rolled back.[/bold yellow]"
852
+ )
853
+ if test_result is not None:
854
+ details = (test_result.stdout + "\n" + test_result.stderr).strip()
855
+ if details:
856
+ console.print(details[-6000:], markup=False, highlight=False)
857
+ for rejection in rejected:
858
+ console.print(f"[yellow]Rolled back:[/yellow] {rejection}")
859
+ patch_failed = patch_failed or bool(rejected)
860
+ else:
861
+ console.print("[green]pytest passed; patches were kept.[/green]")
862
+
863
+ if not apply and not verified:
864
+ console.print("[green]No patch passed AI verification.[/green]")
865
+ if apply and not patches_applied and verified:
866
+ patch_failed = True
867
+ _fail_if_required(verified, fail_on)
868
+ if patch_failed:
869
+ raise typer.Exit(code=1)
870
+
871
+
872
+
873
+
874
+ if __name__ == "__main__":
875
+ app()