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.
Files changed (44) hide show
  1. slopthreshold/__init__.py +1 -0
  2. slopthreshold/guide/STYLE_GUIDE.md +495 -0
  3. slopthreshold/packs/editorconfig-pack/.editorconfig +899 -0
  4. slopthreshold/packs/editorconfig-pack/Directory.Build.props +47 -0
  5. slopthreshold/packs/editorconfig-pack/Directory.Build.targets +16 -0
  6. slopthreshold/packs/editorconfig-pack/Directory.Packages.props +29 -0
  7. slopthreshold/packs/editorconfig-pack/README.md +141 -0
  8. slopthreshold/packs/editorconfig-pack/global.json +7 -0
  9. slopthreshold/packs/editorconfig-pack/nuget.config +19 -0
  10. slopthreshold/packs/editorconfig-pack/ruff.toml +29 -0
  11. slopthreshold/packs/editorconfig-pack/sonar-drift-allowlist.json +10 -0
  12. slopthreshold/packs/frontend-lint-pack/.prettierrc.json +7 -0
  13. slopthreshold/packs/frontend-lint-pack/.stylelintrc.json +64 -0
  14. slopthreshold/packs/frontend-lint-pack/README.md +64 -0
  15. slopthreshold/packs/frontend-lint-pack/eslint.config.mjs +108 -0
  16. slopthreshold/packs/frontend-lint-pack/package.json +23 -0
  17. slopthreshold/packs/frontend-lint-pack/tsconfig.app.json +17 -0
  18. slopthreshold/packs/frontend-lint-pack/tsconfig.base.json +20 -0
  19. slopthreshold/packs/frontend-lint-pack/tsconfig.json +4 -0
  20. slopthreshold/packs/frontend-lint-pack/tsconfig.spec.json +8 -0
  21. slopthreshold/packs/project-guide-starters/app-STYLE_GUIDE.md +35 -0
  22. slopthreshold/packs/project-guide-starters/frontend-STYLE_GUIDE.md +33 -0
  23. slopthreshold/packs/project-guide-starters/library-STYLE_GUIDE.md +36 -0
  24. slopthreshold/packs/three-layer-wiring/.githooks/commit-msg +13 -0
  25. slopthreshold/packs/three-layer-wiring/.githooks/post-merge +8 -0
  26. slopthreshold/packs/three-layer-wiring/.githooks/pre-commit +10 -0
  27. slopthreshold/packs/three-layer-wiring/.githooks/pre-push +14 -0
  28. slopthreshold/packs/three-layer-wiring/.github/actionlint.yaml +3 -0
  29. slopthreshold/packs/three-layer-wiring/.github/workflows/quality.yml +164 -0
  30. slopthreshold/packs/three-layer-wiring/.gitleaks.toml +16 -0
  31. slopthreshold/packs/three-layer-wiring/.hadolint.yaml +6 -0
  32. slopthreshold/packs/three-layer-wiring/README.md +62 -0
  33. slopthreshold/packs/three-layer-wiring/budget.json +14 -0
  34. slopthreshold/tools/check_characters.py +104 -0
  35. slopthreshold/tools/check_ci_config.py +405 -0
  36. slopthreshold/tools/check_package_health.py +554 -0
  37. slopthreshold/tools/check_sonar_drift.py +1123 -0
  38. slopthreshold/tools/mine_sonar_metrics.py +1259 -0
  39. slopthreshold/tools/validate_guide_tags.py +795 -0
  40. slopthreshold/zh.py +973 -0
  41. slopthreshold-2.1.0.dev22.dist-info/METADATA +49 -0
  42. slopthreshold-2.1.0.dev22.dist-info/RECORD +44 -0
  43. slopthreshold-2.1.0.dev22.dist-info/WHEEL +4 -0
  44. slopthreshold-2.1.0.dev22.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,1259 @@
