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/verify.py ADDED
@@ -0,0 +1,288 @@
1
+ """Supported-tool verification helpers."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import subprocess
6
+ import tempfile
7
+ import time
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from .registry import ToolRegistry, default_registry
12
+ from .tools.base import Tool
13
+
14
+ HEAVY_TOOLS = {"sonarless", "semgrep", "pip-audit", "npm-audit"}
15
+
16
+ # Minimum findings each tool must report on its seeded synthetic repo
17
+ # (_seed_repo plants defects for each of these). A tool that runs clean
18
+ # here is silently broken — the exact false-confidence failure mode
19
+ # polycheck exists to prevent — so the verifier reports it as
20
+ # "missed-defects" instead of "no-findings". Tools without an entry keep
21
+ # the permissive behavior until their seed is verified.
22
+ _EXPECTED_FINDINGS: dict[str, int] = {
23
+ "ruff": 1, # unused import in app.py
24
+ "mypy": 1, # incompatible annotation in app.py
25
+ "vulture": 1, # unused_helper
26
+ "deptry": 1, # requests declared but never imported
27
+ "eslint": 1, # unused variable in app.js
28
+ "tsc": 1, # bad.ts type error
29
+ "gitleaks": 1, # AWS key in secret.txt
30
+ "shellcheck": 1, # unquoted $HOME in script.sh
31
+ "hadolint": 1, # untagged FROM ubuntu
32
+ "actionlint": 1, # unknown "runz:" key in ci.yml
33
+ "depcheck": 1, # unused left-pad dependency
34
+ }
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ToolVerification:
39
+ """Result of verifying one supported analyzer."""
40
+
41
+ tool: str
42
+ status: str
43
+ installed: bool
44
+ applicable: bool
45
+ findings: int = 0
46
+ duration_sec: float = 0.0
47
+ message: str = ""
48
+
49
+
50
+ def verify_tools(
51
+ registry: ToolRegistry | None = None,
52
+ *,
53
+ install: bool = False,
54
+ include_heavy: bool = False,
55
+ tools: list[str] | None = None,
56
+ work_dir: Path | None = None,
57
+ ) -> list[ToolVerification]:
58
+ """Run every supported tool against a synthetic repo.
59
+
60
+ Missing tools are reported as skipped, not errors. Heavy tools that use
61
+ Docker or network access are skipped unless ``include_heavy`` is true.
62
+ """
63
+ reg = registry or default_registry
64
+ base = work_dir or Path(tempfile.mkdtemp(prefix="polycheck-verify-"))
65
+ selected = [name for name in (tools or [])]
66
+ results: list[ToolVerification] = []
67
+
68
+ for cls in reg.all():
69
+ if selected and cls.name not in selected:
70
+ continue
71
+ repo = base / cls.name
72
+ repo.mkdir(parents=True, exist_ok=True)
73
+ _seed_repo(cls.name, repo)
74
+ results.append(
75
+ verify_one(
76
+ cls,
77
+ repo,
78
+ install=install,
79
+ include_heavy=include_heavy,
80
+ )
81
+ )
82
+ return results
83
+
84
+
85
+ def verify_one(
86
+ tool_cls: type[Tool],
87
+ repo: Path,
88
+ *,
89
+ install: bool = False,
90
+ include_heavy: bool = False,
91
+ ) -> ToolVerification:
92
+ """Verify one tool class."""
93
+ tool = tool_cls()
94
+ if tool_cls.name in HEAVY_TOOLS and not include_heavy:
95
+ return ToolVerification(
96
+ tool=tool_cls.name,
97
+ status="skipped-heavy",
98
+ installed=tool.is_installed(),
99
+ applicable=_safe_applicable(tool, repo),
100
+ message="pass --include-heavy to run Docker/network-heavy tools",
101
+ )
102
+
103
+ if install and not tool.is_installed() and tool.can_auto_install():
104
+ ok, msg = tool.install()
105
+ if not ok:
106
+ return ToolVerification(
107
+ tool=tool_cls.name,
108
+ status="install-failed",
109
+ installed=False,
110
+ applicable=_safe_applicable(tool, repo),
111
+ message=msg,
112
+ )
113
+
114
+ if not tool.is_installed():
115
+ return ToolVerification(
116
+ tool=tool_cls.name,
117
+ status="skipped-not-installed",
118
+ installed=False,
119
+ applicable=_safe_applicable(tool, repo),
120
+ message=tool.install_hint(),
121
+ )
122
+
123
+ if not _safe_applicable(tool, repo):
124
+ return ToolVerification(
125
+ tool=tool_cls.name,
126
+ status="skipped-not-applicable",
127
+ installed=True,
128
+ applicable=False,
129
+ )
130
+
131
+ start = time.monotonic()
132
+ try:
133
+ findings = tool.run(repo)
134
+ except subprocess.TimeoutExpired:
135
+ return ToolVerification(
136
+ tool=tool_cls.name,
137
+ status="timeout",
138
+ installed=True,
139
+ applicable=True,
140
+ duration_sec=time.monotonic() - start,
141
+ message="tool timed out",
142
+ )
143
+ except Exception as exc: # noqa: BLE001 — verification should capture tool crashes
144
+ return ToolVerification(
145
+ tool=tool_cls.name,
146
+ status="error",
147
+ installed=True,
148
+ applicable=True,
149
+ duration_sec=time.monotonic() - start,
150
+ message=f"{type(exc).__name__}: {exc}",
151
+ )
152
+
153
+ expected = _EXPECTED_FINDINGS.get(tool_cls.name, 0)
154
+ if len(findings) < expected:
155
+ return ToolVerification(
156
+ tool=tool_cls.name,
157
+ status="missed-defects",
158
+ installed=True,
159
+ applicable=True,
160
+ findings=len(findings),
161
+ duration_sec=time.monotonic() - start,
162
+ message=(
163
+ f"expected >= {expected} findings on the seeded repo, "
164
+ f"got {len(findings)} — adapter is likely silently broken"
165
+ ),
166
+ )
167
+
168
+ return ToolVerification(
169
+ tool=tool_cls.name,
170
+ status="ok" if findings else "no-findings",
171
+ installed=True,
172
+ applicable=True,
173
+ findings=len(findings),
174
+ duration_sec=time.monotonic() - start,
175
+ )
176
+
177
+
178
+ def _safe_applicable(tool: Tool, repo: Path) -> bool:
179
+ try:
180
+ return tool.is_applicable(repo)
181
+ except Exception: # noqa: BLE001
182
+ return False
183
+
184
+
185
+ def _seed_repo(tool_name: str, repo: Path) -> None:
186
+ """Create a synthetic repo that makes most tools applicable."""
187
+ (repo / ".git").mkdir(exist_ok=True)
188
+ (repo / "pyproject.toml").write_text(
189
+ """
190
+ [project]
191
+ name = "polycheck-verify"
192
+ version = "0.0.0"
193
+ dependencies = ["requests==2.0.0"]
194
+ """.strip()
195
+ + "\n",
196
+ encoding="utf-8",
197
+ )
198
+ (repo / "requirements.txt").write_text("requests==2.0.0\n", encoding="utf-8")
199
+ (repo / "app.py").write_text(
200
+ "import os\n\nx: int = 'bad'\n\ndef unused_helper() -> None:\n pass\n",
201
+ encoding="utf-8",
202
+ )
203
+ (repo / "package.json").write_text(
204
+ json.dumps(
205
+ {
206
+ "name": "polycheck-verify",
207
+ "private": True,
208
+ "type": "module",
209
+ "scripts": {
210
+ "lint": "eslint .",
211
+ "typecheck": "tsc --noEmit",
212
+ },
213
+ "dependencies": {"left-pad": "1.3.0"},
214
+ "devDependencies": {
215
+ "eslint": "latest",
216
+ "typescript": "latest",
217
+ },
218
+ },
219
+ indent=2,
220
+ )
221
+ + "\n",
222
+ encoding="utf-8",
223
+ )
224
+ (repo / "eslint.config.js").write_text(
225
+ """
226
+ export default [
227
+ {
228
+ files: ["**/*.js"],
229
+ languageOptions: {
230
+ ecmaVersion: 2022,
231
+ sourceType: "module",
232
+ },
233
+ rules: {
234
+ "no-unused-vars": "error",
235
+ },
236
+ },
237
+ ];
238
+ """.strip()
239
+ + "\n",
240
+ encoding="utf-8",
241
+ )
242
+ (repo / "app.js").write_text(
243
+ "const unused = 1;\n// intentionally unused: seeds an eslint no-unused-vars defect\n",
244
+ encoding="utf-8",
245
+ )
246
+ (repo / "tsconfig.json").write_text(
247
+ json.dumps(
248
+ {
249
+ "compilerOptions": {
250
+ "target": "ES2022",
251
+ "module": "ESNext",
252
+ "strict": True,
253
+ "noEmit": True,
254
+ },
255
+ "include": ["*.ts"],
256
+ },
257
+ indent=2,
258
+ )
259
+ + "\n",
260
+ encoding="utf-8",
261
+ )
262
+ (repo / "bad.ts").write_text("const value: number = 'bad';\n", encoding="utf-8")
263
+ (repo / "Dockerfile").write_text("FROM ubuntu\nRUN rm -rf /tmp\n", encoding="utf-8")
264
+ (repo / "script.sh").write_text("#!/bin/sh\necho $HOME\n", encoding="utf-8")
265
+ workflows = repo / ".github" / "workflows"
266
+ workflows.mkdir(parents=True, exist_ok=True)
267
+ (workflows / "ci.yml").write_text(
268
+ """
269
+ name: ci
270
+ on: push
271
+ jobs:
272
+ test:
273
+ runs-on: ubuntu-latest
274
+ steps:
275
+ - runz: echo hello
276
+ """.strip()
277
+ + "\n",
278
+ encoding="utf-8",
279
+ )
280
+
281
+ if tool_name == "gitleaks":
282
+ # gitleaks allowlists the full AWS config key names
283
+ # (aws_access_key_id / aws_secret_access_key); use a key name its
284
+ # generic-api-key rule actually flags.
285
+ (repo / "secret.txt").write_text(
286
+ "aws_key = AKIAQW7YJ2KX9P3M4NB8\n",
287
+ encoding="utf-8",
288
+ )
@@ -0,0 +1,76 @@
1
+ """Workflow templates for coding-assistant slash commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class WorkflowTemplate:
10
+ """Markdown template for one host."""
11
+
12
+ host: str
13
+ path: str
14
+ content: str
15
+
16
+
17
+ _SHARED_STEPS = """
18
+ Run the Polycheck guided static analysis workflow for the current repository.
19
+
20
+ 1. Confirm the current repository root.
21
+ 2. Call the MCP tool `polycheck.run` with `repo` set to the current repository root, `severity` set to `MEDIUM`, `parallel` set to `true`, and `install_mode` set to `none`.
22
+ 3. If the response reports missing analyzers or system dependencies, ask the user before rerunning with `install_mode` set to `tools_only` and `install_confirmed` set to `true`.
23
+ 4. Read the returned markdown and JSON report paths.
24
+ 5. Summarize findings by severity and tool.
25
+ 6. If fixable findings exist, ask the user before applying fixes.
26
+ 7. After fixes, rerun `polycheck.run` to verify the result.
27
+ 8. When the user accepts the current state, suggest `polycheck baseline` so later `polycheck.run` calls with `diff: true` report only new findings.
28
+ 9. For FALSE POSITIVE verdicts, append the rule (or `rule@file`) to the `suppress:` list in `.polycheck.yml` so the verdict persists across runs.
29
+ 10. If the MCP tool is unavailable, run `polycheck run . --severity MEDIUM`, read `polycheck-reports/polycheck-report.md` and `polycheck-reports/polycheck-report.json`, and perform the same triage.
30
+
31
+ Keep the final answer short and actionable.
32
+ """.strip()
33
+
34
+ KILO_WORKFLOW = f"""---
35
+ description: Run the Polycheck guided static analysis workflow
36
+ ---
37
+
38
+ # Polycheck
39
+
40
+ {_SHARED_STEPS}
41
+ """
42
+
43
+ OPENCODE_WORKFLOW = f"""---
44
+ description: Run the Polycheck guided static analysis workflow
45
+ ---
46
+
47
+ # Polycheck
48
+
49
+ {_SHARED_STEPS}
50
+ """
51
+
52
+ CLAUDE_WORKFLOW = f"""---
53
+ name: polycheck
54
+ description: Run the polycheck guided static-analysis workflow (linters, type checkers, CVE and secret scanners) and triage the findings. Use when the user asks to run polycheck, lint the repo, do a static analysis pass, or hunt for bugs efficiently.
55
+ ---
56
+
57
+ # Polycheck
58
+
59
+ {_SHARED_STEPS}
60
+ """
61
+
62
+ WORKFLOW_TEMPLATES: dict[str, WorkflowTemplate] = {
63
+ "kilo": WorkflowTemplate("kilo", ".kilo/commands/polycheck.md", KILO_WORKFLOW),
64
+ "opencode": WorkflowTemplate(
65
+ "opencode",
66
+ ".opencode/commands/polycheck.md",
67
+ OPENCODE_WORKFLOW,
68
+ ),
69
+ "claude": WorkflowTemplate(
70
+ "claude",
71
+ ".claude/skills/polycheck/SKILL.md",
72
+ CLAUDE_WORKFLOW,
73
+ ),
74
+ }
75
+
76
+ __all__ = ["WorkflowTemplate", "WORKFLOW_TEMPLATES"]