Skip to content

Commit 2a294b1

Browse files
committed
feat: audit-driven precision pass (0.4.1) — kill more false positives, fix correctness/output bugs
Verified follow-ups from the multi-agent audit, validated against the 32-package PyPI corpus benchmark. The `elif` fix alone cuts no-deep-nesting findings on respected code from ~6040 to ~1638. False positives removed / narrowed - no-deep-nesting no longer counts `elif` branches as deeper nesting. - Library rules are now gated per-file on an actual import of the library (pandas rules never fire on a file that doesn't import pandas, etc.) instead of running project-wide from the dependency manifest — this also activates a framework's own rules on its own code, which dependency detection missed. - http-missing-timeout scoped to requests.<method>() (dict/object .get(), httpx, and requests.Session() no longer flagged). - logging f-string / exc-info checks only fire on real logger receivers; any truthy exc_info satisfies the traceback check. (LoggingRules was previously dead — never activated — and is now wired up via imports.) - FastAPI: a return-type annotation satisfies response_model; only app/router receivers count as routes (not @cache.get); the sync-endpoint message is now accurate (threadpool, not "blocks the event loop"). - Django: raw-SQL requires an actual SQL keyword; N+1 suppressed when select_related/prefetch_related is already used. - Flask/SQLAlchemy: placeholder-free f-strings are static, not injection; Flask detects SQL f-strings passed directly to execute(). - pandas chained-indexing / NaN-comparison require a real DataFrame/Series base. - no-string-concat-in-loop is scope-aware (no longer flags numeric accumulators). Correctness / robustness - _count_lines no longer crashes the whole scan on a non-UTF-8 file. - Score is clamped to [0, 100] and negative max-deduction overrides are clamped. - Per-category display sub-scores come from a single source in score.py and honour config/profile max-deduction overrides (display no longer diverges from the score). - cli profile suppresses the rule IDs the rules actually emit (no-os-system / no-subprocess-shell). - complexity counts match/case arms; type-coverage counts posonly/kwonly/*args. - run_ruff_fix matches modern ruff output; --fix status goes to stderr (keeps --json/--score/--sarif stdout clean). - SARIF omits region for project-level (line 0) findings; JSON output includes profile. - Badge URL escapes the score slash; pre-commit installer no longer corrupts a foreign hook. Packaging / docs / tests - Ship py.typed (the Typing :: Typed classifier now holds). - Accept the documented [per-file-ignores] config key; fix invalid TOML and inaccurate pre-commit/profile/CLI docs. - Stop tracking committed __pycache__ bytecode. - Add tests/test_audit_fixes.py; full suite green (253), ruff clean, self-scan passes --fail-on error. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016vrB7VNXwJeCKUeh378zJh
1 parent 8c7c895 commit 2a294b1

35 files changed

Lines changed: 664 additions & 212 deletions

‎README.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -256,8 +256,7 @@ files = ["tests/fixtures/**", "migrations/**", "scripts/**"]
256256
"src/legacy/*.py" = ["high-complexity", "no-god-function"]
257257
258258
[scoring]
259-
max-deduction.Security = 20
260-
max-deduction.Dead Code = 0 # disable dead-code penalty entirely
259+
max-deduction = { Security = 20, "Dead Code" = 0 } # 0 disables a category's penalty
261260
```
262261

263262
Or use `pyproject.toml`:
@@ -294,21 +293,23 @@ PyCodeGate auto-detects a project profile and adjusts rule weights accordingly.
294293

295294
## Pre-commit Hook
296295

297-
Use `--pre-commit` to run PyCodeGate as a pre-commit hook. It automatically scans only the staged files:
296+
`--pre-commit` installs a git `pre-commit` hook (one-time) that scores the project on
297+
every commit and blocks the commit when the score falls below the threshold:
298298

299299
```bash
300-
pycodegate . --pre-commit --fail-on error
300+
pycodegate . --pre-commit --min-score 80
301301
```
302302

303-
Add to `.pre-commit-config.yaml`:
303+
If you use the [pre-commit framework](https://pre-commit.com), add it to
304+
`.pre-commit-config.yaml` instead:
304305

305306
```yaml
306307
repos:
307308
- repo: local
308309
hooks:
309310
- id: pycodegate
310311
name: PyCodeGate quality check
311-
entry: pycodegate . --pre-commit --fail-on error
312+
entry: pycodegate . --fail-on error
312313
language: system
313314
types: [python]
314315
pass_filenames: false

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "pycodegate"
3-
version = "0.4.0"
3+
version = "0.4.1"
44
description = "Trust, but verify. The quality gate for AI-generated Python code."
55
readme = "README.md"
66
requires-python = ">=3.10"

‎skills/pycodegate/SKILL.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ Scans your Python codebase for security, performance, correctness, architecture,
1111
## Usage
1212

1313
```bash
14-
uvx pycodegate . --verbose --diff
14+
uvx pycodegate . --verbose
15+
# or scan only what changed vs a base branch:
16+
uvx pycodegate . --verbose --diff main
1517
```
1618

1719
## Workflow
-299 Bytes
Binary file not shown.
-2.85 KB
Binary file not shown.

‎src/pycodegate/cli.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,11 @@ def _maybe_run_fix(opts: CliOptions) -> None:
5858
if not opts.fix:
5959
return
6060
fixes = run_ruff_fix(opts.directory)
61+
# Progress goes to stderr so it never pollutes --json/--score/--sarif stdout.
6162
if fixes == -1:
62-
click.echo("ruff not found, skipping auto-fix")
63+
click.echo("ruff not found, skipping auto-fix", err=True)
6364
else:
64-
click.echo(f"Fixed {fixes} issues via ruff")
65+
click.echo(f"Fixed {fixes} issues via ruff", err=True)
6566

6667

6768
def _build_config(opts: CliOptions):

‎src/pycodegate/config.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def _parse_doctor_toml(path: Path) -> Config:
5353
ignore_rules=ignore.get("rules", []),
5454
ignore_files=ignore.get("files", []),
5555
profile=options.get("profile", None),
56-
per_file_suppress=data.get("per-file-suppress", {}),
56+
per_file_suppress=_read_per_file_suppress(data),
5757
max_deduction=_read_max_deduction(data),
5858
)
5959

@@ -76,11 +76,16 @@ def _parse_pyproject_toml(path: Path) -> Config:
7676
ignore_rules=ignore.get("rules", []),
7777
ignore_files=ignore.get("files", []),
7878
profile=section.get("profile", None),
79-
per_file_suppress=section.get("per-file-suppress", {}),
79+
per_file_suppress=_read_per_file_suppress(section),
8080
max_deduction=_read_max_deduction(section),
8181
)
8282

8383

84+
def _read_per_file_suppress(table: dict) -> dict:
85+
"""Read per-file rule suppression, accepting the documented ``per-file-ignores`` alias."""
86+
return table.get("per-file-suppress") or table.get("per-file-ignores") or {}
87+
88+
8489
def _read_max_deduction(table: dict) -> dict:
8590
"""Read scoring max-deduction overrides.
8691

‎src/pycodegate/output.py‎

Lines changed: 19 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
from pycodegate import __version__
1414
from pycodegate.constants import CATEGORY_WEIGHTS, FRAMEWORK_CATEGORY_MAP
15+
from pycodegate.score import category_breakdown
1516
from pycodegate.types import Category, Diagnostic, ScanResult, Severity
1617

1718
BAR_WIDTH = 50
@@ -78,42 +79,6 @@ def _score_color(score: int) -> str:
7879
return "red"
7980

8081

81-
def _compute_category_sub_scores(
82-
diagnostics: list[Diagnostic],
83-
) -> dict[Category, tuple[int, int]]:
84-
"""Return {resolved_category: (earned, max)} for each category in CATEGORY_WEIGHTS."""
85-
total_weight = sum(CATEGORY_WEIGHTS.values())
86-
max_deductions = {cat: round(w / total_weight * 100) for cat, w in CATEGORY_WEIGHTS.items()}
87-
# Fix rounding to ensure sum == 100
88-
diff = 100 - sum(max_deductions.values())
89-
if diff != 0:
90-
highest = max(CATEGORY_WEIGHTS, key=lambda k: CATEGORY_WEIGHTS[k])
91-
max_deductions[highest] += diff
92-
93-
# Group diagnostics by resolved category
94-
by_category: dict[Category, list[Diagnostic]] = defaultdict(list)
95-
for d in diagnostics:
96-
resolved = FRAMEWORK_CATEGORY_MAP.get(d.category, d.category)
97-
by_category[resolved].append(d)
98-
99-
# Compute actual deduction per category (same logic as score.py)
100-
actual_deductions: dict[Category, float] = {}
101-
for cat, diags in by_category.items():
102-
costs = sorted([d.cost for d in diags], reverse=True)
103-
cat_total = sum(c if i < 3 else c * 0.1 for i, c in enumerate(costs))
104-
cap = max_deductions.get(cat, 10)
105-
actual_deductions[cat] = min(cat_total, cap)
106-
107-
# Build (earned, max) per category
108-
result: dict[Category, tuple[int, int]] = {}
109-
for cat, max_ded in max_deductions.items():
110-
deducted = round(actual_deductions.get(cat, 0.0))
111-
earned = max_ded - deducted
112-
result[cat] = (earned, max_ded)
113-
114-
return result
115-
116-
11782
def format_summary(result: ScanResult) -> str:
11883
"""Format the full scan summary as a string (for testing)."""
11984
lines: list[str] = []
@@ -152,8 +117,9 @@ def print_scan_result(result: ScanResult, verbose: bool = False) -> None:
152117
console.print(f" [dim]Source files:[/dim] {p.source_file_count}")
153118
console.print()
154119

155-
# Category-grouped diagnostics with sub-scores
156-
_print_category_groups(console, result.diagnostics, verbose)
120+
# Category-grouped diagnostics with sub-scores (single source of truth from scoring)
121+
breakdown = result.category_scores or category_breakdown(result.diagnostics)
122+
_print_category_groups(console, result.diagnostics, breakdown, verbose)
157123

158124
# Summary panel
159125
color = _score_color(result.score.value)
@@ -187,6 +153,7 @@ def output_json(result: ScanResult) -> None:
187153
"path": p.path,
188154
"score": result.score.value,
189155
"label": result.score.label,
156+
"profile": result.profile,
190157
"errors": errors,
191158
"warnings": warnings,
192159
"elapsed_ms": result.elapsed_ms,
@@ -231,24 +198,26 @@ def _sarif_rules(diagnostics: list[Diagnostic]) -> list[dict]:
231198
]
232199

233200

201+
def _sarif_location(diag: Diagnostic) -> dict:
202+
"""Build a SARIF physicalLocation, omitting the region for project-level findings.
203+
204+
SARIF 2.1.0 requires region.startLine >= 1, so a line of 0 (project-level
205+
diagnostics) points at the artifact only rather than an invalid line 0.
206+
"""
207+
physical: dict = {"artifactLocation": {"uri": diag.file_path}}
208+
if diag.line and diag.line >= 1:
209+
physical["region"] = {"startLine": diag.line, "startColumn": (diag.column or 0) + 1}
210+
return {"physicalLocation": physical}
211+
212+
234213
def _sarif_results(diagnostics: list[Diagnostic]) -> list[dict]:
235214
"""Build SARIF results array from diagnostics."""
236215
return [
237216
{
238217
"ruleId": d.rule,
239218
"level": "error" if d.severity == Severity.ERROR else "warning",
240219
"message": {"text": d.message},
241-
"locations": [
242-
{
243-
"physicalLocation": {
244-
"artifactLocation": {"uri": d.file_path},
245-
"region": {
246-
"startLine": d.line,
247-
"startColumn": (d.column or 0) + 1,
248-
},
249-
}
250-
}
251-
],
220+
"locations": [_sarif_location(d)],
252221
}
253222
for d in diagnostics
254223
]
@@ -319,11 +288,10 @@ def _print_category_with_issues(
319288
def _print_category_groups(
320289
console: Console,
321290
diagnostics: list[Diagnostic],
291+
sub_scores: dict[Category, tuple[int, int]],
322292
verbose: bool,
323293
) -> None:
324294
"""Print diagnostics grouped by category with sub-scores."""
325-
sub_scores = _compute_category_sub_scores(diagnostics)
326-
327295
# Build rule-grouped diagnostics per resolved category
328296
by_category: dict[Category, list[Diagnostic]] = defaultdict(list)
329297
for d in diagnostics:

‎src/pycodegate/profile.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class Profile:
2020
"web": Profile(name="web"),
2121
"cli": Profile(
2222
name="cli",
23-
suppressed_rules=frozenset({"no-subprocess", "no-shell-exec"}),
23+
suppressed_rules=frozenset({"no-os-system", "no-subprocess-shell"}),
2424
max_deduction_overrides={"Security": 15},
2525
),
2626
"library": Profile(name="library"),

‎src/pycodegate/py.typed‎

Whitespace-only changes.

0 commit comments

Comments
 (0)