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/runner.py ADDED
@@ -0,0 +1,279 @@
1
+ """Runner — orchestrates the execution of every applicable tool.
2
+
3
+ Given a repo, a config, and a registry, the runner:
4
+
5
+ 1. Detects languages in the repo.
6
+ 2. Filters tools by language + applicability + config (enable/disable).
7
+ 3. Runs each tool in a subprocess with a per-tool timeout.
8
+ 4. Collects the parsed ``Finding`` objects.
9
+ 5. Optionally deduplicates across tools.
10
+ 6. Returns the final list.
11
+
12
+ The runner is the only module that touches subprocess. Tool adapters
13
+ are pure: they take a Path, return list[Finding].
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import concurrent.futures
18
+ import json
19
+ import subprocess
20
+ import time
21
+ from collections.abc import Iterable
22
+ from dataclasses import dataclass, field
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+
26
+ from .config import Config
27
+ from .detect import detect
28
+ from .finding import Category, Finding, Severity
29
+ from .registry import ToolRegistry, default_registry
30
+ from .tools.base import Tool
31
+
32
+
33
+ @dataclass
34
+ class ToolResult:
35
+ """Outcome of running one tool. Used for reporting in the markdown
36
+ summary, so the LLM (or user) can see which tools failed vs. which
37
+ tools reported zero findings."""
38
+
39
+ tool: str
40
+ status: str # "ok" | "no-findings" | "skipped" | "error" | "timeout"
41
+ findings: list[Finding] = field(default_factory=list)
42
+ duration_sec: float = 0.0
43
+ error: str | None = None
44
+
45
+
46
+ class Runner:
47
+ """Run a set of tools against a repo and collect findings."""
48
+
49
+ def __init__(
50
+ self,
51
+ repo: Path,
52
+ config: Config,
53
+ registry: ToolRegistry | None = None,
54
+ ) -> None:
55
+ self.repo = Path(repo).resolve()
56
+ self.config = config
57
+ self.registry = registry or default_registry
58
+
59
+ def run(
60
+ self,
61
+ parallel: bool = False,
62
+ tools: Iterable[str] | None = None,
63
+ ) -> tuple[list[Finding], list[ToolResult]]:
64
+ """Run all applicable tools and return ``(findings, results)``.
65
+
66
+ If ``tools`` is given, restrict to those tool names (after the
67
+ enable/disable filter). Otherwise all applicable tools run.
68
+
69
+ If ``parallel`` is True, tools are run in a thread pool (one per
70
+ tool). Tool subprocesses are independent; running in parallel is
71
+ safe and roughly halves total wall time on a 4+ core machine.
72
+ """
73
+ applicable = self._applicable_tools()
74
+ if tools is not None:
75
+ wanted = set(tools)
76
+ applicable = [c for c in applicable if c.name in wanted]
77
+
78
+ results: list[ToolResult] = []
79
+ if parallel:
80
+ with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
81
+ futures = {pool.submit(self._run_one, c): c for c in applicable}
82
+ for fut in concurrent.futures.as_completed(futures):
83
+ results.append(fut.result())
84
+ else:
85
+ for cls in applicable:
86
+ results.append(self._run_one(cls))
87
+
88
+ # Stable order for the report: by tool name.
89
+ results.sort(key=lambda r: r.tool)
90
+ findings = [f for r in results for f in r.findings]
91
+ return findings, results
92
+
93
+ def _applicable_tools(self) -> list[type[Tool]]:
94
+ """Filter registry → language-applicable → user enable/disable → installed."""
95
+ langs = detect(self.repo)
96
+ lang_slugs = {lang.slug for lang in langs}
97
+
98
+ # Build candidate set: anything universal, or that applies to a
99
+ # detected language. A tool that declares a specific language
100
+ # is NOT eligible when no language is detected (e.g. a fresh
101
+ # empty repo where no analyzer is relevant).
102
+ candidates: list[type[Tool]] = []
103
+ for cls in self.registry.all():
104
+ if cls.universal or (lang_slugs and any(slug in lang_slugs for slug in cls.languages)):
105
+ candidates.append(cls)
106
+
107
+ # Apply enable/disable filters.
108
+ candidates = self._apply_filters(candidates)
109
+
110
+ # Filter to installed + applicable.
111
+ out: list[type] = []
112
+ for cls in candidates:
113
+ inst = cls()
114
+ if not inst.is_installed():
115
+ continue
116
+ if not inst.is_applicable(self.repo):
117
+ continue
118
+ out.append(cls)
119
+ return out
120
+
121
+ def _apply_filters(self, candidates: list[type[Tool]]) -> list[type[Tool]]:
122
+ """Apply enable/disable config filters to candidate tools."""
123
+ if self.config.enable:
124
+ wanted = set(self.config.enable)
125
+ candidates = [c for c in candidates if c.name in wanted]
126
+ if self.config.disable:
127
+ excluded = set(self.config.disable)
128
+ candidates = [c for c in candidates if c.name not in excluded]
129
+ return candidates
130
+
131
+ def _run_one(self, tool_cls: type[Tool]) -> ToolResult:
132
+ name = tool_cls.name
133
+ inst = tool_cls()
134
+ start = time.monotonic()
135
+ try:
136
+ findings = inst.run(self.repo)
137
+ duration = time.monotonic() - start
138
+ status = "ok" if findings else "no-findings"
139
+ return ToolResult(tool=name, status=status, findings=findings,
140
+ duration_sec=duration)
141
+ except subprocess.TimeoutExpired:
142
+ duration = time.monotonic() - start
143
+ return ToolResult(tool=name, status="timeout", duration_sec=duration,
144
+ error=f"exceeded {self.config.timeout}s")
145
+ except Exception as e: # noqa: BLE001 — we want to capture *any* tool failure
146
+ duration = time.monotonic() - start
147
+ return ToolResult(tool=name, status="error", duration_sec=duration,
148
+ error=f"{type(e).__name__}: {e}")
149
+
150
+
151
+ def dedupe(findings: list[Finding]) -> list[Finding]:
152
+ """Drop findings with the same fingerprint.
153
+
154
+ In practice this rarely fires (different tools use different file
155
+ paths / line numbers), but the hook is here for tools that wrap the
156
+ same underlying analyzer under different names (e.g. an MCP server
157
+ that proxies another tool).
158
+ """
159
+ seen: set[str] = set()
160
+ out: list[Finding] = []
161
+ for f in findings:
162
+ if f.fingerprint() in seen:
163
+ continue
164
+ seen.add(f.fingerprint())
165
+ out.append(f)
166
+ return out
167
+
168
+
169
+ def apply_suppressions(
170
+ findings: list[Finding], patterns: list[str]
171
+ ) -> list[Finding]:
172
+ """Drop findings matching a durable suppress entry.
173
+
174
+ Entries are ``rule`` (suppress everywhere) or ``rule@file``
175
+ (suppress in one file, repo-relative). This is how triage verdicts
176
+ persist: an LLM (or user) marks a finding FALSE POSITIVE once and
177
+ the entry keeps it out of every later run.
178
+ """
179
+ if not patterns:
180
+ return findings
181
+ rule_only: set[str] = set()
182
+ rule_file: set[tuple[str, str]] = set()
183
+ for pattern in patterns:
184
+ entry = pattern.strip()
185
+ if not entry:
186
+ continue
187
+ if "@" in entry:
188
+ rule, file = entry.split("@", 1)
189
+ rule_file.add((rule.strip(), file.strip()))
190
+ else:
191
+ rule_only.add(entry)
192
+ out: list[Finding] = []
193
+ for f in findings:
194
+ if f.rule in rule_only:
195
+ continue
196
+ if f.file and (f.rule, f.file) in rule_file:
197
+ continue
198
+ out.append(f)
199
+ return out
200
+
201
+
202
+ def filter_by_baseline(
203
+ findings: list[Finding], baseline: set[str] | None
204
+ ) -> list[Finding]:
205
+ """Keep only findings whose fingerprint is not in the baseline.
206
+
207
+ ``None`` (no baseline in play) is an identity function. Diff mode:
208
+ a scan reports what is *new* since the baseline was taken.
209
+ """
210
+ if baseline is None:
211
+ return findings
212
+ return [f for f in findings if f.fingerprint() not in baseline]
213
+
214
+
215
+ # --- baseline ---------------------------------------------------------------
216
+
217
+ BASELINE_FILENAME = "polycheck-baseline.json"
218
+
219
+
220
+ def save_baseline(report_dir: Path, findings: list[Finding]) -> Path:
221
+ """Write the fingerprint baseline for diff mode to ``report_dir``.
222
+
223
+ The baseline holds only fingerprints — no messages or paths — so it
224
+ stays small and stable across message wording changes.
225
+ """
226
+ report_dir.mkdir(parents=True, exist_ok=True)
227
+ path = report_dir / BASELINE_FILENAME
228
+ payload = {
229
+ "schema_version": 1,
230
+ "created_at": datetime.now(timezone.utc).isoformat(),
231
+ "fingerprints": sorted({f.fingerprint() for f in findings}),
232
+ }
233
+ path.write_text(
234
+ json.dumps(payload, indent=2) + "\n", encoding="utf-8"
235
+ )
236
+ return path
237
+
238
+
239
+ def load_baseline(report_dir: Path) -> set[str] | None:
240
+ """Load the baseline fingerprint set, or ``None`` when absent.
241
+
242
+ A malformed baseline is treated as absent (diff mode then reports
243
+ everything) — it must never crash a scan or silently hide findings.
244
+ """
245
+ path = report_dir / BASELINE_FILENAME
246
+ if not path.exists():
247
+ return None
248
+ try:
249
+ data = json.loads(path.read_text(encoding="utf-8"))
250
+ fps = data.get("fingerprints", [])
251
+ if not isinstance(fps, list):
252
+ return None
253
+ return {str(x) for x in fps}
254
+ except (json.JSONDecodeError, OSError, AttributeError):
255
+ return None
256
+
257
+
258
+ def filter_by_severity(
259
+ findings: list[Finding], threshold: str
260
+ ) -> list[Finding]:
261
+ """Drop findings below the given severity.
262
+
263
+ ``threshold`` is one of: INFO, LOW, MEDIUM, HIGH, CRITICAL.
264
+ """
265
+ threshold = threshold.upper()
266
+ if threshold not in Severity.__members__:
267
+ return findings
268
+ cutoff = Severity[threshold]
269
+ return [f for f in findings if f.severity >= cutoff]
270
+
271
+
272
+ def group_by_category(
273
+ findings: list[Finding],
274
+ ) -> dict[Category, list[Finding]]:
275
+ """Bucket findings by category. Useful for the markdown report."""
276
+ out: dict[Category, list[Finding]] = {c: [] for c in Category}
277
+ for f in findings:
278
+ out.setdefault(f.category, []).append(f)
279
+ return out
polycheck/session.py ADDED
@@ -0,0 +1,134 @@
1
+ """Session logging for guided polycheck workflows."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+
10
+ def new_run_id() -> str:
11
+ """Return a stable, sortable run id for a workflow invocation."""
12
+ return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
13
+
14
+
15
+ def run_dir(repo: Path, run_id: str) -> Path:
16
+ """Return the per-run log directory."""
17
+ return repo / ".polycheck" / "runs" / run_id
18
+
19
+
20
+ def append_event(repo: Path, run_id: str, event: dict[str, Any]) -> Path:
21
+ """Append one structured progress event to the run log."""
22
+ directory = run_dir(repo, run_id)
23
+ directory.mkdir(parents=True, exist_ok=True)
24
+ path = directory / "run.jsonl"
25
+ payload = {"timestamp": datetime.now(timezone.utc).isoformat(), **event}
26
+ with path.open("a", encoding="utf-8") as f:
27
+ f.write(json.dumps(payload, default=str) + "\n")
28
+ return path
29
+
30
+
31
+ def write_run_summary(repo: Path, run_id: str, summary: dict[str, Any]) -> Path:
32
+ """Write a human-readable summary for one guided run."""
33
+ directory = run_dir(repo, run_id)
34
+ directory.mkdir(parents=True, exist_ok=True)
35
+ path = directory / "summary.md"
36
+ path.write_text(_render_summary(summary), encoding="utf-8")
37
+ return path
38
+
39
+
40
+ def write_session_summary(repo: Path, payload: dict[str, Any]) -> dict[str, str]:
41
+ """Write the latest workflow summary under ``.polycheck/``."""
42
+ base = repo / ".polycheck"
43
+ sessions = base / "sessions"
44
+ sessions.mkdir(parents=True, exist_ok=True)
45
+
46
+ run_id = new_run_id()
47
+ md_path = sessions / f"{run_id}.md"
48
+ json_path = sessions / f"{run_id}.json"
49
+
50
+ md_path.write_text(_render_summary(payload), encoding="utf-8")
51
+ json_path.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8")
52
+
53
+ latest_md = base / "latest.md"
54
+ latest_json = base / "latest.json"
55
+ latest_md.write_text(_render_summary(payload), encoding="utf-8")
56
+ latest_json.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8")
57
+
58
+ return {
59
+ "markdown": str(md_path),
60
+ "json": str(json_path),
61
+ "latest_markdown": str(latest_md),
62
+ "latest_json": str(latest_json),
63
+ }
64
+
65
+
66
+ def _render_summary(payload: dict[str, Any]) -> str:
67
+ lines = [
68
+ "# polycheck session",
69
+ "",
70
+ f"**Repo:** `{payload.get('repo', '')}`",
71
+ f"**Status:** {payload.get('status', '')}",
72
+ "",
73
+ "## Next action",
74
+ "",
75
+ payload.get("next_action", "none"),
76
+ "",
77
+ "## Findings",
78
+ "",
79
+ f"Total: {payload.get('total_findings', 0)}",
80
+ "",
81
+ ]
82
+
83
+ by_severity = payload.get("by_severity", {})
84
+ if by_severity:
85
+ lines.extend(["| Severity | Count |", "|----------|-------|"])
86
+ for severity, count in by_severity.items():
87
+ lines.append(f"| {severity} | {count} |")
88
+ lines.append("")
89
+
90
+ lines.extend(["## Tools run", ""])
91
+ tools_run = payload.get("tools_run", [])
92
+ if tools_run:
93
+ lines.extend([
94
+ "| Tool | Status | Findings |",
95
+ "|------|--------|----------|",
96
+ ])
97
+ for tool in tools_run:
98
+ lines.append(
99
+ f"| {tool.get('name', '')} | {tool.get('status', '')} | "
100
+ f"{tool.get('finding_count', 0)} |"
101
+ )
102
+ else:
103
+ lines.append("No tools ran.")
104
+ lines.append("")
105
+
106
+ missing_tools = payload.get("missing_tools", [])
107
+ if missing_tools:
108
+ lines.extend(["## Missing tools", ""])
109
+ for tool in missing_tools:
110
+ lines.append(f"- {tool.get('name', '')}: {tool.get('install_hint', '')}")
111
+ lines.append("")
112
+
113
+ missing_system = payload.get("missing_system_dependencies", [])
114
+ if missing_system:
115
+ lines.extend(["## Missing system dependencies", ""])
116
+ for dep in missing_system:
117
+ lines.append(f"- {dep.get('name', '')}: {dep.get('install_hint', '')}")
118
+ lines.append("")
119
+
120
+ reports = payload.get("reports", [])
121
+ if reports:
122
+ lines.extend(["## Reports", ""])
123
+ for report in reports:
124
+ lines.append(f"- `{report}`")
125
+ lines.append("")
126
+
127
+ session = payload.get("session", {})
128
+ if session:
129
+ lines.extend(["## Session files", ""])
130
+ for key, value in session.items():
131
+ lines.append(f"- {key}: `{value}`")
132
+ lines.append("")
133
+
134
+ return "\n".join(lines).rstrip() + "\n"
@@ -0,0 +1,10 @@
1
+ """Tool adapters.
2
+
3
+ The package directory for tool implementations. Each module exports
4
+ a class named ``*Tool`` that subclasses :class:`polycheck.tools.base.Tool`.
5
+
6
+ Concrete tools are auto-discovered by ``ToolRegistry.discover()`` via
7
+ ``pkgutil.iter_modules``.
8
+ """
9
+
10
+ # tool modules
@@ -0,0 +1,66 @@
1
+ """actionlint — GitHub Actions workflow linter.
2
+
3
+ actionlint is a single-binary tool. Default output is a one-line
4
+ diagnostic per finding. It exits 1 when findings exist.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ from pathlib import Path
12
+
13
+ from ..finding import Category, Finding, Severity
14
+ from .base import Tool
15
+
16
+ # actionlint output:
17
+ # .github/workflows/ci.yml:10:5: unexpected key "runs" in workflow ... [syntax_check]
18
+ _ACTIONLINT_LINE = re.compile(
19
+ r"^(?P<file>[^:]+):(?P<line>\d+):(?P<col>\d+):\s*"
20
+ r"(?P<message>.*?)(?:\s*\[(?P<code>[^\]]+)\])?\s*$"
21
+ )
22
+
23
+
24
+ class ActionlintTool(Tool):
25
+ name = "actionlint"
26
+ category = Category.LINT
27
+ languages = [] # applies to GH Actions
28
+ universal = False
29
+ installer = "github-release:rhysd/actionlint"
30
+
31
+ def is_applicable(self, repo: Path) -> bool:
32
+ wf = repo / ".github" / "workflows"
33
+ return wf.exists() and any(wf.glob("*.yml")) or any(wf.glob("*.yaml"))
34
+
35
+ def run(self, repo: Path) -> list[Finding]:
36
+ if shutil.which("actionlint") is None:
37
+ return []
38
+ out = subprocess.run(
39
+ ["actionlint", "-no-color"],
40
+ cwd=repo, capture_output=True, text=True, timeout=120
41
+ )
42
+ text = out.stdout + "\n" + out.stderr
43
+ return self._parse(text)
44
+
45
+ @staticmethod
46
+ def _parse(text: str) -> list[Finding]:
47
+ findings: list[Finding] = []
48
+ for raw in text.splitlines():
49
+ m = _ACTIONLINT_LINE.match(raw.strip())
50
+ if not m:
51
+ continue
52
+ findings.append(
53
+ Finding(
54
+ tool="actionlint",
55
+ rule=m.group("code") or "syntax_check",
56
+ severity=Severity.MEDIUM,
57
+ category=Category.LINT,
58
+ message=m.group("message").strip(),
59
+ file=m.group("file"),
60
+ line=int(m.group("line")),
61
+ column=int(m.group("col")),
62
+ fixable=False,
63
+ raw={"line": raw},
64
+ )
65
+ )
66
+ return findings