polycheck 0.2.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 (42) hide show
  1. polycheck/__init__.py +19 -0
  2. polycheck/cli.py +791 -0
  3. polycheck/config.py +123 -0
  4. polycheck/detect.py +151 -0
  5. polycheck/finding.py +131 -0
  6. polycheck/initializer.py +333 -0
  7. polycheck/languages/__init__.py +10 -0
  8. polycheck/mcp_server.py +994 -0
  9. polycheck/py.typed +0 -0
  10. polycheck/registry.py +119 -0
  11. polycheck/reporters/__init__.py +33 -0
  12. polycheck/reporters/json_reporter.py +58 -0
  13. polycheck/reporters/markdown_reporter.py +141 -0
  14. polycheck/reporters/sarif_reporter.py +114 -0
  15. polycheck/runner.py +279 -0
  16. polycheck/session.py +134 -0
  17. polycheck/tools/__init__.py +10 -0
  18. polycheck/tools/actionlint.py +66 -0
  19. polycheck/tools/base.py +449 -0
  20. polycheck/tools/depcheck.py +96 -0
  21. polycheck/tools/deptry.py +83 -0
  22. polycheck/tools/eslint.py +89 -0
  23. polycheck/tools/gitleaks.py +78 -0
  24. polycheck/tools/hadolint.py +75 -0
  25. polycheck/tools/knip.py +84 -0
  26. polycheck/tools/mypy.py +85 -0
  27. polycheck/tools/npm_audit.py +74 -0
  28. polycheck/tools/pip_audit.py +132 -0
  29. polycheck/tools/ruff.py +80 -0
  30. polycheck/tools/semgrep.py +80 -0
  31. polycheck/tools/shellcheck.py +80 -0
  32. polycheck/tools/sonarless.py +238 -0
  33. polycheck/tools/tsc.py +77 -0
  34. polycheck/tools/vulture.py +82 -0
  35. polycheck/verify.py +288 -0
  36. polycheck/workflows/__init__.py +76 -0
  37. polycheck-0.2.0.dist-info/METADATA +614 -0
  38. polycheck-0.2.0.dist-info/RECORD +42 -0
  39. polycheck-0.2.0.dist-info/WHEEL +5 -0
  40. polycheck-0.2.0.dist-info/entry_points.txt +2 -0
  41. polycheck-0.2.0.dist-info/licenses/LICENSE +21 -0
  42. polycheck-0.2.0.dist-info/top_level.txt +1 -0