1
+ #!/usr/bin/env python3
2
+ """Re-mine SonarQube rule-repeat metrics for the style-guide metrics loop.
3
+
4
+ Mines the house projects on sonar.hassanragai.dev via
5
+ ``/api/issues/search?facets=rules`` (open and resolved separately), aggregates
6
+ counts per rule, and writes:
7
+
8
+ * ``snapshots/YYYY-MM-DD.json`` - dated machine-readable snapshot
9
+ (per-project + totals per rule, open/resolved split).
10
+ * ``reports/YYYY-MM-DD.md`` - dated human report: top repeated rules,
11
+ trend vs the previous snapshot (deltas, new rules, rules gone quiet),
12
+ and severity-tuning suggestions cross-referenced against
13
+ ``editorconfig-pack/.editorconfig``.
14
+
15
+ Authentication follows the custom.sonarqube connector pattern: the stored
16
+ credential is attached via the dynamic-credentials surrogate helper; no
17
+ secret ever appears in this file, in arguments, or in output. A browser
18
+ User-Agent is sent because Cloudflare in front of the server bans the
19
+ default Python-urllib signature (Error 1010).
20
+
21
+ Pure aggregation/trend/suggestion logic is importable and unit-tested
22
+ without network access (see test_mine_sonar_metrics.py). Network imports
23
+ are lazy so importing this module never touches credentials.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import re
31
+ import os
32
+ import sys
33
+ from collections import defaultdict
34
+ from dataclasses import dataclass
35
+ from datetime import datetime, timezone
36
+ from pathlib import Path
37
+
38
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
39
+ from safe_paths import read_text_under, resolve_under # noqa: E402
40
+ from http_util import open_https # noqa: E402
41
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
42
+
43
+ BASE_URL = "https://sonar.hassanragai.dev"
44
+ CONNECTOR_NAME = "custom.sonarqube"
45
+ BROWSER_UA = (
46
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
47
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
48
+ )
49
+
50
+ # House projects (keys verified against the live server).
51
+ PROJECTS: Dict[str, str] = {
52
+ "Essentials": "ZHEAISNSAABN_ZhEaIsNsAaBn.Essentials_46150f9b-9ffd-49a9-96d1-3241c6e39fd0",
53
+ "Libraries.V1": "ZHEAISNSAABN_ZhEaIsNsAaBn.Libraries.V1_0acb29d0-de5a-4470-8561-ba6218da007b",
54
+ "MarketPulse": "ZHEAISNSAABN_ZhEaIsNsAaBn.MarketPulse_294a1803-0b28-4363-bd29-bb25f32f9158",
55
+ "Sql": "ZHEAISNSAABN_ZhEaIsNsAaBn.Sql_706d02f9-2a15-4408-a166-5278b47aaaf7",
56
+ "SlopThreshold": "ZHEAISNSAABN_ZhEaIsNsAaBn.SlopThreshold_760b21a8-586b-4ab6-ad71-ef03efbb0272",
57
+ }
58
+
59
+ # Original mining baseline (2026-12-02, open + resolved across the four
60
+ # projects), from editorconfig-pack/README.md. Keyed by short rule id.
61
+ # Used only as a reference column in reports, never in trend maths.
62
+ BASELINE_DATE = "2026-12-02"
63
+ BASELINE_COUNTS: Dict[str, int] = {
64
+ "S2306": 82, "S6966": 51, "IDE0022": 20, "S3776": 16, "S3358": 16,
65
+ "CA1031": 16, "S107": 14, "S4136": 12, "IDE0028": 8, "S2326": 8,
66
+ "IDE0007": 7, "S101": 6, "S1192": 6, "S1135": 5, "S3267": 4,
67
+ "S2743": 4, "S8969": 4, "S2365": 4, "S3871": 3, "SYSLIB1045": 3,
68
+ "S6471": 3, "S3011": 2, "S2436": 2, "CA1716": 2, "S6562": 2,
69
+ "S6444": 2, "S3220": 2, "S127": 2, "S3604": 2, "CA1304": 2,
70
+ "S7636": 2, "S125": 1, "S2245": 1, "S2178": 1, "S3218": 1,
71
+ "S3875": 1, "S2583": 1, "S2589": 1, "S1751": 1, "S1481": 1,
72
+ "S3398": 1, "S4035": 1, "S3878": 1, "S6672": 1, "IDE0021": 1,
73
+ "CS9236": 1,
74
+ # README lists githubactions S8233/S8264 combined as 3; split 2/1 per
75
+ # the same-day live re-mine (all other baseline counts matched exactly).
76
+ "S8233": 2, "S8264": 1,
77
+ }
78
+
79
+ # Baseline shorts that belong to non-.NET repos (docker / GitHub Actions).
80
+ # Baseline comparison aggregates current counts by short id over .NET rules
81
+ # plus these, so e.g. githubactions:S1135 does not inflate csharpsquid:S1135.
82
+ NON_DOTNET_BASELINE_SHORTS = {"S6471", "S7636", "S8233", "S8264"}
83
+
84
+ # Suggestion thresholds (see make_suggestions).
85
+ ADD_MIN_TOTAL = 3 # repeats at/above this, not in the pack -> add candidate
86
+ ADD_MIN_DELTA = 2 # rising by at least this since previous snapshot -> add candidate
87
+ ADD_NEW_MIN_TOTAL = 2 # brand-new rule with at least this many hits -> add candidate
88
+
89
+ DOTNET_RULE_REPOS = {"csharpsquid", "external_roslyn"}
90
+
91
+ NONE_BULLET = "- None."
92
+
93
+
94
+ # --------------------------------------------------------------------------
95
+ # Rule-id helpers
96
+ # --------------------------------------------------------------------------
97
+
98
+ def short_rule_id(rule_key: str) -> str:
99
+ """'csharpsquid:S2306' -> 'S2306'; 'docker:S6471' -> 'S6471'."""
100
+ return rule_key.rsplit(":", 1)[-1]
101
+
102
+
103
+ def rule_repo(rule_key: str) -> str:
104
+ """'csharpsquid:S2306' -> 'csharpsquid'."""
105
+ return rule_key.rsplit(":", 1)[0] if ":" in rule_key else ""
106
+
107
+
108
+ def is_dotnet_rule(rule_key: str) -> bool:
109
+ """True when the rule can be governed by a .editorconfig diagnostic severity."""
110
+ repo = rule_repo(rule_key)
111
+ return repo in DOTNET_RULE_REPOS or repo.startswith("roslyn")
112
+
113
+
114
+ # --------------------------------------------------------------------------
115
+ # Pure parsing / aggregation logic (no network)
116
+ # --------------------------------------------------------------------------
117
+
118
+ def parse_facet_rules(payload: Dict[str, Any]) -> Tuple[Dict[str, int], int, int]:
119
+ """Extract per-rule counts from an /api/issues/search facets payload.
120
+
121
+ Returns (counts, paging_total, facet_sum). Callers compare paging_total
122
+ with facet_sum as an integrity check: if they differ the facet was
123
+ truncated and counts must be rebuilt by paging the issues themselves.
124
+ """
125
+ counts: Dict[str, int] = {}
126
+ facet_sum = 0
127
+ for facet in payload.get("facets", []):
128
+ if facet.get("property") == "rules":
129
+ for value in facet.get("values", []):
130
+ rule = value.get("val")
131
+ count = int(value.get("count", 0))
132
+ if rule:
133
+ counts[rule] = counts.get(rule, 0) + count
134
+ facet_sum += count
135
+ paging_total = int(payload.get("paging", {}).get("total", payload.get("total", 0)))
136
+ return counts, paging_total, facet_sum
137
+
138
+
139
+ def count_rules_from_issues(issues: Iterable[Dict[str, Any]]) -> Dict[str, int]:
140
+ """Fallback counter: tally the 'rule' field of raw issue objects."""
141
+ counts: Dict[str, int] = defaultdict(int)
142
+ for issue in issues:
143
+ rule = issue.get("rule")
144
+ if rule:
145
+ counts[rule] += 1
146
+ return dict(counts)
147
+
148
+
149
+ _DIAGNOSTIC_RE = re.compile(
150
+ r"^\s*dotnet_diagnostic\.([A-Za-z0-9]+)\.severity\s*=\s*(\w+)", re.MULTILINE
151
+ )
152
+
153
+
154
+ def _style_severity(text: str, key: str) -> Optional[str]:
155
+ match = re.search(rf"^\s*{re.escape(key)}\s*=\s*[^:\n]+:(\w+)", text, re.MULTILINE)
156
+ return match.group(1).lower() if match else None
157
+
158
+
159
+ def parse_editorconfig_severities(text: str) -> Dict[str, str]:
160
+ """Parse rule severities declared in an .editorconfig file.
161
+
162
+ Primary source: ``dotnet_diagnostic.<RULE>.severity`` lines. A few IDE
163
+ rules are governed by style-preference keys instead of diagnostics, so
164
+ they are mapped synthetically when those keys are present:
165
+
166
+ * IDE0022 / IDE0021 <- csharp_style_expression_bodied_methods/_constructors
167
+ * IDE0007 <- csharp_style_var_* keys
168
+ * IDE0028 <- dotnet_style_prefer_collection_expression
169
+ (fallback: dotnet_style_collection_initializer)
170
+
171
+ Returns {short_rule_id: severity} with severity in
172
+ error|warning|suggestion|silent|none|default (as written, lower-cased).
173
+ """
174
+ severities: Dict[str, str] = {}
175
+ for rule, severity in _DIAGNOSTIC_RE.findall(text):
176
+ severities[rule] = severity.lower()
177
+
178
+ synthetic = {
179
+ "IDE0022": _style_severity(text, "csharp_style_expression_bodied_methods"),
180
+ "IDE0021": _style_severity(text, "csharp_style_expression_bodied_constructors"),
181
+ "IDE0007": _style_severity(text, "csharp_style_var_for_built_in_types")
182
+ or _style_severity(text, "csharp_style_var_when_type_is_apparent"),
183
+ "IDE0028": _style_severity(text, "dotnet_style_prefer_collection_expression")
184
+ or _style_severity(text, "dotnet_style_collection_initializer"),
185
+ }
186
+ for rule, severity in synthetic.items():
187
+ if severity and rule not in severities:
188
+ severities[rule] = severity
189
+ return severities
190
+
191
+
192
+ def aggregate_counts(
193
+ per_project: Dict[str, Dict[str, Dict[str, int]]]
194
+ ) -> Dict[str, Dict[str, Any]]:
195
+ """Aggregate {project: {open|resolved: {rule: count}}} into per-rule totals.
196
+
197
+ Returns {rule_key: {open, resolved, total, projects: {name: {open, resolved}}}}.
198
+ """
199
+ totals: Dict[str, Dict[str, Any]] = {}
200
+ for project, split in per_project.items():
201
+ for state in ("open", "resolved"):
202
+ for rule, count in split.get(state, {}).items():
203
+ entry = totals.setdefault(
204
+ rule, {"open": 0, "resolved": 0, "total": 0, "projects": {}}
205
+ )
206
+ entry[state] += int(count)
207
+ entry["total"] += int(count)
208
+ proj = entry["projects"].setdefault(project, {"open": 0, "resolved": 0})
209
+ proj[state] += int(count)
210
+ return totals
211
+
212
+
213
+ @dataclass
214
+ class SnapshotData:
215
+ """Mined inputs for one snapshot (counts, keys, rule metadata)."""
216
+
217
+ per_project: Dict[str, Dict[str, Dict[str, int]]]
218
+ project_keys: Dict[str, str]
219
+ rule_metadata: Dict[str, Dict[str, str]]
220
+ editorconfig_severities: Dict[str, str]
221
+
222
+
223
+ @dataclass
224
+ class SnapshotMeta:
225
+ """Provenance recorded beside the mined counts in a snapshot."""
226
+
227
+ editorconfig_path: str = ""
228
+ server: Optional[Dict[str, str]] = None
229
+ mining_meta: Optional[Dict[str, Any]] = None
230
+ generated_at: Optional[str] = None
231
+
232
+
233
+ def build_snapshot(date: str, data: SnapshotData, meta: Optional[SnapshotMeta] = None) -> Dict[str, Any]:
234
+ """Assemble the dated snapshot document (see README for the schema)."""
235
+ meta = meta or SnapshotMeta()
236
+ per_rule = aggregate_counts(data.per_project)
237
+ projects_doc: Dict[str, Any] = {}
238
+ for project, split in data.per_project.items():
239
+ open_counts = dict(sorted(split.get("open", {}).items()))
240
+ resolved_counts = dict(sorted(split.get("resolved", {}).items()))
241
+ projects_doc[project] = {
242
+ "key": data.project_keys.get(project, ""),
243
+ "open": open_counts,
244
+ "resolved": resolved_counts,
245
+ "totals": {
246
+ "open": sum(open_counts.values()),
247
+ "resolved": sum(resolved_counts.values()),
248
+ "total": sum(open_counts.values()) + sum(resolved_counts.values()),
249
+ "distinct_rules": len(set(open_counts) | set(resolved_counts)),
250
+ },
251
+ }
252
+ totals_doc = {
253
+ "open": sum(e["open"] for e in per_rule.values()),
254
+ "resolved": sum(e["resolved"] for e in per_rule.values()),
255
+ "total": sum(e["total"] for e in per_rule.values()),
256
+ "distinct_rules": len(per_rule),
257
+ "per_rule": {
258
+ rule: {
259
+ "short_id": short_rule_id(rule),
260
+ "repo": rule_repo(rule),
261
+ "name": data.rule_metadata.get(rule, {}).get("name", short_rule_id(rule)),
262
+ "sonar_severity": data.rule_metadata.get(rule, {}).get("severity", ""),
263
+ "sonar_type": data.rule_metadata.get(rule, {}).get("type", ""),
264
+ "open": entry["open"],
265
+ "resolved": entry["resolved"],
266
+ "total": entry["total"],
267
+ "projects": entry["projects"],
268
+ }
269
+ for rule, entry in sorted(per_rule.items())
270
+ },
271
+ }
272
+ return {
273
+ "schema_version": 1,
274
+ "date": date,
275
+ "generated_at_utc": meta.generated_at
276
+ or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
277
+ "server": meta.server or {"base_url": BASE_URL, "version": "", "status": ""},
278
+ "projects": projects_doc,
279
+ "totals": totals_doc,
280
+ "editorconfig": {
281
+ "path": meta.editorconfig_path,
282
+ "severities": dict(sorted(data.editorconfig_severities.items())),
283
+ },
284
+ "baseline_reference": {"date": BASELINE_DATE, "counts_by_short_id": BASELINE_COUNTS},
285
+ "mining": meta.mining_meta or {},
286
+ }
287
+
288
+
289
+ def _per_rule(snapshot: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
290
+ return snapshot.get("totals", {}).get("per_rule", {})
291
+
292
+
293
+ def compute_trend(
294
+ current: Dict[str, Any], previous: Optional[Dict[str, Any]]
295
+ ) -> Dict[str, Any]:
296
+ """Compare two snapshots.
297
+
298
+ Returns previous_date (None on the first run), per-rule deltas, the list
299
+ of new rules (present now, absent/zero before), rules gone quiet (had
300
+ open issues before, none now), disappeared rules, and rising/falling
301
+ rule lists sorted by total delta.
302
+ """
303
+ curr = _per_rule(current)
304
+ if previous is None:
305
+ return {
306
+ "previous_date": None,
307
+ "deltas": {},
308
+ "new_rules": [],
309
+ "gone_quiet": [],
310
+ "disappeared": [],
311
+ "rising": [],
312
+ "falling": [],
313
+ }
314
+ prev = _per_rule(previous)
315
+ deltas: Dict[str, Dict[str, int]] = {}
316
+ new_rules: List[str] = []
317
+ gone_quiet: List[str] = []
318
+ disappeared: List[str] = []
319
+ for rule in sorted(set(curr) | set(prev)):
320
+ c = curr.get(rule, {"open": 0, "resolved": 0, "total": 0})
321
+ p = prev.get(rule, {"open": 0, "resolved": 0, "total": 0})
322
+ deltas[rule] = {
323
+ "open_delta": c["open"] - p["open"],
324
+ "resolved_delta": c["resolved"] - p["resolved"],
325
+ "total_delta": c["total"] - p["total"],
326
+ "current_open": c["open"],
327
+ "current_total": c["total"],
328
+ "previous_open": p["open"],
329
+ "previous_total": p["total"],
330
+ }
331
+ if c["total"] > 0 and p["total"] == 0:
332
+ new_rules.append(rule)
333
+ if p["open"] > 0 and c["open"] == 0:
334
+ gone_quiet.append(rule)
335
+ if p["total"] > 0 and c["total"] == 0:
336
+ disappeared.append(rule)
337
+ rising = sorted(
338
+ (r for r, d in deltas.items() if d["total_delta"] > 0),
339
+ key=lambda r: (-deltas[r]["total_delta"], r),
340
+ )
341
+ falling = sorted(
342
+ (r for r, d in deltas.items() if d["total_delta"] < 0),
343
+ key=lambda r: (deltas[r]["total_delta"], r),
344
+ )
345
+ return {
346
+ "previous_date": previous.get("date"),
347
+ "deltas": deltas,
348
+ "new_rules": new_rules,
349
+ "gone_quiet": gone_quiet,
350
+ "disappeared": disappeared,
351
+ "rising": rising,
352
+ "falling": falling,
353
+ }
354
+
355
+
356
+ def _suggested_severity(entry: Dict[str, Any]) -> str:
357
+ sonar_sev = (entry.get("sonar_severity") or "").upper()
358
+ if sonar_sev in ("BLOCKER", "CRITICAL"):
359
+ return "error"
360
+ if sonar_sev == "MAJOR":
361
+ return "warning"
362
+ return "warning" if entry.get("total", 0) >= 5 else "suggestion"
363
+
364
+
365
+ def _index_by_short(
366
+ per_rule: Dict[str, Dict[str, Any]]
367
+ ) -> Dict[str, Dict[str, int]]:
368
+ by_short: Dict[str, Dict[str, int]] = defaultdict(
369
+ lambda: {"open": 0, "resolved": 0, "total": 0}
370
+ )
371
+ for rule, entry in per_rule.items():
372
+ bucket = by_short[short_rule_id(rule)]
373
+ bucket["open"] += entry["open"]
374
+ bucket["resolved"] += entry["resolved"]
375
+ bucket["total"] += entry["total"]
376
+ return by_short
377
+
378
+
379
+ def _short_deltas(
380
+ deltas: Dict[str, Dict[str, int]], short: str
381
+ ) -> Tuple[int, int]:
382
+ total_delta = sum(
383
+ d["total_delta"] for r, d in deltas.items() if short_rule_id(r) == short
384
+ )
385
+ open_delta = sum(
386
+ d["open_delta"] for r, d in deltas.items() if short_rule_id(r) == short
387
+ )
388
+ return total_delta, open_delta
389
+
390
+
391
+ def _relax_candidate_with_previous(
392
+ short: str,
393
+ severity: str,
394
+ counts: Dict[str, int],
395
+ deltas: Dict[str, Dict[str, int]],
396
+ previous_date: Any,
397
+ ) -> Optional[Dict[str, Any]]:
398
+ total_delta, open_delta = _short_deltas(deltas, short)
399
+ if total_delta > 0 or open_delta > 0 or counts["open"] != 0:
400
+ return None
401
+ return {
402
+ "rule": short,
403
+ "severity": severity,
404
+ "open": counts["open"],
405
+ "total": counts["total"],
406
+ "total_delta": total_delta,
407
+ "reason": (
408
+ f"zero new hits since {previous_date} and no open "
409
+ f"issues remain (total delta {total_delta:+d}, open delta "
410
+ f"{open_delta:+d}); candidate to relax one step - suggestion only"
411
+ ),
412
+ }
413
+
414
+
415
+ def _relax_candidate_first(
416
+ short: str, severity: str, counts: Dict[str, int]
417
+ ) -> Optional[Dict[str, Any]]:
418
+ if counts["total"] != 0:
419
+ return None
420
+ return {
421
+ "rule": short,
422
+ "severity": severity,
423
+ "open": 0,
424
+ "total": 0,
425
+ "total_delta": None,
426
+ "reason": (
427
+ "never fired in the mined set; provisional relax "
428
+ "candidate (no previous snapshot yet - weak signal)"
429
+ ),
430
+ }
431
+
432
+
433
+ def _relax_candidates(
434
+ editorconfig_severities: Dict[str, str],
435
+ by_short: Dict[str, Dict[str, int]],
436
+ deltas: Dict[str, Dict[str, int]],
437
+ has_previous: bool,
438
+ previous_date: Any,
439
+ ) -> List[Dict[str, Any]]:
440
+ relax: List[Dict[str, Any]] = []
441
+ for short, severity in sorted(editorconfig_severities.items()):
442
+ if severity not in ("error", "warning"):
443
+ continue
444
+ counts = by_short.get(short, {"open": 0, "resolved": 0, "total": 0})
445
+ if has_previous:
446
+ candidate = _relax_candidate_with_previous(
447
+ short, severity, counts, deltas, previous_date
448
+ )
449
+ else:
450
+ candidate = _relax_candidate_first(short, severity, counts)
451
+ if candidate is not None:
452
+ relax.append(candidate)
453
+ return relax
454
+
455
+
456
+ def _qualifies_for_add(
457
+ rule: str,
458
+ entry: Dict[str, Any],
459
+ delta: Optional[int],
460
+ new_rules: Any,
461
+ ) -> bool:
462
+ return (
463
+ entry["total"] >= ADD_MIN_TOTAL
464
+ or (delta is not None and delta >= ADD_MIN_DELTA)
465
+ or (rule in new_rules and entry["total"] >= ADD_NEW_MIN_TOTAL)
466
+ )
467
+
468
+
469
+ def _add_candidate(
470
+ rule: str,
471
+ entry: Dict[str, Any],
472
+ delta: Optional[int],
473
+ new_rules: Any,
474
+ ) -> Dict[str, Any]:
475
+ short = short_rule_id(rule)
476
+ if is_dotnet_rule(rule):
477
+ suggested = _suggested_severity(entry)
478
+ handling = (
479
+ f"add `dotnet_diagnostic.{short}.severity = {suggested}` "
480
+ "to editorconfig-pack"
481
+ )
482
+ else:
483
+ handling = (
484
+ "not a .editorconfig diagnostic - handle via the "
485
+ "Dockerfile/CI snippets in editorconfig-pack/README.md"
486
+ )
487
+ suggested = ""
488
+ return {
489
+ "rule": rule,
490
+ "short_id": short,
491
+ "name": entry.get("name", short),
492
+ "open": entry["open"],
493
+ "total": entry["total"],
494
+ "total_delta": delta,
495
+ "is_new": rule in new_rules,
496
+ "suggested_severity": suggested,
497
+ "handling": handling,
498
+ }
499
+
500
+
501
+ def _still_firing_reason(
502
+ has_previous: bool, delta: Optional[int], previous_date: Any
503
+ ) -> str:
504
+ if has_previous and delta is not None and delta > 0:
505
+ return (
506
+ f"{delta:+d} new hits since {previous_date} despite "
507
+ "local error severity - pack not adopted or profile drift - investigate"
508
+ )
509
+ if has_previous:
510
+ return (
511
+ "open backlog remains but no new hits since "
512
+ f"{previous_date} - may be pre-pack legacy; "
513
+ "pack not adopted or profile drift - investigate"
514
+ )
515
+ return (
516
+ "open issues exist despite local error severity - may be "
517
+ "pre-pack legacy; pack not adopted or profile drift - investigate"
518
+ )
519
+
520
+
521
+ def _still_firing_candidate(
522
+ rule: str,
523
+ entry: Dict[str, Any],
524
+ severity: str,
525
+ delta: Optional[int],
526
+ has_previous: bool,
527
+ previous_date: Any,
528
+ ) -> Dict[str, Any]:
529
+ short = short_rule_id(rule)
530
+ return {
531
+ "rule": rule,
532
+ "short_id": short,
533
+ "name": entry.get("name", short),
534
+ "severity": severity,
535
+ "open": entry["open"],
536
+ "total": entry["total"],
537
+ "total_delta": delta,
538
+ "reason": _still_firing_reason(has_previous, delta, previous_date),
539
+ }
540
+
541
+
542
+ def _add_and_still_firing(
543
+ per_rule: Dict[str, Dict[str, Any]],
544
+ editorconfig_severities: Dict[str, str],
545
+ deltas: Dict[str, Dict[str, int]],
546
+ new_rules: Any,
547
+ has_previous: bool,
548
+ previous_date: Any,
549
+ ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
550
+ add: List[Dict[str, Any]] = []
551
+ still_firing: List[Dict[str, Any]] = []
552
+ for rule, entry in sorted(
553
+ per_rule.items(), key=lambda kv: (-kv[1]["total"], kv[0])
554
+ ):
555
+ short = short_rule_id(rule)
556
+ severity = editorconfig_severities.get(short)
557
+ delta = deltas.get(rule, {}).get("total_delta")
558
+ if severity is None:
559
+ if _qualifies_for_add(rule, entry, delta, new_rules):
560
+ add.append(_add_candidate(rule, entry, delta, new_rules))
561
+ elif severity == "error" and entry["open"] > 0:
562
+ still_firing.append(
563
+ _still_firing_candidate(
564
+ rule, entry, severity, delta, has_previous, previous_date
565
+ )
566
+ )
567
+ return add, still_firing
568
+
569
+
570
+ def make_suggestions(
571
+ snapshot: Dict[str, Any],
572
+ trend: Dict[str, Any],
573
+ editorconfig_severities: Dict[str, str],
574
+ ) -> Dict[str, List[Dict[str, Any]]]:
575
+ """Severity-tuning suggestions. All output is advisory (suggestion only).
576
+
577
+ * relax_candidates - rules the pack already governs at error/warning
578
+ with zero new hits and no open issues remaining: with a previous
579
+ snapshot that means total and open deltas <= 0 and open == 0 now; on
580
+ the first snapshot it means the rule never fired at all in the mined
581
+ set (weak signal, labelled provisional).
582
+ * add_candidates - repeated rules the pack does not govern yet:
583
+ total >= ADD_MIN_TOTAL, or rising by >= ADD_MIN_DELTA, or brand new
584
+ with >= ADD_NEW_MIN_TOTAL hits. Non-.NET rules (docker, GitHub
585
+ Actions, ...) get a handling note instead of an editorconfig severity.
586
+ * still_firing - rules governed locally at *error* that still have
587
+ open Sonar issues: "pack not adopted or profile drift - investigate".
588
+ """
589
+ per_rule = _per_rule(snapshot)
590
+ deltas = trend.get("deltas", {})
591
+ has_previous = trend.get("previous_date") is not None
592
+ new_rules = set(trend.get("new_rules", []))
593
+ previous_date = trend.get("previous_date")
594
+ by_short = _index_by_short(per_rule)
595
+ relax = _relax_candidates(
596
+ editorconfig_severities, by_short, deltas, has_previous, previous_date
597
+ )
598
+ add, still_firing = _add_and_still_firing(
599
+ per_rule,
600
+ editorconfig_severities,
601
+ deltas,
602
+ new_rules,
603
+ has_previous,
604
+ previous_date,
605
+ )
606
+ return {
607
+ "relax_candidates": relax,
608
+ "add_candidates": add,
609
+ "still_firing": still_firing,
610
+ }
611
+
612
+ # --------------------------------------------------------------------------
613
+ # Report rendering
614
+ # --------------------------------------------------------------------------
615
+
616
+ def _md(text: Any) -> str:
617
+ return str(text).replace("|", "\\|")
618
+
619
+
620
+ def _fmt_delta(value: Optional[int]) -> str:
621
+ return "-" if value is None else f"{value:+d}"
622
+
623
+
624
+ def _report_header_lines(snapshot: Dict[str, Any]) -> List[str]:
625
+ server = snapshot.get("server", {})
626
+ generated = (
627
+ f"Generated {snapshot.get('generated_at_utc', '')} - server "
628
+ f"{server.get('base_url', BASE_URL)} (version {server.get('version') or 'unknown'}, "
629
+ f"status {server.get('status') or 'unknown'}) - method: "
630
+ "`/api/issues/search?facets=rules`, open and resolved mined separately."
631
+ )
632
+ return [f"# SonarQube metrics - {snapshot['date']}", "", generated, ""]
633
+
634
+
635
+ def _headline_lines(
636
+ snapshot: Dict[str, Any], totals: Dict[str, Any]
637
+ ) -> List[str]:
638
+ lines: List[str] = [
639
+ "## Headline numbers",
640
+ "",
641
+ "| Project | Open | Resolved | Total | Distinct rules |",
642
+ "|---|---:|---:|---:|---:|",
643
+ ]
644
+ for project, doc in snapshot["projects"].items():
645
+ t = doc["totals"]
646
+ lines.append(
647
+ f"| {_md(project)} | {t['open']} | {t['resolved']} | {t['total']} | {t['distinct_rules']} |"
648
+ )
649
+ lines.append(
650
+ f"| **All projects** | **{totals['open']}** | **{totals['resolved']}** | "
651
+ f"**{totals['total']}** | **{totals['distinct_rules']}** |"
652
+ )
653
+ lines.append("")
654
+ return lines
655
+
656
+
657
+ def _top_rules_lines(
658
+ per_rule: Dict[str, Dict[str, Any]],
659
+ severities: Dict[str, str],
660
+ deltas: Dict[str, Dict[str, int]],
661
+ has_previous: bool,
662
+ top_n: int,
663
+ ) -> List[str]:
664
+ lines: List[str] = [
665
+ f"## Top repeated rules (top {top_n} by total)",
666
+ "",
667
+ "| # | Rule | Name | Open | Resolved | Total | \u0394 total vs prev | editorconfig-pack | Projects |",
668
+ "|---:|---|---|---:|---:|---:|---:|---|---|",
669
+ ]
670
+ ranked = sorted(per_rule.items(), key=lambda kv: (-kv[1]["total"], kv[0]))
671
+ for idx, (rule, entry) in enumerate(ranked[:top_n], start=1):
672
+ severity = severities.get(short_rule_id(rule), "-")
673
+ projects = ", ".join(
674
+ f"{name} ({p['open']}+{p['resolved']})"
675
+ for name, p in sorted(entry["projects"].items())
676
+ )
677
+ delta = deltas.get(rule, {}).get("total_delta") if has_previous else None
678
+ lines.append(
679
+ f"| {idx} | {_md(rule)} | {_md(entry.get('name', ''))} | {entry['open']} | "
680
+ f"{entry['resolved']} | {entry['total']} | {_fmt_delta(delta)} | {severity} | {_md(projects)} |"
681
+ )
682
+ lines.append("")
683
+ return lines
684
+
685
+
686
+ def _trend_changed_lines(deltas: Dict[str, Dict[str, int]]) -> List[str]:
687
+ changed = [
688
+ (rule, deltas[rule])
689
+ for rule in sorted(deltas, key=lambda r: (-abs(deltas[r]["total_delta"]), r))
690
+ if deltas[rule]["total_delta"] != 0 or deltas[rule]["open_delta"] != 0
691
+ ]
692
+ if not changed:
693
+ return ["No rule changed since the previous snapshot.", ""]
694
+ lines: List[str] = [
695
+ "| Rule | \u0394 open | \u0394 resolved | \u0394 total | Open now | Total now |",
696
+ "|---|---:|---:|---:|---:|---:|",
697
+ ]
698
+ for rule, d in changed:
699
+ lines.append(
700
+ f"| {_md(rule)} | {_fmt_delta(d['open_delta'])} | {_fmt_delta(d['resolved_delta'])} | "
701
+ f"{_fmt_delta(d['total_delta'])} | {d['current_open']} | {d['current_total']} |"
702
+ )
703
+ lines.append("")
704
+ return lines
705
+
706
+
707
+ def _trend_new_rules_lines(
708
+ trend: Dict[str, Any], per_rule: Dict[str, Dict[str, Any]]
709
+ ) -> List[str]:
710
+ lines: List[str] = ["### New rules appearing", ""]
711
+ if trend["new_rules"]:
712
+ for rule in trend["new_rules"]:
713
+ e = per_rule[rule]
714
+ lines.append(
715
+ f"- `{rule}` - {_md(e.get('name', ''))}: {e['total']} hits "
716
+ f"({e['open']} open, {e['resolved']} resolved)"
717
+ )
718
+ else:
719
+ lines.append(NONE_BULLET)
720
+ lines.append("")
721
+ return lines
722
+
723
+
724
+ def _trend_gone_quiet_lines(
725
+ trend: Dict[str, Any], deltas: Dict[str, Dict[str, int]]
726
+ ) -> List[str]:
727
+ lines: List[str] = ["### Rules gone quiet", ""]
728
+ if trend["gone_quiet"]:
729
+ for rule in trend["gone_quiet"]:
730
+ d = deltas[rule]
731
+ lines.append(
732
+ f"- `{rule}` - open {d['previous_open']} -> 0 "
733
+ f"(total {d['previous_total']} -> {d['current_total']})"
734
+ )
735
+ else:
736
+ lines.append(NONE_BULLET)
737
+ lines.append("")
738
+ return lines
739
+
740
+
741
+ def _trend_disappeared_lines(
742
+ trend: Dict[str, Any], deltas: Dict[str, Dict[str, int]]
743
+ ) -> List[str]:
744
+ if not trend["disappeared"]:
745
+ return []
746
+ lines: List[str] = ["### Rules no longer present at all", ""]
747
+ for rule in trend["disappeared"]:
748
+ lines.append(f"- `{rule}` (was {deltas[rule]['previous_total']} total)")
749
+ lines.append("")
750
+ return lines
751
+
752
+
753
+ def _trend_lines(
754
+ trend: Dict[str, Any],
755
+ per_rule: Dict[str, Dict[str, Any]],
756
+ deltas: Dict[str, Dict[str, int]],
757
+ has_previous: bool,
758
+ ) -> List[str]:
759
+ lines: List[str] = ["## Trend vs previous snapshot", ""]
760
+ if not has_previous:
761
+ lines.append(
762
+ "No previous snapshot exists yet - this run is the baseline for "
763
+ "future trend comparisons. Deltas, new-rule and gone-quiet "
764
+ "sections start with the next run."
765
+ )
766
+ lines.append("")
767
+ return lines
768
+ lines.append(f"Previous snapshot: **{trend['previous_date']}**.")
769
+ lines.append("")
770
+ lines.extend(_trend_changed_lines(deltas))
771
+ lines.extend(_trend_new_rules_lines(trend, per_rule))
772
+ lines.extend(_trend_gone_quiet_lines(trend, deltas))
773
+ lines.extend(_trend_disappeared_lines(trend, deltas))
774
+ return lines
775
+
776
+
777
+ def _relax_table_lines(items: List[Dict[str, Any]]) -> List[str]:
778
+ if not items:
779
+ return [NONE_BULLET, ""]
780
+ lines: List[str] = [
781
+ "| Rule | Current severity | Open | Total | \u0394 total | Why |",
782
+ "|---|---|---:|---:|---:|---|",
783
+ ]
784
+ for item in items:
785
+ lines.append(
786
+ f"| {item['rule']} | {item['severity']} | {item['open']} | {item['total']} | "
787
+ f"{_fmt_delta(item['total_delta'])} | {_md(item['reason'])} |"
788
+ )
789
+ lines.append("")
790
+ return lines
791
+
792
+
793
+ def _add_table_lines(items: List[Dict[str, Any]]) -> List[str]:
794
+ if not items:
795
+ return [NONE_BULLET, ""]
796
+ lines: List[str] = [
797
+ "| Rule | Name | Open | Total | \u0394 total | Suggested severity | Handling |",
798
+ "|---|---|---:|---:|---:|---|---|",
799
+ ]
800
+ for item in items:
801
+ lines.append(
802
+ f"| {_md(item['rule'])} | {_md(item['name'])} | {item['open']} | {item['total']} | "
803
+ f"{_fmt_delta(item['total_delta'])} | {item['suggested_severity'] or '-'} | {_md(item['handling'])} |"
804
+ )
805
+ lines.append("")
806
+ return lines
807
+
808
+
809
+ def _still_firing_table_lines(items: List[Dict[str, Any]]) -> List[str]:
810
+ if not items:
811
+ return ["- None. No error-severity rule has open issues.", ""]
812
+ lines: List[str] = [
813
+ "| Rule | Name | Open | Total | \u0394 total | Assessment |",
814
+ "|---|---|---:|---:|---:|---|",
815
+ ]
816
+ for item in items:
817
+ lines.append(
818
+ f"| {_md(item['rule'])} | {_md(item['name'])} | {item['open']} | {item['total']} | "
819
+ f"{_fmt_delta(item['total_delta'])} | {_md(item['reason'])} |"
820
+ )
821
+ lines.append("")
822
+ return lines
823
+
824
+
825
+ def _suggestions_lines(
826
+ suggestions: Dict[str, List[Dict[str, Any]]]
827
+ ) -> List[str]:
828
+ lines: List[str] = [
829
+ "## Severity-tuning suggestions",
830
+ "",
831
+ "Advisory only - nothing here changes severities automatically. "
832
+ "Cross-reference: `editorconfig-pack/.editorconfig`.",
833
+ "",
834
+ "### Candidates to relax (zero new hits)",
835
+ "",
836
+ ]
837
+ lines.extend(_relax_table_lines(suggestions["relax_candidates"]))
838
+ lines.append(
839
+ "### Candidates to add to editorconfig-pack (new/rising repeats not governed yet)"
840
+ )
841
+ lines.append("")
842
+ lines.extend(_add_table_lines(suggestions["add_candidates"]))
843
+ lines.append("### Still firing despite local error severity")
844
+ lines.append("")
845
+ lines.extend(_still_firing_table_lines(suggestions["still_firing"]))
846
+ return lines
847
+
848
+
849
+ def _baseline_lines(per_rule: Dict[str, Dict[str, Any]]) -> List[str]:
850
+ lines: List[str] = [
851
+ f"## Vs original mining baseline ({BASELINE_DATE})",
852
+ "",
853
+ "Reference only: the original 2026-12-02 mining (open + resolved, "
854
+ "editorconfig-pack/README.md) vs this snapshot, by short rule id. "
855
+ "Differences can reflect fixes, re-analyses, or SonarQube purging "
856
+ "closed issues - read alongside the trend section, not instead of it.",
857
+ "",
858
+ ]
859
+ by_short: Dict[str, int] = defaultdict(int)
860
+ for rule, entry in per_rule.items():
861
+ short = short_rule_id(rule)
862
+ if is_dotnet_rule(rule) or short in NON_DOTNET_BASELINE_SHORTS:
863
+ by_short[short] += entry["total"]
864
+ lines.append("| Rule | Baseline | Now | \u0394 |")
865
+ lines.append("|---|---:|---:|---:|")
866
+ for short in sorted(
867
+ set(BASELINE_COUNTS) | set(by_short),
868
+ key=lambda s: (-BASELINE_COUNTS.get(s, 0), s),
869
+ ):
870
+ base = BASELINE_COUNTS.get(short, 0)
871
+ now = by_short.get(short, 0)
872
+ lines.append(f"| {short} | {base} | {now} | {_fmt_delta(now - base)} |")
873
+ lines.append("")
874
+ return lines
875
+
876
+
877
+ def _method_lines(snapshot: Dict[str, Any]) -> List[str]:
878
+ lines: List[str] = [
879
+ "## Method & caveats",
880
+ "",
881
+ "- Counts come from `/api/issues/search` rule facets per project, "
882
+ "`resolved=false` (open) and `resolved=true` mined separately; each "
883
+ "facet sum is checked against the paging total and rebuilt by paging "
884
+ "raw issues if they ever disagree.",
885
+ "- Rule names/severities come from `/api/rules/show` per distinct rule.",
886
+ "- `total` = open + resolved as SonarQube currently stores them. "
887
+ "Closed issues can be purged after re-analysis, so totals are not a "
888
+ "strictly cumulative lifetime counter; trend deltas are still the "
889
+ "right signal for new hits between snapshots taken close together.",
890
+ "- Relax/add suggestions are heuristics over these counts, not "
891
+ "decisions: confirm against the style guide before editing the pack.",
892
+ ]
893
+ mining = snapshot.get("mining", {})
894
+ for warning in mining.get("warnings", []):
895
+ lines.append(f"- Mining warning: {_md(warning)}")
896
+ lines.append("")
897
+ return lines
898
+
899
+
900
+ def render_report(
901
+ snapshot: Dict[str, Any],
902
+ trend: Dict[str, Any],
903
+ suggestions: Dict[str, List[Dict[str, Any]]],
904
+ top_n: int = 25,
905
+ ) -> str:
906
+ per_rule = _per_rule(snapshot)
907
+ severities = snapshot.get("editorconfig", {}).get("severities", {})
908
+ deltas = trend.get("deltas", {})
909
+ has_previous = trend.get("previous_date") is not None
910
+ totals = snapshot["totals"]
911
+ lines: List[str] = []
912
+ lines.extend(_report_header_lines(snapshot))
913
+ lines.extend(_headline_lines(snapshot, totals))
914
+ lines.extend(_top_rules_lines(per_rule, severities, deltas, has_previous, top_n))
915
+ lines.extend(_trend_lines(trend, per_rule, deltas, has_previous))
916
+ lines.extend(_suggestions_lines(suggestions))
917
+ lines.extend(_baseline_lines(per_rule))
918
+ lines.extend(_method_lines(snapshot))
919
+ return "\n".join(lines)
920
+
921
+ # --------------------------------------------------------------------------
922
+ # Snapshot file handling
923
+ # --------------------------------------------------------------------------
924
+
925
+ _SNAPSHOT_RE = re.compile(r"^(\d{4}-\d{2}-\d{2})\.json$")
926
+
927
+
928
+ def find_previous_snapshot(snapshot_dir: Path, current_date: str) -> Optional[Path]:
929
+ """Latest snapshot file dated strictly before current_date, if any."""
930
+ candidates = []
931
+ if snapshot_dir.is_dir():
932
+ for path in snapshot_dir.iterdir():
933
+ match = _SNAPSHOT_RE.match(path.name)
934
+ if match and match.group(1) < current_date:
935
+ candidates.append((match.group(1), path))
936
+ if not candidates:
937
+ return None
938
+ return max(candidates)[1]
939
+
940
+
941
+ def load_snapshot(path: Path) -> Dict[str, Any]:
942
+ with path.open(encoding="utf-8") as handle:
943
+ return json.load(handle)
944
+
945
+
946
+ # --------------------------------------------------------------------------
947
+ # Live SonarQube access (lazy credential import; never prints secrets)
948
+ # --------------------------------------------------------------------------
949
+
950
+ def _sonar_call(path: str) -> Dict[str, Any]:
951
+ import urllib.request
952
+
953
+ try:
954
+ sys.path.insert(0, "/opt/muse/skills/custom-connector-setup/bin")
955
+ from dynamic_credentials import add_surrogate_to_request, read_json_response
956
+ except ImportError: # CI: no Muse credential helper; SONAR_TOKEN env is used
957
+ add_surrogate_to_request = None
958
+
959
+ def read_json_response(resp):
960
+ import json as _json
961
+ return _json.loads(resp.read().decode("utf-8"))
962
+
963
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
964
+ def redirect_request(self, *args): # noqa: D102
965
+ raise RuntimeError("redirect refused, verify the endpoint")
966
+
967
+ # Cloudflare bans Python-urllib's default UA (Error 1010); send a browser UA.
968
+ headers = {"Accept": "application/json", "User-Agent": BROWSER_UA}
969
+ request_hook = None
970
+ token = os.environ.get("SONAR_TOKEN", "")
971
+ if token:
972
+ headers["Authorization"] = f"Bearer {token}"
973
+ elif add_surrogate_to_request is not None:
974
+ def request_hook(request):
975
+ add_surrogate_to_request(
976
+ request, CONNECTOR_NAME, allowed_hosts=["sonar.hassanragai.dev"]
977
+ )
978
+ else:
979
+ raise RuntimeError("no Sonar auth: set SONAR_TOKEN or run where the Muse credential helper exists")
980
+ opener = urllib.request.build_opener(NoRedirect())
981
+ with open_https(BASE_URL + path, headers=headers, timeout=30,
982
+ opener=opener, request_hook=request_hook) as resp:
983
+ return read_json_response(resp)
984
+
985
+
986
+ def fetch_project_counts(
987
+ project_key: str,
988
+ ) -> Tuple[Dict[str, Dict[str, int]], Dict[str, Any]]:
989
+ """Mine open+resolved rule counts for one project via rule facets.
990
+
991
+ Falls back to paging raw issues (ps=500) if a facet sum disagrees with
992
+ the paging total. Returns ({"open": {...}, "resolved": {...}}, meta).
993
+ """
994
+ import urllib.parse
995
+
996
+ result: Dict[str, Dict[str, int]] = {}
997
+ meta: Dict[str, Any] = {"facet_checks": [], "fallback_used": False, "warnings": []}
998
+ quoted = urllib.parse.quote(project_key)
999
+ for state, resolved in (("open", "false"), ("resolved", "true")):
1000
+ payload = _sonar_call(
1001
+ f"/api/issues/search?componentKeys={quoted}&ps=1&facets=rules&resolved={resolved}"
1002
+ )
1003
+ counts, paging_total, facet_sum = parse_facet_rules(payload)
1004
+ check = {
1005
+ "state": state,
1006
+ "paging_total": paging_total,
1007
+ "facet_sum": facet_sum,
1008
+ "ok": paging_total == facet_sum,
1009
+ }
1010
+ meta["facet_checks"].append(check)
1011
+ if paging_total != facet_sum:
1012
+ meta["fallback_used"] = True
1013
+ meta["warnings"].append(
1014
+ f"{project_key} {state}: facet sum {facet_sum} != paging total "
1015
+ f"{paging_total}; rebuilt counts by paging raw issues"
1016
+ )
1017
+ issues: List[Dict[str, Any]] = []
1018
+ page = 1
1019
+ while True:
1020
+ page_payload = _sonar_call(
1021
+ f"/api/issues/search?componentKeys={quoted}&ps=500&p={page}&resolved={resolved}"
1022
+ )
1023
+ batch = page_payload.get("issues", [])
1024
+ issues.extend(batch)
1025
+ total = int(page_payload.get("paging", {}).get("total", 0))
1026
+ if len(issues) >= total or not batch:
1027
+ break
1028
+ page += 1
1029
+ counts = count_rules_from_issues(issues)
1030
+ result[state] = counts
1031
+ return result, meta
1032
+
1033
+
1034
+ def fetch_rule_metadata(rule_keys: Iterable[str]) -> Tuple[Dict[str, Dict[str, str]], List[str]]:
1035
+ """Rule name/severity/type per distinct rule via /api/rules/show."""
1036
+ import urllib.parse
1037
+
1038
+ metadata: Dict[str, Dict[str, str]] = {}
1039
+ warnings: List[str] = []
1040
+ for rule in sorted(set(rule_keys)):
1041
+ try:
1042
+ payload = _sonar_call(f"/api/rules/show?key={urllib.parse.quote(rule)}")
1043
+ doc = payload.get("rule", {})
1044
+ metadata[rule] = {
1045
+ "name": doc.get("name", short_rule_id(rule)),
1046
+ "severity": doc.get("severity", ""),
1047
+ "type": doc.get("type", ""),
1048
+ }
1049
+ except Exception as exc: # keep mining; name falls back to the id
1050
+ metadata[rule] = {"name": short_rule_id(rule), "severity": "", "type": ""}
1051
+ warnings.append(f"rules/show failed for {rule}: {type(exc).__name__}")
1052
+ return metadata, warnings
1053
+
1054
+
1055
+ def fetch_server_status() -> Dict[str, str]:
1056
+ try:
1057
+ payload = _sonar_call("/api/system/status")
1058
+ return {
1059
+ "base_url": BASE_URL,
1060
+ "version": str(payload.get("version", "")),
1061
+ "status": str(payload.get("status", "")),
1062
+ }
1063
+ except Exception:
1064
+ return {"base_url": BASE_URL, "version": "", "status": ""}
1065
+
1066
+
1067
+ # --------------------------------------------------------------------------
1068
+ # CLI
1069
+ # --------------------------------------------------------------------------
1070
+
1071
+ def _prepare_out_dirs(
1072
+ args: argparse.Namespace,
1073
+ ) -> Tuple[Path, Path, Path]:
1074
+ script_dir = Path(__file__).resolve().parent
1075
+ out_dir = resolve_under(args.out_dir, Path.cwd()) if args.out_dir else script_dir
1076
+ snapshot_dir = out_dir / "snapshots"
1077
+ report_dir = out_dir / "reports"
1078
+ snapshot_dir.mkdir(parents=True, exist_ok=True)
1079
+ report_dir.mkdir(parents=True, exist_ok=True)
1080
+ return script_dir, snapshot_dir, report_dir
1081
+
1082
+
1083
+ def _load_severities(
1084
+ args: argparse.Namespace, script_dir: Path
1085
+ ) -> Tuple[Path, Dict[str, str]]:
1086
+ editorconfig_path = (
1087
+ Path(args.editorconfig)
1088
+ if args.editorconfig
1089
+ else script_dir.parent / "editorconfig-pack" / ".editorconfig"
1090
+ )
1091
+ if editorconfig_path.is_file():
1092
+ severities = parse_editorconfig_severities(
1093
+ read_text_under(editorconfig_path, Path.cwd())
1094
+ )
1095
+ return editorconfig_path, severities
1096
+ print(f"warning: editorconfig not found at {editorconfig_path}", file=sys.stderr)
1097
+ return editorconfig_path, {}
1098
+
1099
+
1100
+ def _load_offline_raw(
1101
+ args: argparse.Namespace, mining_meta: Dict[str, Any]
1102
+ ) -> Tuple[
1103
+ Dict[str, Dict[str, Dict[str, int]]],
1104
+ Dict[str, Dict[str, str]],
1105
+ Dict[str, str],
1106
+ Dict[str, str],
1107
+ ]:
1108
+ raw = json.loads(read_text_under(args.offline_raw, Path.cwd()))
1109
+ per_project = raw["per_project"]
1110
+ rule_metadata = raw.get("rule_metadata", {})
1111
+ server = raw.get(
1112
+ "server", {"base_url": BASE_URL, "version": "", "status": ""}
1113
+ )
1114
+ mining_meta["offline_raw"] = str(args.offline_raw)
1115
+ project_keys = {name: PROJECTS.get(name, "") for name in per_project}
1116
+ return per_project, rule_metadata, server, project_keys
1117
+
1118
+
1119
+ def _mine_live(
1120
+ args: argparse.Namespace, mining_meta: Dict[str, Any]
1121
+ ) -> Optional[
1122
+ Tuple[
1123
+ Dict[str, Dict[str, Dict[str, int]]],
1124
+ Dict[str, Dict[str, str]],
1125
+ Dict[str, str],
1126
+ Dict[str, str],
1127
+ ]
1128
+ ]:
1129
+ project_names = (
1130
+ [p.strip() for p in args.projects.split(",") if p.strip()]
1131
+ if args.projects
1132
+ else list(PROJECTS)
1133
+ )
1134
+ unknown = [p for p in project_names if p not in PROJECTS]
1135
+ if unknown:
1136
+ print(f"error: unknown project(s): {', '.join(unknown)}", file=sys.stderr)
1137
+ return None
1138
+ project_keys = {name: PROJECTS[name] for name in project_names}
1139
+ server = fetch_server_status()
1140
+ per_project: Dict[str, Dict[str, Dict[str, int]]] = {}
1141
+ for name in project_names:
1142
+ counts, meta = fetch_project_counts(project_keys[name])
1143
+ per_project[name] = counts
1144
+ mining_meta["projects"][name] = meta
1145
+ mining_meta["warnings"].extend(meta.get("warnings", []))
1146
+ all_rules = [
1147
+ rule
1148
+ for split in per_project.values()
1149
+ for state_counts in split.values()
1150
+ for rule in state_counts
1151
+ ]
1152
+ rule_metadata, meta_warnings = fetch_rule_metadata(all_rules)
1153
+ mining_meta["warnings"].extend(meta_warnings)
1154
+ return per_project, rule_metadata, server, project_keys
1155
+
1156
+
1157
+ def _write_outputs(
1158
+ snapshot_dir: Path,
1159
+ report_dir: Path,
1160
+ date: str,
1161
+ snapshot: Dict[str, Any],
1162
+ report: str,
1163
+ ) -> Tuple[Path, Path]:
1164
+ snapshot_path = snapshot_dir / f"{date}.json"
1165
+ report_path = report_dir / f"{date}.md"
1166
+ snapshot_path.write_text(
1167
+ json.dumps(snapshot, indent=2, sort_keys=True) + "\n", encoding="utf-8"
1168
+ )
1169
+ report_path.write_text(report, encoding="utf-8")
1170
+ return snapshot_path, report_path
1171
+
1172
+
1173
+ def _print_summary(
1174
+ snapshot_path: Path,
1175
+ report_path: Path,
1176
+ per_project: Dict[str, Dict[str, Dict[str, int]]],
1177
+ snapshot: Dict[str, Any],
1178
+ trend: Dict[str, Any],
1179
+ suggestions: Dict[str, List[Dict[str, Any]]],
1180
+ ) -> None:
1181
+ totals = snapshot["totals"]
1182
+ print(f"snapshot: {snapshot_path}")
1183
+ print(f"report: {report_path}")
1184
+ print(
1185
+ f"projects={len(per_project)} open={totals['open']} "
1186
+ f"resolved={totals['resolved']} total={totals['total']} "
1187
+ f"distinct_rules={totals['distinct_rules']}"
1188
+ )
1189
+ print(
1190
+ f"previous_snapshot={trend['previous_date'] or 'none'} "
1191
+ f"new_rules={len(trend['new_rules'])} gone_quiet={len(trend['gone_quiet'])} "
1192
+ f"relax={len(suggestions['relax_candidates'])} "
1193
+ f"add={len(suggestions['add_candidates'])} "
1194
+ f"still_firing={len(suggestions['still_firing'])}"
1195
+ )
1196
+
1197
+
1198
+ def run(args: argparse.Namespace) -> int:
1199
+ script_dir, snapshot_dir, report_dir = _prepare_out_dirs(args)
1200
+ date = args.date or datetime.now().astimezone().strftime("%Y-%m-%d")
1201
+ editorconfig_path, severities = _load_severities(args, script_dir)
1202
+ mining_meta: Dict[str, Any] = {"warnings": [], "projects": {}}
1203
+ if args.offline_raw:
1204
+ per_project, rule_metadata, server, project_keys = _load_offline_raw(
1205
+ args, mining_meta
1206
+ )
1207
+ else:
1208
+ live = _mine_live(args, mining_meta)
1209
+ if live is None:
1210
+ return 2
1211
+ per_project, rule_metadata, server, project_keys = live
1212
+ snapshot = build_snapshot(
1213
+ date,
1214
+ SnapshotData(
1215
+ per_project=per_project,
1216
+ project_keys=project_keys,
1217
+ rule_metadata=rule_metadata,
1218
+ editorconfig_severities=severities,
1219
+ ),
1220
+ SnapshotMeta(
1221
+ editorconfig_path=str(editorconfig_path),
1222
+ server=server,
1223
+ mining_meta=mining_meta,
1224
+ ),
1225
+ )
1226
+ previous_path = find_previous_snapshot(snapshot_dir, date)
1227
+ previous = load_snapshot(previous_path) if previous_path else None
1228
+ trend = compute_trend(snapshot, previous)
1229
+ suggestions = make_suggestions(snapshot, trend, severities)
1230
+ report = render_report(snapshot, trend, suggestions, top_n=args.top)
1231
+ snapshot_path, report_path = _write_outputs(
1232
+ snapshot_dir, report_dir, date, snapshot, report
1233
+ )
1234
+ _print_summary(snapshot_path, report_path, per_project, snapshot, trend, suggestions)
1235
+ return 0
1236
+
1237
+
1238
+ def main(argv: Optional[List[str]] = None) -> int:
1239
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
1240
+ parser.add_argument("--date", help="snapshot date YYYY-MM-DD (default: today, local)")
1241
+ parser.add_argument("--out-dir", help="output root (default: this script's folder)")
1242
+ parser.add_argument(
1243
+ "--editorconfig",
1244
+ help="path to editorconfig-pack/.editorconfig (default: ../editorconfig-pack/.editorconfig)",
1245
+ )
1246
+ parser.add_argument(
1247
+ "--projects",
1248
+ help="comma-separated project names (default: all house projects)",
1249
+ )
1250
+ parser.add_argument("--top", type=int, default=25, help="rows in the top-rules table")
1251
+ parser.add_argument(
1252
+ "--offline-raw",
1253
+ help="JSON file with per_project/rule_metadata; skip network (testing/demo)",
1254
+ )
1255
+ return run(parser.parse_args(argv))
1256
+
1257
+
1258
+ if __name__ == "__main__":
1259
+ raise SystemExit(main())