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
@@ -0,0 +1,994 @@
1
+ """polycheck MCP server (stdio transport).
2
+
3
+ Exposes one primary workflow tool to an AI agent:
4
+
5
+ * ``polycheck.run`` — primary guided dependency check, scan, reports,
6
+ summary, coverage metadata, and next approval step.
7
+ * ``polycheck`` — compatibility alias for ``polycheck.run``.
8
+
9
+ And advanced/low-level tools:
10
+
11
+ * ``polycheck.audit_run`` — run the scan primitive and return the
12
+ report paths, dependency context, and a short summary. Heavy: spawns
13
+ subprocesses.
14
+ * ``polycheck.list_tools`` — list available analyzers.
15
+ * ``polycheck.explain_finding`` — explain a finding's category and
16
+ how to triage it.
17
+ * ``polycheck.doctor`` — check which tools are installed and which
18
+ are missing. Reports Docker status for sonarless.
19
+ * ``polycheck.install`` — install missing tools.
20
+
21
+ And resources for reports and session context:
22
+
23
+ * ``polycheck://findings/markdown`` — last run's markdown report.
24
+ * ``polycheck://findings/json`` — last run's JSON report.
25
+ * ``polycheck://session/latest`` — latest guided workflow summary.
26
+ * ``polycheck://triage/prompt`` — the LLM triage prompt template.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import json
31
+ import shutil
32
+ import subprocess
33
+ import uuid
34
+ from datetime import datetime, timezone
35
+ from pathlib import Path
36
+
37
+ from mcp.types import TextContent
38
+
39
+ from .config import Config
40
+ from .finding import Category, Finding, Severity
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
+ )
51
+ from .session import append_event, write_run_summary, write_session_summary
52
+ from .tools.base import Tool
53
+
54
+ # Module-level state for the last run's reports. Safe for stdio transport
55
+ # (single request at a time). Not thread-safe for concurrent requests.
56
+ _LAST_RUN: dict = {}
57
+
58
+ # Status messages for tool availability checks.
59
+ _STATUS_NOT_FOUND = "not found"
60
+ _STATUS_INSTALLED = "installed"
61
+
62
+
63
+ def _text_content(payload: dict) -> list:
64
+ return [TextContent(type="text", text=json.dumps(payload, indent=2))]
65
+
66
+
67
+ _TRIAGE_PROMPT = """\
68
+ You are a senior code reviewer guiding the user through code quality
69
+ improvements. The file polycheck-report.md is the output of a
70
+ static-analysis pipeline covering LINT, TYPE, SECURITY, DEAD_CODE,
71
+ DEPS, CVE, and SECRETS findings — including results from SonarQube
72
+ (bugs, vulnerabilities, code smells across 30+ languages).
73
+
74
+ ## Workflow
75
+
76
+ 1. For normal polycheck runs, call the guided MCP tool `polycheck.run`
77
+ first. Do not manually call `polycheck.doctor` or `polycheck.install`
78
+ unless the user explicitly asks for diagnostics.
79
+ 2. Read the returned `status`, `next_action`, and `scan_coverage`.
80
+ 3. If `status` is `needs_user_input` and the tool reports missing
81
+ analyzers, ask the user whether to approve installation.
82
+ 4. If the user approves, call `polycheck.run` again with:
83
+ - `install_mode: "tools_only"`
84
+ - `install_confirmed: true`
85
+ 5. Present findings grouped by severity:
86
+ - CRITICAL and HIGH first (urgent — these are likely real bugs)
87
+ - MEDIUM next (real smells, worth fixing)
88
+ - LOW and INFO only if the user asks
89
+ 6. For each finding, tell the user:
90
+ - Which tool found it (ruff, mypy, sonarless, gitleaks, etc.)
91
+ - What the issue is (one sentence)
92
+ - Why it matters (security risk, type error, dead code, etc.)
93
+ 7. Ask: "Should I fix the [HIGH/CRITICAL] issues?"
94
+ 8. Apply fixes ONLY after user approval.
95
+ 9. Summarize: what was fixed, what was deferred, what was flagged as
96
+ false positive.
97
+
98
+ ## Baseline & Durable Suppressions
99
+
100
+ Keep the triage loop cheap across runs:
101
+
102
+ 1. After a run the user accepts (fixed or triaged everything), suggest
103
+ taking a baseline: `polycheck baseline <repo>`.
104
+ 2. Later runs with `diff: true` report only NEW findings — the payload's
105
+ `baseline` object carries `known` and `new` counts.
106
+ 3. When a finding is a FALSE POSITIVE, persist the verdict instead of
107
+ re-arguing it every run: append the rule to the `suppress:` list in
108
+ `.polycheck.yml` (format: `- RULE` for everywhere, or
109
+ `- RULE@path/file.ext` for one file). Example:
110
+
111
+ suppress:
112
+ - F401
113
+ - SC2086@scripts/legacy.sh
114
+
115
+ 4. Never edit reports or code to silence a finding — suppressions live
116
+ in `.polycheck.yml` so they are reviewable and revertible.
117
+
118
+ ## Missing Tools
119
+
120
+ If the report mentions missing tools or the user asks about installing them:
121
+
122
+ 1. Use the guided `polycheck.run` workflow again with
123
+ `install_mode: "tools_only"`.
124
+ 2. Ask the user to approve analyzer installation before setting
125
+ `install_confirmed: true`.
126
+ 3. Do not manually chain `polycheck.doctor` and `polycheck.install` for
127
+ the normal workflow. Use those only for debugging or advanced use.
128
+ 4. For tools requiring manual installation, such as Docker for sonarless:
129
+ - **Docker**: Ask your LLM coding assistant to help install Docker
130
+ for this OS. Common options:
131
+ * Linux: `sudo apt install docker.io && sudo usermod -aG docker $USER`
132
+ * Or follow https://docs.docker.com/get-docker/
133
+ * After install, log out and back in for group changes to take effect
134
+ - After Docker is installed, rerun `polycheck.run`; polycheck will
135
+ offer to install sonarless if it is still missing.
136
+
137
+
138
+
139
+ ## Triage Rules
140
+
141
+ For each finding, classify it as:
142
+
143
+ REAL BUG — must be fixed; do not ship without a fix.
144
+ REAL SMELL — not wrong, but worth refactoring; flag for follow-up.
145
+ FALSE POSITIVE — analyzer is wrong here; suppress or whitelist.
146
+ DEFERRED — known issue, tracked elsewhere; leave it.
147
+
148
+ For REAL BUG and REAL SMELL, give the smallest possible patch. Do not
149
+ rewrite surrounding code. Do not add new dependencies. Do not change
150
+ public APIs unless the finding says to. Prefer the analyzer's suggested
151
+ fix if one exists.
152
+
153
+ Ignore findings that are clearly tooling noise (e.g. "Library stubs
154
+ not installed for X" from mypy — that's the lint venv, not the project).
155
+
156
+ Do not re-read the source files unless a finding's message is genuinely
157
+ ambiguous. Trust the static report. Read the full markdown report with
158
+ the `read_file` tool, then the JSON report with `read_file` for any
159
+ findings you need full `raw` data on.
160
+
161
+ ## Output
162
+
163
+ When you're done, return a single JSON object shaped like:
164
+
165
+ {
166
+ "actions": [
167
+ {
168
+ "tool": "ruff",
169
+ "rule": "I001",
170
+ "file": "src/foo.py",
171
+ "line": 12,
172
+ "verdict": "REAL BUG",
173
+ "patch": "…unified diff or null…",
174
+ "comment": "one sentence"
175
+ }
176
+ ],
177
+ "summary": "X real bugs, Y real smells, Z false positives, W deferred"
178
+ }
179
+ """
180
+
181
+
182
+ def run_server() -> None:
183
+ """Start the MCP server. Blocks until the parent closes stdin."""
184
+ try:
185
+ from mcp.server import Server
186
+ from mcp.server.stdio import stdio_server
187
+ from mcp.types import AnyUrl, Resource, TextContent, Tool
188
+ except ImportError as e:
189
+ raise SystemExit(
190
+ f"polycheck MCP requires the `mcp` package: {e}. "
191
+ "Install with `pip install mcp`."
192
+ ) from e
193
+
194
+ server = Server("polycheck")
195
+
196
+ @server.list_tools()
197
+ async def _list_tools():
198
+ return _build_tool_definitions()
199
+
200
+ @server.call_tool()
201
+ async def _call_tool(name: str, arguments: dict):
202
+ return _dispatch_tool(name, arguments)
203
+
204
+ @server.list_resources()
205
+ async def _list_resources():
206
+ return [
207
+ Resource(
208
+ uri=AnyUrl("polycheck://triage/prompt"),
209
+ name="LLM triage prompt",
210
+ description="The prompt to feed to an LLM with the markdown report.",
211
+ mimeType="text/plain",
212
+ ),
213
+ Resource(
214
+ uri=AnyUrl("polycheck://session/latest"),
215
+ name="Latest polycheck session",
216
+ description="The latest guided workflow summary.",
217
+ mimeType="text/markdown",
218
+ ),
219
+ ]
220
+
221
+ @server.read_resource()
222
+ async def _read_resource(uri: str):
223
+ return _read_resource_content(uri)
224
+
225
+ import anyio
226
+
227
+ async def _run():
228
+ async with stdio_server() as (read_stream, write_stream):
229
+ await server.run(read_stream, write_stream, server.create_initialization_options())
230
+
231
+ anyio.run(_run)
232
+
233
+
234
+ _WORKFLOW_TOOL_DESCRIPTION = (
235
+ "Primary guided workflow entrypoint for normal use. This is the "
236
+ "only tool most LLMs should call for polycheck. It checks dependencies, "
237
+ "offers approved analyzer installs, runs the scan, writes reports, "
238
+ "returns coverage metadata, and returns next_action. Do not call "
239
+ "polycheck.doctor or polycheck.install manually unless debugging."
240
+ )
241
+
242
+
243
+ def _workflow_tool(name: str):
244
+ from mcp.types import Tool
245
+
246
+ return Tool(
247
+ name=name,
248
+ description=_WORKFLOW_TOOL_DESCRIPTION,
249
+ inputSchema={
250
+ "type": "object",
251
+ "properties": {
252
+ "repo": {"type": "string", "description": "Path to the repo root"},
253
+ "tools": {
254
+ "type": "array",
255
+ "items": {"type": "string"},
256
+ "description": "Restrict to specific tool names",
257
+ },
258
+ "severity": {
259
+ "type": "string",
260
+ "enum": ["INFO", "LOW", "MEDIUM", "HIGH", "CRITICAL"],
261
+ "description": "Minimum severity to keep. Default: MEDIUM.",
262
+ },
263
+ "install_mode": {
264
+ "type": "string",
265
+ "enum": ["none", "tools_only"],
266
+ "description": "none or tools_only. Default: none.",
267
+ },
268
+ "install_confirmed": {
269
+ "type": "boolean",
270
+ "description": "Must be true when install_mode is tools_only. Default: false.",
271
+ },
272
+ "diff": {
273
+ "type": "boolean",
274
+ "description": "Only report findings that are new since the last "
275
+ "baseline (created by running polycheck with diff off and "
276
+ "saving it via `polycheck baseline`). Default: false.",
277
+ },
278
+ "parallel": {
279
+ "type": "boolean",
280
+ "description": "Run tools concurrently. Default: true.",
281
+ },
282
+ },
283
+ "required": ["repo"],
284
+ },
285
+ )
286
+
287
+
288
+ def _build_tool_definitions():
289
+ """Build the list of MCP tool definitions."""
290
+ from mcp.types import Tool
291
+
292
+ return [
293
+ _workflow_tool("polycheck.run"),
294
+ _workflow_tool("polycheck"),
295
+ Tool(
296
+ name="polycheck.audit_run",
297
+ description=(
298
+ "Run the polycheck pipeline on a repository. Returns the "
299
+ "report paths, dependency context, and a one-line summary. "
300
+ "Use the `polycheck://findings/markdown` resource to read "
301
+ "the full report."
302
+ ),
303
+ inputSchema={
304
+ "type": "object",
305
+ "properties": {
306
+ "repo": {"type": "string", "description": "Path to the repo root"},
307
+ "tools": {
308
+ "type": "array",
309
+ "items": {"type": "string"},
310
+ "description": "Restrict to specific tool names",
311
+ },
312
+ "severity": {
313
+ "type": "string",
314
+ "enum": ["INFO", "LOW", "MEDIUM", "HIGH", "CRITICAL"],
315
+ },
316
+ },
317
+ "required": ["repo"],
318
+ },
319
+ ),
320
+ Tool(
321
+ name="polycheck.list_tools",
322
+ description="List every analyzer polycheck knows about.",
323
+ inputSchema={"type": "object", "properties": {}},
324
+ ),
325
+ Tool(
326
+ name="polycheck.explain_finding",
327
+ description=(
328
+ "Explain what a category of finding means and how to "
329
+ "triage it (e.g. 'CVE', 'DEAD_CODE', 'LINT')."
330
+ ),
331
+ inputSchema={
332
+ "type": "object",
333
+ "properties": {
334
+ "category": {
335
+ "type": "string",
336
+ "enum": [c.value for c in Category],
337
+ },
338
+ "tool": {"type": "string", "description": "Optional tool name"},
339
+ },
340
+ "required": ["category"],
341
+ },
342
+ ),
343
+ Tool(
344
+ name="polycheck.doctor",
345
+ description=(
346
+ "Check which tools are installed and which are missing. "
347
+ "Reports Docker status (needed for sonarless)."
348
+ ),
349
+ inputSchema={"type": "object", "properties": {}},
350
+ ),
351
+ Tool(
352
+ name="polycheck.install",
353
+ description=(
354
+ "Install missing tools. Without arguments, installs all "
355
+ "missing tools. Pass specific tool names to install only those."
356
+ ),
357
+ inputSchema={
358
+ "type": "object",
359
+ "properties": {
360
+ "tools": {
361
+ "type": "array",
362
+ "items": {"type": "string"},
363
+ "description": "Specific tool names to install (default: all missing)",
364
+ },
365
+ },
366
+ },
367
+ ),
368
+ ]
369
+
370
+
371
+ def _dispatch_tool(name: str, arguments: dict):
372
+ """Dispatch an MCP tool call to the appropriate handler."""
373
+ handlers = {
374
+ "polycheck.run": _handle_polycheck,
375
+ "polycheck": _handle_polycheck,
376
+ "polycheck.audit_run": _handle_audit_run,
377
+ "polycheck.list_tools": lambda _: _handle_list_tools(),
378
+ "polycheck.explain_finding": _handle_explain,
379
+ "polycheck.doctor": lambda _: _handle_doctor(),
380
+ "polycheck.install": _handle_install,
381
+ }
382
+ handler = handlers.get(name)
383
+ if handler is None:
384
+ raise ValueError(f"Unknown tool: {name}")
385
+ return handler(arguments)
386
+
387
+
388
+ def _read_resource_content(uri: str) -> str:
389
+ """Read content from an MCP resource URI."""
390
+ if uri == "polycheck://triage/prompt":
391
+ return _TRIAGE_PROMPT
392
+ if uri == "polycheck://findings/markdown":
393
+ return _last("polycheck-report.md")
394
+ if uri == "polycheck://findings/json":
395
+ return _last("polycheck-report.json")
396
+ if uri == "polycheck://session/latest":
397
+ latest = _latest_session_markdown()
398
+ if latest:
399
+ return latest
400
+ return "(no session yet — run polycheck.run first)"
401
+ raise ValueError(f"Unknown resource: {uri}")
402
+
403
+
404
+ def _last(name: str) -> str:
405
+ path = _LAST_RUN.get("report_dir")
406
+ if not path:
407
+ return "(no report yet — run polycheck.run first)"
408
+ p = Path(path) / name
409
+ if not p.exists():
410
+ return f"(report not written: {p})"
411
+ return p.read_text(encoding="utf-8")
412
+
413
+
414
+ def _latest_session_markdown() -> str:
415
+ path_text = _LAST_RUN.get("latest_markdown", "")
416
+ if not path_text:
417
+ return ""
418
+ path = Path(path_text)
419
+ if not path.is_file():
420
+ path = Path(_LAST_RUN.get("repo", ".")) / ".polycheck" / "latest.md"
421
+ if not path.is_file():
422
+ return ""
423
+ return path.read_text(encoding="utf-8")
424
+
425
+
426
+ def _repo_from_arguments(arguments: dict) -> Path | list:
427
+ repo = Path(arguments["repo"]).resolve()
428
+ if not repo.exists():
429
+ return _text_content({"error": f"Repo not found: {repo}"})
430
+ if not repo.is_dir():
431
+ return _text_content({"error": f"Not a directory: {repo}"})
432
+ return repo
433
+
434
+
435
+ def _validate_report_dir(repo: Path, configured: str) -> Path | list:
436
+ configured_path = Path(configured)
437
+ if configured_path.is_absolute() or ".." in configured_path.parts:
438
+ return _text_content({"error": "output.report_dir must be a relative path inside the repo"})
439
+ base = (repo / configured_path).resolve()
440
+ try:
441
+ base.relative_to(repo.resolve())
442
+ except ValueError:
443
+ return _text_content({"error": "output.report_dir must stay inside the repo"})
444
+ return base
445
+
446
+
447
+ def _guided_report_dir(repo: Path, configured: str, run_id: str) -> Path | list:
448
+ base = _validate_report_dir(repo, configured)
449
+ if isinstance(base, list):
450
+ return base
451
+ out_dir = base / run_id
452
+ out_dir.mkdir(parents=True, exist_ok=True)
453
+ return out_dir
454
+
455
+
456
+ def _handle_audit_run(arguments: dict) -> list:
457
+ """Run the scan primitive and return report paths plus context."""
458
+ repo = _repo_from_arguments(arguments)
459
+ if isinstance(repo, list):
460
+ return repo
461
+
462
+ cfg = Config.load(repo)
463
+ severity = arguments.get("severity", "MEDIUM").upper()
464
+ if severity not in Severity.__members__:
465
+ return _text_content({"error": f"Unknown severity: {severity}"})
466
+
467
+ dependency = _dependency_check(repo, cfg, tools=arguments.get("tools"))
468
+ runner = Runner(repo=repo, config=cfg)
469
+ findings, results = runner.run(
470
+ parallel=bool(arguments.get("parallel", True)),
471
+ tools=arguments.get("tools"),
472
+ )
473
+ findings = dedupe(findings)
474
+ findings = filter_by_severity(findings, severity)
475
+
476
+ report_dir = _validate_report_dir(repo, cfg.output.report_dir)
477
+ if isinstance(report_dir, list):
478
+ return report_dir
479
+ written: list[Path] = []
480
+ for fmt in cfg.output.formats:
481
+ written.extend(render_report(fmt, repo, findings, results, report_dir=report_dir))
482
+
483
+ _LAST_RUN["report_dir"] = str(report_dir)
484
+ _LAST_RUN["findings"] = [f.to_dict() for f in findings]
485
+ _LAST_RUN["repo"] = str(repo)
486
+
487
+ summary = _audit_summary(
488
+ repo=repo,
489
+ findings=findings,
490
+ results=results,
491
+ reports=written,
492
+ dependency=dependency,
493
+ severity=severity,
494
+ )
495
+ return [TextContent(type="text", text=json.dumps(summary, indent=2, default=str))]
496
+
497
+
498
+ def _handle_polycheck(arguments: dict) -> list:
499
+ """Run the guided workflow used by LLM coding assistants."""
500
+ repo = _repo_from_arguments(arguments)
501
+ if isinstance(repo, list):
502
+ return repo
503
+
504
+ run_id = f"{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}-{uuid.uuid4().hex[:8]}"
505
+ cfg = Config.load(repo)
506
+ severity = arguments.get("severity", "MEDIUM").upper()
507
+ install_mode = arguments.get("install_mode", "none")
508
+ if install_mode not in {"none", "tools_only"}:
509
+ return _text_content({"error": "install_mode must be none or tools_only"})
510
+ install_confirmed = bool(arguments.get("install_confirmed", False))
511
+
512
+ append_event(repo, run_id, {"event": "dependency_check_started"})
513
+ dependency = _dependency_check(repo, cfg, tools=arguments.get("tools"))
514
+ append_event(repo, run_id, {"event": "dependency_check_finished", **dependency})
515
+
516
+ if install_mode == "tools_only":
517
+ append_event(repo, run_id, {"event": "install_started", "install_confirmed": install_confirmed})
518
+ if install_confirmed:
519
+ install_results = _install_missing_tools(dependency["missing_tools"])
520
+ else:
521
+ install_results = []
522
+ append_event(repo, run_id, {"event": "install_finished", "results": install_results})
523
+ dependency = _dependency_check(repo, cfg, tools=arguments.get("tools"))
524
+ else:
525
+ install_results = []
526
+
527
+ append_event(repo, run_id, {"event": "scan_started", "severity": severity})
528
+ cfg.severity_threshold = severity
529
+ runner = Runner(repo=repo, config=cfg)
530
+ findings, results = runner.run(
531
+ parallel=bool(arguments.get("parallel", True)),
532
+ tools=arguments.get("tools"),
533
+ )
534
+ findings = dedupe(findings)
535
+ findings = filter_by_severity(findings, cfg.severity_threshold)
536
+ findings = apply_suppressions(findings, cfg.suppress)
537
+ append_event(repo, run_id, {"event": "scan_finished", "total_findings": len(findings)})
538
+
539
+ diff_requested = bool(arguments.get("diff", False))
540
+ baseline_info: dict | None = None
541
+ if diff_requested:
542
+ findings, baseline_info = _filter_to_new_findings(repo, cfg, findings)
543
+
544
+ out_dir = _guided_report_dir(repo, cfg.output.report_dir, run_id)
545
+ if isinstance(out_dir, list):
546
+ return out_dir
547
+ written: list[Path] = []
548
+
549
+ for fmt in cfg.output.formats:
550
+ written.extend(render_report(fmt, repo, findings, results, report_dir=out_dir))
551
+
552
+ _LAST_RUN["report_dir"] = str(out_dir)
553
+ _LAST_RUN["findings"] = [f.to_dict() for f in findings]
554
+ _LAST_RUN["repo"] = str(repo)
555
+
556
+ summary = _workflow_summary(
557
+ repo=repo,
558
+ findings=findings,
559
+ results=results,
560
+ reports=written,
561
+ dependency=dependency,
562
+ install_results=install_results,
563
+ install_requested=install_mode == "tools_only",
564
+ install_confirmed=install_confirmed,
565
+ severity=severity,
566
+ run_id=run_id,
567
+ )
568
+
569
+ session = write_session_summary(repo, summary)
570
+ summary["session"] = session
571
+ if baseline_info is not None:
572
+ summary["baseline"] = baseline_info
573
+ _LAST_RUN["latest_markdown"] = session["latest_markdown"]
574
+ _LAST_RUN["latest_json"] = session["latest_json"]
575
+
576
+ write_run_summary(repo, run_id, summary)
577
+ return [TextContent(type="text", text=json.dumps(summary, indent=2, default=str))]
578
+
579
+
580
+ def _filter_to_new_findings(
581
+ repo: Path, cfg: Config, findings: list[Finding]
582
+ ) -> tuple[list[Finding], dict]:
583
+ """Diff mode: keep only findings newer than the baseline and return
584
+ the payload the summary should carry about it."""
585
+ baseline = load_baseline(repo / cfg.output.report_dir)
586
+ if baseline is None:
587
+ return findings, {
588
+ "diff": True,
589
+ "baseline": None,
590
+ "note": (
591
+ "no baseline yet — take one with `polycheck baseline` so "
592
+ "future runs report only new findings"
593
+ ),
594
+ }
595
+ new = filter_by_baseline(findings, baseline)
596
+ info = {
597
+ "diff": True,
598
+ "baseline_count": len(baseline),
599
+ "known": len(findings) - len(new),
600
+ "new": len(new),
601
+ }
602
+ return new, info
603
+
604
+
605
+ def _dependency_check(repo: Path, cfg: Config | None = None, tools: list[str] | None = None) -> dict:
606
+ missing_tools = _missing_tools_for_mcp(repo, cfg, only=tools)
607
+ missing_system = _missing_system_dependencies(repo, cfg, tools=tools)
608
+ return {
609
+ "missing_tools": [_missing_tool_to_dict(cls) for cls in missing_tools],
610
+ "missing_system_dependencies": missing_system,
611
+ }
612
+
613
+
614
+ def _missing_tools_for_mcp(repo: Path, cfg: Config | None = None, only: list[str] | None = None) -> list[type]:
615
+ from .cli import _missing_tools
616
+
617
+ return _missing_tools(repo, only=only, exclude=set(), config=cfg)
618
+
619
+
620
+ def _missing_tool_to_dict(cls: type[Tool]) -> dict:
621
+ inst = cls()
622
+ return {
623
+ "name": inst.name,
624
+ "kind": "analyzer",
625
+ "install_hint": inst.install_hint(),
626
+ "auto_installable": inst.can_auto_install(),
627
+ "risk": "low",
628
+ }
629
+
630
+
631
+ def _missing_system_dependencies(repo: Path, cfg: Config | None, tools: list[str] | None = None) -> list[dict]:
632
+ if tools is not None and "sonarless" not in tools:
633
+ return []
634
+ if not _tool_enabled_by_config("sonarless", cfg):
635
+ return []
636
+ docker = _check_docker()
637
+ if docker["status"] == _STATUS_INSTALLED:
638
+ return []
639
+ return [{
640
+ "name": "docker",
641
+ "kind": "system",
642
+ "needed_for": ["sonarless"],
643
+ "status": docker["status"],
644
+ "install_hint": (
645
+ "Docker is required for sonarless. Ask your LLM coding assistant "
646
+ "to help install Docker for this OS, then rerun /polycheck."
647
+ ),
648
+ "auto_installable": False,
649
+ "risk": "high",
650
+ }]
651
+
652
+
653
+ def _tool_enabled_by_config(name: str, cfg: Config | None) -> bool:
654
+ if cfg and cfg.enable and name not in cfg.enable:
655
+ return False
656
+ if cfg and name in cfg.disable:
657
+ return False
658
+ return True
659
+
660
+
661
+ def _install_missing_tools(missing_tools: list[dict]) -> list[dict]:
662
+ results = []
663
+ for item in missing_tools:
664
+ cls = default_registry.get(item["name"])
665
+ if cls is None:
666
+ results.append({"name": item["name"], "installed": False, "message": "unknown tool"})
667
+ continue
668
+ inst = cls()
669
+ ok, message = inst.install()
670
+ results.append({"name": item["name"], "installed": ok, "message": message})
671
+ return results
672
+
673
+
674
+ def _scan_coverage(results: list, missing_tools: list[dict], missing_system: list[dict]) -> dict:
675
+ tools_run = [r.tool for r in results]
676
+ applicable_tools = len(tools_run) + len(missing_tools)
677
+ coverage = "full" if not missing_tools and not missing_system else "partial"
678
+ warnings = []
679
+ if missing_tools or missing_system:
680
+ warnings.append(
681
+ f"Partial scan: only {len(tools_run)} of {applicable_tools} applicable analyzers ran. "
682
+ "No findings does not mean the repo is clean."
683
+ )
684
+ if missing_system:
685
+ names = ", ".join(item.get("name", "system dependency") for item in missing_system)
686
+ warnings.append(f"Missing system dependencies blocked some analyzers: {names}.")
687
+ return {
688
+ "coverage": coverage,
689
+ "applicable_tools": applicable_tools,
690
+ "tools_run": tools_run,
691
+ "missing_tools": missing_tools,
692
+ "missing_system_dependencies": missing_system,
693
+ "warning": " ".join(warnings) if warnings else "",
694
+ }
695
+
696
+
697
+ def _audit_summary(
698
+ *,
699
+ repo: Path,
700
+ findings: list,
701
+ results: list,
702
+ reports: list[Path],
703
+ dependency: dict,
704
+ severity: str,
705
+ ) -> dict:
706
+ by_severity = {
707
+ severity_name: sum(1 for f in findings if f.severity.name == severity_name)
708
+ for severity_name in ("CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO")
709
+ }
710
+ by_tool = {
711
+ tool_name: sum(1 for f in findings if f.tool == tool_name)
712
+ for tool_name in sorted({f.tool for f in findings})
713
+ }
714
+ tools_run = [
715
+ {
716
+ "name": r.tool,
717
+ "status": r.status,
718
+ "finding_count": len(r.findings),
719
+ "duration_sec": round(r.duration_sec, 2),
720
+ "error": r.error,
721
+ }
722
+ for r in results
723
+ ]
724
+ return {
725
+ "schema_version": 1,
726
+ "status": "completed",
727
+ "next_action": "",
728
+ "repo": str(repo),
729
+ "severity": severity,
730
+ "total_findings": len(findings),
731
+ "by_severity": by_severity,
732
+ "by_tool": by_tool,
733
+ "tools_run": tools_run,
734
+ "tools_failed": [r.tool for r in results if r.status in ("error", "timeout")],
735
+ "missing_tools": dependency["missing_tools"],
736
+ "missing_system_dependencies": dependency["missing_system_dependencies"],
737
+ "reports": [str(p) for p in reports],
738
+ "resources": ["polycheck://findings/markdown", "polycheck://findings/json"],
739
+ }
740
+
741
+
742
+ def _workflow_summary(
743
+ *,
744
+ repo: Path,
745
+ findings: list,
746
+ results: list,
747
+ reports: list[Path],
748
+ dependency: dict,
749
+ install_results: list[dict],
750
+ install_requested: bool,
751
+ install_confirmed: bool,
752
+ severity: str,
753
+ run_id: str,
754
+ ) -> dict:
755
+ by_severity = {
756
+ severity_name: sum(1 for f in findings if f.severity.name == severity_name)
757
+ for severity_name in ("CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO")
758
+ }
759
+ by_tool = {
760
+ tool_name: sum(1 for f in findings if f.tool == tool_name)
761
+ for tool_name in sorted({f.tool for f in findings})
762
+ }
763
+ tools_run = [
764
+ {
765
+ "name": r.tool,
766
+ "status": r.status,
767
+ "finding_count": len(r.findings),
768
+ "duration_sec": round(r.duration_sec, 2),
769
+ "error": r.error,
770
+ }
771
+ for r in results
772
+ ]
773
+ missing_tools = dependency["missing_tools"]
774
+ missing_system = dependency["missing_system_dependencies"]
775
+ scan_coverage = _scan_coverage(results, missing_tools, missing_system)
776
+ next_action = _next_action(
777
+ findings=findings,
778
+ missing_tools=missing_tools,
779
+ missing_system=missing_system,
780
+ install_requested=install_requested,
781
+ install_confirmed=install_confirmed,
782
+ install_results=install_results,
783
+ severity=severity,
784
+ )
785
+ status = "needs_user_input" if next_action else "completed"
786
+
787
+ return {
788
+ "schema_version": 1,
789
+ "run_id": run_id,
790
+ "status": status,
791
+ "next_action": next_action,
792
+ "repo": str(repo),
793
+ "severity": severity,
794
+ "total_findings": len(findings),
795
+ "by_severity": by_severity,
796
+ "by_tool": by_tool,
797
+ "scan_coverage": scan_coverage,
798
+ "tools_run": tools_run,
799
+ "tools_skipped": missing_tools + missing_system,
800
+ "missing_tools": missing_tools,
801
+ "missing_system_dependencies": missing_system,
802
+ "install_requested": install_requested,
803
+ "install_confirmed": install_confirmed,
804
+ "install_results": install_results,
805
+ "tools_failed": [r.tool for r in results if r.status in ("error", "timeout")],
806
+ "reports": [str(p) for p in reports],
807
+ "resources": ["polycheck://findings/markdown", "polycheck://findings/json"],
808
+ }
809
+
810
+
811
+ def _next_action(
812
+ *,
813
+ findings: list,
814
+ missing_tools: list[dict],
815
+ missing_system: list[dict],
816
+ install_requested: bool,
817
+ install_confirmed: bool,
818
+ install_results: list[dict],
819
+ severity: str,
820
+ ) -> str:
821
+ failed_installs = [r for r in install_results if not r.get("installed")]
822
+ if failed_installs:
823
+ names = ", ".join(r.get("name", "tool") for r in failed_installs)
824
+ return f"install failed for {names}; ask user to review the install message and rerun"
825
+ if missing_tools or missing_system:
826
+ if install_requested and not install_confirmed:
827
+ return "ask user to confirm analyzer tool installation before continuing with polycheck.run"
828
+ if missing_system:
829
+ return (
830
+ "system dependencies are missing, so some analyzers did not run; "
831
+ "ask the user to install the listed system dependencies with their "
832
+ "LLM coding assistant or rerun with available tools"
833
+ )
834
+ return "ask user to approve installing missing analyzers, then rerun polycheck.run"
835
+ if any(f.fixable for f in findings):
836
+ return f"ask user whether to fix {severity}+ findings or skip fixes"
837
+ if findings:
838
+ return "no fixable findings; ask user whether to lower the severity threshold, install skipped tools, or end the workflow"
839
+ return ""
840
+
841
+
842
+ def _handle_list_tools() -> list:
843
+ rows = []
844
+ for cls in default_registry.all():
845
+ inst = cls()
846
+ installed = inst.is_installed()
847
+ rows.append({
848
+ "name": cls.name,
849
+ "category": cls.category.value,
850
+ "languages": cls.languages,
851
+ "universal": cls.universal,
852
+ "installed": installed,
853
+ "version": inst.version() if installed else None,
854
+ "install_hint": "" if installed else inst.install_hint(),
855
+ })
856
+ return [TextContent(type="text", text=json.dumps(rows, indent=2))]
857
+
858
+
859
+ def _handle_explain(arguments: dict) -> list:
860
+ cat = arguments.get("category", "").upper()
861
+ tool = arguments.get("tool")
862
+ text = _CATEGORY_HELP.get(cat, f"No help for category: {cat}")
863
+ if tool:
864
+ cls = default_registry.get(tool)
865
+ if cls is None:
866
+ text += f"\n\nNote: unknown tool '{tool}'."
867
+ else:
868
+ inst = cls()
869
+ text += f"\n\nFor {tool}, run: `{inst.install_hint()}`."
870
+ return [TextContent(type="text", text=text)]
871
+
872
+
873
+ def _handle_doctor() -> list:
874
+ """Check Docker, sonarless, and all registered tools."""
875
+ rows = []
876
+
877
+ # Docker check
878
+ docker_status = _check_docker()
879
+ rows.append(docker_status)
880
+
881
+ # sonarless check
882
+ sonarless_ok = shutil.which("sonarless") is not None
883
+ rows.append({
884
+ "name": "sonarless",
885
+ "status": _STATUS_INSTALLED if sonarless_ok else _STATUS_NOT_FOUND,
886
+ "note": "" if sonarless_ok else (
887
+ "Install: curl -s https://raw.githubusercontent.com/gitricko/sonarless/main/install.sh | bash"
888
+ ),
889
+ })
890
+
891
+ # All registered tools
892
+ for cls in default_registry.all():
893
+ inst = cls()
894
+ installed = inst.is_installed()
895
+ rows.append({
896
+ "name": cls.name,
897
+ "status": _STATUS_INSTALLED if installed else _STATUS_NOT_FOUND,
898
+ "version": inst.version() if installed else None,
899
+ "languages": cls.languages,
900
+ "universal": cls.universal,
901
+ "note": "" if installed else f"Install: {inst.install_hint()}",
902
+ })
903
+
904
+ return [TextContent(type="text", text=json.dumps(rows, indent=2))]
905
+
906
+
907
+ def _check_docker() -> dict:
908
+ """Check if Docker is installed and running."""
909
+ docker_ok = shutil.which("docker") is not None
910
+ docker_running = False
911
+ if docker_ok:
912
+ try:
913
+ r = subprocess.run(["docker", "info"], capture_output=True, timeout=5)
914
+ docker_running = r.returncode == 0
915
+ except (subprocess.TimeoutExpired, OSError):
916
+ pass
917
+
918
+ if docker_running:
919
+ status = _STATUS_INSTALLED
920
+ elif docker_ok:
921
+ status = "exists but not running"
922
+ else:
923
+ status = _STATUS_NOT_FOUND
924
+
925
+ note = "" if docker_running else (
926
+ "Docker is needed for sonarless (SonarQube analysis). "
927
+ "Install Docker: https://docs.docker.com/get-docker/"
928
+ )
929
+ return {"name": "docker", "status": status, "note": note}
930
+
931
+
932
+ def _handle_install(arguments: dict) -> list:
933
+ """Install missing tools."""
934
+ tools_filter = arguments.get("tools")
935
+ results = []
936
+
937
+ for cls in default_registry.all():
938
+ if tools_filter and cls.name not in tools_filter:
939
+ continue
940
+ inst = cls()
941
+ if inst.is_installed():
942
+ results.append({"name": cls.name, "installed": True, "message": "already installed"})
943
+ continue
944
+ success, message = inst.install()
945
+ results.append({"name": cls.name, "installed": success, "message": message})
946
+
947
+ return [TextContent(type="text", text=json.dumps(results, indent=2))]
948
+
949
+
950
+ _CATEGORY_HELP = {
951
+ "LINT": (
952
+ "LINT findings are style + simple bug-shape rules. Mostly auto-fixable. "
953
+ "Most are LOW/INFO. Triage: prefer the analyzer's --fix, or suppress "
954
+ "with an inline directive if the rule genuinely doesn't fit."
955
+ ),
956
+ "TYPE": (
957
+ "TYPE findings are static type errors. Usually HIGH. They may be real "
958
+ "bugs (passing a string to a function expecting int) or env noise "
959
+ "(missing library stubs in the lint venv). Triage: read the message; "
960
+ "if it says 'library stubs not installed' or 'cannot find "
961
+ "implementation', mark FALSE POSITIVE for *this run* and add the "
962
+ "package to your mypy requirements."
963
+ ),
964
+ "SECURITY": (
965
+ "SECURITY findings are pattern-based bugs, vulnerabilities, and "
966
+ "security hotspots. Many are HIGH. They have a high signal but not "
967
+ "all are bugs (e.g. 'use of MD5' is a smell, not always a bug). "
968
+ "Triage: for each, ask 'is the dangerous operation actually "
969
+ "reachable with attacker-controlled input?'"
970
+ ),
971
+ "DEAD_CODE": (
972
+ "DEAD_CODE findings are symbols not called from anywhere. Mostly LOW. "
973
+ "Many are false positives in dynamic or plugin code. Triage: prefer "
974
+ "REAL SMELL over REAL BUG; if removing breaks tests, mark DEFERRED."
975
+ ),
976
+ "DEPS": (
977
+ "DEPS findings are dependency hygiene (declared but unused, or used "
978
+ "but undeclared). MEDIUM. Triage: add the missing dep to pyproject or "
979
+ "remove the unused one. 'dev-only' findings mean the import happens "
980
+ "in test code; declare under [project.optional-dependencies.test]."
981
+ ),
982
+ "CVE": (
983
+ "CVE findings are known vulnerabilities in a dependency. CRITICAL. "
984
+ "Triage: upgrade to the fix version listed in the finding. If no fix "
985
+ "exists, mark DEFERRED and add a runtime mitigation (e.g. input "
986
+ "validation)."
987
+ ),
988
+ "SECRETS": (
989
+ "SECRETS findings are leaked credentials. CRITICAL. Triage: rotate "
990
+ "the secret immediately, remove from git history (git filter-repo), "
991
+ "and add a gitleaks:allow directive only after the rotation is "
992
+ "complete."
993
+ ),
994
+ }