polycheck/cli.py ADDED
@@ -0,0 +1,791 @@
1
+ """Polycheck CLI.
2
+
3
+ Subcommands
4
+ -----------
5
+
6
+ ``polycheck run [PATH]``
7
+ Detect languages, run all applicable tools, write reports.
8
+
9
+ ``polycheck list-tools``
10
+ Print every available tool and which languages it supports.
11
+
12
+ ``polycheck explain RULE``
13
+ Print a short explanation of a tool/rule identifier.
14
+
15
+ ``polycheck init``
16
+ Initialize `/polycheck` for Kilo Code, OpenCode, and Claude Code.
17
+
18
+ ``polycheck mcp``
19
+ Start the MCP server (stdio transport).
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ import typer
27
+ from rich.console import Console
28
+ from rich.table import Table
29
+
30
+ from . import __version__
31
+ from .config import Config
32
+ from .detect import detect
33
+ from .finding import Finding
34
+ from .initializer import (
35
+ HOSTS,
36
+ apply_plan,
37
+ build_plan,
38
+ format_action,
39
+ normalize_hosts,
40
+ )
41
+ from .registry import default_registry
42
+ from .reporters import render as render_report
43
+ from .runner import (
44
+ Runner,
45
+ apply_suppressions,
46
+ dedupe,
47
+ filter_by_baseline,
48
+ filter_by_severity,
49
+ load_baseline,
50
+ save_baseline,
51
+ )
52
+ from .tools.base import Tool
53
+ from .verify import HEAVY_TOOLS, verify_tools
54
+
55
+ # Auto-discover all bundled tools on import so the CLI is ready to go.
56
+ default_registry.discover()
57
+
58
+
59
+ app = typer.Typer(
60
+ name="polycheck",
61
+ no_args_is_help=True,
62
+ help="Static-first, LLM-triage-ready code analysis. See `polycheck run --help`.",
63
+ )
64
+ console = Console()
65
+
66
+
67
+ def _version_callback(value: bool) -> None:
68
+ if value:
69
+ typer.echo(f"polycheck {__version__}")
70
+ raise typer.Exit()
71
+
72
+
73
+ @app.callback()
74
+ def main_callback(
75
+ version: bool = typer.Option(
76
+ False, "--version", callback=_version_callback, is_eager=True
77
+ ),
78
+ ) -> None:
79
+ """polycheck — static-first, LLM-triage-ready code analysis."""
80
+
81
+
82
+ @app.command()
83
+ def run(
84
+ path: Path = typer.Argument(
85
+ Path("."), exists=True, file_okay=False, dir_okay=True, resolve_path=True
86
+ ),
87
+ parallel: bool = typer.Option(False, "--parallel", help="Run tools in parallel"),
88
+ tool: list[str] = typer.Option(
89
+ None, "--tool", "-t", help="Restrict to specific tool name(s) (repeatable)"
90
+ ),
91
+ severity: str = typer.Option(
92
+ None,
93
+ "--severity",
94
+ help="Minimum severity to keep (INFO, LOW, MEDIUM, HIGH, CRITICAL)",
95
+ ),
96
+ config: Path = typer.Option(
97
+ None, "--config", "-c", help="Path to a .polycheck.yml"
98
+ ),
99
+ output: list[str] = typer.Option(
100
+ None, "--output", "-o", help="Report format(s): markdown, json, sarif"
101
+ ),
102
+ report_dir: Path = typer.Option(
103
+ None, "--report-dir", help="Where to write reports (default: polycheck-reports)"
104
+ ),
105
+ no_dedupe: bool = typer.Option(False, "--no-dedupe"),
106
+ diff: bool = typer.Option(
107
+ False,
108
+ "--diff",
109
+ help="Only report findings that are new since the last "
110
+ "`polycheck baseline` (reports everything when no baseline exists).",
111
+ ),
112
+ install: bool = typer.Option(
113
+ False,
114
+ "--install",
115
+ help="Auto-install any missing analyzers before running",
116
+ ),
117
+ fail_on: str = typer.Option(
118
+ "MEDIUM",
119
+ "--fail-on",
120
+ help="Exit non-zero if any finding is at or above this severity (INFO, LOW, MEDIUM, HIGH, CRITICAL). Default MEDIUM.",
121
+ ),
122
+ ) -> None:
123
+ """Run all applicable tools and write reports."""
124
+ cfg = _load_config(config, path, severity, output, report_dir)
125
+ repo = path.resolve()
126
+ console.print(f"[bold]polycheck[/bold] {__version__} — {repo}")
127
+
128
+ _print_detected_languages(repo)
129
+
130
+ if install:
131
+ _auto_install_missing(only=tool or None, repo=repo)
132
+
133
+ runner = Runner(repo=repo, config=cfg, registry=default_registry)
134
+ findings, results = runner.run(parallel=parallel, tools=tool or None)
135
+
136
+ if not no_dedupe:
137
+ findings = dedupe(findings)
138
+ findings = filter_by_severity(findings, cfg.severity_threshold)
139
+ findings = apply_suppressions(findings, cfg.suppress)
140
+
141
+ if diff:
142
+ findings = _apply_diff_baseline(cfg, repo, findings)
143
+
144
+ written = _write_reports(cfg, repo, findings, results)
145
+ _print_summary(results, findings, written)
146
+
147
+ failed = [r for r in results if r.status in ("error", "timeout")]
148
+ if failed:
149
+ _print_failures(failed)
150
+
151
+ not_run = _missing_tools(repo, only=tool or None, exclude={r.tool for r in results})
152
+ if not_run:
153
+ _print_missing(not_run)
154
+
155
+ raise typer.Exit(code=_exit_code(findings, fail_on.upper()))
156
+
157
+
158
+ def _apply_diff_baseline(cfg: Config, repo: Path, findings: list) -> list:
159
+ """Filter findings to those newer than the baseline, with an
160
+ honest console note when no baseline exists yet."""
161
+ baseline = load_baseline(repo / cfg.output.report_dir)
162
+ if baseline is None:
163
+ console.print(
164
+ "[yellow]--diff:[/yellow] no baseline yet — run "
165
+ "[bold]polycheck baseline[/bold] first; reporting all findings"
166
+ )
167
+ return findings
168
+ new = filter_by_baseline(findings, baseline)
169
+ known = len(findings) - len(new)
170
+ console.print(
171
+ f"[cyan]--diff:[/cyan] baseline has {len(baseline)} finding(s) — "
172
+ f"{known} known, [bold]{len(new)} new[/bold]"
173
+ )
174
+ return new
175
+
176
+
177
+ @app.command()
178
+ def baseline(
179
+ path: Path = typer.Argument(
180
+ Path("."), exists=True, file_okay=False, dir_okay=True, resolve_path=True
181
+ ),
182
+ parallel: bool = typer.Option(False, "--parallel", help="Run tools in parallel"),
183
+ tool: list[str] = typer.Option(
184
+ None, "--tool", "-t", help="Restrict to specific tool name(s) (repeatable)"
185
+ ),
186
+ severity: str = typer.Option(
187
+ None,
188
+ "--severity",
189
+ help="Minimum severity to keep (INFO, LOW, MEDIUM, HIGH, CRITICAL)",
190
+ ),
191
+ config: Path = typer.Option(
192
+ None, "--config", "-c", help="Path to a .polycheck.yml"
193
+ ),
194
+ report_dir: Path = typer.Option(
195
+ None, "--report-dir", help="Where to write the baseline (default: polycheck-reports)"
196
+ ),
197
+ ) -> None:
198
+ """Snapshot today's findings as the baseline for `run --diff`.
199
+
200
+ Run this once on a repo whose current findings are accepted; later
201
+ `polycheck run --diff` then reports only NEW findings. Re-run it
202
+ after fixing or triaging to move the needle forward.
203
+ """
204
+ cfg = _load_config(config, path, severity, None, report_dir)
205
+ repo = path.resolve()
206
+ console.print(f"[bold]polycheck[/bold] {__version__} — {repo}")
207
+
208
+ runner = Runner(repo=repo, config=cfg, registry=default_registry)
209
+ findings, _results = runner.run(parallel=parallel, tools=tool or None)
210
+ findings = dedupe(findings)
211
+ findings = filter_by_severity(findings, cfg.severity_threshold)
212
+ findings = apply_suppressions(findings, cfg.suppress)
213
+
214
+ baseline_path = save_baseline(repo / cfg.output.report_dir, findings)
215
+ console.print(
216
+ f"[green]Baseline saved:[/green] {len(findings)} findings "
217
+ f"→ {baseline_path}"
218
+ )
219
+
220
+
221
+ def _load_config(
222
+ config: Path | None,
223
+ path: Path,
224
+ severity: str | None,
225
+ output: list[str] | None,
226
+ report_dir: Path | None,
227
+ ) -> Config:
228
+ """Load and apply CLI overrides to the config."""
229
+ cfg = Config.load(config) if config else Config.load(path)
230
+ if severity:
231
+ cfg.severity_threshold = severity.upper()
232
+ if output:
233
+ cfg.output.formats = list(output)
234
+ if report_dir:
235
+ cfg.output.report_dir = str(report_dir)
236
+ return cfg
237
+
238
+
239
+ def _print_detected_languages(repo: Path) -> None:
240
+ """Print detected languages to the console."""
241
+ langs = detect(repo)
242
+ if langs:
243
+ console.print(
244
+ "Detected: " + ", ".join(f"[cyan]{lang.slug}[/cyan]" for lang in langs)
245
+ )
246
+ else:
247
+ console.print("[yellow]No supported languages detected.[/yellow]")
248
+
249
+
250
+ def _write_reports(
251
+ cfg: Config, repo: Path, findings: list, results: list
252
+ ) -> list[Path]:
253
+ """Write reports in all configured formats."""
254
+ out_dir = repo / cfg.output.report_dir
255
+ written: list[Path] = []
256
+ for fmt in cfg.output.formats:
257
+ written.extend(
258
+ render_report(fmt, repo, findings, results, report_dir=out_dir)
259
+ )
260
+ return written
261
+
262
+
263
+ def _print_summary(results: list, findings: list, written: list[Path]) -> None:
264
+ """Print the tool summary table and findings count."""
265
+ by_tool = Table(title="Tools")
266
+ by_tool.add_column("Tool", style="cyan")
267
+ by_tool.add_column("Status")
268
+ by_tool.add_column("Findings", justify="right")
269
+ by_tool.add_column("Time (s)", justify="right")
270
+ for r in sorted(results, key=lambda r: r.tool):
271
+ by_tool.add_row(
272
+ r.tool, r.status, str(len(r.findings)), f"{r.duration_sec:.1f}"
273
+ )
274
+ console.print(by_tool)
275
+ console.print(f"\n[bold]{len(findings)}[/bold] findings after filtering")
276
+ if written:
277
+ console.print("\nReports written:")
278
+ for p in written:
279
+ console.print(f" [green]{p}[/green]")
280
+
281
+
282
+ def _print_failures(failed: list) -> None:
283
+ """Print failed tool information."""
284
+ console.print(
285
+ f"[yellow]{len(failed)} tool(s) failed:[/yellow] "
286
+ + ", ".join(r.tool for r in failed)
287
+ )
288
+ for r in failed:
289
+ if r.error:
290
+ console.print(f" [red]{r.tool}[/red]: {r.error}")
291
+
292
+
293
+ def _print_missing(not_run: list) -> None:
294
+ """Print missing tool information."""
295
+ console.print(f"\n[yellow]{len(not_run)} tool(s) not installed:[/yellow]")
296
+ for cls in not_run:
297
+ inst = cls()
298
+ console.print(f" [cyan]{inst.name}[/cyan]: {inst.install_hint()}")
299
+
300
+
301
+ @app.command(name="list-tools")
302
+ def list_tools() -> None:
303
+ """Print every available tool and which languages it supports."""
304
+ table = Table(title="Available tools")
305
+ table.add_column("Tool", style="cyan")
306
+ table.add_column("Category")
307
+ table.add_column("Languages")
308
+ table.add_column("Universal?", justify="center")
309
+ table.add_column("Installer")
310
+ for cls in default_registry.all():
311
+ langs = ", ".join(cls.languages) if not cls.universal else "—"
312
+ installer = cls.installer or "—"
313
+ table.add_row(
314
+ cls.name, cls.category.value, langs, "yes" if cls.universal else "",
315
+ installer,
316
+ )
317
+ console.print(table)
318
+
319
+
320
+ @app.command(name="verify-tools")
321
+ def verify_tools_cmd(
322
+ tool: list[str] | None = typer.Option(
323
+ None,
324
+ "--tool",
325
+ "-t",
326
+ help="Restrict verification to specific tool name(s) (repeatable)",
327
+ ),
328
+ install_missing: bool = typer.Option(
329
+ False,
330
+ "--install",
331
+ help="Attempt automatic installation for missing installable tools before running them.",
332
+ ),
333
+ yes: bool = typer.Option(
334
+ False,
335
+ "-y",
336
+ "--yes",
337
+ help="Skip confirmation when --install is used.",
338
+ ),
339
+ include_heavy: bool = typer.Option(
340
+ False,
341
+ "--include-heavy",
342
+ help="Run Docker/network-heavy tools such as sonarless, semgrep, pip-audit, and npm-audit.",
343
+ ),
344
+ ) -> None:
345
+ """Verify every supported analyzer can install and run.
346
+
347
+ By default this checks installed tools against synthetic repositories and
348
+ skips missing tools. Use --install to attempt automatic installs, and
349
+ --include-heavy only when Docker/network access are acceptable.
350
+ """
351
+ selected = list(tool or [])
352
+ known = {cls.name for cls in default_registry.all()}
353
+ unknown = [name for name in selected if name not in known]
354
+ if unknown:
355
+ console.print(f"[red]Unknown tool(s): {', '.join(unknown)}[/red]")
356
+ raise typer.Exit(2)
357
+
358
+ if install_missing and not yes:
359
+ missing = [
360
+ cls for cls in default_registry.all()
361
+ if (not selected or cls.name in selected)
362
+ and not cls().is_installed()
363
+ and cls().can_auto_install()
364
+ ]
365
+ if missing:
366
+ console.print("Will attempt to install missing tools:")
367
+ for cls in missing:
368
+ console.print(f" [cyan]{cls.name}[/cyan]: {cls().install_hint()}")
369
+ if not typer.confirm("Proceed?"):
370
+ raise typer.Abort()
371
+
372
+ results = verify_tools(
373
+ default_registry,
374
+ install=install_missing,
375
+ include_heavy=include_heavy,
376
+ tools=selected,
377
+ )
378
+
379
+ table = Table(title="polycheck verify-tools")
380
+ table.add_column("Tool", style="cyan")
381
+ table.add_column("Status")
382
+ table.add_column("Installed")
383
+ table.add_column("Applicable")
384
+ table.add_column("Findings", justify="right")
385
+ table.add_column("Time (s)", justify="right")
386
+ table.add_column("Message")
387
+ for result in results:
388
+ table.add_row(
389
+ result.tool,
390
+ result.status,
391
+ "yes" if result.installed else "no",
392
+ "yes" if result.applicable else "no",
393
+ str(result.findings),
394
+ f"{result.duration_sec:.1f}",
395
+ result.message,
396
+ )
397
+ console.print(table)
398
+
399
+ failed = [r for r in results if r.status in {"error", "timeout", "install-failed"}]
400
+ if failed:
401
+ console.print(
402
+ "[red]Verification failed:[/red] "
403
+ + ", ".join(f"{r.tool} ({r.status})" for r in failed)
404
+ )
405
+ raise typer.Exit(1)
406
+
407
+ heavy = ", ".join(sorted(HEAVY_TOOLS))
408
+ console.print(
409
+ "[green]Verification complete.[/green] "
410
+ f"Heavy tools skipped by default: {heavy}. Use --include-heavy to run them."
411
+ )
412
+
413
+
414
+ @app.command()
415
+ def explain(
416
+ tool: str = typer.Argument(..., help="Tool name (e.g. ruff)"),
417
+ rule: str = typer.Argument(None, help="Optional rule id (e.g. I001)"),
418
+ ) -> None:
419
+ """Explain a tool or a specific rule. Prints a doc URL when known."""
420
+ cls = default_registry.get(tool)
421
+ if cls is None:
422
+ console.print(f"[red]Unknown tool:[/red] {tool}")
423
+ raise typer.Exit(1)
424
+ inst = cls()
425
+ console.print(f"[bold]{tool}[/bold] — {inst.category.value}")
426
+ console.print(f"Languages: {', '.join(cls.languages) or '*'}")
427
+ console.print(f"Install hint: {inst.install_hint}")
428
+ if rule:
429
+ # Most tool adapters expose a per-rule doc_url; this is a
430
+ # best-effort guess based on common conventions.
431
+ candidates = [
432
+ f"https://docs.astral.sh/ruff/rules/{rule.lower()}",
433
+ f"https://eslint.org/docs/rules/{rule.lower()}",
434
+ f"https://mypy.readthedocs.io/en/stable/_refs.html#code-{rule}",
435
+ ]
436
+ for url in candidates:
437
+ console.print(f" [blue]{url}[/blue]")
438
+
439
+
440
+ @app.command()
441
+ def mcp() -> None:
442
+ """Start the polycheck MCP server (stdio transport)."""
443
+ from .mcp_server import run_server
444
+ run_server()
445
+
446
+
447
+ @app.command(name="init")
448
+ def init_cmd(
449
+ host: list[str] | None = typer.Option(
450
+ None,
451
+ "--host",
452
+ "-H",
453
+ help=f"Host(s) to configure: {', '.join((*HOSTS, 'all'))}. Repeatable; default: all.",
454
+ ),
455
+ scope: str = typer.Option(
456
+ "global",
457
+ "--scope",
458
+ help="Write project-local or global workflow/config files.",
459
+ ),
460
+ dry_run: bool = typer.Option(
461
+ False,
462
+ "--dry-run",
463
+ help="Print what would be written without modifying files.",
464
+ ),
465
+ yes: bool = typer.Option(
466
+ False,
467
+ "-y",
468
+ "--yes",
469
+ help="Write files without an interactive confirmation prompt.",
470
+ ),
471
+ force: bool = typer.Option(
472
+ False,
473
+ "--force",
474
+ help="Overwrite existing workflow files. MCP config is merged when valid JSON.",
475
+ ),
476
+ no_mcp: bool = typer.Option(
477
+ False,
478
+ "--no-mcp",
479
+ help="Write slash-command workflow files only.",
480
+ ),
481
+ mcp_only: bool = typer.Option(
482
+ False,
483
+ "--mcp-only",
484
+ help="Write MCP config only; do not write slash-command workflow files.",
485
+ ),
486
+ ) -> None:
487
+ """Initialize /polycheck for Kilo Code, OpenCode, and Claude Code."""
488
+ selected_scope = scope.lower()
489
+ if selected_scope not in {"global", "project"}:
490
+ console.print("[red]Invalid scope. Use --scope global or --scope project.[/red]")
491
+ raise typer.Exit(2)
492
+ if no_mcp and mcp_only:
493
+ console.print("[red]Use either --no-mcp or --mcp-only, not both.[/red]")
494
+ raise typer.Exit(2)
495
+
496
+ try:
497
+ selected_hosts = normalize_hosts(host)
498
+ except ValueError as exc:
499
+ console.print(f"[red]{exc}[/red]")
500
+ raise typer.Exit(2) from exc
501
+
502
+ project_root = Path.cwd().resolve()
503
+ home = Path.home().resolve()
504
+ plan = build_plan(
505
+ hosts=selected_hosts,
506
+ scope=selected_scope,
507
+ project_root=project_root,
508
+ home=home,
509
+ include_workflows=not mcp_only,
510
+ include_mcp=not no_mcp,
511
+ )
512
+
513
+ console.print(f"[bold]polycheck init[/bold] — {selected_scope} scope")
514
+ for action in plan:
515
+ console.print(format_action(action))
516
+
517
+ if dry_run:
518
+ console.print("\nDry run complete; no files were changed.")
519
+ return
520
+
521
+ if not yes and not typer.confirm("Write these files?"):
522
+ raise typer.Abort()
523
+
524
+ results = apply_plan(plan, force=force, dry_run=False)
525
+ for action in results:
526
+ console.print(format_action(action))
527
+
528
+ _print_init_next_steps(selected_hosts, selected_scope)
529
+
530
+
531
+ def _print_init_next_steps(hosts: list[str], scope: str) -> None:
532
+ """Print concise next steps after initialization."""
533
+ console.print("\nNext steps:")
534
+ console.print(" 1. Restart your LLM coding assistant so it reloads commands and MCP servers.")
535
+ console.print(" 2. Run `/polycheck` in any project.")
536
+
537
+
538
+ @app.command()
539
+ def detected(
540
+ path: Path = typer.Argument(Path("."), exists=True, resolve_path=True),
541
+ ) -> None:
542
+ """Show the languages polycheck detected in PATH."""
543
+ for lang in detect(path):
544
+ console.print(f" [cyan]{lang.slug}[/cyan]")
545
+
546
+
547
+ @app.command(name="prompt")
548
+ def show_prompt(
549
+ plain: bool = typer.Option(
550
+ False,
551
+ "--plain",
552
+ help="Print the prompt without the surrounding explanation (for piping)",
553
+ ),
554
+ ) -> None:
555
+ """Print the LLM triage prompt.
556
+
557
+ Pipe the output to your LLM tool of choice, or copy it from the
558
+ terminal. Use ``--plain`` to drop the surrounding explanation.
559
+ """
560
+ from .mcp_server import _TRIAGE_PROMPT
561
+ if plain:
562
+ typer.echo(_TRIAGE_PROMPT)
563
+ return
564
+ console.print("[bold]The LLM triage prompt[/bold]")
565
+ console.print(
566
+ "Pipe this to your LLM tool, or copy-paste it together with the "
567
+ "markdown report into a chat. Use [cyan]--plain[/cyan] to drop "
568
+ "this explanation."
569
+ )
570
+ console.print()
571
+ console.print("─" * 60)
572
+ console.print(_TRIAGE_PROMPT)
573
+ console.print("─" * 60)
574
+
575
+
576
+ @app.command(name="doctor")
577
+ def doctor(
578
+ fail_on_missing: bool = typer.Option(
579
+ False,
580
+ "--fail-on-missing",
581
+ help="Exit non-zero if any bundled analyzer is missing. Default: exit 0.",
582
+ ),
583
+ ) -> None:
584
+ """Check which bundled analyzers are installed and which are missing.
585
+
586
+ For each missing tool, prints the install command. For each
587
+ installed tool, prints its version. This is the recommended first
588
+ step on a fresh machine.
589
+ """
590
+ table = Table(title="polycheck doctor")
591
+ table.add_column("Tool", style="cyan")
592
+ table.add_column("Status")
593
+ table.add_column("Version")
594
+ table.add_column("Install")
595
+ missing = 0
596
+ for cls in sorted(default_registry.all(), key=lambda c: c.name):
597
+ inst = cls()
598
+ if inst.is_installed():
599
+ table.add_row(
600
+ inst.name, "[green]installed[/green]", inst.version() or "?", ""
601
+ )
602
+ else:
603
+ missing += 1
604
+ table.add_row(
605
+ inst.name, "[yellow]missing[/yellow]", "—", inst.install_hint()
606
+ )
607
+ console.print(table)
608
+ if missing:
609
+ console.print(
610
+ f"\n[yellow]{missing} tool(s) missing.[/yellow] "
611
+ f"Install them with: [cyan]polycheck install[/cyan]"
612
+ )
613
+ if fail_on_missing:
614
+ raise typer.Exit(code=1)
615
+ console.print("\n[green]Doctor complete.[/green]")
616
+
617
+
618
+ @app.command(name="install")
619
+ def install_cmd(
620
+ tool: list[str] = typer.Argument(
621
+ None, help="Specific tool name(s) to install (default: all missing)"
622
+ ),
623
+ all_tools: bool = typer.Option(
624
+ False, "--all", help="Install every bundled tool, not just the missing ones"
625
+ ),
626
+ yes: bool = typer.Option(
627
+ False, "-y", "--yes", help="Skip confirmation prompt"
628
+ ),
629
+ ) -> None:
630
+ """Install missing bundled analyzers.
631
+
632
+ With no arguments, installs every tool whose ``is_installed()`` is
633
+ currently False. Use ``--all`` to reinstall everything. Use
634
+ ``polycheck install ruff mypy`` to install specific tools.
635
+
636
+ Installation is delegated to the underlying package manager
637
+ (``pipx``, ``npm``, ``brew``, ``apt``, …) as configured per-tool
638
+ in the ``installer`` class attribute.
639
+ """
640
+ targets = _resolve_install_targets(tool, all_tools)
641
+ if not targets:
642
+ console.print("[green]Nothing to install — all selected tools are present.[/green]")
643
+ return
644
+
645
+ _confirm_install(targets, yes)
646
+ failed = _execute_installs(targets)
647
+
648
+ if failed:
649
+ raise typer.Exit(code=1)
650
+
651
+
652
+ def _resolve_install_targets(tool: list[str] | None, all_tools: bool) -> list[type]:
653
+ """Determine which tools to install based on CLI arguments."""
654
+ if tool:
655
+ return _resolve_named_tools(tool)
656
+ if all_tools:
657
+ return list(default_registry.all())
658
+ return [cls for cls in default_registry.all() if not cls().is_installed()]
659
+
660
+
661
+ def _resolve_named_tools(names: list[str]) -> list[type[Tool]]:
662
+ """Resolve tool names to tool classes, exiting on unknown names."""
663
+ targets = []
664
+ for name in names:
665
+ cls = default_registry.get(name)
666
+ if cls is None:
667
+ console.print(f"[red]Unknown tool:[/red] {name}")
668
+ raise typer.Exit(code=1)
669
+ targets.append(cls)
670
+ return targets
671
+
672
+
673
+ def _confirm_install(targets: list[type[Tool]], yes: bool) -> None:
674
+ """Show installation plan and confirm with user."""
675
+ console.print(f"Will install {len(targets)} tool(s):")
676
+ for cls in targets:
677
+ console.print(f" [cyan]{cls.name}[/cyan]: {cls().install_hint()}")
678
+ if not yes and not typer.confirm("Proceed?"):
679
+ raise typer.Abort()
680
+
681
+
682
+ def _execute_installs(targets: list[type[Tool]]) -> list[tuple[str, str]]:
683
+ """Install each target tool, returning list of failures."""
684
+ failed: list[tuple[str, str]] = []
685
+ for cls in targets:
686
+ inst = cls()
687
+ ok, msg = inst.install()
688
+ if ok:
689
+ console.print(f" [green]✓[/green] {msg}")
690
+ else:
691
+ console.print(f" [red]✗[/red] {inst.name}: {msg}")
692
+ failed.append((inst.name, msg))
693
+ return failed
694
+
695
+
696
+ def _auto_install_missing(
697
+ *,
698
+ only: list[str] | None,
699
+ repo: Path,
700
+ ) -> None:
701
+ """Used by ``polycheck run --install`` to install any missing tools
702
+ that would otherwise be skipped."""
703
+ missing = _missing_tools(repo, only=only, exclude=set())
704
+ if not missing:
705
+ return
706
+ console.print(
707
+ f"[cyan]--install:[/cyan] installing {len(missing)} missing tool(s)…"
708
+ )
709
+ for cls in missing:
710
+ inst = cls()
711
+ ok, msg = inst.install()
712
+ if ok:
713
+ console.print(f" [green]✓[/green] {msg}")
714
+ else:
715
+ console.print(f" [red]✗[/red] {inst.name}: {msg}")
716
+
717
+
718
+ def _missing_tools(
719
+ repo: Path,
720
+ *,
721
+ only: list[str] | None,
722
+ exclude: set[str],
723
+ config: Config | None = None,
724
+ ) -> list[type[Tool]]:
725
+ """Tool classes that *would* be applicable to ``repo`` but whose
726
+ binary is not on PATH. Excludes any name in ``exclude`` (typically
727
+ the set of tools that already ran).
728
+ """
729
+ langs = detect(repo)
730
+ lang_slugs = {lang.slug for lang in langs}
731
+ out: list[type[Tool]] = []
732
+ for cls in default_registry.all():
733
+ if cls.name in exclude:
734
+ continue
735
+ if only and cls.name not in only:
736
+ continue
737
+ if not _tool_enabled(cls, config):
738
+ continue
739
+ if not _language_matches(cls, lang_slugs):
740
+ continue
741
+ inst = cls()
742
+ if not inst.is_installed():
743
+ if not _tool_applicable(cls, repo):
744
+ continue
745
+ out.append(cls)
746
+ return out
747
+
748
+
749
+ def _tool_enabled(cls: type[Tool], config: Config | None) -> bool:
750
+ if config and config.enable and cls.name not in config.enable:
751
+ return False
752
+ if config and cls.name in config.disable:
753
+ return False
754
+ return True
755
+
756
+
757
+ def _language_matches(cls: type[Tool], lang_slugs: set[str]) -> bool:
758
+ if cls.universal:
759
+ return bool(lang_slugs)
760
+ return bool(lang_slugs and any(slug in lang_slugs for slug in cls.languages))
761
+
762
+
763
+ def _tool_applicable(cls: type[Tool], repo: Path) -> bool:
764
+ try:
765
+ return cls().is_applicable(repo)
766
+ except Exception: # noqa: BLE001 — missing-tool checks should not crash
767
+ return True
768
+
769
+
770
+ def _exit_code(findings: list[Finding], fail_on: str) -> int:
771
+ """Return 0 if all findings are below ``fail_on``; 1 otherwise.
772
+
773
+ The default is MEDIUM, so LOW and INFO findings don't fail the build.
774
+ """
775
+ if not findings:
776
+ return 0
777
+ from .finding import Severity
778
+ try:
779
+ threshold = Severity[fail_on]
780
+ except KeyError:
781
+ return 0
782
+ return 1 if any(f.severity >= threshold for f in findings) else 0
783
+
784
+
785
+ def main() -> None:
786
+ """Entry point declared in pyproject.toml."""
787
+ app()
788
+
789
+
790
+ if __name__ == "__main__":
791
+ sys.exit(app())