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/py.typed ADDED
File without changes
polycheck/registry.py ADDED
@@ -0,0 +1,119 @@
1
+ """Tool registry — the single source of truth for available tools.
2
+
3
+ The registry collects all bundled tool classes (auto-discovered from the
4
+ ``polycheck.tools`` subpackage) and lets the runner look them up by
5
+ language or applicability.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import importlib
10
+ import pkgutil
11
+ from collections.abc import Iterator
12
+ from pathlib import Path
13
+
14
+ from .tools.base import Tool
15
+
16
+
17
+ class ToolRegistry:
18
+ """Container for ``Tool`` subclasses.
19
+
20
+ Tools are registered either:
21
+ * automatically, by being subclasses of ``Tool`` in the
22
+ ``polycheck.tools`` subpackage (see ``discover()``)
23
+ * programmatically, via ``register()`` (used by tests and by
24
+ downstream packages that want to add their own tools)
25
+ """
26
+
27
+ def __init__(self) -> None:
28
+ self._tools: dict[str, type[Tool]] = {}
29
+
30
+ def register(self, tool_class: type[Tool]) -> type[Tool]:
31
+ """Register a tool class. Idempotent; same class can be registered
32
+ multiple times. Returns the class for decorator use."""
33
+ if not tool_class.name:
34
+ raise ValueError(f"{tool_class.__name__}.name must be set")
35
+ self._tools[tool_class.name] = tool_class
36
+ return tool_class
37
+
38
+ def all(self) -> list[type[Tool]]:
39
+ return list(self._tools.values())
40
+
41
+ def get(self, name: str) -> type[Tool] | None:
42
+ return self._tools.get(name)
43
+
44
+ def for_language(self, language: str) -> list[type[Tool]]:
45
+ """Tools that advertise support for the given language slug, or
46
+ are universal (i.e. apply to every repo)."""
47
+ out: list[type[Tool]] = []
48
+ for c in self._tools.values():
49
+ if c.universal or language in c.languages:
50
+ out.append(c)
51
+ return out
52
+
53
+ def applicable(self, repo: Path) -> list[type[Tool]]:
54
+ """All tools that are both installed and applicable to this repo.
55
+
56
+ Note: this instantiates each tool and runs ``is_applicable``.
57
+ Instances are not cached — cheap, no I/O.
58
+ """
59
+ out: list[type[Tool]] = []
60
+ for cls in self._tools.values():
61
+ instance = cls()
62
+ if not instance.is_installed():
63
+ continue
64
+ if not instance.is_applicable(repo):
65
+ continue
66
+ out.append(cls)
67
+ return out
68
+
69
+ def discover(self) -> int:
70
+ """Auto-import every module in ``polycheck.tools`` and register
71
+ any ``Tool`` subclasses found. Returns the number of tools
72
+ registered (including ones that were already there)."""
73
+
74
+ from . import tools as tools_pkg # local import to avoid cycle
75
+
76
+ self._import_tool_modules(tools_pkg)
77
+ self._register_tool_classes(tools_pkg)
78
+ return len(self._tools)
79
+
80
+ def _import_tool_modules(self, tools_pkg) -> None:
81
+ """Import all tool modules from the tools package."""
82
+ import sys
83
+
84
+ for _finder, name, _is_pkg in pkgutil.iter_modules(tools_pkg.__path__):
85
+ if name == "base" or not name.isidentifier():
86
+ continue
87
+ try:
88
+ importlib.import_module(f"{tools_pkg.__name__}.{name}") # nosemgrep
89
+ except ImportError as e:
90
+ # A tool may fail to import if its 3rd-party SDK is
91
+ # missing (e.g. knip). Don't fail the whole discovery.
92
+ print(f"polycheck: skipping tool {name}: {e}", file=sys.stderr)
93
+
94
+ def _register_tool_classes(self, tools_pkg) -> None:
95
+ """Register all Tool subclasses from imported modules."""
96
+ import inspect
97
+ import sys
98
+
99
+ for module_name, module in list(sys.modules.items()):
100
+ if not module_name.startswith(tools_pkg.__name__ + "."):
101
+ continue
102
+ if module_name == tools_pkg.__name__ + ".base":
103
+ continue
104
+ for _name, obj in inspect.getmembers(module, inspect.isclass):
105
+ if obj is Tool or obj.__module__ != module_name:
106
+ continue
107
+ if issubclass(obj, Tool):
108
+ self.register(obj)
109
+
110
+ def __iter__(self) -> Iterator[type[Tool]]:
111
+ return iter(self._tools.values())
112
+
113
+ def __len__(self) -> int:
114
+ return len(self._tools)
115
+
116
+
117
+ # Module-level singleton. Tests can replace it via monkeypatching the
118
+ # ``default_registry`` attribute if they want a clean slate.
119
+ default_registry = ToolRegistry()
@@ -0,0 +1,33 @@
1
+ """Reporter registry.
2
+
3
+ Maps a format name to a renderer. The CLI uses this to dispatch.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+
10
+ from ..finding import Finding
11
+ from ..runner import ToolResult
12
+ from . import json_reporter, markdown_reporter, sarif_reporter
13
+
14
+ REPORTERS = {
15
+ "json": json_reporter.render,
16
+ "markdown": markdown_reporter.render,
17
+ "sarif": sarif_reporter.render,
18
+ }
19
+
20
+
21
+ def render(
22
+ fmt: str,
23
+ repo: Path,
24
+ findings: list[Finding],
25
+ results: list[ToolResult],
26
+ *,
27
+ report_dir: Path,
28
+ ) -> list[Path]:
29
+ """Dispatch to the right renderer. Unknown format → empty list."""
30
+ fn = REPORTERS.get(fmt)
31
+ if fn is None:
32
+ return []
33
+ return fn(repo, findings, results, report_dir=report_dir)
@@ -0,0 +1,58 @@
1
+ """JSON reporter — emits a single JSON file with the run summary and
2
+ all findings. This is the canonical machine-readable output and the
3
+ format the LLM-triage prompt is designed to consume."""
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ from collections import Counter
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+ from ..runner import ToolResult
12
+
13
+
14
+ def render(
15
+ repo: Path,
16
+ findings: list,
17
+ results: list[ToolResult],
18
+ *,
19
+ report_dir: Path,
20
+ ) -> list[Path]:
21
+ """Write ``polycheck-report.json`` to ``report_dir``.
22
+
23
+ Returns the list of files written.
24
+ """
25
+ report_dir.mkdir(parents=True, exist_ok=True)
26
+ out = report_dir / "polycheck-report.json"
27
+
28
+ by_sev = Counter(f.severity.name for f in findings)
29
+ by_cat = Counter(f.category.value for f in findings)
30
+ by_tool = Counter(f.tool for f in findings)
31
+
32
+ payload = {
33
+ "schema_version": 1,
34
+ "generated_at": datetime.now(timezone.utc).isoformat(),
35
+ "repo": str(repo),
36
+ "summary": {
37
+ "total_findings": len(findings),
38
+ "by_severity": dict(by_sev),
39
+ "by_category": dict(by_cat),
40
+ "by_tool": dict(by_tool),
41
+ "tools_run": len(results),
42
+ "tools_failed": [r.tool for r in results if r.status in ("error", "timeout")],
43
+ },
44
+ "tools": [
45
+ {
46
+ "name": r.tool,
47
+ "status": r.status,
48
+ "duration_sec": round(r.duration_sec, 2),
49
+ "finding_count": len(r.findings),
50
+ "error": r.error,
51
+ }
52
+ for r in results
53
+ ],
54
+ "findings": [f.to_dict() for f in findings],
55
+ }
56
+
57
+ out.write_text(json.dumps(payload, indent=2, default=str), encoding="utf-8")
58
+ return [out]
@@ -0,0 +1,141 @@
1
+ """Markdown reporter — human-readable summary + per-category tables.
2
+
3
+ This is the format the LLM-triage prompt is designed to read. The
4
+ ``findings:markdown`` MCP resource will return the same content, so
5
+ agents can ``read_file()`` the report rather than re-walk the JSON.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from collections import Counter
10
+ from pathlib import Path
11
+
12
+ from ..finding import Category, Severity
13
+ from ..runner import ToolResult
14
+
15
+ # Severity → emoji + label, used in the summary table.
16
+ _SEV_BADGE = {
17
+ Severity.CRITICAL: "CRIT",
18
+ Severity.HIGH: "HIGH",
19
+ Severity.MEDIUM: "MED ",
20
+ Severity.LOW: "LOW ",
21
+ Severity.INFO: "INFO",
22
+ }
23
+
24
+
25
+ def render(
26
+ repo: Path,
27
+ findings: list,
28
+ results: list[ToolResult],
29
+ *,
30
+ report_dir: Path,
31
+ ) -> list[Path]:
32
+ report_dir.mkdir(parents=True, exist_ok=True)
33
+ out = report_dir / "polycheck-report.md"
34
+
35
+ lines: list[str] = []
36
+ lines.extend(_header(repo, findings, results))
37
+ lines.extend(_severity_section(findings))
38
+ lines.extend(_category_section(findings))
39
+ lines.extend(_tool_execution_section(results))
40
+ lines.extend(_findings_sections(findings))
41
+
42
+ out.write_text("\n".join(lines), encoding="utf-8")
43
+ return [out]
44
+
45
+
46
+ def _header(repo: Path, findings: list, results: list) -> list[str]:
47
+ """Generate the report header."""
48
+ return [
49
+ f"# polycheck report — `{repo.name}`",
50
+ "",
51
+ f"**Total findings:** {len(findings)} | "
52
+ f"**Tools run:** {len(results)} | "
53
+ f"**Tools failed:** "
54
+ f"{sum(1 for r in results if r.status in ('error', 'timeout'))}",
55
+ "",
56
+ ]
57
+
58
+
59
+ def _severity_section(findings: list) -> list[str]:
60
+ """Generate the severity breakdown table."""
61
+ by_sev = Counter(f.severity for f in findings)
62
+ lines = ["## By severity", "", "| Severity | Count |", "|----------|-------|"]
63
+ for sev in (Severity.CRITICAL, Severity.HIGH, Severity.MEDIUM, Severity.LOW, Severity.INFO):
64
+ n = by_sev.get(sev, 0)
65
+ if n:
66
+ lines.append(f"| {_SEV_BADGE[sev]} | {n} |")
67
+ lines.append("")
68
+ return lines
69
+
70
+
71
+ def _category_section(findings: list) -> list[str]:
72
+ """Generate the category breakdown table."""
73
+ by_cat = Counter(f.category for f in findings)
74
+ lines = ["## By category", "", "| Category | Count |", "|----------|-------|"]
75
+ for cat, n in sorted(by_cat.items(), key=lambda kv: -kv[1]):
76
+ if n:
77
+ lines.append(f"| {cat.value} | {n} |")
78
+ lines.append("")
79
+ return lines
80
+
81
+
82
+ def _tool_execution_section(results: list) -> list[str]:
83
+ """Generate the tool execution table."""
84
+ lines = [
85
+ "## Tool execution",
86
+ "",
87
+ "| Tool | Status | Duration (s) | Findings |",
88
+ "|------|--------|--------------|----------|",
89
+ ]
90
+ for r in results:
91
+ lines.append(
92
+ f"| `{r.tool}` | {r.status} | {r.duration_sec:.1f} | {len(r.findings)} |"
93
+ )
94
+ if any(r.error for r in results):
95
+ lines.extend(["", "### Tool errors", ""])
96
+ for r in results:
97
+ if r.error:
98
+ lines.append(f"- **{r.tool}**: `{r.error}`")
99
+ lines.append("")
100
+ return lines
101
+
102
+
103
+ def _findings_sections(findings: list) -> list[str]:
104
+ """Generate per-category findings sections."""
105
+ per_cat_cap = 50
106
+ grouped: dict[Category, list] = {c: [] for c in Category}
107
+ for f in findings:
108
+ grouped[f.category].append(f)
109
+
110
+ lines: list[str] = []
111
+ for cat in Category:
112
+ items = sorted(grouped[cat], key=lambda f: (-f.severity.value, f.tool, f.file or ""))
113
+ if not items:
114
+ continue
115
+ lines.extend(_category_findings_table(cat, items, per_cat_cap))
116
+ return lines
117
+
118
+
119
+ def _category_findings_table(cat: Category, items: list, cap: int) -> list[str]:
120
+ """Generate a findings table for a single category."""
121
+ lines = [
122
+ f"## {cat.value} ({len(items)})",
123
+ "",
124
+ "| Severity | Tool | Rule | Location | Message |",
125
+ "|----------|------|------|----------|---------|",
126
+ ]
127
+ for f in items[:cap]:
128
+ sev = _SEV_BADGE.get(f.severity, "?")
129
+ loc = f.file or "?"
130
+ if f.line:
131
+ loc += f":{f.line}"
132
+ msg = f.message.replace("|", "\\|")[:120]
133
+ lines.append(f"| {sev} | `{f.tool}` | `{f.rule}` | `{loc}` | {msg} |")
134
+ if len(items) > cap:
135
+ lines.extend([
136
+ "",
137
+ f"_…and {len(items) - cap} more. See "
138
+ f"`polycheck-report.json` for the full list._",
139
+ ])
140
+ lines.append("")
141
+ return lines
@@ -0,0 +1,114 @@
1
+ """SARIF reporter — emits SARIF 2.1.0 JSON for IDE integration.
2
+
3
+ SARIF is the OASIS standard that GitHub Code Scanning, VS Code, and
4
+ most CI dashboards consume. This is *optional* output — most users
5
+ will only want the markdown + JSON pair.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+
12
+ from ..finding import Severity
13
+ from ..runner import ToolResult
14
+
15
+ # SARIF severity mapping
16
+ _SARIF_LEVEL = {
17
+ Severity.CRITICAL: "error",
18
+ Severity.HIGH: "error",
19
+ Severity.MEDIUM: "warning",
20
+ Severity.LOW: "note",
21
+ Severity.INFO: "note",
22
+ }
23
+
24
+
25
+ def render(
26
+ repo: Path,
27
+ findings: list,
28
+ results: list[ToolResult],
29
+ *,
30
+ report_dir: Path,
31
+ ) -> list[Path]:
32
+ report_dir.mkdir(parents=True, exist_ok=True)
33
+ out = report_dir / "polycheck-report.sarif"
34
+
35
+ rules, results_sarif = _build_sarif_results(repo, findings, results)
36
+ sarif = _build_sarif_document(rules, results_sarif)
37
+
38
+ out.write_text(json.dumps(sarif, indent=2), encoding="utf-8")
39
+ return [out]
40
+
41
+
42
+ def _build_sarif_results(repo: Path, findings: list, results: list[ToolResult]) -> tuple[dict, list]:
43
+ """Build SARIF rules and results from findings."""
44
+ rules: dict[str, dict] = {}
45
+ results_sarif: list[dict] = []
46
+
47
+ for f in findings:
48
+ rule_id = f"{f.tool}/{f.rule}"
49
+ if rule_id not in rules:
50
+ rules[rule_id] = _make_rule(rule_id, f)
51
+ results_sarif.append(_make_result(repo, f, rule_id))
52
+
53
+ return rules, results_sarif
54
+
55
+
56
+ def _make_rule(rule_id: str, f) -> dict:
57
+ """Create a SARIF rule definition."""
58
+ return {
59
+ "id": rule_id,
60
+ "name": f.rule,
61
+ "shortDescription": {"text": f"{f.tool}: {f.rule}"},
62
+ "defaultConfiguration": {"level": _SARIF_LEVEL.get(f.severity, "warning")},
63
+ }
64
+
65
+
66
+ def _make_result(repo: Path, f, rule_id: str) -> dict:
67
+ """Create a SARIF result for a finding."""
68
+ result: dict = {
69
+ "ruleId": rule_id,
70
+ "level": _SARIF_LEVEL.get(f.severity, "warning"),
71
+ "message": {"text": f.message},
72
+ }
73
+ if f.file:
74
+ result["locations"] = [_make_location(repo, f)]
75
+ if f.doc_url:
76
+ result["properties"] = {"helpUri": f.doc_url}
77
+ return result
78
+
79
+
80
+ def _make_location(repo: Path, f) -> dict:
81
+ """Create a SARIF location for a finding."""
82
+ uri = f.file if f.file.startswith("/") else f"{repo.name}/{f.file}"
83
+ region: dict = {}
84
+ if f.line:
85
+ region["startLine"] = f.line
86
+ if f.column:
87
+ region["startColumn"] = f.column
88
+ return {
89
+ "physicalLocation": {
90
+ "artifactLocation": {"uri": uri},
91
+ "region": region,
92
+ }
93
+ }
94
+
95
+
96
+ def _build_sarif_document(rules: dict, results_sarif: list) -> dict:
97
+ """Build the complete SARIF document."""
98
+ return {
99
+ "$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json",
100
+ "version": "2.1.0",
101
+ "runs": [
102
+ {
103
+ "tool": {
104
+ "driver": {
105
+ "name": "polycheck",
106
+ "informationUri": "https://github.com/KiloApp2/polycheck",
107
+ "version": "0.1.0",
108
+ "rules": list(rules.values()),
109
+ }
110
+ },
111
+ "results": results_sarif,
112
+ }
113
+ ],
114
+ }