slopthreshold 2.1.0.dev22__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.
- slopthreshold/__init__.py +1 -0
- slopthreshold/guide/STYLE_GUIDE.md +495 -0
- slopthreshold/packs/editorconfig-pack/.editorconfig +899 -0
- slopthreshold/packs/editorconfig-pack/Directory.Build.props +47 -0
- slopthreshold/packs/editorconfig-pack/Directory.Build.targets +16 -0
- slopthreshold/packs/editorconfig-pack/Directory.Packages.props +29 -0
- slopthreshold/packs/editorconfig-pack/README.md +141 -0
- slopthreshold/packs/editorconfig-pack/global.json +7 -0
- slopthreshold/packs/editorconfig-pack/nuget.config +19 -0
- slopthreshold/packs/editorconfig-pack/ruff.toml +29 -0
- slopthreshold/packs/editorconfig-pack/sonar-drift-allowlist.json +10 -0
- slopthreshold/packs/frontend-lint-pack/.prettierrc.json +7 -0
- slopthreshold/packs/frontend-lint-pack/.stylelintrc.json +64 -0
- slopthreshold/packs/frontend-lint-pack/README.md +64 -0
- slopthreshold/packs/frontend-lint-pack/eslint.config.mjs +108 -0
- slopthreshold/packs/frontend-lint-pack/package.json +23 -0
- slopthreshold/packs/frontend-lint-pack/tsconfig.app.json +17 -0
- slopthreshold/packs/frontend-lint-pack/tsconfig.base.json +20 -0
- slopthreshold/packs/frontend-lint-pack/tsconfig.json +4 -0
- slopthreshold/packs/frontend-lint-pack/tsconfig.spec.json +8 -0
- slopthreshold/packs/project-guide-starters/app-STYLE_GUIDE.md +35 -0
- slopthreshold/packs/project-guide-starters/frontend-STYLE_GUIDE.md +33 -0
- slopthreshold/packs/project-guide-starters/library-STYLE_GUIDE.md +36 -0
- slopthreshold/packs/three-layer-wiring/.githooks/commit-msg +13 -0
- slopthreshold/packs/three-layer-wiring/.githooks/post-merge +8 -0
- slopthreshold/packs/three-layer-wiring/.githooks/pre-commit +10 -0
- slopthreshold/packs/three-layer-wiring/.githooks/pre-push +14 -0
- slopthreshold/packs/three-layer-wiring/.github/actionlint.yaml +3 -0
- slopthreshold/packs/three-layer-wiring/.github/workflows/quality.yml +164 -0
- slopthreshold/packs/three-layer-wiring/.gitleaks.toml +16 -0
- slopthreshold/packs/three-layer-wiring/.hadolint.yaml +6 -0
- slopthreshold/packs/three-layer-wiring/README.md +62 -0
- slopthreshold/packs/three-layer-wiring/budget.json +14 -0
- slopthreshold/tools/check_characters.py +104 -0
- slopthreshold/tools/check_ci_config.py +405 -0
- slopthreshold/tools/check_package_health.py +554 -0
- slopthreshold/tools/check_sonar_drift.py +1123 -0
- slopthreshold/tools/mine_sonar_metrics.py +1259 -0
- slopthreshold/tools/validate_guide_tags.py +795 -0
- slopthreshold/zh.py +973 -0
- slopthreshold-2.1.0.dev22.dist-info/METADATA +49 -0
- slopthreshold-2.1.0.dev22.dist-info/RECORD +44 -0
- slopthreshold-2.1.0.dev22.dist-info/WHEEL +4 -0
- slopthreshold-2.1.0.dev22.dist-info/entry_points.txt +2 -0
slopthreshold/zh.py
ADDED
|
@@ -0,0 +1,973 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""zh - the SlopThreshold command line: one entry point for the house enforcement tools.
|
|
3
|
+
|
|
4
|
+
Granular commands (one concern each; CI runs these in parallel jobs):
|
|
5
|
+
zh tags validate style-guide OVERRIDE/BYPASS tags
|
|
6
|
+
zh chars human-characters check (ST-FMT-13/14/15)
|
|
7
|
+
zh ci CI config check (ST-SEC-15: no inline keys/hosts/tokens)
|
|
8
|
+
zh hook AI-agent edit hook: route checks by edited file, exit 2 with findings
|
|
9
|
+
zh health grade package pins against the ST-DEP health gate
|
|
10
|
+
zh drift Sonar profile vs editorconfig severity drift
|
|
11
|
+
zh metrics Sonar repeat-mining report
|
|
12
|
+
zh format formatting verify (dotnet format / prettier)
|
|
13
|
+
zh lint eslint / stylelint / hadolint / actionlint
|
|
14
|
+
zh secrets gitleaks scan
|
|
15
|
+
zh build build what the repo contains
|
|
16
|
+
zh test run the repo's tests
|
|
17
|
+
|
|
18
|
+
Composite commands (one per moment; humans and hooks run these):
|
|
19
|
+
zh check tags + health + format + lint + secrets (+ drift)
|
|
20
|
+
zh pr check + build + test (local mirror of CI)
|
|
21
|
+
zh release pr + health evidence refresh + metrics
|
|
22
|
+
zh adopt install packs, starter guide, tools and hook into a repo
|
|
23
|
+
zh doctor tool availability, pins and repo wiring status
|
|
24
|
+
|
|
25
|
+
Every command is a thin wrapper: the real work stays in the existing
|
|
26
|
+
scripts and binaries, so granular and composite runs can never disagree.
|
|
27
|
+
Exit code: 0 pass, 1 a check failed, 2 usage/setup problem.
|
|
28
|
+
--json prints one structured summary (for CI and AI review layers).
|
|
29
|
+
--staged scopes file-based checks to staged files (pre-commit use).
|
|
30
|
+
"""
|
|
31
|
+
import argparse
|
|
32
|
+
import json
|
|
33
|
+
import os
|
|
34
|
+
import os
|
|
35
|
+
import pathlib
|
|
36
|
+
import re
|
|
37
|
+
import shutil
|
|
38
|
+
import subprocess
|
|
39
|
+
import sys
|
|
40
|
+
|
|
41
|
+
HERE = pathlib.Path(__file__).resolve().parent
|
|
42
|
+
|
|
43
|
+
STYLE_GUIDE_MD = "STYLE_GUIDE.md"
|
|
44
|
+
VALIDATE_GUIDE_TAGS_PY = "validate_guide_tags.py"
|
|
45
|
+
BYPASS_TAG_VALIDATOR_SCRIPT = "bypass-tag-validator/validate_guide_tags.py"
|
|
46
|
+
CHECK_PACKAGE_HEALTH_PY = "check_package_health.py"
|
|
47
|
+
HEALTH_GATE_CHECKER_SCRIPT = "health-gate-checker/check_package_health.py"
|
|
48
|
+
DIRECTORY_PACKAGES_PROPS = "Directory.Packages.props"
|
|
49
|
+
PACKAGE_JSON = "package.json"
|
|
50
|
+
CHECK_CHARACTERS_PY = "check_characters.py"
|
|
51
|
+
HUMAN_CHARACTERS_SCRIPT = "human-characters/check_characters.py"
|
|
52
|
+
CSPROJ_GLOB = "*.csproj"
|
|
53
|
+
SLN_GLOB = "*.sln*"
|
|
54
|
+
CHECK_CI_CONFIG_PY = "check_ci_config.py"
|
|
55
|
+
CI_CONFIG_CHECK_SCRIPT = "ci-config-check/check_ci_config.py"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def find_tool(*relative_candidates):
|
|
59
|
+
"""Locate a house script: beside zh.py, in tools/, or in the staging layout."""
|
|
60
|
+
roots = [HERE, HERE / "tools", pathlib.Path.cwd() / "tools", HERE.parent]
|
|
61
|
+
for root in roots:
|
|
62
|
+
for rel in relative_candidates:
|
|
63
|
+
candidate = root / rel
|
|
64
|
+
if candidate.is_file():
|
|
65
|
+
return candidate
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def run(cmd, cwd=None):
|
|
70
|
+
proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
|
|
71
|
+
return proc.returncode, (proc.stdout + proc.stderr).strip()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def staged_files():
|
|
75
|
+
code, out = run(["git", "diff", "--cached", "--name-only", "--diff-filter=ACM"])
|
|
76
|
+
return out.splitlines() if code == 0 else []
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def find_guide():
|
|
80
|
+
for candidate in ["docs/STYLE_GUIDE.md", STYLE_GUIDE_MD]:
|
|
81
|
+
if pathlib.Path(candidate).is_file():
|
|
82
|
+
return candidate
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _load_zh_config():
|
|
87
|
+
"""Repo-local zh.json: chars_allow (globs), drift_args (extra args)."""
|
|
88
|
+
cfg_path = pathlib.Path(__file__).resolve().parent.parent / "zh.json"
|
|
89
|
+
if cfg_path.is_file():
|
|
90
|
+
try:
|
|
91
|
+
return json.loads(cfg_path.read_text(encoding="utf-8"))
|
|
92
|
+
except (OSError, ValueError):
|
|
93
|
+
return {}
|
|
94
|
+
return {}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
ZH_CONFIG = _load_zh_config()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def result(name, status, detail=""):
|
|
101
|
+
return {"check": name, "status": status, "detail": detail}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def check_tags(args):
|
|
105
|
+
script = find_tool(VALIDATE_GUIDE_TAGS_PY, BYPASS_TAG_VALIDATOR_SCRIPT)
|
|
106
|
+
guide = args.guide or find_guide()
|
|
107
|
+
if not script:
|
|
108
|
+
return result("tags", "skip", "validator not found")
|
|
109
|
+
if not guide:
|
|
110
|
+
return result("tags", "skip", "no project guide found")
|
|
111
|
+
code, out = run([sys.executable, str(script), guide, "--strict"])
|
|
112
|
+
return result("tags", "pass" if code == 0 else "fail", out.splitlines()[-1] if out else "")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _pin_applies(filename, staged_mode, staged):
|
|
116
|
+
if not pathlib.Path(filename).is_file():
|
|
117
|
+
return False
|
|
118
|
+
if not staged_mode:
|
|
119
|
+
return True
|
|
120
|
+
return filename in staged
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _health_targets(staged_mode, staged):
|
|
124
|
+
targets = []
|
|
125
|
+
for flag, filename in (("--props", DIRECTORY_PACKAGES_PROPS), ("--npm", PACKAGE_JSON)):
|
|
126
|
+
if _pin_applies(filename, staged_mode, staged):
|
|
127
|
+
targets.append([flag, filename])
|
|
128
|
+
return targets
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _health_detail(out):
|
|
132
|
+
for ln in out.splitlines():
|
|
133
|
+
if ln.startswith(("FAIL", "WARN")):
|
|
134
|
+
return ln
|
|
135
|
+
return out.splitlines()[0] if out else ""
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _health_results(script, targets):
|
|
139
|
+
worst = "pass"
|
|
140
|
+
details = []
|
|
141
|
+
for target in targets:
|
|
142
|
+
code, out = run([sys.executable, str(script), *target])
|
|
143
|
+
if code != 0:
|
|
144
|
+
worst = "fail"
|
|
145
|
+
details.append(_health_detail(out))
|
|
146
|
+
return worst, details
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def check_health(args):
|
|
150
|
+
script = find_tool(CHECK_PACKAGE_HEALTH_PY, HEALTH_GATE_CHECKER_SCRIPT)
|
|
151
|
+
if not script:
|
|
152
|
+
return result("health", "skip", "health checker not found")
|
|
153
|
+
staged = staged_files() if args.staged else []
|
|
154
|
+
targets = _health_targets(args.staged, staged)
|
|
155
|
+
if args.staged and not targets:
|
|
156
|
+
return result("health", "skip", "pins unchanged")
|
|
157
|
+
if not targets:
|
|
158
|
+
return result("health", "skip", "no Directory.Packages.props or package.json")
|
|
159
|
+
worst, details = _health_results(script, targets)
|
|
160
|
+
return result("health", worst, "; ".join(details))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def check_script(name, candidates, extra=None):
|
|
164
|
+
script = find_tool(*candidates)
|
|
165
|
+
if not script:
|
|
166
|
+
return result(name, "skip", f"{name} tool not installed yet")
|
|
167
|
+
code, out = run([sys.executable, str(script), *(extra or [])])
|
|
168
|
+
return result(name, "pass" if code == 0 else "fail", out.splitlines()[-1] if out else "")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def check_chars(args):
|
|
172
|
+
"""ST-FMT-13/14/15: human characters only (staged files in pre-commit)."""
|
|
173
|
+
script = find_tool(CHECK_CHARACTERS_PY, HUMAN_CHARACTERS_SCRIPT)
|
|
174
|
+
if not script:
|
|
175
|
+
return result("chars", "skip", "chars tool not installed yet")
|
|
176
|
+
targets = staged_files() if args.staged else ["."]
|
|
177
|
+
if args.staged and not targets:
|
|
178
|
+
return result("chars", "skip", "nothing staged")
|
|
179
|
+
allow = [a for g in ZH_CONFIG.get("chars_allow", []) for a in ("--allow", g)]
|
|
180
|
+
code, out = run([sys.executable, str(script), *targets, *allow])
|
|
181
|
+
detail = out.splitlines()[-1] if out else ""
|
|
182
|
+
if code != 0 and out:
|
|
183
|
+
detail = out.splitlines()[0] + f" (+{len(out.splitlines()) - 2} more)"
|
|
184
|
+
return result("chars", "pass" if code == 0 else "fail", detail)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _pass_fail_result(name, ran):
|
|
188
|
+
failed = [n for n, c in ran if c != 0]
|
|
189
|
+
if failed:
|
|
190
|
+
return result(name, "fail", ", ".join(failed))
|
|
191
|
+
return result(name, "pass", "clean")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _has_dotnet_project():
|
|
195
|
+
return bool(list(pathlib.Path(".").glob(SLN_GLOB)) + list(pathlib.Path(".").glob(CSPROJ_GLOB)))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _dotnet_format_cmd(args):
|
|
199
|
+
cmd = ["dotnet", "format", "--verify-no-changes"] if not args.fix else ["dotnet", "format"]
|
|
200
|
+
if not args.staged:
|
|
201
|
+
return cmd
|
|
202
|
+
cs = [f for f in staged_files() if f.endswith(".cs")]
|
|
203
|
+
if cs:
|
|
204
|
+
cmd += ["--include", *cs]
|
|
205
|
+
return cmd
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _format_dotnet(args):
|
|
209
|
+
if not shutil.which("dotnet"):
|
|
210
|
+
return None
|
|
211
|
+
if not _has_dotnet_project():
|
|
212
|
+
return None
|
|
213
|
+
code, _ = run(_dotnet_format_cmd(args))
|
|
214
|
+
return ("dotnet-format", code)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _format_prettier(args):
|
|
218
|
+
if not shutil.which("npx"):
|
|
219
|
+
return None
|
|
220
|
+
if not pathlib.Path(".prettierrc.json").is_file():
|
|
221
|
+
return None
|
|
222
|
+
if not pathlib.Path("node_modules").is_dir():
|
|
223
|
+
return None
|
|
224
|
+
cmd = ["npx", "prettier", "--write" if args.fix else "--check", "src/**/*.{ts,html,scss,json}"]
|
|
225
|
+
code, _ = run(cmd)
|
|
226
|
+
return ("prettier", code)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def check_format(args):
|
|
230
|
+
ran = [entry for entry in (_format_dotnet(args), _format_prettier(args)) if entry is not None]
|
|
231
|
+
if not ran:
|
|
232
|
+
return result("format", "skip", "no formatters apply")
|
|
233
|
+
return _pass_fail_result("format", ran)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _node_linter_ready(config_glob):
|
|
237
|
+
if not shutil.which("npx"):
|
|
238
|
+
return False
|
|
239
|
+
if not list(pathlib.Path(".").glob(config_glob)):
|
|
240
|
+
return False
|
|
241
|
+
return pathlib.Path("node_modules").is_dir()
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _lint_files(args, staged, extensions, default):
|
|
245
|
+
if not args.staged:
|
|
246
|
+
return default
|
|
247
|
+
return [f for f in staged if f.endswith(extensions)]
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _lint_eslint(args, staged):
|
|
251
|
+
if not _node_linter_ready("eslint.config.*"):
|
|
252
|
+
return None
|
|
253
|
+
files = _lint_files(args, staged, (".ts", ".html"), ["."])
|
|
254
|
+
if not files:
|
|
255
|
+
return None
|
|
256
|
+
code, _ = run(["npx", "eslint", "--max-warnings=0", *files])
|
|
257
|
+
return ("eslint", code)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _lint_stylelint(args, staged):
|
|
261
|
+
if not _node_linter_ready(".stylelintrc*"):
|
|
262
|
+
return None
|
|
263
|
+
files = _lint_files(args, staged, (".scss", ".css"), ["src/**/*.scss"])
|
|
264
|
+
if not files:
|
|
265
|
+
return None
|
|
266
|
+
code, _ = run(["npx", "stylelint", *files])
|
|
267
|
+
return ("stylelint", code)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _lint_actionlint():
|
|
271
|
+
if not shutil.which("actionlint"):
|
|
272
|
+
return None
|
|
273
|
+
if not pathlib.Path(".github/workflows").is_dir():
|
|
274
|
+
return None
|
|
275
|
+
code, _ = run(["actionlint"])
|
|
276
|
+
return ("actionlint", code)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _lint_hadolint():
|
|
280
|
+
if not shutil.which("hadolint"):
|
|
281
|
+
return None
|
|
282
|
+
dockerfiles = [str(p) for p in pathlib.Path(".").rglob("Dockerfile*") if "node_modules" not in str(p)]
|
|
283
|
+
if not dockerfiles:
|
|
284
|
+
return None
|
|
285
|
+
code, _ = run(["hadolint", "--config", ".hadolint.yaml", *dockerfiles])
|
|
286
|
+
return ("hadolint", code)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _lint_ruff(args, staged):
|
|
290
|
+
files = _lint_files(args, staged, (".py",), ["tools"])
|
|
291
|
+
if not files:
|
|
292
|
+
return None
|
|
293
|
+
if not (shutil.which("ruff") or _module_available("ruff")):
|
|
294
|
+
return None
|
|
295
|
+
code, out = run([sys.executable, "-m", "ruff", "check", *files])
|
|
296
|
+
if code != 0 and out:
|
|
297
|
+
print(out)
|
|
298
|
+
return ("ruff", code)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _module_available(name):
|
|
302
|
+
import importlib.util
|
|
303
|
+
return importlib.util.find_spec(name) is not None
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _lint_skip_hint():
|
|
307
|
+
if pathlib.Path(PACKAGE_JSON).is_file() and not pathlib.Path("node_modules").is_dir():
|
|
308
|
+
return "run npm ci first"
|
|
309
|
+
return "no linters apply"
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def check_lint(args):
|
|
313
|
+
staged = staged_files() if args.staged else []
|
|
314
|
+
entries = (_lint_eslint(args, staged), _lint_stylelint(args, staged), _lint_actionlint(), _lint_hadolint(), _lint_ruff(args, staged))
|
|
315
|
+
ran = [entry for entry in entries if entry is not None]
|
|
316
|
+
if not ran:
|
|
317
|
+
return result("lint", "skip", _lint_skip_hint())
|
|
318
|
+
return _pass_fail_result("lint", ran)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def check_secrets(args):
|
|
322
|
+
if not shutil.which("gitleaks"):
|
|
323
|
+
return result("secrets", "skip", "gitleaks not installed (CI enforces)")
|
|
324
|
+
cmd = ["gitleaks", "protect", "--staged", "--redact"] if args.staged else ["gitleaks", "detect", "--redact"]
|
|
325
|
+
if pathlib.Path(".gitleaks.toml").is_file():
|
|
326
|
+
cmd += ["--config", ".gitleaks.toml"]
|
|
327
|
+
code, _ = run(cmd)
|
|
328
|
+
return result("secrets", "pass" if code == 0 else "fail", "clean" if code == 0 else "leaks found")
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def check_build():
|
|
332
|
+
if shutil.which("dotnet") and (list(pathlib.Path(".").glob(SLN_GLOB)) or list(pathlib.Path(".").glob(CSPROJ_GLOB))):
|
|
333
|
+
code, _ = run(["dotnet", "build"])
|
|
334
|
+
return result("build", "pass" if code == 0 else "fail", "dotnet build")
|
|
335
|
+
if pathlib.Path(PACKAGE_JSON).is_file():
|
|
336
|
+
if not pathlib.Path("node_modules").is_dir():
|
|
337
|
+
return result("build", "skip", "run npm ci first")
|
|
338
|
+
code, _ = run(["npm", "run", "typecheck"])
|
|
339
|
+
return result("build", "pass" if code == 0 else "fail", "npm typecheck")
|
|
340
|
+
return result("build", "skip", "nothing to build")
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def check_test():
|
|
344
|
+
if shutil.which("dotnet") and (list(pathlib.Path(".").glob(SLN_GLOB)) or list(pathlib.Path(".").glob(CSPROJ_GLOB))):
|
|
345
|
+
code, _ = run(["dotnet", "test"])
|
|
346
|
+
return result("test", "pass" if code == 0 else "fail", "dotnet test")
|
|
347
|
+
return result("test", "skip", "no test runner detected")
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
_MSG_SUBJECT_RE = re.compile(r"^(feat|fix|refactor|docs|test|chore|perf|build|ci|style|revert)(\([a-z0-9._/-]+\))?(!)?: (.+)$")
|
|
351
|
+
_MSG_EXEMPT_PREFIXES = ("Merge ", "Revert ", "fixup!", "squash!")
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _msg_lines(path):
|
|
355
|
+
text = pathlib.Path(path).read_text(encoding="utf-8", errors="ignore")
|
|
356
|
+
return [ln for ln in text.splitlines() if not ln.startswith("#")]
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _msg_subject_style_problems(subject, text):
|
|
360
|
+
problems = []
|
|
361
|
+
if len(subject) > 72:
|
|
362
|
+
problems.append(f"subject is {len(subject)} chars (max 72)")
|
|
363
|
+
if text.endswith("."):
|
|
364
|
+
problems.append("subject ends with a period")
|
|
365
|
+
if len(text) < 10:
|
|
366
|
+
problems.append("subject too short to say what changed")
|
|
367
|
+
return problems
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _msg_subject_problems(subject):
|
|
371
|
+
m = _MSG_SUBJECT_RE.match(subject)
|
|
372
|
+
if not m:
|
|
373
|
+
return ["subject must start with a Conventional Commits type (feat:, fix:, refactor:, docs:, test:, chore:)"]
|
|
374
|
+
return _msg_subject_style_problems(subject, m.group(4))
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _msg_body_problems(lines):
|
|
378
|
+
long_lines = [ln for ln in lines[1:] if len(ln) > 100]
|
|
379
|
+
if not long_lines:
|
|
380
|
+
return []
|
|
381
|
+
return [f"{len(long_lines)} body line(s) over 100 chars"]
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def check_msg(args):
|
|
385
|
+
"""ST-GIT-02: Conventional Commits. Malformed = fail; style nits = detail."""
|
|
386
|
+
path = args.msg_file
|
|
387
|
+
if not path:
|
|
388
|
+
return result("msg", "skip", "no commit message file")
|
|
389
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
|
390
|
+
from safe_paths import resolve_under
|
|
391
|
+
try:
|
|
392
|
+
msg_path = resolve_under(path, pathlib.Path.cwd())
|
|
393
|
+
except ValueError:
|
|
394
|
+
return result("msg", "fail", "commit message file escapes the repository")
|
|
395
|
+
if not msg_path.is_file():
|
|
396
|
+
return result("msg", "skip", "no commit message file")
|
|
397
|
+
lines = _msg_lines(str(msg_path))
|
|
398
|
+
subject = lines[0].strip() if lines else ""
|
|
399
|
+
if subject.startswith(_MSG_EXEMPT_PREFIXES):
|
|
400
|
+
return result("msg", "pass", "merge/revert/fixup subject exempt")
|
|
401
|
+
problems = _msg_subject_problems(subject) + _msg_body_problems(lines)
|
|
402
|
+
if problems:
|
|
403
|
+
return result("msg", "fail", "; ".join(problems))
|
|
404
|
+
return result("msg", "pass", "conventional subject")
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def check_codeql():
|
|
409
|
+
"""ST-SEC-16: CodeQL security scan. Manual/on-demand locally; CI runs it
|
|
410
|
+
on PRs to UAT/Prod. Skips cleanly when the CodeQL CLI is not installed."""
|
|
411
|
+
cli = shutil.which("codeql") or os.environ.get("CODEQL_CLI")
|
|
412
|
+
if not cli:
|
|
413
|
+
return result("codeql", "skip", "codeql CLI not installed (CI runs it on UAT/Prod PRs)")
|
|
414
|
+
lang = os.environ.get("ZH_CODEQL_LANGUAGE")
|
|
415
|
+
if not lang:
|
|
416
|
+
if list(pathlib.Path(".").glob(SLN_GLOB)) or list(pathlib.Path(".").rglob(CSPROJ_GLOB)):
|
|
417
|
+
lang = "csharp"
|
|
418
|
+
else:
|
|
419
|
+
lang = "python"
|
|
420
|
+
db = pathlib.Path("artifacts/codeql-db")
|
|
421
|
+
sarif = pathlib.Path("artifacts/codeql.sarif")
|
|
422
|
+
db.parent.mkdir(parents=True, exist_ok=True)
|
|
423
|
+
code, _ = run([cli, "database", "create", str(db), f"--language={lang}",
|
|
424
|
+
"--overwrite", "--build-mode=none"])
|
|
425
|
+
if code != 0:
|
|
426
|
+
return result("codeql", "fail", "database creation failed")
|
|
427
|
+
suite = f"codeql/{lang}-queries:codeql-suites/{lang}-security-and-quality.qls"
|
|
428
|
+
code, _ = run([cli, "database", "analyze", str(db), suite,
|
|
429
|
+
"--format=sarif-latest", f"--output={sarif}"])
|
|
430
|
+
if code != 0 or not sarif.is_file():
|
|
431
|
+
return result("codeql", "fail", "analysis failed")
|
|
432
|
+
script = find_tool("codeql_report.py", "tools/codeql_report.py")
|
|
433
|
+
if script:
|
|
434
|
+
sys.path.insert(0, str(pathlib.Path(script).parent))
|
|
435
|
+
import codeql_report
|
|
436
|
+
summary = codeql_report.parse_sarif(sarif)
|
|
437
|
+
errors = summary["by_level"].get("error", 0)
|
|
438
|
+
return result("codeql", "fail" if errors else "pass",
|
|
439
|
+
codeql_report.summary_line(summary) + f" ({sarif})")
|
|
440
|
+
return result("codeql", "pass", f"SARIF written ({sarif})")
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def cmd_pdf():
|
|
444
|
+
"""Manual PDF export of the build report (reportlab; on demand only)."""
|
|
445
|
+
script = find_tool("report_pdf.py", "tools/report_pdf.py")
|
|
446
|
+
builder = find_tool("build_reports_site.py", "tools/build_reports_site.py")
|
|
447
|
+
if not script or not builder:
|
|
448
|
+
print("zh pdf: report tools not found")
|
|
449
|
+
return 2
|
|
450
|
+
code, out = run([sys.executable, str(builder)])
|
|
451
|
+
if code != 0:
|
|
452
|
+
print(out[-500:])
|
|
453
|
+
print("zh pdf: report build failed")
|
|
454
|
+
return 1
|
|
455
|
+
manifest = pathlib.Path("artifacts/reports-input/manifest.json")
|
|
456
|
+
if not manifest.is_file():
|
|
457
|
+
print("zh pdf: manifest not produced")
|
|
458
|
+
return 1
|
|
459
|
+
security = pathlib.Path("artifacts/reports-input/security.md")
|
|
460
|
+
cmd = [sys.executable, str(script), "--manifest", str(manifest),
|
|
461
|
+
"--out", "artifacts/build-report.pdf"]
|
|
462
|
+
if security.is_file():
|
|
463
|
+
cmd += ["--security-md", str(security)]
|
|
464
|
+
code, out = run(cmd)
|
|
465
|
+
print(out.strip())
|
|
466
|
+
return code
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
GRANULAR = {
|
|
470
|
+
"tags": check_tags,
|
|
471
|
+
"chars": check_chars,
|
|
472
|
+
"ci": lambda a: check_script("ci", [CHECK_CI_CONFIG_PY, CI_CONFIG_CHECK_SCRIPT]),
|
|
473
|
+
"health": check_health,
|
|
474
|
+
"drift": lambda a: check_script("drift", ["check_sonar_drift.py", "sonar-drift-check/check_sonar_drift.py"], extra=list(ZH_CONFIG.get("drift_args", []))),
|
|
475
|
+
"metrics": lambda a: check_script("metrics", ["mine_sonar_metrics.py", "sonar_metrics.py", "metrics-loop/mine_sonar_metrics.py"]),
|
|
476
|
+
"format": check_format,
|
|
477
|
+
"lint": check_lint,
|
|
478
|
+
"secrets": check_secrets,
|
|
479
|
+
"build": lambda a: check_build(),
|
|
480
|
+
"test": lambda a: check_test(),
|
|
481
|
+
"msg": check_msg,
|
|
482
|
+
"codeql": lambda a: check_codeql(),
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
COMPOSITES = {
|
|
486
|
+
"check": ["tags", "chars", "ci", "health", "format", "lint", "secrets", "drift"],
|
|
487
|
+
"pr": ["tags", "chars", "ci", "health", "format", "lint", "secrets", "drift", "build", "test"],
|
|
488
|
+
"release": ["tags", "chars", "ci", "health", "format", "lint", "secrets", "drift", "build", "test", "metrics"],
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def emit(results, as_json):
|
|
493
|
+
if as_json:
|
|
494
|
+
print(json.dumps({"results": results,
|
|
495
|
+
"verdict": "fail" if any(r["status"] == "fail" for r in results) else "pass"}, indent=1))
|
|
496
|
+
else:
|
|
497
|
+
for r in results:
|
|
498
|
+
mark = {"pass": "PASS", "fail": "FAIL", "skip": "SKIP"}[r["status"]]
|
|
499
|
+
print(f"{mark:4} {r['check']:8} {r['detail']}")
|
|
500
|
+
failed = [r["check"] for r in results if r["status"] == "fail"]
|
|
501
|
+
print("FAILED: " + ", ".join(failed) if failed else "All checks passed.")
|
|
502
|
+
return 1 if any(r["status"] == "fail" for r in results) else 0
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def pack_source():
|
|
506
|
+
"""Locate the pack folders: staging layout or Documentations repo layout."""
|
|
507
|
+
for root in [HERE / "packs", HERE.parent, HERE.parent / "packs", HERE.parent / "style-guide", pathlib.Path.cwd() / "style-guide"]:
|
|
508
|
+
if (root / "editorconfig-pack").is_dir():
|
|
509
|
+
return root
|
|
510
|
+
return None
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
_ADOPT_TOOL_SOURCES = [
|
|
514
|
+
(VALIDATE_GUIDE_TAGS_PY, [BYPASS_TAG_VALIDATOR_SCRIPT, "tools/validate_guide_tags.py", "../tools/validate_guide_tags.py"]),
|
|
515
|
+
(CHECK_PACKAGE_HEALTH_PY, [HEALTH_GATE_CHECKER_SCRIPT, "tools/check_package_health.py", "../tools/check_package_health.py"]),
|
|
516
|
+
(CHECK_CHARACTERS_PY, [HUMAN_CHARACTERS_SCRIPT, "tools/check_characters.py", "../tools/check_characters.py"]),
|
|
517
|
+
(CHECK_CI_CONFIG_PY, [CI_CONFIG_CHECK_SCRIPT, "tools/check_ci_config.py", "../tools/check_ci_config.py"]),
|
|
518
|
+
("GENERALIZED_STYLE_GUIDE.md", ["generalized-style-guide/STYLE_GUIDE.md", "../docs/style-guide.md", "../guide/STYLE_GUIDE.md"]),
|
|
519
|
+
]
|
|
520
|
+
|
|
521
|
+
_AI_PACK_FILES = [
|
|
522
|
+
("claude-code/settings.json", ".claude/settings.json"),
|
|
523
|
+
("codex/hooks.json", ".codex/hooks.json"),
|
|
524
|
+
("cursor/slopthreshold.mdc", ".cursor/rules/slopthreshold.mdc"),
|
|
525
|
+
]
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _adopt_copy(copied, target, src, dst):
|
|
529
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
530
|
+
shutil.copy2(src, dst)
|
|
531
|
+
copied.append(str(dst.relative_to(target)))
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _adopt_editorconfig(source, target, kind, copied):
|
|
535
|
+
if kind not in ("app", "library"):
|
|
536
|
+
return
|
|
537
|
+
pack = source / "editorconfig-pack"
|
|
538
|
+
for f in pack.rglob("*"):
|
|
539
|
+
if f.is_file():
|
|
540
|
+
_adopt_copy(copied, target, f, target / f.relative_to(pack))
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _adopt_frontend(source, target, kind, copied):
|
|
544
|
+
if kind not in ("app", "frontend"):
|
|
545
|
+
return
|
|
546
|
+
for f in (source / "frontend-lint-pack").iterdir():
|
|
547
|
+
if f.is_file():
|
|
548
|
+
_adopt_copy(copied, target, f, target / f.name)
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _adopt_starter(source, target, kind, copied):
|
|
552
|
+
starter = source / "project-guide-starters" / f"{kind}-STYLE_GUIDE.md"
|
|
553
|
+
if starter.is_file():
|
|
554
|
+
_adopt_copy(copied, target, starter, target / "docs" / STYLE_GUIDE_MD)
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _adopt_tool(source, target, copied, name, candidates):
|
|
558
|
+
for rel in candidates:
|
|
559
|
+
src = source / rel
|
|
560
|
+
if src.is_file():
|
|
561
|
+
_adopt_copy(copied, target, src, target / "tools" / name)
|
|
562
|
+
return
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _adopt_tools(source, target, copied):
|
|
566
|
+
for name, candidates in _ADOPT_TOOL_SOURCES:
|
|
567
|
+
_adopt_tool(source, target, copied, name, candidates)
|
|
568
|
+
_adopt_copy(copied, target, HERE / "zh.py", target / "tools" / "zh.py")
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def _adopt_hooks(source, target, copied):
|
|
572
|
+
hooks_dir = source / "three-layer-wiring" / ".githooks"
|
|
573
|
+
if not hooks_dir.is_dir():
|
|
574
|
+
return
|
|
575
|
+
for hook in sorted(hooks_dir.iterdir()):
|
|
576
|
+
if hook.is_file():
|
|
577
|
+
_adopt_copy(copied, target, hook, target / ".githooks" / hook.name)
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _print_adopted(kind, copied):
|
|
581
|
+
print(f"Adopted {kind} pack: {len(copied)} files")
|
|
582
|
+
for c in copied:
|
|
583
|
+
print(f" {c}")
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _adopt_ai_file(ai_pack, target, copied, src, dst):
|
|
587
|
+
s = ai_pack / src
|
|
588
|
+
d = target / dst
|
|
589
|
+
if s.is_file() and not d.exists():
|
|
590
|
+
_adopt_copy(copied, target, s, d)
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _adopt_ai_pack(target, copied):
|
|
594
|
+
root = pack_source()
|
|
595
|
+
if not root:
|
|
596
|
+
return
|
|
597
|
+
ai_pack = root / "ai-hooks-pack"
|
|
598
|
+
for src, dst in _AI_PACK_FILES:
|
|
599
|
+
_adopt_ai_file(ai_pack, target, copied, src, dst)
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def adopt(args):
|
|
603
|
+
source = pack_source()
|
|
604
|
+
if not source:
|
|
605
|
+
print("zh adopt: pack source not found (run from the staging tree or a repo with style-guide/)")
|
|
606
|
+
return 2
|
|
607
|
+
target = pathlib.Path.cwd()
|
|
608
|
+
kind = args.kind
|
|
609
|
+
copied = []
|
|
610
|
+
_adopt_editorconfig(source, target, kind, copied)
|
|
611
|
+
_adopt_frontend(source, target, kind, copied)
|
|
612
|
+
_adopt_starter(source, target, kind, copied)
|
|
613
|
+
_adopt_tools(source, target, copied)
|
|
614
|
+
_adopt_hooks(source, target, copied)
|
|
615
|
+
_print_adopted(kind, copied)
|
|
616
|
+
_adopt_ai_pack(target, copied)
|
|
617
|
+
print("Next: git config core.hooksPath .githooks && python3 tools/zh.py doctor")
|
|
618
|
+
return 0
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
RULE_CONTEXT = {
|
|
622
|
+
".cs": "ST-PAT-09/10/11 one responsibility, size caps; ST-FMT-13 ASCII only; ST-SEC-01 no secrets",
|
|
623
|
+
".ts": "ST-FE-TS-10 size caps; ST-FMT-13 ASCII only; OnPush + signals per guide frontend section",
|
|
624
|
+
".tsx": "ST-FE-TS-10 size caps; ST-FMT-13 ASCII only",
|
|
625
|
+
".yml": "ST-SEC-15 vars/secrets only; ST-CI-01 SHA-pinned actions; ST-CI-02 least-privilege permissions",
|
|
626
|
+
".yaml": "ST-SEC-15 vars/secrets only; ST-CI-01 SHA-pinned actions; ST-CI-02 least-privilege permissions",
|
|
627
|
+
".props": "ST-DEP-02/03 package health gate; ST-DEP-04 pin evidence comments",
|
|
628
|
+
".json": "ST-DEP-02/03 package health gate for dependency files; ST-FMT-13 ASCII only",
|
|
629
|
+
".md": "ST-FMT-14 no invisible characters; guide tags need OVERRIDE/BYPASS discipline",
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _explicit_hook_files(args):
|
|
634
|
+
candidates = [getattr(args, "kind", None), getattr(args, "msg_file", None), *(args.hook_files or [])]
|
|
635
|
+
return [a for a in candidates if a]
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _append_str_path(paths, value):
|
|
639
|
+
if isinstance(value, str):
|
|
640
|
+
paths.append(value)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def _payload_edits(ti):
|
|
644
|
+
edits = ti.get("edits", [])
|
|
645
|
+
return edits if isinstance(edits, list) else []
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def _append_edit_path(paths, edit):
|
|
649
|
+
if not isinstance(edit, dict):
|
|
650
|
+
return
|
|
651
|
+
_append_str_path(paths, edit.get("file_path"))
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def _tool_input_paths(ti):
|
|
655
|
+
paths = []
|
|
656
|
+
for key in ("file_path", "path"):
|
|
657
|
+
_append_str_path(paths, ti.get(key))
|
|
658
|
+
for edit in _payload_edits(ti):
|
|
659
|
+
_append_edit_path(paths, edit)
|
|
660
|
+
return paths
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def _payload_paths(payload):
|
|
664
|
+
if not isinstance(payload, dict):
|
|
665
|
+
return []
|
|
666
|
+
ti = payload.get("tool_input", {})
|
|
667
|
+
return _tool_input_paths(ti) if isinstance(ti, dict) else []
|
|
668
|
+
|
|
669
|
+
|
|
670
|
+
def _stdin_hook_files():
|
|
671
|
+
try:
|
|
672
|
+
payload = json.load(sys.stdin)
|
|
673
|
+
except (ValueError, OSError):
|
|
674
|
+
return []
|
|
675
|
+
return _payload_paths(payload)
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def hook_files(args):
|
|
679
|
+
"""Edited files: explicit args, else Claude Code hook JSON on stdin."""
|
|
680
|
+
files = _explicit_hook_files(args)
|
|
681
|
+
if files:
|
|
682
|
+
return files
|
|
683
|
+
if sys.stdin.isatty():
|
|
684
|
+
return []
|
|
685
|
+
return _stdin_hook_files()
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def _hook_existing_files(args):
|
|
689
|
+
return [f for f in hook_files(args) if pathlib.Path(f).is_file()]
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def _append_context_line(seen, f):
|
|
693
|
+
ctx = RULE_CONTEXT.get(pathlib.Path(f).suffix.lower())
|
|
694
|
+
if ctx and ctx not in seen:
|
|
695
|
+
seen.append(ctx)
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _hook_print_context(files):
|
|
699
|
+
seen = []
|
|
700
|
+
for f in files:
|
|
701
|
+
_append_context_line(seen, f)
|
|
702
|
+
for line in seen:
|
|
703
|
+
print(f"SlopThreshold rules for this edit: {line}")
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _append_finding(findings, finding):
|
|
707
|
+
if finding is not None:
|
|
708
|
+
findings.append(finding)
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def _hook_chars_finding(files):
|
|
712
|
+
script = find_tool(CHECK_CHARACTERS_PY, HUMAN_CHARACTERS_SCRIPT)
|
|
713
|
+
if not script:
|
|
714
|
+
return None
|
|
715
|
+
code, out = run([sys.executable, str(script), *files])
|
|
716
|
+
if code == 0:
|
|
717
|
+
return None
|
|
718
|
+
return "ST-FMT-13/14/15 human characters:\n" + out
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def _hook_guide_finding(script, guide):
|
|
722
|
+
code, out = run([sys.executable, str(script), guide, "--strict"])
|
|
723
|
+
if code == 0:
|
|
724
|
+
return None
|
|
725
|
+
return f"guide tags in {guide}:\n" + out
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def _hook_guide_findings(files):
|
|
729
|
+
guides = [f for f in files if f.endswith(STYLE_GUIDE_MD)]
|
|
730
|
+
if not guides:
|
|
731
|
+
return []
|
|
732
|
+
script = find_tool(VALIDATE_GUIDE_TAGS_PY, BYPASS_TAG_VALIDATOR_SCRIPT)
|
|
733
|
+
if not script:
|
|
734
|
+
return []
|
|
735
|
+
findings = []
|
|
736
|
+
for g in guides:
|
|
737
|
+
_append_finding(findings, _hook_guide_finding(script, g))
|
|
738
|
+
return findings
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def _hook_workflow_findings(files):
|
|
742
|
+
workflows = [f for f in files if ".github/workflows/" in f.replace("\\", "/")]
|
|
743
|
+
if not workflows:
|
|
744
|
+
return []
|
|
745
|
+
script = find_tool(CHECK_CI_CONFIG_PY, CI_CONFIG_CHECK_SCRIPT)
|
|
746
|
+
if not script:
|
|
747
|
+
return []
|
|
748
|
+
code, out = run([sys.executable, str(script), *workflows])
|
|
749
|
+
if code == 0:
|
|
750
|
+
return []
|
|
751
|
+
return ["ST-SEC-15/ST-CI CI config:\n" + out]
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def _hook_pkg_finding(script, pf):
|
|
755
|
+
flag = "--props" if pf.endswith(".props") else "--package-json"
|
|
756
|
+
code, out = run([sys.executable, str(script), flag, pf])
|
|
757
|
+
if code == 0:
|
|
758
|
+
return None
|
|
759
|
+
return f"ST-DEP package health ({pf}):\n" + out
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def _hook_pkg_findings(files):
|
|
763
|
+
pkg_files = [f for f in files if pathlib.Path(f).name in (DIRECTORY_PACKAGES_PROPS, PACKAGE_JSON)]
|
|
764
|
+
if not pkg_files:
|
|
765
|
+
return []
|
|
766
|
+
script = find_tool(CHECK_PACKAGE_HEALTH_PY, HEALTH_GATE_CHECKER_SCRIPT)
|
|
767
|
+
if not script:
|
|
768
|
+
return []
|
|
769
|
+
findings = []
|
|
770
|
+
for pf in pkg_files:
|
|
771
|
+
_append_finding(findings, _hook_pkg_finding(script, pf))
|
|
772
|
+
return findings
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def _nearest_project(f):
|
|
776
|
+
d = pathlib.Path(f).resolve().parent
|
|
777
|
+
while d != d.parent:
|
|
778
|
+
hits = list(d.glob(CSPROJ_GLOB)) + list(d.glob("*.sln"))
|
|
779
|
+
if hits:
|
|
780
|
+
return str(hits[0])
|
|
781
|
+
d = d.parent
|
|
782
|
+
return None
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def _hook_format_finding(cs_files):
|
|
786
|
+
scoped = [f for f in cs_files if _nearest_project(f)]
|
|
787
|
+
if not scoped:
|
|
788
|
+
return None
|
|
789
|
+
code, out = run(["dotnet", "format", "--verify-no-changes", "--include", *scoped])
|
|
790
|
+
if code == 0:
|
|
791
|
+
return None
|
|
792
|
+
return "format (dotnet format):\n" + out[-2000:]
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def _add_build_project(projects, f):
|
|
796
|
+
project = _nearest_project(f)
|
|
797
|
+
if project and project.endswith(".csproj"):
|
|
798
|
+
projects.add(project)
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def _hook_build_finding(proj):
|
|
802
|
+
code, out = run(["dotnet", "build", proj, "--nologo", "-v", "q"])
|
|
803
|
+
if code == 0:
|
|
804
|
+
return None
|
|
805
|
+
return f"build/analyzers ({proj}):\n" + out[-3000:]
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def _hook_build_findings(cs_files):
|
|
809
|
+
if os.environ.get("ZH_HOOK_BUILD") != "1":
|
|
810
|
+
return []
|
|
811
|
+
projects = set()
|
|
812
|
+
for f in cs_files:
|
|
813
|
+
_add_build_project(projects, f)
|
|
814
|
+
findings = []
|
|
815
|
+
for proj in sorted(projects):
|
|
816
|
+
_append_finding(findings, _hook_build_finding(proj))
|
|
817
|
+
return findings
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def _hook_cs_findings(files):
|
|
821
|
+
cs_files = [f for f in files if f.endswith(".cs")]
|
|
822
|
+
if not cs_files:
|
|
823
|
+
return []
|
|
824
|
+
if not shutil.which("dotnet"):
|
|
825
|
+
return []
|
|
826
|
+
findings = []
|
|
827
|
+
_append_finding(findings, _hook_format_finding(cs_files))
|
|
828
|
+
findings += _hook_build_findings(cs_files)
|
|
829
|
+
return findings
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def _hook_ruff_findings(files):
|
|
833
|
+
py_files = [f for f in files if f.endswith(".py")]
|
|
834
|
+
if not py_files or not _module_available("ruff"):
|
|
835
|
+
return []
|
|
836
|
+
code, out = run([sys.executable, "-m", "ruff", "check", *py_files])
|
|
837
|
+
if code == 0:
|
|
838
|
+
return []
|
|
839
|
+
return [line for line in out.splitlines() if line.strip()][:20]
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def _collect_hook_findings(files):
|
|
843
|
+
findings = []
|
|
844
|
+
_append_finding(findings, _hook_chars_finding(files))
|
|
845
|
+
findings += _hook_guide_findings(files)
|
|
846
|
+
findings += _hook_workflow_findings(files)
|
|
847
|
+
findings += _hook_pkg_findings(files)
|
|
848
|
+
findings += _hook_cs_findings(files)
|
|
849
|
+
findings += _hook_ruff_findings(files)
|
|
850
|
+
return findings
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def _report_hook_findings(findings):
|
|
854
|
+
print("SlopThreshold hook: fix these findings before continuing.", file=sys.stderr)
|
|
855
|
+
for f in findings:
|
|
856
|
+
print(f, file=sys.stderr)
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def hook(args):
|
|
860
|
+
"""AI-agent edit hook (Claude Code PostToolUse / Codex / Cursor).
|
|
861
|
+
|
|
862
|
+
Routes deterministic checks by edited file type and reports rule-tagged
|
|
863
|
+
findings on stderr. Exit 2 = findings the agent must fix now (Claude Code
|
|
864
|
+
feeds stderr back to the model); exit 0 = clean. --context prints the
|
|
865
|
+
guide rules that apply to the edited file types (soft enforcement).
|
|
866
|
+
"""
|
|
867
|
+
files = _hook_existing_files(args)
|
|
868
|
+
if args.context:
|
|
869
|
+
_hook_print_context(files)
|
|
870
|
+
return 0
|
|
871
|
+
if not files:
|
|
872
|
+
return 0
|
|
873
|
+
findings = _collect_hook_findings(files)
|
|
874
|
+
if not findings:
|
|
875
|
+
return 0
|
|
876
|
+
_report_hook_findings(findings)
|
|
877
|
+
return 2
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
def doctor(args):
|
|
881
|
+
rows = []
|
|
882
|
+
for tool in ["dotnet", "node", "npx", "gitleaks", "actionlint", "hadolint", "python3"]:
|
|
883
|
+
path = shutil.which(tool)
|
|
884
|
+
version = ""
|
|
885
|
+
if path:
|
|
886
|
+
_, out = run([tool, "--version"])
|
|
887
|
+
version = out.splitlines()[0][:40] if out else ""
|
|
888
|
+
rows.append(result(tool, "pass" if path else "skip", version or "not installed"))
|
|
889
|
+
rows.append(result("guide", "pass" if find_guide() else "skip", find_guide() or "no project guide"))
|
|
890
|
+
rows.append(result("validator", "pass" if find_tool(VALIDATE_GUIDE_TAGS_PY, BYPASS_TAG_VALIDATOR_SCRIPT) else "skip", ""))
|
|
891
|
+
rows.append(result("health", "pass" if find_tool(CHECK_PACKAGE_HEALTH_PY, HEALTH_GATE_CHECKER_SCRIPT) else "skip", ""))
|
|
892
|
+
hook = pathlib.Path(".githooks/pre-commit").is_file()
|
|
893
|
+
rows.append(result("hook", "pass" if hook else "skip", "installed" if hook else "run zh adopt"))
|
|
894
|
+
return emit(rows, args.json)
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
class _HookArgs:
|
|
898
|
+
pass
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
def _hook_args_from_argv(argv):
|
|
902
|
+
# hook parses its own args (files are positionals)
|
|
903
|
+
a = _HookArgs()
|
|
904
|
+
a.context = "--context" in argv
|
|
905
|
+
a.hook_files = [x for x in argv[1:] if not x.startswith("-")]
|
|
906
|
+
a.kind = None
|
|
907
|
+
a.msg_file = None
|
|
908
|
+
return a
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
def _build_parser():
|
|
912
|
+
ap = argparse.ArgumentParser(prog="zh", description="House enforcement commands.")
|
|
913
|
+
ap.add_argument("command", choices=[*GRANULAR, *COMPOSITES, "adopt", "doctor", "hook", "pdf"])
|
|
914
|
+
ap.add_argument("kind", nargs="?", help="adopt kind (app|library|frontend) or msg file path")
|
|
915
|
+
ap.add_argument("--guide", help="project guide path (tags)")
|
|
916
|
+
ap.add_argument("msg_file", nargs="?", help="commit message file (msg)")
|
|
917
|
+
ap.add_argument("--staged", action="store_true", help="scope file checks to staged files")
|
|
918
|
+
ap.add_argument("--fix", action="store_true", help="format: apply fixes instead of verifying")
|
|
919
|
+
ap.add_argument("--json", action="store_true", help="structured summary")
|
|
920
|
+
ap.add_argument("--only", help="comma-separated subset for composites")
|
|
921
|
+
ap.add_argument("--skip", help="comma-separated checks to skip in composites")
|
|
922
|
+
ap.add_argument("--context", action="store_true", help="hook: print applicable guide rules instead of checking")
|
|
923
|
+
ap.add_argument("hook_files", nargs="*", help="hook: edited files (default: hook JSON on stdin)")
|
|
924
|
+
return ap
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
def _run_msg(args):
|
|
928
|
+
args.msg_file = args.kind
|
|
929
|
+
return emit([check_msg(args)], args.json)
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
def _run_adopt(args):
|
|
933
|
+
if args.kind not in ("app", "library", "frontend"):
|
|
934
|
+
args.kind = "app"
|
|
935
|
+
return adopt(args)
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
def _composite_names(args):
|
|
939
|
+
names = COMPOSITES[args.command]
|
|
940
|
+
if args.only:
|
|
941
|
+
names = [n for n in names if n in args.only.split(",")]
|
|
942
|
+
if args.skip:
|
|
943
|
+
names = [n for n in names if n not in args.skip.split(",")]
|
|
944
|
+
return names
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def _dispatch(args):
|
|
948
|
+
if args.command == "pdf":
|
|
949
|
+
return cmd_pdf()
|
|
950
|
+
if args.command == "hook":
|
|
951
|
+
return hook(args)
|
|
952
|
+
if args.command == "msg":
|
|
953
|
+
return _run_msg(args)
|
|
954
|
+
if args.command == "adopt":
|
|
955
|
+
return _run_adopt(args)
|
|
956
|
+
if args.command == "doctor":
|
|
957
|
+
return doctor(args)
|
|
958
|
+
if args.command in GRANULAR:
|
|
959
|
+
return emit([GRANULAR[args.command](args)], args.json)
|
|
960
|
+
names = _composite_names(args)
|
|
961
|
+
return emit([GRANULAR[n](args) for n in names], args.json)
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
def main(argv=None):
|
|
965
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
966
|
+
if argv and argv[0] == "hook":
|
|
967
|
+
return hook(_hook_args_from_argv(argv))
|
|
968
|
+
args = _build_parser().parse_args(argv)
|
|
969
|
+
return _dispatch(args)
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
if __name__ == "__main__":
|
|
973
|
+
raise SystemExit(main())
|