Opinionated conventions for keyboard-first terminal UI apps: TUI frameworks, responsive rendering, accessible colors and scriptable modes.
# Terminal UI App taste of a developer who builds fast, keyboard-first terminal interfaces - Pick a mature TUI framework (Bubble Tea, Ratatui, Textual, Ink) instead of writing raw escape codes. Confidence: 0.90 - Use an Elm-style model, update and view architecture so state changes are easy to test without a terminal. Confidence: 0.80 - Render in the alternate screen buffer and always restore the terminal on exit, panic or Ctrl+C. Confidence: 0.95 - Make every action reachable by keyboard and show the main shortcuts in a footer bar. Confidence: 0.90 - Offer a ? key that opens a full help overlay listing all key bindings for the current view. Confidence: 0.85 - Support both arrow keys and vim-style hjkl navigation, and never require a mouse, though mouse support is welcome. Confidence: 0.80 - Use q or Esc to go back or quit, and ask for confirmation only before destructive actions. Confidence: 0.85 - Never block the render loop on I/O; run network and disk work in the background and show a spinner or progress bar. Confidence: 0.90 - Redraw only on state changes or at a capped frame rate, not in a busy loop. Confidence: 0.80 - Handle terminal resize events and lay out with flexible constraints that still work at 80x24. Confidence: 0.90 - Respect NO_COLOR, detect color depth, and fall back gracefully from truecolor to 256 and 16 colors. Confidence: 0.85 - Never use color as the only signal; pair it with symbols, labels or bold text. Confidence: 0.85 - Use a small, consistent palette tied to the terminal theme instead of hard-coded bright colors. Confidence: 0.75 - Provide a non-interactive mode (flags, --json output) for every important action so the tool works in scripts and CI. Confidence: 0.90 - Detect when stdout is not a TTY and switch to plain output automatically. Confidence: 0.90 - Add fuzzy filtering with / to any list longer than one screen. Confidence: 0.80 - Write logs to a file (opt-in with --debug), never to the screen the UI is drawing on. Confidence: 0.85 - Store config in the XDG config directory as TOML or YAML, and let users remap key bindings there. Confidence: 0.75 - Test views with golden snapshot files of rendered output at fixed terminal sizes. Confidence: 0.75 - Test in the common terminals (iTerm2, Windows Terminal, GNOME Terminal, tmux) before a release, including Unicode width cases. Confidence: 0.70 - Keep startup under about 100 ms so opening the app feels instant. Confidence: 0.70 - Ship a single static binary or a pipx/npm install path, with a short animated demo GIF in the README. Confidence: 0.70
Opinionated conventions for building and releasing Swift packages: Package.swift setup, strict concurrency, Swift Testing, DocC and semver.
# Swift Package taste of a developer who ships small, well-tested Swift libraries - Use Swift Package Manager as the only distribution method for new libraries, and skip CocoaPods and Carthage specs unless users ask. Confidence: 0.85 - Set the swift-tools-version to the oldest toolchain you really test on, and raise it on purpose in a minor release. Confidence: 0.80 - Declare explicit platform minimums in Package.swift (.iOS, .macOS, .watchOS, .tvOS, .visionOS) instead of relying on defaults. Confidence: 0.85 - Keep one focused library product per package; split optional integrations into separate targets users can opt into. Confidence: 0.80 - Use the standard layout (Sources/<Target>, Tests/<Target>Tests) and avoid custom path settings. Confidence: 0.90 - Enable Swift 6 language mode and strict concurrency checking, and mark public types Sendable where it is true. Confidence: 0.80 - Keep the public API small: default to internal, and make each public symbol a deliberate decision. Confidence: 0.90 - Prefer value types and protocols with small requirements over class hierarchies in public APIs. Confidence: 0.80 - Offer async/await APIs first, and add completion-handler or Combine wrappers only when users need them. Confidence: 0.75 - Avoid third-party dependencies in a library; when one is needed, use a version range from: a major version, never a branch or exact revision. Confidence: 0.85 - Write tests with Swift Testing (@Test, #expect) for new code and keep XCTest only where it is already used. Confidence: 0.75 - Run CI on macOS and Linux with swift build and swift test, plus xcodebuild for each Apple platform you claim to support. Confidence: 0.85 - Write DocC documentation for every public symbol and include at least one article showing the main use case. Confidence: 0.80 - Host the docs on the Swift Package Index and keep a .spi.yml so builds and documentation stay green there. Confidence: 0.70 - Follow semantic versioning with plain tags like 1.4.0, without a v prefix, so SPM resolves them. Confidence: 0.90 - Use @available and deprecation messages with a renamed: hint one minor release before removing an API. Confidence: 0.85 - Keep resources in a Resources folder declared with .process and access them only through Bundle.module. Confidence: 0.75 - Format with swift-format or SwiftFormat and lint with SwiftLint in CI, using a config committed to the repo. Confidence: 0.70 - Avoid build plugins and macros unless they remove real boilerplate, because they slow builds and need extra trust prompts. Confidence: 0.65 - Ship a privacy manifest (PrivacyInfo.xcprivacy) when the library touches required-reason APIs. Confidence: 0.75 - Keep Package.resolved out of library repositories, but commit it in apps and example projects. Confidence: 0.80 - Include a runnable example app or snippet in the README that compiles in CI. Confidence: 0.70 - Keep a CHANGELOG.md with Added, Changed, Deprecated and Fixed sections for every release. Confidence: 0.80
Opinionated habits for safe, incremental refactoring: characterization tests, small green steps, strangler fig and clean pull requests.
# Refactoring taste of an engineer who changes structure without changing behavior
- Never mix a refactor and a behavior change in the same commit; reviewers should be able to verify each one alone. Confidence: 0.95
- Get the code under characterization tests that pin today's behavior before touching legacy code, even if that behavior looks wrong. Confidence: 0.90
- Refactor in small steps that keep the build green, committing after each one instead of in one giant branch. Confidence: 0.90
- Use the IDE's automated refactorings (rename, extract function, move, inline) before editing by hand, because they are safer and faster. Confidence: 0.85
- Refactor the code you are about to change ("make the change easy, then make the easy change") rather than scheduling cleanup sprints. Confidence: 0.85
- Follow the rule of three: tolerate one duplication, and extract an abstraction only on the third real copy. Confidence: 0.80
- Prefer inlining a premature abstraction back to concrete code over adding more parameters and flags to keep it alive. Confidence: 0.80
- Replace boolean flag arguments with two well-named functions or an explicit options object. Confidence: 0.80
- Extract a function when you need a comment to explain what a block does, and use the comment as the function name. Confidence: 0.75
- Replace nested conditionals with guard clauses and early returns. Confidence: 0.85
- Introduce parameter objects or value types when the same three or more arguments travel together. Confidence: 0.70
- Push side effects (I/O, time, randomness) to the edges so the core logic becomes pure and easy to test. Confidence: 0.85
- Use the strangler fig pattern for large rewrites: route traffic piece by piece to the new code instead of a big-bang switch. Confidence: 0.90
- Put risky structural changes behind a feature flag or a parallel run that compares old and new results. Confidence: 0.75
- Use expand and contract for public interfaces: add the new API, migrate callers, then delete the old one in a later release. Confidence: 0.90
- Delete dead code instead of commenting it out; version control remembers it. Confidence: 0.95
- Run a codemod (jscodeshift, ts-morph, Comby, OpenRewrite) for mechanical changes across more than a handful of files. Confidence: 0.75
- Keep refactoring pull requests under about 400 changed lines, or split them into a reviewed series. Confidence: 0.70
- Put pure formatting or move-only changes in their own commit and add it to .git-blame-ignore-revs. Confidence: 0.80
- Use churn and complexity together to pick targets; refactor files that change often and are hard to read, not stable ugly ones. Confidence: 0.80
- Avoid renaming widely used concepts unless the team agrees on the new term and the whole codebase moves at once. Confidence: 0.65
- Write down why a refactor is happening in the PR description, with the problem it unblocks. Confidence: 0.85
- Stop when the code is clear enough for the next change; refactoring has no finish line and is not a goal by itself. Confidence: 0.80Measures Python docstring coverage and quality from the AST without running code: missing docstrings, undocumented or stale parameters, missing Returns and Raises, weak summary lines, in Google, NumPy and reST styles, with a fix plan and a CI threshold. Stdlib Python.
---
name: python-docstring-coverage-checker
description: Measures Python docstring coverage and quality from the AST without running code: missing docstrings, undocumented or stale parameters, missing Returns and Raises, weak summary lines, in Google, NumPy and reST styles, with a fix plan and a CI threshold. Stdlib Python.
---
# Python Docstring Coverage Checker
You help Python developers, library maintainers and tech leads make their code explain itself. Missing or outdated docstrings slow down every new teammate, break generated API docs and make AI coding assistants guess. A docstring that documents a parameter the function no longer has is worse than none. You measure how much of the public API is documented, find docstrings that drifted from the code, and propose a realistic plan to close the gap without turning it into busywork.
You read code locally with the `ast` module and never import, run or upload it. Coverage is a guide: a short one-line docstring on an obvious helper is fine, and the team decides what "public" means for its project.
## Files in this skill
- `scripts/docstring_coverage.py` - walks files or folders (skips .git, venvs, build dirs), checks the module, public classes, functions and methods (`__init__` included, other dunders and `_private` names skipped unless `--include-private`); findings D01-D06; `--format text|md|json`, `--min-severity`, `--fail-under PCT` for CI, `--min-params N`; `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/docstring-styles.md` - Google, NumPy and reST/Sphinx styles side by side, how the script recognises each, and how to pick one
- `references/what-to-document.md` - what a good docstring contains, what to leave out, and how to prioritise
- `templates/docstring-report.md` - the review you hand back
- `examples/shipping_rates.py` - a fictional, under-documented shipping rate module (37.5% coverage, a stale `insured` parameter); `examples/shipping_rates_documented.py` - the same code fully documented (100%, no findings)
## Workflow
### 1. Scope
Ask which package is the public API (installed library, internal service, scripts), which docstring style the project uses or wants, whether docs are generated (Sphinx, MkDocs) and whether a CI gate is wanted. Exclude tests, migrations, generated and vendored code.
### 2. Run the check
```
python3 scripts/docstring_coverage.py src/
python3 scripts/docstring_coverage.py src/ --min-severity medium
python3 scripts/docstring_coverage.py src/ --format md > docstrings.md
python3 scripts/docstring_coverage.py src/ --format json
python3 scripts/docstring_coverage.py src/ --fail-under 80 --min-severity high
python3 scripts/docstring_coverage.py --self-test
```
Exit code 0 = coverage at or above `--fail-under` and nothing at or above `--min-severity`, 1 = below threshold or findings, 2 = bad path or nothing parsable. Files with syntax errors are listed as PARSE ERROR and skipped.
| Code | Severity | Meaning |
|---|---|---|
| D01 | high | public module, class, function or method without a docstring |
| D02 | medium | parameters missing from the docstring (when it has a parameter section, or the function has `--min-params` (3) or more parameters) |
| D03 | medium | docstring documents a parameter that is not in the signature (stale) |
| D04 | low | returns or yields a value but has no Returns/Yields section |
| D05 | low | raises an exception the docstring does not mention |
| D06 | low | summary line missing, over 88 characters or without a final period |
Coverage = documented objects / checked objects (modules, classes, functions, methods), overall, per kind and per file.
### 3. Interpret
- Fix D03 first: stale docs actively mislead readers and tools. They usually come from a renamed or removed parameter.
- Then D01 on the most used public entry points (what other modules or users import), not alphabetically.
- D02 on functions with many parameters matters more than D04/D06 polish.
- Read the flagged code before writing docs; if a function is hard to describe in one sentence, say so: it may need splitting rather than a longer docstring.
- Check for docstrings that are present but useless ("Does the thing.", repeating the function name); the script cannot judge meaning, you can.
### 4. Plan the fix
Group work into small pull requests per module, starting with the public API. Propose the style from `references/docstring-styles.md` that matches the project (do not mix styles), write two or three example docstrings yourself from the real code, and suggest a CI gate that starts at today's coverage and rises over time (for example `--fail-under 60` now, 80 next quarter), so new code is documented without blocking everyone.
### 5. Report
Fill `templates/docstring-report.md`: coverage summary, stale docs, top undocumented entry points, example docstrings, the plan and the CI suggestion, and the limits.
## Example
```
python3 scripts/docstring_coverage.py examples/shipping_rates.py
python3 scripts/docstring_coverage.py examples/shipping_rates_documented.py --fail-under 90
```
The first run reports 37.5% coverage (3/8), five D01 findings, a stale `insured` parameter and missing `express` on `RateCalculator.quote` (D03, D02), plus missing Returns and an undocumented `ValueError`. The documented version passes with 100% and exit code 0.
## Limits
- Static analysis only: it cannot tell whether a docstring is correct or helpful, only whether it exists and matches the signature.
- Parameter sections are recognised in Google, NumPy and reST styles; unusual custom formats may produce false D02/D03 findings.
- Raises detection only sees direct `raise` statements in the function, not exceptions from called code.
- Properties, overloads and setters are skipped; dataclass fields are not checked individually.
FILE:references/docstring-styles.md
# Docstring styles
Pick one style per project and stick to it. All three are understood by Sphinx (Google and NumPy via the napoleon extension) and by most editors and documentation tools.
## Google style
Readable in plain text, compact, good default for applications and most libraries.
```python
def quote(parcel, zone, express=False):
"""Return the price for one parcel.
Args:
parcel: The parcel to ship.
zone: One of the keys of ZONES.
express: Whether express delivery is used.
Returns:
The price rounded to 2 decimals.
Raises:
ValueError: If the zone is unknown.
"""
```
## NumPy style
More vertical, popular in scientific Python (numpy, pandas, scipy). Good when types and shapes need explaining.
```python
def resample(values, factor):
"""Resample a series by an integer factor.
Parameters
----------
values : list of float
Input samples.
factor : int
How many input samples make one output sample.
Returns
-------
list of float
The resampled series.
"""
```
## reST / Sphinx field style
Common in older projects and in Sphinx-first documentation.
```python
def connect(host, port=5432):
"""Open a database connection.
:param host: Server host name.
:param int port: Server port.
:returns: An open connection.
:raises ConnectionError: If the server cannot be reached.
"""
```
## How the script recognises them
- Parameter sections: `Args:`, `Arguments:`, `Parameters:`, `Keyword Args:`, `Other Parameters:` (Google), `Parameters` followed by a dashed line (NumPy), and `:param name:` / `:param type name:` (reST). `*args` and `**kwargs` may be written with or without stars.
- Returns: `Returns:`, `Return:`, `Yields:`, NumPy `Returns` / `Yields` headings, `:returns:`, `:rtype:`, `:yields:`.
- Raises: `Raises:` sections, `:raises X:` fields, or simply the exception name anywhere in the docstring.
## Choosing
| Situation | Suggested style |
|---|---|
| New application or internal library | Google |
| Scientific / data code with arrays and shapes | NumPy |
| Existing Sphinx docs already using fields | reST |
| Mixed project | the style most existing docstrings use; convert the rest gradually |
Type hints in the signature do not replace a docstring: they say what type a value is, the docstring says what it means, its units, defaults and edge cases. When hints exist, leave the types out of the docstring to avoid them drifting apart.
FILE:references/what-to-document.md
# What to document (and what not)
## A good docstring
1. **Summary line**: one sentence in the imperative or descriptive mood, under 88 characters, ending with a period. "Return the cheapest zone for a parcel." not "This function is used to get zone."
2. **Details (optional)**: a short paragraph on behavior the name does not reveal: units, side effects (writes a file, sends an email, hits the network), caching, thread safety, performance characteristics.
3. **Parameters**: what each one means, its unit and allowed values, and what the default does. Skip obvious type repetition when there are type hints.
4. **Returns / Yields**: what comes back, including special values (None when not found, empty list).
5. **Raises**: exceptions callers are expected to handle, and when.
6. **Example (optional)**: a two-line usage example for public entry points, ideally as a doctest.
## Leave out
- Restating the code line by line or the function name in other words.
- History ("changed in March to fix bug 123"): that belongs in git and the changelog.
- Implementation details that will change often; document the contract, not the internals.
- TODOs: track them as issues.
## Priorities when coverage is low
1. Stale docs (D03): wrong information is worse than none.
2. Public entry points used by other modules, services or users (what `__init__.py` exports, CLI commands, API handlers).
3. Functions with many parameters or surprising behavior (side effects, units, None returns).
4. Classes: one paragraph on what the object represents and its lifecycle.
5. Module docstrings: one or two sentences on what lives in the file.
6. Polish (summary periods, Returns sections on obvious getters) last, ideally fixed while touching the code anyway.
## Coverage targets
- Libraries published for others: 90-100% of the public API.
- Internal services: 70-85% of public functions and classes, 100% of anything other teams call.
- Scripts and glue code: module docstring plus the main entry point.
Ratchet the CI threshold up from today's number instead of jumping to a target that blocks every pull request.
## Writing with an AI assistant
Generated docstrings are a good first draft, but always check them against the code: assistants happily document parameters the function does not have, invent exceptions or describe what the name suggests instead of what the code does. Re-run the checker afterwards to catch stale parameters.
FILE:templates/docstring-report.md
# Docstring review: {project or package}
**Scanned:** {paths} on {date} - {files} files, {objects} public objects
**Style:** {Google | NumPy | reST | mixed}
**Command:** `python3 scripts/docstring_coverage.py {paths} {options}`
## Summary
- Coverage: **{pct}%** ({documented}/{objects}); modules {m}%, classes {c}%, functions {f}%, methods {me}%
- Stale docstrings (D03): {n}
- Undocumented public objects (D01): {n}, of which {k} are main entry points
- One-sentence verdict: {e.g. "Core API mostly documented; billing module has stale parameters after the March refactor."}
## Fix first: stale or wrong docs
| Location | Object | Problem | Fix |
|---|---|---|---|
| {file:line} | `{name}` | {documents `insured`, not in signature} | {remove or rename to `express`} |
## Top undocumented entry points
| Location | Object | Why it matters | Suggested summary line |
|---|---|---|---|
| {file:line} | `{name}` | {called from 6 modules / public API} | {Return the cheapest zone for a parcel.} |
## Example docstrings (from the real code)
```python
{2-3 complete docstrings in the chosen style}
```
## Plan
1. {PR 1: fix all D03 + document public API of module X}
2. {PR 2: ...}
3. {Agree on the style in CONTRIBUTING.md}
## CI gate
`python3 scripts/docstring_coverage.py {src} --fail-under {today's pct rounded down} --min-severity high`, raise by {5-10} points per {month/quarter}.
## Deliberately left alone
- {e.g. private helpers, tests, generated code, obvious one-line properties}
## Limits
Static check only: presence and signature match, not correctness. Exceptions raised by called functions are not detected. Custom docstring formats may need manual review.
FILE:examples/shipping_rates.py
# Fictional example module for the docstring coverage checker: deliberately under-documented.
from dataclasses import dataclass
ZONES = {"domestic": 1.0, "eu": 1.6, "world": 2.4}
@dataclass
class Parcel:
weight_kg: float
length_cm: float
width_cm: float
height_cm: float
def volumetric_weight(self, divisor=5000):
"""Volumetric weight in kilograms"""
return self.length_cm * self.width_cm * self.height_cm / divisor
class RateCalculator:
"""Calculate shipping rates for parcels."""
def __init__(self, base_rate, per_kg, fuel_surcharge_pct):
self.base_rate = base_rate
self.per_kg = per_kg
self.fuel_surcharge_pct = fuel_surcharge_pct
def quote(self, parcel, zone, express=False):
"""Return the price for one parcel.
Args:
parcel: The parcel to ship.
zone: One of the keys of ZONES.
insured: Whether insurance is added.
"""
if zone not in ZONES:
raise ValueError("unknown zone: %s" % zone)
billable = max(parcel.weight_kg, parcel.volumetric_weight())
price = (self.base_rate + billable * self.per_kg) * ZONES[zone]
if express:
price *= 1.5
return round(price * (1 + self.fuel_surcharge_pct / 100), 2)
def quote_many(self, parcels, zone):
return [self.quote(p, zone) for p in parcels]
def cheapest_zone_for(parcel, calculator):
best = None
for zone in ZONES:
price = calculator.quote(parcel, zone)
if best is None or price < best[1]:
best = (zone, price)
return best
def _round_up(value, step):
return -(-value // step) * step
FILE:examples/shipping_rates_documented.py
"""Shipping rate calculation for parcels (fictional example, fully documented version)."""
from dataclasses import dataclass
ZONES = {"domestic": 1.0, "eu": 1.6, "world": 2.4}
@dataclass
class Parcel:
"""A parcel with its real weight and outer dimensions."""
weight_kg: float
length_cm: float
width_cm: float
height_cm: float
def volumetric_weight(self, divisor=5000):
"""Return the volumetric weight in kilograms.
Args:
divisor: Carrier divisor in cubic centimeters per kilogram.
Returns:
The volumetric weight as a float.
"""
return self.length_cm * self.width_cm * self.height_cm / divisor
class RateCalculator:
"""Calculate shipping rates for parcels."""
def __init__(self, base_rate, per_kg, fuel_surcharge_pct):
"""Create a calculator with one carrier's tariff.
Args:
base_rate: Fixed price per parcel.
per_kg: Price per billable kilogram.
fuel_surcharge_pct: Fuel surcharge in percent, added at the end.
"""
self.base_rate = base_rate
self.per_kg = per_kg
self.fuel_surcharge_pct = fuel_surcharge_pct
def quote(self, parcel, zone, express=False):
"""Return the price for one parcel.
Args:
parcel: The parcel to ship.
zone: One of the keys of ZONES.
express: Whether express delivery (+50 percent) is used.
Returns:
The price rounded to 2 decimals.
Raises:
ValueError: If the zone is unknown.
"""
if zone not in ZONES:
raise ValueError("unknown zone: %s" % zone)
billable = max(parcel.weight_kg, parcel.volumetric_weight())
price = (self.base_rate + billable * self.per_kg) * ZONES[zone]
if express:
price *= 1.5
return round(price * (1 + self.fuel_surcharge_pct / 100), 2)
def quote_many(self, parcels, zone):
"""Return standard prices for several parcels to the same zone.
Args:
parcels: Iterable of parcels.
zone: One of the keys of ZONES.
Returns:
A list of prices in the same order as the parcels.
"""
return [self.quote(p, zone) for p in parcels]
def cheapest_zone_for(parcel, calculator):
"""Find the zone with the lowest standard price for a parcel.
Args:
parcel: The parcel to ship.
calculator: A RateCalculator.
Returns:
A (zone, price) tuple.
"""
best = None
for zone in ZONES:
price = calculator.quote(parcel, zone)
if best is None or price < best[1]:
best = (zone, price)
return best
def _round_up(value, step):
return -(-value // step) * step
FILE:scripts/docstring_coverage.py
#!/usr/bin/env python3
"""docstring_coverage.py - measure docstring coverage and quality for Python code (standard library only).
Walks files or folders, parses each file with the ast module (code is never imported or run) and checks
every module, public class, public function and public method:
D01 high public module, class, function or method has no docstring
D02 medium parameters missing from the docstring (only when the docstring documents parameters,
or when the function has --min-params or more parameters)
D03 medium docstring documents a parameter that is not in the signature (stale)
D04 low function returns a value but the docstring has no Returns/Yields section
D05 low function raises exceptions that the docstring does not mention
D06 low summary line missing, longer than 88 characters or not ending with a period
Docstring sections are recognised in Google (Args:), NumPy (Parameters / ----------) and
reST/Sphinx (:param x:) styles.
Usage:
python3 docstring_coverage.py PATH [PATH ...] [--format text|md|json] [--min-severity low|medium|high]
[--fail-under PCT] [--include-private] [--min-params N]
python3 docstring_coverage.py --self-test
Exit code: 0 = coverage >= --fail-under and no findings at or above --min-severity,
1 = below threshold or findings present, 2 = bad path / nothing parsable.
"""
import argparse, ast, json, os, re, sys
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "node_modules", "build", "dist", "__pycache__", ".tox", ".mypy_cache", "site-packages"}
SEV = {"low": 1, "medium": 2, "high": 3}
CODES = {"D01": "high", "D02": "medium", "D03": "medium", "D04": "low", "D05": "low", "D06": "low"}
SECTION_PARAMS = re.compile(r"^\s*(Args|Arguments|Parameters|Params|Keyword Args|Keyword Arguments|Other Parameters)\s*:?\s*$", re.M)
SECTION_RETURNS = re.compile(r"^\s*(Returns?|Yields?)\s*:?\s*$|:returns?:|:rtype:|:yields?:", re.M)
SECTION_RAISES = re.compile(r"^\s*(Raises|Exceptions)\s*:?\s*$|:raises?\s", re.M)
REST_PARAM = re.compile(r":param\s+(?:[\w\[\], .]+\s+)?\*{0,2}(\w+)\s*:")
def documented_params(doc):
"""Return the set of parameter names a docstring documents, in any of the three styles."""
names = set(REST_PARAM.findall(doc))
lines = doc.splitlines()
i = 0
while i < len(lines):
if SECTION_PARAMS.match(lines[i]):
numpy = i + 1 < len(lines) and set(lines[i + 1].strip()) == {"-"}
j = i + (2 if numpy else 1)
base = None
while j < len(lines):
line = lines[j]
if not line.strip():
j += 1
continue
indent = len(line) - len(line.lstrip())
if numpy:
if j + 1 < len(lines) and set(lines[j + 1].strip()) == {"-"} and lines[j + 1].strip():
break # next numpy section
if base is None:
base = indent
if indent == base:
if re.match(r"\s*\*{0,2}\w+", line):
for part in line.split(":")[0].split(","):
p = part.strip().lstrip("*")
if p.isidentifier():
names.add(p)
else:
if re.match(r"^\s*[A-Z][A-Za-z ]+:\s*$", line) and (base is None or indent < base):
break # next google section
if base is None:
base = indent
if indent < base:
break
if indent == base:
m = re.match(r"\s*\*{0,2}(\w+)\s*(\([^)]*\))?\s*:", line)
if m:
names.add(m.group(1))
j += 1
i = j
continue
i += 1
return names
def signature_params(fn, is_method):
a = fn.args
params = [x.arg for x in getattr(a, "posonlyargs", [])] + [x.arg for x in a.args] + [x.arg for x in a.kwonlyargs]
if a.vararg:
params.append(a.vararg.arg)
if a.kwarg:
params.append(a.kwarg.arg)
if is_method and params and params[0] in ("self", "cls"):
params = params[1:]
return [p for p in params if p != "_"]
def _own_nodes(fn):
"""Walk a function body without descending into nested functions or classes."""
stack = [n for n in fn.body if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))]
while stack:
node = stack.pop()
yield node
for child in ast.iter_child_nodes(node):
if not isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
stack.append(child)
def returns_value(fn):
for n in _own_nodes(fn):
if isinstance(n, ast.Return) and n.value is not None and not (isinstance(n.value, ast.Constant) and n.value.value is None):
return True
if isinstance(n, (ast.Yield, ast.YieldFrom)):
return True
return False
def raised_names(fn):
out = set()
for n in _own_nodes(fn):
if isinstance(n, ast.Raise) and n.exc is not None:
e = n.exc.func if isinstance(n.exc, ast.Call) else n.exc
if isinstance(e, ast.Name):
out.add(e.id)
elif isinstance(e, ast.Attribute):
out.add(e.attr)
return out
def is_public(name):
return not name.startswith("_") or (name.startswith("__") and name.endswith("__") and name == "__init__")
def check_summary(doc):
first = doc.strip().splitlines()[0].strip() if doc.strip() else ""
if not first:
return "empty summary line"
if len(first) > 88:
return "summary line is %d characters (max 88)" % len(first)
if not first.endswith((".", "!", "?", ":")):
return "summary line does not end with a period"
return None
def analyze_source(src, path="<string>", include_private=False, min_params=3):
tree = ast.parse(src, filename=path)
items, findings = [], []
def add(code, obj, line, msg):
findings.append({"code": code, "severity": CODES[code], "path": path, "line": line, "object": obj, "message": msg})
mod_doc = ast.get_docstring(tree)
items.append({"path": path, "object": "<module>", "kind": "module", "line": 1, "documented": bool(mod_doc)})
if not mod_doc:
add("D01", "<module>", 1, "module has no docstring")
elif check_summary(mod_doc):
add("D06", "<module>", 1, check_summary(mod_doc))
def visit(body, prefix, in_class, parent_public):
for node in body:
if isinstance(node, ast.ClassDef):
public = parent_public and (include_private or is_public(node.name))
name = prefix + node.name
if public:
doc = ast.get_docstring(node)
items.append({"path": path, "object": name, "kind": "class", "line": node.lineno, "documented": bool(doc)})
if not doc:
add("D01", name, node.lineno, "class has no docstring")
elif check_summary(doc):
add("D06", name, node.lineno, check_summary(doc))
visit(node.body, name + ".", True, public)
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
public = parent_public and (include_private or is_public(node.name))
if any(isinstance(d, ast.Name) and d.id == "overload" or isinstance(d, ast.Attribute) and d.attr in ("overload", "setter", "deleter") for d in node.decorator_list):
continue
name = prefix + node.name
if not public:
continue
kind = "method" if in_class else "function"
doc = ast.get_docstring(node)
items.append({"path": path, "object": name, "kind": kind, "line": node.lineno, "documented": bool(doc)})
if not doc:
add("D01", name, node.lineno, "%s has no docstring" % kind)
continue
params = signature_params(node, in_class)
documented = documented_params(doc)
has_section = bool(documented) or bool(SECTION_PARAMS.search(doc))
if has_section or len(params) >= min_params:
missing = [p for p in params if p not in documented]
if missing:
add("D02", name, node.lineno, "parameters not documented: " + ", ".join(missing))
stale = sorted(documented - set(params) - {"self", "cls"})
if stale:
add("D03", name, node.lineno, "docstring documents parameters not in the signature: " + ", ".join(stale))
if returns_value(node) and not SECTION_RETURNS.search(doc) and node.name != "__init__":
add("D04", name, node.lineno, "returns a value but the docstring has no Returns/Yields section")
raised = raised_names(node)
undocumented = sorted(r for r in raised if r not in doc)
if undocumented:
add("D05", name, node.lineno, "raises without mention in the docstring: " + ", ".join(undocumented))
s = check_summary(doc)
if s:
add("D06", name, node.lineno, s)
visit(tree.body, "", False, True)
return items, findings
def iter_files(paths):
for p in paths:
if os.path.isfile(p):
yield p
elif os.path.isdir(p):
for root, dirs, files in os.walk(p):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.endswith(".egg-info"))
for f in sorted(files):
if f.endswith(".py"):
yield os.path.join(root, f)
else:
raise FileNotFoundError(p)
def summarize(items):
by_kind = {}
for it in items:
k = by_kind.setdefault(it["kind"], [0, 0])
k[0] += 1
k[1] += it["documented"]
total = len(items)
doc = sum(it["documented"] for it in items)
return {"objects": total, "documented": doc, "coverage_pct": round(100.0 * doc / total, 1) if total else 100.0,
"by_kind": {k: {"objects": v[0], "documented": v[1], "coverage_pct": round(100.0 * v[1] / v[0], 1)} for k, v in sorted(by_kind.items())}}
def render(fmt, summary, findings, errors, per_file):
if fmt == "json":
return json.dumps({"summary": summary, "files": per_file, "findings": findings, "parse_errors": errors}, indent=2)
out = []
if fmt == "md":
out.append("## Docstring coverage: %.1f%% (%d/%d objects)" % (summary["coverage_pct"], summary["documented"], summary["objects"]))
out.append("")
out.append("| Kind | Documented | Coverage |")
out.append("|---|---|---|")
for k, v in summary["by_kind"].items():
out.append("| %s | %d/%d | %.1f%% |" % (k, v["documented"], v["objects"], v["coverage_pct"]))
out.append("")
if findings:
out.append("| Code | Severity | Location | Object | Finding |")
out.append("|---|---|---|---|---|")
for f in findings:
out.append("| %s | %s | %s:%d | `%s` | %s |" % (f["code"], f["severity"], f["path"], f["line"], f["object"], f["message"]))
else:
out.append("No findings at the selected severity.")
else:
out.append("Docstring coverage: %.1f%% (%d/%d objects)" % (summary["coverage_pct"], summary["documented"], summary["objects"]))
for k, v in summary["by_kind"].items():
out.append(" %-8s %d/%d (%.1f%%)" % (k, v["documented"], v["objects"], v["coverage_pct"]))
for pf in per_file:
out.append(" file %s: %.1f%% (%d/%d)" % (pf["path"], pf["coverage_pct"], pf["documented"], pf["objects"]))
out.append("")
for f in findings:
out.append("%s %-6s %s:%d %s - %s" % (f["code"], f["severity"], f["path"], f["line"], f["object"], f["message"]))
if not findings:
out.append("No findings at the selected severity.")
for e in errors:
out.append("PARSE ERROR %s: %s" % (e["path"], e["error"]))
return "\n".join(out)
def self_test():
T = []
def check(name, cond):
T.append((name, bool(cond)))
src = '''"""Module summary."""
def a(x, y):
"""Add two numbers.
Args:
x: first.
y (int): second.
Returns:
The sum.
"""
return x + y
def b(x):
return x
'''
items, f = analyze_source(src)
codes = [x["code"] for x in f]
check("google style fully documented gives no finding for a", not [x for x in f if x["object"] == "a"])
check("missing docstring gives D01", ("D01", "b") in [(x["code"], x["object"]) for x in f])
check("coverage counts module and functions", summarize(items)["coverage_pct"] == 66.7)
items, f = analyze_source('"""M."""\ndef c(a, b):\n """Do it.\n\n Args:\n a: one.\n """\n pass\n')
check("missing param gives D02", [x["message"] for x in f if x["code"] == "D02"] == ["parameters not documented: b"])
items, f = analyze_source('"""M."""\ndef c(a):\n """Do it.\n\n Args:\n a: one.\n old: gone.\n """\n')
check("stale param gives D03", any(x["code"] == "D03" and "old" in x["message"] for x in f))
numpy = '"""M."""\ndef n(a, b):\n """Numpy style.\n\n Parameters\n ----------\n a : int\n One.\n b : str\n Two.\n\n Returns\n -------\n int\n """\n return 1\n'
items, f = analyze_source(numpy)
check("numpy style params and returns recognised", not f)
rest = '"""M."""\ndef r(a, b):\n """Rest style.\n\n :param a: one.\n :param int b: two.\n :returns: value.\n :raises ValueError: bad.\n """\n if a:\n raise ValueError("x")\n return a\n'
items, f = analyze_source(rest)
check("rest style params, returns and raises recognised", not f)
items, f = analyze_source('"""M."""\ndef s(a):\n """Short."""\n return a * 2\n')
check("return without Returns section gives D04", any(x["code"] == "D04" for x in f))
check("one short param below --min-params gives no D02", not any(x["code"] == "D02" for x in f))
items, f = analyze_source('"""M."""\ndef g(a):\n """Get."""\n raise KeyError(a)\n')
check("undocumented raise gives D05", any(x["code"] == "D05" and "KeyError" in x["message"] for x in f))
items, f = analyze_source('"""M."""\ndef h():\n """no period here"""\n')
check("summary without period gives D06", any(x["code"] == "D06" for x in f))
items, f = analyze_source('def _p():\n pass\nclass _Q:\n def m(self):\n pass\n')
check("private function and class skipped, module flagged", [x["object"] for x in f] == ["<module>"])
items, f = analyze_source('def _p():\n pass\n', include_private=True)
check("--include-private checks private names", any(x["object"] == "_p" for x in f))
cls = '"""M."""\nclass K:\n """A class."""\n def __init__(self, a, b, c):\n """Create it."""\n def run(self):\n """Run it."""\n def __repr__(self):\n return "K"\n'
items, f = analyze_source(cls)
check("__init__ with 3 params gives D02, self excluded", any(x["code"] == "D02" and x["object"] == "K.__init__" and "self" not in x["message"] for x in f))
check("dunder methods other than __init__ are skipped", not any(x["object"] == "K.__repr__" for x in f))
items, f = analyze_source('"""M."""\ndef outer():\n """Outer."""\n def inner():\n return 1\n return None\n')
check("nested return does not count for outer", not any(x["code"] == "D04" for x in f))
items, f = analyze_source('"""M."""\ndef gen(n):\n """Generate.\n\n Yields:\n Numbers.\n """\n yield n\n')
check("Yields section satisfies D04", not f)
items, f = analyze_source('"""M."""\ndef v(*args, **kwargs):\n """Var.\n\n Args:\n *args: values.\n **kwargs: options.\n """\n')
check("*args and **kwargs documented with stars", not f)
try:
analyze_source("def broken(:\n")
check("syntax error raised", False)
except SyntaxError:
check("syntax error raised", True)
for name, ok in T:
print(("PASS " if ok else "FAIL ") + name)
passed = sum(ok for _, ok in T)
print("%d/%d checks passed" % (passed, len(T)))
return 0 if passed == len(T) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description="Docstring coverage and quality checker (stdlib only).")
ap.add_argument("paths", nargs="*")
ap.add_argument("--format", choices=["text", "md", "json"], default="text")
ap.add_argument("--min-severity", choices=list(SEV), default="low")
ap.add_argument("--fail-under", type=float, default=0.0, help="minimum coverage percent (default 0)")
ap.add_argument("--include-private", action="store_true")
ap.add_argument("--min-params", type=int, default=3, help="require a parameter section from this many parameters (default 3)")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.paths:
ap.error("give at least one path or --self-test")
try:
files = list(iter_files(a.paths))
except FileNotFoundError as e:
print("no such path: %s" % e, file=sys.stderr)
return 2
all_items, findings, errors, per_file = [], [], [], []
for p in files:
try:
with open(p, encoding="utf-8") as fh:
items, f = analyze_source(fh.read(), p, a.include_private, a.min_params)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append({"path": p, "error": str(e).splitlines()[0]})
continue
all_items += items
findings += f
s = summarize(items)
per_file.append({"path": p, "objects": s["objects"], "documented": s["documented"], "coverage_pct": s["coverage_pct"]})
if not all_items:
print(render(a.format, summarize([]), [], errors, []))
return 2
shown = [f for f in findings if SEV[f["severity"]] >= SEV[a.min_severity]]
shown.sort(key=lambda f: (-SEV[f["severity"]], f["path"], f["line"], f["code"]))
summary = summarize(all_items)
summary["fail_under"] = a.fail_under
print(render(a.format, summary, shown, errors, per_file))
return 1 if shown or summary["coverage_pct"] < a.fail_under else 0
if __name__ == "__main__":
sys.exit(main())
Opinionated habits for measuring and fixing performance problems: profilers, benchmarks, percentiles and evidence-backed optimizations.
# Performance Profiling taste of an engineer who measures before optimizing anything - Never optimize without a reproducible benchmark or production profile that shows the hot path first. Confidence: 0.95 - Write down the target before starting (for example "p95 under 200 ms at 500 rps") and stop once it is met. Confidence: 0.85 - Profile in an environment close to production: optimized build, realistic data size and the same CPU architecture. Confidence: 0.90 - Use sampling profilers (perf, py-spy, async-profiler, pprof, Chrome DevTools) before instrumenting ones, because they barely change what they measure. Confidence: 0.85 - Read flame graphs for wide frames, not tall stacks; the widest box near the top is usually the place to work on. Confidence: 0.85 - Keep continuous profiling running in production (Pyroscope, Parca, Datadog) so regressions can be compared with last week. Confidence: 0.70 - Look at wall-clock time and CPU time separately; a slow request that is mostly waiting needs tracing, not a CPU profile. Confidence: 0.90 - Use distributed tracing to find which service or query owns the latency before profiling any single process. Confidence: 0.80 - Report latency as percentiles (p50, p95, p99) with sample counts, never averages alone. Confidence: 0.95 - Warm up before measuring and run each benchmark enough times to report variance, using tools like hyperfine, criterion, BenchmarkDotNet or pytest-benchmark. Confidence: 0.85 - Change one thing at a time and keep before and after numbers in the pull request description. Confidence: 0.90 - Check the algorithm and the number of round trips (N+1 queries, chatty APIs) before micro-optimizing code. Confidence: 0.90 - Run `EXPLAIN ANALYZE` on the slow query with production-like statistics before adding an index or rewriting it. Confidence: 0.85 - Profile memory as a separate pass: allocation rate, heap growth and GC pauses, using heap snapshots or allocation profilers. Confidence: 0.80 - Treat lock contention and thread pool saturation as first-class suspects in concurrent services, and profile off-CPU time to see them. Confidence: 0.70 - Prefer caching only after proving the work is repeated and the data can tolerate staleness. Confidence: 0.80 - Keep micro-benchmarks in the repository next to the code they measure, and run the critical ones in CI with a regression threshold. Confidence: 0.70 - Pin CPU frequency and isolate benchmark runners, or use instruction counts, so CI noise does not trigger false alarms. Confidence: 0.60 - For frontend work, profile on a throttled mid-range device and track Core Web Vitals from real users, not only Lighthouse on a laptop. Confidence: 0.80 - Leave a short comment next to any non-obvious optimization explaining the measurement that justified it. Confidence: 0.85 - Remove an optimization that no longer shows up in profiles if it makes the code harder to read. Confidence: 0.65 - Share profiles as files or links in the incident or PR so others can reproduce the analysis. Confidence: 0.75
Opinionated Deno conventions for secure, zero-config TypeScript servers and tools: permissions, JSR imports, testing and publishing.
# Deno Project taste of a TypeScript developer who wants secure, zero-config server code - Start with `deno init` and keep a single `deno.json` for tasks, imports, lint, fmt and compiler options; no separate tsconfig or eslintrc. Confidence: 0.90 - Pin dependencies in the `imports` map of `deno.json` with `jsr:` and `npm:` specifiers, and keep version numbers out of source files. Confidence: 0.90 - Prefer JSR packages, starting with `@std/*`, over npm equivalents when both exist. Confidence: 0.80 - Commit `deno.lock` and run CI with `--frozen` so a dependency can never change silently. Confidence: 0.90 - Grant the narrowest permissions possible, scoped to hosts and paths (`--allow-net=api.example.com`, `--allow-read=./data`); never `-A` outside quick local experiments. Confidence: 0.95 - Write the permission flags into the `deno.json` tasks so every developer runs the app with the same sandbox. Confidence: 0.85 - Use `Deno.serve` with a plain `(req: Request) => Response` handler, and add Hono only when routing grows beyond a few paths. Confidence: 0.80 - Stick to Web standard APIs (`fetch`, `Request`, `URL`, `crypto.subtle`, streams) before reaching for Deno-only or Node-compat APIs. Confidence: 0.85 - Treat `node:` imports and npm packages as an escape hatch and keep them out of core domain modules. Confidence: 0.70 - Keep TypeScript strict as Deno ships it and never weaken compiler options to silence errors. Confidence: 0.90 - Use `deno fmt` and `deno lint` with default rules; argue about logic, not formatting. Confidence: 0.85 - Write tests with `Deno.test` and `@std/assert` next to the code as `*_test.ts` files. Confidence: 0.85 - Run `deno test` with the same narrow permissions as production, so missing grants fail in CI and not at runtime. Confidence: 0.75 - Use `t.step` for grouped scenarios and rely on the built-in resource and op sanitizers to catch leaked timers and sockets. Confidence: 0.70 - Collect coverage with `deno test --coverage` and `deno coverage --lcov` without extra tooling. Confidence: 0.65 - Run `deno check` in CI on every entry point, including scripts that are not imported by the main app. Confidence: 0.80 - Read configuration through a single typed module that validates `Deno.env` once at startup and fails fast on missing values. Confidence: 0.85 - Use the `--env-file` flag for local `.env` files instead of a dotenv dependency. Confidence: 0.75 - Use Deno KV for small queues, counters and session data when deploying to Deno Deploy; use Postgres once relations matter. Confidence: 0.60 - Ship single-binary internal tools with `deno compile`, embedding only the permissions the tool needs. Confidence: 0.75 - Publish shared libraries to JSR with explicit `exports`, JSDoc on every public symbol and no slow types, and check them with `deno publish --dry-run`. Confidence: 0.85 - Handle shutdown by listening for `SIGTERM` with `Deno.addSignalListener` and awaiting `server.shutdown()`. Confidence: 0.70 - Use `deno task` for every repeated command instead of a Makefile or npm scripts. Confidence: 0.80
Opinionated conventions for building, testing and releasing small, dependable Ruby gems with clean gemspecs and safe publishing.
# Ruby Gem taste of a maintainer who ships small, dependable gems with boring releases - Scaffold new gems with `bundle gem <name> --test=rspec --ci=github --linter=rubocop` and keep the generated layout instead of inventing a custom one. Confidence: 0.80 - Keep the gemspec as the single source of truth for metadata, required Ruby version and runtime dependencies; the Gemfile only adds development tools. Confidence: 0.90 - Set `required_ruby_version` explicitly and support only Ruby versions that still receive security fixes. Confidence: 0.85 - Build `spec.files` from `git ls-files` filtered to `lib`, `sig`, `exe`, LICENSE, README and CHANGELOG so tests and fixtures never ship in the package. Confidence: 0.85 - Add as few runtime dependencies as possible and give each one a pessimistic constraint like `~> 2.3`, never an unbounded `>=`. Confidence: 0.90 - Do not commit `Gemfile.lock` for a library; let CI resolve fresh dependencies so breakage shows up early. Confidence: 0.65 - Namespace everything under one top-level module that matches the gem name, and never monkey-patch core classes from a library. Confidence: 0.95 - Use Zeitwerk for gems with many files, and plain `require_relative` for small ones. Confidence: 0.70 - Expose configuration through a `configure` block that yields a plain configuration object with documented defaults. Confidence: 0.80 - Define a base `<GemName>::Error < StandardError` and raise specific subclasses so callers can rescue the whole family. Confidence: 0.90 - Add `# frozen_string_literal: true` to every Ruby file. Confidence: 0.80 - Write tests in RSpec with `--require spec_helper`, random order and `disable_monkey_patching!` turned on. Confidence: 0.80 - Run CI on a matrix of all supported Rubies plus `head`, with `head` allowed to fail. Confidence: 0.85 - Enforce style with RuboCop (or Standard) in CI, and keep project-wide disables in `.rubocop.yml` instead of inline comments. Confidence: 0.75 - Ship RBS signatures in `sig/` for the public API, or at least YARD types, so editors and Steep can check callers. Confidence: 0.60 - Document every public method with YARD and keep a runnable quick-start example at the top of the README. Confidence: 0.80 - Follow Semantic Versioning strictly and keep `VERSION` in `lib/<gem>/version.rb` as the only place the version lives. Confidence: 0.95 - Maintain a CHANGELOG in Keep a Changelog format and update it in the same pull request as the change. Confidence: 0.85 - Deprecate before removing: warn through `Kernel#warn` with `category: :deprecated` for at least one minor release. Confidence: 0.85 - Publish from CI with RubyGems trusted publishing on a tagged release instead of running `gem push` from a laptop. Confidence: 0.85 - Require MFA for every owner by setting `rubygems_mfa_required` to "true" in the gemspec metadata. Confidence: 0.95 - Set `source_code_uri`, `changelog_uri` and `bug_tracker_uri` in the metadata so rubygems.org links back to the repository. Confidence: 0.75 - Keep optional integrations (Rails, Sidekiq) behind separate requires such as `require "<gem>/rails"` so they never load by default. Confidence: 0.80 - Test the packaged gem, not only the repo: build it in CI, install it into a clean bundle and run a smoke script. Confidence: 0.70
Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.
---
name: python-complexity-hotspot-finder
description: Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.
---
# Python Complexity Hotspot Finder
You help Python developers, tech leads and maintainers find the functions that are hardest to change safely and decide what to refactor first. Big if/elif ladders, deep nesting and functions with seven flags are where bugs hide and where new teammates get stuck, but not every complex function is worth touching. You combine complexity metrics with how often code actually changes, explain the results in plain language, and propose small, test-backed refactoring steps.
You read code locally and never upload it. Metrics are a guide, not a verdict: you say when a high number is fine (for example a flat lookup) and the team makes the final call.
## Files in this skill
- `scripts/complexity_hotspots.py` - walks files or folders (skips .git, venvs, build dirs), measures every function and method with the `ast` module: cyclomatic complexity, nesting depth, lines, parameters, returns; optional `--churn DAYS` adds git commit counts per file and ranks by `cc x (1 + churn)`; findings H01-H07; `--format text|md|json`, `--min-severity`, `--top N`, threshold flags; `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/complexity-metrics.md` - how each metric is counted, rough bands, what churn adds and what the numbers do not tell you
- `references/refactoring-recipes.md` - guard clauses, lookup tables, extract function, flag parameters, condition helpers, and what not to do
- `templates/hotspot-report.md` - the review you hand back
- `examples/billing.py` - a fictional billing module with a CC 22, 7-parameter pricing function; `examples/billing_refactored.py` - the same logic after refactoring (CC 5 at most)
## Workflow
### 1. Scope
Ask which package or folders matter, whether it is a git repository (for churn), what is changing soon (upcoming features touch which modules?), and whether there are tests. Exclude generated code, migrations and vendored libraries.
### 2. Run the scan
```
python3 scripts/complexity_hotspots.py src/
python3 scripts/complexity_hotspots.py src/ --churn 90 --top 15
python3 scripts/complexity_hotspots.py src/ --churn 90 --min-severity medium --format md > hotspots.md
python3 scripts/complexity_hotspots.py src/ --format json
python3 scripts/complexity_hotspots.py --self-test
```
Exit code 0 = nothing at or above `--min-severity`, 1 = findings, 2 = bad path or only unparsable files. Files with syntax errors are listed as PARSE ERROR and skipped.
| Code | Severity | Meaning |
|---|---|---|
| H01 | high | CC >= 15 (`--cc-high`) |
| H02 | medium | CC >= 10 (`--cc-warn`) |
| H03 | medium | nesting depth >= 4 |
| H04 | medium | 60+ lines |
| H05 | low | 6+ parameters (self/cls excluded) |
| H06 | low | 6+ return statements |
| H07 | high | hotspot: CC >= warn and file changed in 5+ commits in the churn window |
### 3. Interpret
- Rank by hotspot score when churn is available; a complex function nobody touches is low priority.
- Read the top 3-5 functions yourself before recommending anything. Check whether the complexity is accidental (copy-pasted branches, flags, deep nesting) or essential (real business rules).
- Flat dispatch functions (`invoice_status` with six early returns) are usually fine: say so.
- Check test coverage for each top hotspot; untested hotspots get characterization tests first.
### 4. Plan the refactor
For each top hotspot pick recipes from `references/refactoring-recipes.md`, list small steps (one commit each), estimate effort (S/M/L) and the expected CC afterwards. Never mix behavior changes with refactoring. Re-run the script after the change to show the before/after numbers.
### 5. Report
Fill `templates/hotspot-report.md`: summary, top hotspots table, a step-by-step plan for #1, what you leave alone on purpose and why, and the limits (per-file churn, renames).
## Example
```
python3 scripts/complexity_hotspots.py examples/billing.py
```
flags `calculate_invoice_total` with H01 (CC 22) and H05 (7 parameters) and `invoice_status` with H06 (6 returns, fine for a flat lookup). After extracting `tax_rate`, `line_total`, `apply_coupon` and `loyalty_discount` and moving rates into tables, `examples/billing_refactored.py` peaks at CC 5.
## Rules
- Measure first, then read the code; never recommend a refactor from numbers alone.
- Prefer small, reversible steps behind tests.
- Be honest about trade-offs: tables move complexity into data; helpers add jumps.
- Keep code on the user's machine.
FILE:references/complexity-metrics.md
# Complexity metrics: what they mean and how to read them
## Cyclomatic complexity (CC)
The number of independent paths through a function: 1 plus one for every decision point. `complexity_hotspots.py` counts:
| Construct | Adds |
|---|---|
| `if` / `elif` | 1 each (an `else` adds nothing) |
| `for`, `async for`, `while` | 1 |
| each `except` handler | 1 |
| `and` / `or` | 1 per extra operand (`a and b or c` adds 2) |
| comprehension (`for` part) and each of its `if` filters | 1 each |
| ternary `x if c else y` | 1 |
| `assert` | 1 |
| each `case` in `match` (Python 3.10+) | 1 |
Nested functions, classes and lambdas are measured on their own and do not add to the outer function.
### Rough bands (adjust with `--cc-warn` / `--cc-high`)
| CC | Reading |
|---|---|
| 1-5 | simple, easy to test |
| 6-10 | fine, keep an eye on it |
| 11-15 | hard to test fully; refactor when you next change it (H02) |
| 16+ | high risk; bugs hide here, plan a refactor (H01) |
CC is also the minimum number of test cases needed to cover every branch, which makes it a useful argument when talking to a team about test effort.
## Nesting depth
How many blocks deep the deepest statement sits (`if` inside `for` inside `try` = 3). An `elif` chain stays at the same depth. Depth 4+ (H03) usually means guard clauses or extracted helpers would help readability more than anything else.
## Length, parameters, returns
- **Lines** (H04, default 60): long functions mix several jobs. Length alone is weak; combined with high CC it is strong.
- **Parameters** (H05, default 6, `self`/`cls` excluded, `*args`/`**kwargs` counted): many flags often mean the function does several things; boolean flags are the strongest smell.
- **Returns** (H06, default 6): many exits are fine for a flat lookup (`invoice_status` style) but confusing in a long, nested function.
## Churn and hotspots (H07)
Complexity hurts only where people change code. With `--churn DAYS` the script counts how many commits touched each file in the last DAYS days (`git log --name-only`) and ranks by `score = cc x (1 + churn)`. A function with CC 12 in a file changed 30 times this quarter is a better refactoring target than a CC 25 parser nobody has touched in three years.
Limits: churn is per file, not per function; renames and big formatting commits inflate it; squash-merge workflows deflate it. Mention this when presenting results.
## What these numbers do not tell you
- Whether the code is correct or well tested; pair hotspots with coverage data if you have it.
- Domain complexity: some rules are genuinely complex, and a table-driven rewrite just moves the complexity into data (often still a win: data is easier to review and test).
- Readability of names and comments.
FILE:references/refactoring-recipes.md
# Refactoring recipes for complex Python functions
Always refactor behind tests. If the hotspot has no tests, first write characterization tests that pin today's behavior (including odd cases), then change structure in small commits, running tests after each step.
## 1. Guard clauses (fixes deep nesting, H03)
Return or `continue` early for the invalid or trivial cases instead of wrapping the main path in `if`.
```python
# before
for item in items:
if item.qty > 0:
if item.active:
process(item)
# after
for item in items:
if item.qty <= 0 or not item.active:
continue
process(item)
```
## 2. Lookup table instead of if/elif ladders (fixes H01/H02)
When branches only pick a value (a rate, a label, a handler), move the mapping into a dict.
```python
RATES = {("books", "EU"): 1.05, ("books", "*"): 1.08, ("*", "EU"): 1.2}
rate = RATES.get((cat, region), RATES.get((cat, "*"), 1.0))
```
For branches that run different code, map keys to functions: `HANDLERS[event.type](event)`.
## 3. Extract function (fixes H01, H04)
Give each job its own small, named function (`line_total`, `apply_coupon`, `loyalty_discount`). The parent becomes a readable sequence of steps, and each helper can be tested alone.
## 4. Replace boolean flag parameters (fixes H05)
`rush=False, gift_wrap=False, express=False` -> a small options set, an enum, or separate functions (`send_rush_order`). Group related parameters into a dataclass (`Address`, `PricingContext`).
## 5. Decompose complex conditions
`if customer.get("vip") or customer.get("orders", 0) > 20:` -> `if is_loyal(customer):`. The CC moves into a tiny, well-named function.
## 6. Polymorphism or `match` for type switches
A long `if kind == ...` over object types can become classes with a shared method, or a `match` statement that is easier to scan (CC stays similar but readability improves; say so honestly).
## 7. Split loops that do several things
One loop that filters, transforms, totals and logs -> a comprehension for filtering, a helper for transforming, `sum()` for totals.
## What not to do
- Do not chase a number: a flat 12-case lookup with CC 13 can be perfectly clear. Explain why you leave it.
- Do not refactor and change behavior in the same commit.
- Do not split a function into helpers that only make sense together and must be read in order; that adds jumps without reducing complexity.
- Do not refactor stable, untouched code just because it scores high; prioritize by churn and upcoming work.
FILE:templates/hotspot-report.md
# Complexity hotspot review: {{project}} ({{date}})
**Scope:** {{paths}} - {{function_count}} functions, average CC {{average_cc}}
**Thresholds:** CC warn {{cc_warn}} / high {{cc_high}}, depth {{max_depth}}, lines {{max_lines}}, params {{max_params}}; churn window {{churn_days}} days
## Summary
- {{one_sentence_overall_health}}
- Top risk: `{{top_function}}` ({{top_file}}) - {{why_it_matters}}
- Recommended next step: {{next_step}}
## Top hotspots
| Rank | Function | File | CC | Depth | Lines | Churn | Why it matters | Suggested refactor | Effort |
|---|---|---|---|---|---|---|---|---|---|
| 1 | | | | | | | | | S / M / L |
| 2 | | | | | | | | | |
| 3 | | | | | | | | | |
## Refactoring plan for the #1 hotspot
1. Characterization tests to add first: {{tests}}
2. Steps (one commit each): {{steps}}
3. Expected result: CC {{cc_before}} -> about {{cc_after}}, no behavior change
4. Risks and how we will check them: {{risks}}
## Left as is (on purpose)
- `{{function}}`: {{reason, e.g. flat lookup, stable for 2 years, scheduled for removal}}
## Notes and limits
- Churn is counted per file from git history; renames or formatting commits can inflate it.
- Metrics point to where to look; the team decides what to change.
FILE:examples/billing.py
"""Fictional billing module with typical hotspots (demo data for complexity_hotspots.py)."""
def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", rush=False, gift_wrap=False):
total = 0
for item in items:
if item.get("qty", 0) <= 0:
continue
price = item["price"] * item["qty"]
if item.get("category") == "books":
if region == "EU":
price = price * 1.05
elif region == "UK":
price = price
else:
price = price * 1.08
elif item.get("category") == "food":
if region == "EU" and not customer.get("business"):
price = price * 1.07
else:
price = price * 1.0
else:
if region == "EU":
price = price * 1.2
elif region == "UK":
price = price * 1.2
elif region == "US" and customer.get("state") in ("CA", "NY"):
price = price * 1.09
else:
price = price * 1.0
total += price
if coupon:
if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
total = total * (1 - coupon["value"] / 100)
elif coupon.get("type") == "fixed":
total = max(0, total - coupon["value"])
if customer.get("vip") or customer.get("orders", 0) > 20:
total = total * 0.95
if rush:
total += 15 if currency == "EUR" else 18
if gift_wrap:
total += 3
return round(total, 2)
def invoice_status(invoice, today):
if invoice["paid"]:
return "paid"
if invoice.get("disputed"):
return "disputed"
days = (today - invoice["due"]).days
if days <= 0:
return "open"
if days <= 30:
return "overdue"
if days <= 90:
return "late"
return "collections"
def format_amount(value, currency):
return "%s %.2f" % (currency, value)
FILE:examples/billing_refactored.py
"""The same billing logic after refactoring the hotspot (demo data for complexity_hotspots.py)."""
TAX_RATES = {
# (category, region) -> rate; "*" means any
("books", "EU"): 1.05, ("books", "UK"): 1.0, ("books", "*"): 1.08,
("food", "EU"): 1.07, ("food", "*"): 1.0,
("*", "EU"): 1.2, ("*", "UK"): 1.2, ("*", "*"): 1.0,
}
US_TAXED_STATES = {"CA": 1.09, "NY": 1.09}
RUSH_FEE = {"EUR": 15, "USD": 18}
GIFT_WRAP_FEE = 3
def tax_rate(category, region, customer):
if category == "food" and customer.get("business"):
return 1.0
if category not in ("books", "food") and region == "US":
return US_TAXED_STATES.get(customer.get("state"), 1.0)
key_category = category if category in ("books", "food") else "*"
return TAX_RATES.get((key_category, region), TAX_RATES[(key_category, "*")])
def line_total(item, region, customer):
return item["price"] * item["qty"] * tax_rate(item.get("category"), region, customer)
def apply_coupon(total, coupon):
if not coupon:
return total
if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
return total * (1 - coupon["value"] / 100)
if coupon.get("type") == "fixed":
return max(0, total - coupon["value"])
return total
def loyalty_discount(total, customer):
loyal = customer.get("vip") or customer.get("orders", 0) > 20
return total * 0.95 if loyal else total
def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", options=()):
subtotal = sum(line_total(i, region, customer) for i in items if i.get("qty", 0) > 0)
total = loyalty_discount(apply_coupon(subtotal, coupon), customer)
if "rush" in options:
total += RUSH_FEE.get(currency, 18)
if "gift_wrap" in options:
total += GIFT_WRAP_FEE
return round(total, 2)
FILE:scripts/complexity_hotspots.py
#!/usr/bin/env python3
"""complexity_hotspots.py - find Python functions that are hard to change safely.
Measures per function/method (standard library only, Python 3.8+):
cc cyclomatic complexity (1 + decision points: if/elif, for/while, except,
boolean operators, comprehension ifs, ternaries, match cases, assert)
depth deepest nesting of blocks inside the function
lines function length in source lines
params number of parameters (excluding self/cls)
returns number of return statements
Optional --churn adds how many commits touched each file in the last N days (git log),
and ranks hotspots by cc x (1 + churn).
Findings (severity):
H01 cc >= --cc-high (default 15) high
H02 cc >= --cc-warn (default 10) medium
H03 nesting depth >= --max-depth (4) medium
H04 lines >= --max-lines (60) medium
H05 params >= --max-params (6) low
H06 returns >= --max-returns (6) low
H07 hotspot: cc >= cc-warn and file churn >= --churn-min (5) high
Usage:
complexity_hotspots.py PATH [PATH ...] [--format text|md|json] [--min-severity low|medium|high]
[--churn DAYS] [--top N] [--cc-warn N] [--cc-high N] ...
complexity_hotspots.py --self-test
Exit codes: 0 no findings at or above min severity, 1 findings present, 2 usage/parse error.
"""
import argparse, ast, json, os, subprocess, sys
SEV = {"low": 1, "medium": 2, "high": 3}
SKIP_DIRS = {".git", ".venv", "venv", "env", "__pycache__", "node_modules", "build", "dist", ".tox", ".mypy_cache"}
class FuncVisitor(ast.NodeVisitor):
"""Computes metrics for one function body without descending into nested defs."""
BLOCKS = (ast.If, ast.For, ast.AsyncFor, ast.While, ast.Try, ast.With, ast.AsyncWith)
def __init__(self):
self.cc = 1
self.max_depth = 0
self.returns = 0
self._depth = 0
def generic_visit(self, node):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
return # nested definitions are measured separately (lambdas count as 0)
block = isinstance(node, self.BLOCKS) or type(node).__name__ in ("TryStar", "Match")
if isinstance(node, (ast.If, ast.For, ast.AsyncFor, ast.While, ast.IfExp, ast.Assert)):
self.cc += 1
elif isinstance(node, ast.ExceptHandler):
self.cc += 1
elif isinstance(node, ast.BoolOp):
self.cc += len(node.values) - 1
elif isinstance(node, ast.comprehension):
self.cc += 1 + len(node.ifs)
elif type(node).__name__ == "match_case":
self.cc += 1
elif isinstance(node, ast.Return):
self.returns += 1
if block:
# an elif is an If inside orelse; do not count it as deeper nesting
self._depth += 1
self.max_depth = max(self.max_depth, self._depth)
super().generic_visit(node)
if block:
self._depth -= 1
def visit_If(self, node):
self.cc += 1
self.visit(node.test)
self._depth += 1
self.max_depth = max(self.max_depth, self._depth)
for n in node.body:
self.visit(n)
self._depth -= 1
orelse = node.orelse
if len(orelse) == 1 and isinstance(orelse[0], ast.If):
self.visit_If(orelse[0]) # elif chain: same depth
else:
self._depth += 1
for n in orelse:
self.visit(n)
self._depth -= 1
def measure_function(node):
v = FuncVisitor()
for stmt in node.body:
v.visit(stmt)
args = node.args
names = [a.arg for a in getattr(args, "posonlyargs", []) + args.args + args.kwonlyargs]
if args.vararg: names.append(args.vararg.arg)
if args.kwarg: names.append(args.kwarg.arg)
params = len([n for n in names if n not in ("self", "cls")])
end = getattr(node, "end_lineno", node.lineno)
return {"cc": v.cc, "depth": v.max_depth, "lines": end - node.lineno + 1, "params": params, "returns": v.returns}
def analyze_source(src, filename="<string>"):
tree = ast.parse(src, filename=filename)
out = []
def walk(node, prefix):
for child in ast.iter_child_nodes(node):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
name = prefix + child.name
m = measure_function(child)
m.update({"file": filename, "function": name, "line": child.lineno})
out.append(m)
walk(child, name + ".")
elif isinstance(child, ast.ClassDef):
walk(child, prefix + child.name + ".")
else:
walk(child, prefix)
walk(tree, "")
return out
def iter_py_files(paths):
for p in paths:
if os.path.isfile(p):
if p.endswith(".py"): yield p
continue
for root, dirs, files in os.walk(p):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
for f in sorted(files):
if f.endswith(".py"):
yield os.path.join(root, f)
def git_churn(path, days):
"""Commits per file in the last `days` days, keyed by absolute path. Empty dict if not a git repo."""
base = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path)) or "."
try:
top = subprocess.run(["git", "-C", base, "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=True).stdout.strip()
log = subprocess.run(["git", "-C", top, "log", "--since=%d.days" % days, "--name-only", "--pretty=format:"],
capture_output=True, text=True, check=True).stdout
except (OSError, subprocess.CalledProcessError):
return {}
churn = {}
for line in log.splitlines():
line = line.strip()
if line.endswith(".py"):
k = os.path.normpath(os.path.join(top, line))
churn[k] = churn.get(k, 0) + 1
return churn
def findings_for(m, o):
f = []
if m["cc"] >= o.cc_high: f.append(("H01", "high", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_high)))
elif m["cc"] >= o.cc_warn: f.append(("H02", "medium", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_warn)))
if m["depth"] >= o.max_depth: f.append(("H03", "medium", "nesting depth %d >= %d" % (m["depth"], o.max_depth)))
if m["lines"] >= o.max_lines: f.append(("H04", "medium", "%d lines >= %d" % (m["lines"], o.max_lines)))
if m["params"] >= o.max_params: f.append(("H05", "low", "%d parameters >= %d" % (m["params"], o.max_params)))
if m["returns"] >= o.max_returns: f.append(("H06", "low", "%d return statements >= %d" % (m["returns"], o.max_returns)))
if m.get("churn") is not None and m["cc"] >= o.cc_warn and m["churn"] >= o.churn_min:
f.append(("H07", "high", "hotspot: complex (cc %d) and changed in %d commits recently" % (m["cc"], m["churn"])))
return f
def run(paths, o):
results, errors = [], []
churn = {}
if o.churn:
for p in paths:
churn.update(git_churn(p, o.churn))
for f in iter_py_files(paths):
try:
with open(f, encoding="utf-8") as fh:
ms = analyze_source(fh.read(), f)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append("%s: %s" % (f, e)); continue
for m in ms:
if o.churn:
m["churn"] = churn.get(os.path.normpath(os.path.abspath(f)), 0)
m["score"] = m["cc"] * (1 + m.get("churn", 0))
m["findings"] = [dict(code=c, severity=s, message=t) for c, s, t in findings_for(m, o)]
results.append(m)
results.sort(key=lambda m: (-m["score"], -m["cc"], m["file"], m["line"]))
return results, errors
def render(results, errors, o):
minsev = SEV[o.min_severity]
flagged = [m for m in results if any(SEV[x["severity"]] >= minsev for x in m["findings"])]
top = flagged[: o.top] if o.top else flagged
n = len(results)
avg = sum(m["cc"] for m in results) / n if n else 0
if o.format == "json":
return json.dumps({"functions": n, "average_cc": round(avg, 2), "flagged": len(flagged), "errors": errors,
"hotspots": top}, indent=2)
churn_col = o.churn is not None and o.churn > 0
if o.format == "md":
head = "| Rank | Function | File:line | CC | Depth | Lines | Params |" + (" Churn |" if churn_col else "") + " Findings |"
sep = "|---|---|---|---|---|---|---|" + ("---|" if churn_col else "") + "---|"
rows = [head, sep]
for i, m in enumerate(top, 1):
fs = "; ".join("%s %s" % (x["code"], x["message"]) for x in m["findings"])
rows.append("| %d | `%s` | %s:%d | %d | %d | %d | %d |%s %s |" % (i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"],
(" %d |" % m.get("churn", 0)) if churn_col else "", fs))
rows.append("")
rows.append("%d functions, average CC %.1f, %d flagged at %s+." % (n, avg, len(flagged), o.min_severity))
return "\n".join(rows)
lines = ["Complexity hotspots: %d functions, average CC %.1f, %d flagged (min severity %s)" % (n, avg, len(flagged), o.min_severity), ""]
for i, m in enumerate(top, 1):
extra = (" churn=%d" % m["churn"]) if "churn" in m else ""
lines.append("%2d. %s (%s:%d) cc=%d depth=%d lines=%d params=%d returns=%d%s score=%d" % (
i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"], m["returns"], extra, m["score"]))
for x in m["findings"]:
lines.append(" [%s] %s %s" % (x["severity"].upper(), x["code"], x["message"]))
if not top: lines.append("No functions above the thresholds.")
for e in errors: lines.append("PARSE ERROR " + e)
return "\n".join(lines)
def parser():
p = argparse.ArgumentParser(description="Find complex, frequently changed Python functions.")
p.add_argument("paths", nargs="*")
p.add_argument("--format", choices=["text", "md", "json"], default="text")
p.add_argument("--min-severity", choices=list(SEV), default="low")
p.add_argument("--churn", type=int, metavar="DAYS", help="add git churn for the last DAYS days")
p.add_argument("--churn-min", type=int, default=5)
p.add_argument("--top", type=int, default=0, help="show only the top N flagged functions")
p.add_argument("--cc-warn", type=int, default=10)
p.add_argument("--cc-high", type=int, default=15)
p.add_argument("--max-depth", type=int, default=4)
p.add_argument("--max-lines", type=int, default=60)
p.add_argument("--max-params", type=int, default=6)
p.add_argument("--max-returns", type=int, default=6)
p.add_argument("--self-test", action="store_true")
return p
def self_test():
o = parser().parse_args([])
def cc(src):
return {m["function"]: m for m in analyze_source(src)}
checks = []
def check(name, cond): checks.append((name, bool(cond)))
m = cc("def f():\n return 1\n")["f"]
check("straight-line function has cc 1", m["cc"] == 1 and m["depth"] == 0)
m = cc("def f(x):\n if x:\n return 1\n return 2\n")["f"]
check("one if gives cc 2", m["cc"] == 2 and m["returns"] == 2)
m = cc("def f(x):\n if x == 1:\n a = 1\n elif x == 2:\n a = 2\n elif x == 3:\n a = 3\n else:\n a = 0\n return a\n")["f"]
check("elif chain adds 1 each, depth stays 1", m["cc"] == 4 and m["depth"] == 1)
m = cc("def f(a, b, c):\n return a and b or c\n")["f"]
check("boolean operators add per operand", m["cc"] == 3)
m = cc("def f(xs):\n return [x for x in xs if x if x > 2]\n")["f"]
check("comprehension and its ifs count", m["cc"] == 4)
m = cc("def f():\n try:\n g()\n except ValueError:\n pass\n except KeyError:\n pass\n")["f"]
check("each except handler counts", m["cc"] == 3)
m = cc("def f(x):\n return 1 if x else 2\n")["f"]
check("ternary counts", m["cc"] == 2)
m = cc("def f(x):\n while x:\n for i in x:\n if i:\n with open(i) as h:\n pass\n")["f"]
check("nesting depth 4", m["depth"] == 4 and m["cc"] == 4)
r = cc("def outer():\n def inner(x):\n if x: return 1\n return inner\n")
check("nested function measured separately", r["outer"]["cc"] == 1 and r["outer.inner"]["cc"] == 2)
r = cc("class A:\n def m(self, a, b):\n pass\n")
check("method name and self excluded from params", r["A.m"]["params"] == 2)
r = cc("def f(a, b, c, d, e, f, *args, **kw):\n pass\n")
check("varargs counted as params", r["f"]["params"] == 8)
m = cc("def f(x):\n assert x\n return x\n")["f"]
check("assert counts", m["cc"] == 2)
if sys.version_info >= (3, 10):
m = cc("def f(x):\n match x:\n case 1:\n return 1\n case _:\n return 0\n")["f"]
check("match cases count", m["cc"] == 3)
else:
check("match cases count (skipped < 3.10)", True)
big = "def big(x):\n" + "".join(" if x == %d:\n return %d\n" % (i, i) for i in range(16)) + " return -1\n"
m = cc(big)["big"]
fs = [c for c, _, _ in findings_for(m, o)]
check("cc 17 gives H01 and many returns H06", m["cc"] == 17 and "H01" in fs and "H06" in fs and "H02" not in fs)
m = dict(cc=11, depth=1, lines=10, params=1, returns=1)
check("cc 11 gives H02 only", [c for c, _, _ in findings_for(m, o)] == ["H02"])
m = dict(cc=11, depth=1, lines=10, params=1, returns=1, churn=7)
check("complex + churn gives H07", "H07" in [c for c, _, _ in findings_for(m, o)])
m = dict(cc=3, depth=1, lines=10, params=1, returns=1, churn=40)
check("simple + churn is not a hotspot", findings_for(m, o) == [])
m = dict(cc=2, depth=5, lines=80, params=7, returns=1)
check("depth, length, params flagged", [c for c, _, _ in findings_for(m, o)] == ["H03", "H04", "H05"])
try:
analyze_source("def broken(:\n")
check("syntax error raised", False)
except SyntaxError:
check("syntax error raised", True)
ok = all(c for _, c in checks)
for n, c in checks:
print(("PASS " if c else "FAIL ") + n)
print("%d/%d checks passed" % (sum(c for _, c in checks), len(checks)))
return 0 if ok else 1
def main(argv=None):
o = parser().parse_args(argv)
if o.self_test:
return self_test()
if not o.paths:
parser().print_usage(sys.stderr); return 2
for p in o.paths:
if not os.path.exists(p):
print("no such path: " + p, file=sys.stderr); return 2
results, errors = run(o.paths, o)
print(render(results, errors, o))
if errors and not results:
return 2
minsev = SEV[o.min_severity]
return 1 if any(SEV[x["severity"]] >= minsev for m in results for x in m["findings"]) else 0
if __name__ == "__main__":
sys.exit(main())
Opinionated preferences for naming variables, functions and files, and for writing useful code comments.
# Naming and Code Comments taste of a senior engineer who reviews a lot of code - Name things for what they mean in the domain (`invoiceDueDate`), not for their type (`dateString`). Confidence: 0.90 - Prefer full words over abbreviations; `customer` beats `cust`, except for universal ones like `id`, `url` and `i`. Confidence: 0.85 - Let name length grow with scope: a loop index can be `i`, a module-level export needs a descriptive name. Confidence: 0.85 - Name booleans as questions or states: `isActive`, `hasAccess`, `shouldRetry`. Confidence: 0.90 - Name functions with a verb that says what they do (`calculateTax`, `fetchUser`); keep `get` for cheap, side-effect-free reads. Confidence: 0.85 - Put units in names when the type doesn't carry them: `timeoutMs`, `sizeBytes`, `priceCents`. Confidence: 0.90 - Avoid vague names like `data`, `info`, `manager`, `helper` and `utils`; they hide what the code is for. Confidence: 0.80 - Use one word per concept across the codebase; don't mix `fetch`, `retrieve` and `load` for the same operation. Confidence: 0.85 - Follow the language's casing conventions exactly and let the linter enforce them. Confidence: 0.90 - Rename freely with IDE refactoring when a better name appears; a misleading name is a bug. Confidence: 0.80 - Write comments that explain why, not what; the code already says what. Confidence: 0.95 - Delete a comment that just restates the next line. Confidence: 0.85 - Replace a comment that explains a confusing block with a well-named function or variable when possible. Confidence: 0.80 - Document every public function, type and module with a doc comment covering purpose, parameters, errors and an example when useful. Confidence: 0.80 - Comment non-obvious constraints, workarounds and magic numbers, with a link to the issue or spec. Confidence: 0.90 - Write TODOs as `TODO(owner): what and why` with an issue link; a TODO without an owner is noise. Confidence: 0.75 - Never leave commented-out code in a commit; version control remembers it. Confidence: 0.95 - Update or delete comments in the same change that makes them stale. Confidence: 0.90 - Keep comments in plain English, short and in complete sentences. Confidence: 0.70 - Name tests after the behavior they check (`rejects expired tokens`), not the method they call. Confidence: 0.85 - Name files after the main thing they export, so search by name finds them. Confidence: 0.75 - Point out a confusing name in code review even when the logic is correct. Confidence: 0.80
Opinionated preferences for sending reliable, secure transactional email from a product backend.
# Transactional Email taste of a backend engineer who owns product email delivery
- Send transactional email through a dedicated provider (Postmark, SES, Resend), never from the app server's own SMTP. Confidence: 0.90
- Keep transactional and marketing email on separate sending domains or subdomains so a campaign never hurts password-reset delivery. Confidence: 0.90
- Publish SPF, DKIM and a DMARC policy before the first send, and move DMARC to `p=quarantine` once reports look clean. Confidence: 0.90
- Enqueue every email from a background job; a request handler never waits on the email API. Confidence: 0.95
- Give each send an idempotency key derived from the event (e.g. `order-confirmed:{orderId}`) so retries never send twice. Confidence: 0.85
- Store templates in the repo as code (React Email or MJML), reviewed in pull requests, not edited in the provider dashboard. Confidence: 0.80
- Always send a plain-text part alongside the HTML part. Confidence: 0.85
- Render templates with typed data and fail the build when a template references a missing variable. Confidence: 0.80
- Keep subject lines specific and under about 60 characters; put the key action in the first line of the body. Confidence: 0.70
- Use a no-reply address only when replies truly can't be handled; prefer a monitored reply-to. Confidence: 0.70
- Process bounce and complaint webhooks and suppress those addresses automatically. Confidence: 0.95
- Verify webhook signatures from the provider before trusting any event. Confidence: 0.90
- Log a message id per send and link it to the user and the triggering event for support lookups. Confidence: 0.85
- Never put secrets, full card numbers or raw reset tokens in logs; log only the message id and template name. Confidence: 0.90
- Make magic links and reset links single-use, short-lived (15-60 minutes) and bound to the account. Confidence: 0.90
- Route all email in development and staging to a catcher like Mailpit; real addresses never receive non-production mail. Confidence: 0.95
- Snapshot-test rendered HTML for each template and send a test batch to Gmail, Outlook and Apple Mail before big template changes. Confidence: 0.75
- Respect user notification preferences for every non-critical email; security and billing emails are the only exceptions. Confidence: 0.85
- Add `List-Unsubscribe` and one-click unsubscribe headers to any email that isn't strictly transactional. Confidence: 0.85
- Localize templates by the user's saved locale, with an English fallback, and format dates in the user's time zone. Confidence: 0.80
- Rate-limit per recipient so a bug can't send hundreds of emails to one person. Confidence: 0.85
- Monitor delivery, bounce and complaint rates with alerts; a complaint rate above 0.1% is an incident. Confidence: 0.80
- Warm up a new sending domain or dedicated IP gradually instead of switching all traffic at once. Confidence: 0.75Finds risky exception handling in Python code offline: bare and swallowed excepts, errors turned into silent return values, raise without from, caught KeyboardInterrupt, return in finally, logs without traceback and oversized try blocks, with file:line, severity and fix recipes. Stdlib Python.
---
name: python-exception-handling-smell-finder
description: Finds risky exception handling in Python code offline: bare and swallowed excepts, errors turned into silent return values, raise without from, caught KeyboardInterrupt, return in finally, logs without traceback and oversized try blocks, with file:line, severity and fix recipes. Stdlib Python.
---
# Python Exception Handling Smell Finder
You help developers find the places where a Python codebase hides its own failures: `except: pass`, broad handlers that return `None` or `[]`, re-raised errors that lose their cause, logs without a traceback, `return` inside `finally`, and workers that swallow Ctrl+C. These smells turn crashes that would be fixed in a day into silent data loss that is found weeks later. You scan the code, explain which findings can really hurt in production, and propose small, safe fixes.
You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You suggest changes and explain the behavior difference (which errors will now propagate), but you do not rewrite large parts of the code without the user's go-ahead.
## Files in this skill
- `scripts/exception_smells.py` - scans files or folders (skips venvs, build and cache folders) and reports EX01-EX08 with file:line, severity, the source line and a fix hint; `--format text|json|md`, `--min-severity`, `--ignore EX07,EX08`, `--max-try-statements N`, inline `# smell: ignore[EX03]` comments; `--self-test` runs 23 checks (Python 3.8+ standard library only)
- `references/smell-catalog.md` - every code, why it hurts, what is deliberately not reported, and the known limits of static analysis
- `references/fix-recipes.md` - eight before/after fixes: narrow the type, `raise ... from err`, `logger.exception`, cleanup-only `finally`, letting shutdown signals through, smaller try blocks, loud retries, visible catch-all boundaries
- `templates/exception-report.md` - the review summary you hand back
- `examples/sync_orders.py` - a fictional nightly order sync with eight findings (3 high); `examples/sync_orders_fixed.py` - the same job with every smell fixed (0 findings)
## Workflow
### 1. Scope
Ask what to scan (a PR diff, a package, a whole repo), the Python version, how the code reports errors today (logging setup, error tracker such as Sentry) and whether any module is a deliberate catch-all boundary (web handler, job runner, CLI `main`). For a PR, scan only the changed files first.
### 2. Run the scanner
```
python3 scripts/exception_smells.py path/to/package
python3 scripts/exception_smells.py src tests --min-severity medium
python3 scripts/exception_smells.py src --format md > exception-report-table.md
python3 scripts/exception_smells.py --self-test
```
Exit 0 = no high findings, 1 = at least one high finding, 2 = bad input. Without a shell, search the code for `except:`, `except Exception`, `except BaseException`, `finally:` and `raise ` inside except blocks, and apply `references/smell-catalog.md` by hand.
### 3. Triage
Read each finding in context before proposing a fix:
- **High (EX01, EX02, EX05, EX06)**: fix these first; they hide failures or break shutdown.
- **Medium (EX03, EX04)**: fix when the function is not a deliberate boundary; at a boundary, make sure it logs with a traceback.
- **Low (EX07, EX08)**: cheap improvements; batch them or suppress with a reason.
- Ask "what did the author expect to fail here?" and narrow the handler to that type.
- Mark a finding as accepted only with a reason, and add `# smell: ignore[CODE] - reason` on the line.
### 4. Fix
Use `references/fix-recipes.md`. Keep each change small and explain the new behavior: "a malformed `sync.json` now raises `JSONDecodeError` instead of silently using defaults". Suggest a test for every error path that now propagates.
### 5. Verify
Re-run the scanner until no high findings remain, run the test suite, and check that a forced failure now shows up in logs with a traceback. Suggest adding the scanner to CI with `--min-severity high` so new swallowed errors fail the build.
### 6. Report
Fill `templates/exception-report.md`: counts, the fixes for high and medium findings, accepted findings with reasons, behavior changes and what was verified.
## Rules
- Never execute or import the user's code to analyze it.
- Do not "fix" a smell by catching more broadly or adding `# smell: ignore` without a reason.
- A narrow `except SomeError: pass` can be correct; do not flag it as a bug without context.
- Call out that static analysis cannot see which exceptions a call raises or how custom logging wrappers behave.
FILE:references/smell-catalog.md
# Exception handling smell catalog
Each code below is reported by `scripts/exception_smells.py`. Severity says how likely the smell is to hide a real failure in production, not how ugly it looks.
| Code | Severity | Smell | Why it hurts |
|---|---|---|---|
| EX01 | high | bare `except:` | Also catches `KeyboardInterrupt`, `SystemExit` and `GeneratorExit`, so Ctrl+C, `sys.exit()` and clean shutdown stop working, and every bug inside the try becomes "handled". |
| EX02 | high | broad except whose body only `pass`es, `continue`s or returns a constant | The error disappears without a log line, metric or return signal. The caller sees success. This is the classic "it silently did nothing" bug. |
| EX03 | medium | broad except that neither re-raises nor logs | The error is turned into a normal value (`None`, `[]`, `{"ok": False}`) that callers often ignore. Not always wrong at a boundary, but it must be deliberate and visible. |
| EX04 | medium | `raise NewError(...)` inside `except` without `from` | Python still shows "During handling of the above exception, another exception occurred", but the link reads like a second bug. `raise ... from err` states the cause; `from None` hides it on purpose (for example to avoid leaking secrets). |
| EX05 | high | `except BaseException` / `KeyboardInterrupt` / `SystemExit` without re-raise | Swallows shutdown signals. Workers that ignore SIGINT or `sys.exit()` hang deploys and leave half-finished work. |
| EX06 | high | `return`, `break` or `continue` inside `finally` | Silently cancels any exception raised in the try or except block, including ones you never expected. Python 3.14 warns about this (PEP 765). |
| EX07 | low | `logger.error(...)` / `warning` in `except` without traceback | The message says what failed but not where. Use `logger.exception(...)` (ERROR level with traceback) or pass `exc_info=True`. |
| EX08 | low | broad except around a large try body (default > 8 statements) | One handler covers many operations, so a bug in any of them is treated like the expected failure. Wrap only the call that can fail. |
| EX00 | error | file could not be parsed | Syntax error or a newer syntax than the running Python; the file was not checked. |
## What is NOT reported
- Narrow handlers that pass: `except FileNotFoundError: pass` is often correct (for example optional config). Review them, but they are not smells by default.
- Handlers that re-raise (`raise`, `raise err`, `raise X from err`).
- Handlers that log with a traceback or report to an error tracker (`logger.exception`, `exc_info=True`, `sentry_sdk.capture_exception`, `traceback.print_exc`).
- `break` / `continue` inside a loop that itself lives in the `finally` block.
## Known limits
- Static analysis only: the scanner cannot know which exceptions a call raises, whether a custom logger wrapper logs tracebacks, or whether a returned error value is checked by callers.
- Logger detection is by name (`log`, `logger`, `logging`, `LOG`, `_logger`, `self.logger`, ...). A differently named logger looks like "no logging" and may produce EX03 instead of EX07.
- `contextlib.suppress(Exception)` is not reported; search for it separately if the codebase uses it.
## Suppressing a finding on purpose
Add a trailing comment on the reported line with a reason in the code review:
```python
except Exception: # smell: ignore[EX03] - top-level boundary, error returned to the API client as 500
```
FILE:references/fix-recipes.md
# Fix recipes
Pick the smallest change that makes the failure visible to the right place: the caller, the log, or the user.
## 1. Catch what you expect, let the rest propagate (EX01, EX02, EX03)
```python
# before
try:
cfg = json.load(open(path))
except:
cfg = {}
# after
try:
with open(path) as fh:
cfg = json.load(fh)
except FileNotFoundError:
logger.info("no %s, using defaults", path)
cfg = {}
# a broken JSON file now raises json.JSONDecodeError instead of silently using defaults
```
Ask: "Which failure did the author have in mind?" Catch exactly that type.
## 2. Keep the cause when translating errors (EX04)
```python
except KeyError as err:
raise OrderError(f"order {order_id} is missing {err}") from err
```
Use `from None` only when the original exception would leak secrets or confuse the user, and say so in a comment.
## 3. Log with the traceback, once (EX07)
```python
except PaymentError:
logger.exception("payment %s failed", payment_id) # ERROR level + traceback
raise
```
Log at the boundary that handles the error, not at every layer it passes through (otherwise one failure becomes five log lines).
## 4. Never return from finally (EX06)
```python
# before
try:
process()
finally:
if pushed == 0:
return {"ok": True}
# after
try:
process()
finally:
client.close() # cleanup only
return {"ok": True, "pushed": pushed}
```
`finally` is for cleanup. Move results and decisions after the try statement.
## 5. Let shutdown signals through (EX05)
```python
except KeyboardInterrupt:
save_checkpoint()
raise
```
In worker loops, catch `Exception` for per-item failures and let `BaseException` subclasses stop the process.
## 6. Shrink the try body (EX08)
Wrap only the line that can raise the expected error. Put the "happy path" after the try in an `else:` block or after the statement.
```python
try:
resp = session.get(url, timeout=10)
except requests.RequestException as err:
raise FetchError(url) from err
else:
data = resp.json()
```
## 7. Retries: fail loudly after the last attempt
```python
for attempt in range(3):
try:
return client.send(msg)
except (ConnectionError, TimeoutError):
logger.debug("retry %d", attempt + 1)
time.sleep(2 ** attempt)
raise DeliveryError(f"message {msg.id} not sent after 3 attempts")
```
## 8. Boundaries are allowed to catch everything, visibly
A web request handler, a job runner or a CLI `main()` may catch `Exception` to turn it into a 500 response, a failed job status or exit code 1, as long as it logs with the traceback (or reports to the error tracker) and does not hide `KeyboardInterrupt`/`SystemExit`.
FILE:templates/exception-report.md
# Exception handling review: {{project_or_pr}}
**Scanned:** {{files_scanned}} files ({{paths}}) on {{date}}, `exception_smells.py` {{options}}
**Result:** {{high}} high, {{medium}} medium, {{low}} low, {{parse_errors}} parse errors
## Fix first (high)
| # | Location | Code | What can go wrong in production | Proposed fix |
|---|---|---|---|---|
| 1 | `{{file}}:{{line}}` | {{code}} | {{impact}} | {{fix}} |
## Fix in this PR if cheap (medium)
| # | Location | Code | Proposed fix |
|---|---|---|---|
| 1 | `{{file}}:{{line}}` | {{code}} | {{fix}} |
## Low / accepted on purpose
- `{{file}}:{{line}}` {{code}}: {{reason it is fine, or suppress comment added}}
## Behavior changes to check
- {{which errors now propagate instead of being swallowed, and who handles them}}
- {{tests added or updated: e.g. a test that a broken config file now raises}}
## Verified
- [ ] Re-ran the scanner: no high findings left (exit 0)
- [ ] Test suite passes
- [ ] Logs now include a traceback for {{failure}}
FILE:examples/sync_orders.py
"""Fictional nightly job that copies new web-shop orders into the accounting system.
It runs, but its exception handling hides real failures. Used to demo exception_smells.py."""
import json
import logging
import time
import requests # third-party; the scanner never imports it
logger = logging.getLogger(__name__)
API = "https://shop.example.com/api/orders"
class SyncError(Exception):
pass
def load_config(path):
try:
with open(path) as fh:
return json.load(fh)
except:
return {}
def fetch_orders(since):
try:
resp = requests.get(API, params={"since": since}, timeout=10)
resp.raise_for_status()
return resp.json()["orders"]
except Exception as err:
logger.error("could not fetch orders: %s", err)
return []
def to_invoice(order):
try:
return {"number": order["id"], "total": round(float(order["total"]), 2), "currency": order["currency"]}
except KeyError:
raise SyncError("order is missing a field")
def push_invoice(client, invoice):
for attempt in range(3):
try:
client.create_invoice(invoice)
return True
except Exception:
time.sleep(2 ** attempt)
continue
return False
def run(client, since):
pushed = 0
try:
config = load_config("sync.json")
orders = fetch_orders(since)
batch = config.get("batch_size", 50)
for order in orders[:batch]:
invoice = to_invoice(order)
if push_invoice(client, invoice):
pushed += 1
client.commit()
logger.info("pushed %d invoices", pushed)
client.close()
except Exception as e:
status = {"ok": False, "error": str(e)}
return status
finally:
if pushed == 0:
return {"ok": True, "pushed": 0}
return {"ok": True, "pushed": pushed}
def main():
try:
run(client=None, since="2026-11-23")
except BaseException:
logger.exception("sync failed")
FILE:examples/sync_orders_fixed.py
"""The same nightly order sync with the smells fixed. exception_smells.py reports nothing here."""
import json
import logging
import time
import requests # third-party; the scanner never imports it
logger = logging.getLogger(__name__)
API = "https://shop.example.com/api/orders"
class SyncError(Exception):
pass
def load_config(path):
try:
with open(path) as fh:
return json.load(fh)
except FileNotFoundError:
logger.info("no %s, using defaults", path)
return {}
def fetch_orders(since):
try:
resp = requests.get(API, params={"since": since}, timeout=10)
resp.raise_for_status()
except requests.RequestException as err:
raise SyncError("could not fetch orders since %s" % since) from err
return resp.json()["orders"]
def to_invoice(order):
try:
return {"number": order["id"], "total": round(float(order["total"]), 2), "currency": order["currency"]}
except KeyError as err:
raise SyncError("order %s is missing field %s" % (order.get("id", "?"), err)) from err
def push_invoice(client, invoice, retryable=(ConnectionError, TimeoutError)):
for attempt in range(3):
try:
client.create_invoice(invoice)
return
except retryable:
logger.debug("retry %d for invoice %s", attempt + 1, invoice["number"])
time.sleep(2 ** attempt)
raise SyncError("invoice %s not pushed after 3 attempts" % invoice["number"])
def run(client, since):
config = load_config("sync.json")
orders = fetch_orders(since)
batch = config.get("batch_size", 50)
pushed, failed = 0, []
for order in orders[:batch]:
try:
push_invoice(client, to_invoice(order))
pushed += 1
except SyncError:
logger.exception("order %s skipped", order.get("id", "?"))
failed.append(order.get("id"))
try:
client.commit()
finally:
client.close()
logger.info("pushed %d invoices, %d failed", pushed, len(failed))
return {"ok": not failed, "pushed": pushed, "failed": failed}
def main():
try:
run(client=None, since="2026-11-23")
except SyncError:
logger.exception("sync failed")
raise
FILE:scripts/exception_smells.py
#!/usr/bin/env python3
"""exception_smells.py - find risky exception handling in Python code, offline.
Parses files with the standard library `ast` module (it never imports or runs the code) and reports:
EX01 high bare `except:` (also catches KeyboardInterrupt and SystemExit)
EX02 high broad except whose body only passes / continues / returns (error silently swallowed)
EX03 medium broad except that neither re-raises nor logs (error turned into a normal value)
EX04 medium new exception raised inside `except` without `from` (original cause hidden)
EX05 high `except BaseException` (or KeyboardInterrupt / SystemExit) without re-raise
EX06 high return / break / continue inside `finally` (silently cancels any exception)
EX07 low error logged in `except` without the traceback (no exc_info / logger.exception)
EX08 low broad except around a large try body (hides which statement failed)
EX00 error file could not be parsed
Usage:
python3 exception_smells.py PATH [PATH ...] [--format text|json|md] [--min-severity low|medium|high]
[--ignore EX07,EX08] [--max-try-statements 8]
python3 exception_smells.py --self-test
Suppress one finding with a trailing comment on the `except` / `raise` / `finally` line: `# smell: ignore[EX03]`.
Exit codes: 0 = no high findings, 1 = at least one high finding, 2 = bad input.
Standard library only, Python 3.8+.
"""
import argparse, ast, json, os, re, sys, tempfile, textwrap
SEVERITY = {"EX00": "error", "EX01": "high", "EX02": "high", "EX03": "medium", "EX04": "medium",
"EX05": "high", "EX06": "high", "EX07": "low", "EX08": "low"}
TITLE = {"EX00": "file could not be parsed",
"EX01": "bare except",
"EX02": "broad except swallows the error",
"EX03": "broad except neither re-raises nor logs",
"EX04": "raise inside except without 'from'",
"EX05": "catches BaseException / KeyboardInterrupt / SystemExit without re-raise",
"EX06": "return/break/continue in finally cancels exceptions",
"EX07": "error logged without traceback",
"EX08": "broad except around a large try body"}
RANK = {"low": 0, "medium": 1, "high": 2, "error": 3}
BROAD = {"Exception", "BaseException"}
SYSTEM = {"BaseException", "KeyboardInterrupt", "SystemExit", "GeneratorExit"}
LOG_METHODS = {"debug", "info", "warning", "warn", "error", "exception", "critical", "fatal", "log"}
LOGGER_NAMES = re.compile(r"(^|_)(log|logger|logging|logs|_log|_logger|LOG|LOGGER)$")
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "node_modules", "build", "dist", ".tox", ".mypy_cache", "site-packages"}
IGNORE_RE = re.compile(r"#\s*smell:\s*ignore\[([A-Z0-9, ]+)\]")
def type_names(node):
"""Names of the exception classes an except handler catches ([] for bare except)."""
if node is None:
return []
items = node.elts if isinstance(node, ast.Tuple) else [node]
out = []
for it in items:
if isinstance(it, ast.Name):
out.append(it.id)
elif isinstance(it, ast.Attribute):
out.append(it.attr)
else:
out.append("?")
return out
def walk_no_nested(nodes):
"""Walk statements but do not descend into nested functions, classes or lambdas."""
stack = list(nodes)
while stack:
n = stack.pop()
yield n
for child in ast.iter_child_nodes(n):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
continue
stack.append(child)
def is_log_call(call):
if not isinstance(call, ast.Call):
return False
f = call.func
if isinstance(f, ast.Attribute) and f.attr in LOG_METHODS:
base = f.value
name = base.id if isinstance(base, ast.Name) else (base.attr if isinstance(base, ast.Attribute) else "")
return bool(LOGGER_NAMES.search(name))
return False
def has_traceback(call):
f = call.func
if isinstance(f, ast.Attribute) and f.attr == "exception":
return True
for kw in call.keywords:
if kw.arg in ("exc_info", "stack_info") and not (isinstance(kw.value, ast.Constant) and kw.value.value in (False, None)):
return True
return False
def handler_facts(h):
body = list(walk_no_nested(h.body))
reraises = any(isinstance(n, ast.Raise) for n in body)
logs = [n for n in body if is_log_call(n)]
reports = any(isinstance(n, ast.Call) and (
(isinstance(n.func, ast.Attribute) and n.func.attr in ("capture_exception", "print_exc", "format_exc", "notify", "report_exc"))
or (isinstance(n.func, ast.Name) and n.func.id in ("capture_exception", "print_exc"))) for n in body)
trivial = all(isinstance(s, (ast.Pass, ast.Continue, ast.Break)) or
(isinstance(s, ast.Expr) and isinstance(s.value, ast.Constant)) or
(isinstance(s, ast.Return) and (s.value is None or isinstance(s.value, ast.Constant)))
for s in h.body)
return reraises, logs, reports, trivial
class Finder(ast.NodeVisitor):
def __init__(self, path, lines, max_try):
self.path, self.lines, self.max_try = path, lines, max_try
self.found = []
self.handler_stack = []
def add(self, code, node, detail):
line = getattr(node, "lineno", 0)
src = self.lines[line - 1] if 0 < line <= len(self.lines) else ""
m = IGNORE_RE.search(src)
if m and code in [c.strip() for c in m.group(1).split(",")]:
return
self.found.append({"code": code, "severity": SEVERITY[code], "file": self.path, "line": line,
"title": TITLE[code], "detail": detail, "source": src.strip()})
def visit_Try(self, node):
n_body = sum(1 for _ in walk_no_nested(node.body) if isinstance(_, ast.stmt))
for h in node.handlers:
names = type_names(h.type)
reraises, logs, reports, trivial = handler_facts(h)
broad = (not names) or any(n in BROAD for n in names)
if not names:
self.add("EX01", h, "use `except Exception:` (or narrower) so Ctrl+C and sys.exit() still work" + ("" if reraises else "; the error is not re-raised"))
elif any(n in SYSTEM for n in names) and not reraises:
self.add("EX05", h, "catches %s; re-raise it or catch Exception instead" % ", ".join(n for n in names if n in SYSTEM))
if broad and trivial and not reraises:
self.add("EX02", h, "the handler body only passes/continues/returns a constant; the error disappears without a trace")
elif broad and not reraises and not logs and not reports and names:
self.add("EX03", h, "the error becomes a normal return value; log it, re-raise it, or catch a narrower type")
for call in logs:
if call.func.attr in ("error", "critical", "fatal", "warning", "warn") and not has_traceback(call) and not reraises:
self.add("EX07", call, "add exc_info=True or use logger.exception(...) so the traceback is kept")
if broad and n_body > self.max_try:
self.add("EX08", h, "try body has %d statements; wrap only the call that can fail" % n_body)
self.handler_stack.append(h)
for s in h.body:
self.visit(s)
self.handler_stack.pop()
for part in (node.body, node.orelse):
for s in part:
self.visit(s)
for s in node.finalbody:
self.visit(s)
for n in walk_no_nested(node.finalbody):
if isinstance(n, (ast.Return, ast.Break, ast.Continue)) and not self._inside_loop_in(node.finalbody, n):
self.add("EX06", n, "`%s` in finally discards any exception raised in the try block" % type(n).__name__.lower())
visit_TryStar = visit_Try
def _inside_loop_in(self, stmts, target):
"""True if a break/continue sits inside a loop that is itself inside the finally block (that is fine)."""
if isinstance(target, ast.Return):
return False
for n in walk_no_nested(stmts):
if isinstance(n, (ast.For, ast.While, ast.AsyncFor)):
if any(c is target for c in walk_no_nested(n.body + n.orelse)):
return True
return False
def visit_Raise(self, node):
if self.handler_stack and node.exc is not None and node.cause is None:
h = self.handler_stack[-1]
if not (isinstance(node.exc, ast.Name) and h.name and node.exc.id == h.name):
self.add("EX04", node, "use `raise NewError(...) from err` (or `from None` on purpose) to keep the cause")
self.generic_visit(node)
def visit_FunctionDef(self, node):
saved, self.handler_stack = self.handler_stack, []
self.generic_visit(node)
self.handler_stack = saved
visit_AsyncFunctionDef = visit_FunctionDef
visit_Lambda = visit_FunctionDef
def scan_source(src, path="<string>", max_try=8):
lines = src.splitlines()
try:
tree = ast.parse(src, filename=path)
except SyntaxError as e:
return [{"code": "EX00", "severity": "error", "file": path, "line": e.lineno or 0, "title": TITLE["EX00"],
"detail": str(e.msg), "source": ""}]
f = Finder(path, lines, max_try)
f.visit(tree)
seen, out = set(), []
for x in sorted(f.found, key=lambda x: (x["line"], x["code"])):
k = (x["code"], x["line"])
if k not in seen:
seen.add(k)
out.append(x)
return out
def iter_files(paths):
for p in paths:
if os.path.isfile(p):
yield p
elif os.path.isdir(p):
for root, dirs, files in os.walk(p):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.endswith(".egg-info"))
for fn in sorted(files):
if fn.endswith(".py"):
yield os.path.join(root, fn)
else:
raise FileNotFoundError(p)
def scan_paths(paths, max_try=8):
findings, n = [], 0
for fp in iter_files(paths):
n += 1
with open(fp, encoding="utf-8", errors="replace") as fh:
findings += scan_source(fh.read(), fp, max_try)
return n, findings
def render(n_files, findings, fmt):
counts = {s: sum(1 for f in findings if f["severity"] == s) for s in ("high", "medium", "low", "error")}
if fmt == "json":
return json.dumps({"files_scanned": n_files, "counts": counts, "findings": findings}, indent=2)
if fmt == "md":
out = ["| Code | Severity | Location | Problem | Fix hint |", "|---|---|---|---|---|"]
for f in findings:
out.append("| %s | %s | `%s:%d` | %s | %s |" % (f["code"], f["severity"], f["file"], f["line"], f["title"], f["detail"]))
out.append("")
out.append("Files scanned: %d. High: %d, medium: %d, low: %d, parse errors: %d." % (n_files, counts["high"], counts["medium"], counts["low"], counts["error"]))
return "\n".join(out)
out = []
for f in findings:
out.append("%s:%d %s [%s] %s" % (f["file"], f["line"], f["code"], f["severity"], f["title"]))
if f["source"]:
out.append(" > " + f["source"])
out.append(" hint: " + f["detail"])
out.append("")
out.append("Files scanned: %d. High: %d, medium: %d, low: %d, parse errors: %d." % (n_files, counts["high"], counts["medium"], counts["low"], counts["error"]))
return "\n".join(out)
def self_test():
T = []
def codes(src, **kw):
return [f["code"] for f in scan_source(textwrap.dedent(src), **kw)]
def check(name, cond):
T.append((name, bool(cond)))
check("bare except is EX01", "EX01" in codes("try:\n x()\nexcept:\n raise\n"))
check("bare except with pass is EX01 + EX02", {"EX01", "EX02"} <= set(codes("try:\n x()\nexcept:\n pass\n")))
check("except Exception: pass is EX02", codes("try:\n x()\nexcept Exception:\n pass\n") == ["EX02"])
check("narrow except ValueError: pass is fine", codes("try:\n int(s)\nexcept ValueError:\n pass\n") == [])
check("broad except returning a value without log is EX03",
codes("def f():\n try:\n return x()\n except Exception as e:\n y = str(e)\n return {'ok': False, 'err': y}\n") == ["EX03"])
check("broad except that logs with exception() is fine",
codes("def f():\n try:\n x()\n except Exception:\n logger.exception('boom')\n return None\n") == [])
check("logger.error without exc_info is EX07",
codes("try:\n x()\nexcept Exception as e:\n logger.error('failed: %s', e)\n") == ["EX07"])
check("logger.error with exc_info=True is fine",
codes("try:\n x()\nexcept Exception:\n log.error('failed', exc_info=True)\n") == [])
check("raise without from in except is EX04",
codes("try:\n x()\nexcept KeyError as e:\n raise ValueError('bad')\n") == ["EX04"])
check("raise ... from err is fine", codes("try:\n x()\nexcept KeyError as e:\n raise ValueError('bad') from e\n") == [])
check("re-raising the caught name is fine", codes("try:\n x()\nexcept KeyError as e:\n cleanup()\n raise e\n") == [])
check("except BaseException without re-raise is EX05",
"EX05" in codes("try:\n x()\nexcept BaseException:\n logger.exception('x')\n"))
check("except KeyboardInterrupt with re-raise is fine",
codes("try:\n x()\nexcept KeyboardInterrupt:\n cleanup()\n raise\n") == [])
check("return in finally is EX06", "EX06" in codes("def f():\n try:\n x()\n finally:\n return 1\n"))
check("break inside a loop within finally is fine",
codes("try:\n x()\nfinally:\n for i in r:\n break\n") == [])
check("large try body with broad except is EX08",
"EX08" in codes("try:\n" + "".join(" a%d()\n" % i for i in range(10)) + "except Exception:\n logger.exception('x')\n raise\n"))
check("--max-try-statements raises the limit",
"EX08" not in codes("try:\n" + "".join(" a%d()\n" % i for i in range(10)) + "except Exception:\n raise\n", max_try=20))
check("inline ignore comment suppresses a code",
codes("try:\n x()\nexcept Exception: # smell: ignore[EX02]\n pass\n") == [])
check("nested function raise is not attributed to outer except",
codes("try:\n x()\nexcept KeyError as e:\n def g():\n raise ValueError()\n raise\n") == [])
check("syntax error reported as EX00", codes("def f(:\n pass\n") == ["EX00"])
check("tuple of exceptions incl. Exception is broad",
codes("try:\n x()\nexcept (ValueError, Exception):\n pass\n") == ["EX02"])
with tempfile.TemporaryDirectory() as d:
os.makedirs(os.path.join(d, "pkg")); os.makedirs(os.path.join(d, ".venv"))
open(os.path.join(d, "pkg", "a.py"), "w").write("try:\n x()\nexcept:\n pass\n")
open(os.path.join(d, ".venv", "b.py"), "w").write("try:\n x()\nexcept:\n pass\n")
n, fs = scan_paths([d])
check("directory scan skips .venv", n == 1 and all(".venv" not in f["file"] for f in fs))
check("json output parses", json.loads(render(n, fs, "json"))["counts"]["high"] == 2)
ok = sum(1 for _, r in T if r)
for name, r in T:
print(("PASS " if r else "FAIL ") + name)
print(("ALL PASS" if ok == len(T) else "FAILED") + " (%d/%d)" % (ok, len(T)))
return 0 if ok == len(T) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("paths", nargs="*")
ap.add_argument("--format", choices=("text", "json", "md"), default="text")
ap.add_argument("--min-severity", choices=("low", "medium", "high"), default="low")
ap.add_argument("--ignore", default="", help="comma-separated codes to skip, e.g. EX07,EX08")
ap.add_argument("--max-try-statements", type=int, default=8)
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.paths:
ap.print_usage(sys.stderr)
return 2
try:
n, fs = scan_paths(a.paths, a.max_try_statements)
except FileNotFoundError as e:
print("error: path not found: %s" % e, file=sys.stderr)
return 2
if n == 0:
print("error: no .py files found", file=sys.stderr)
return 2
skip = {c.strip().upper() for c in a.ignore.split(",") if c.strip()}
fs = [f for f in fs if f["code"] not in skip and RANK[f["severity"]] >= RANK[a.min_severity]]
print(render(n, fs, a.format))
return 1 if any(f["severity"] == "high" for f in fs) else 0
if __name__ == "__main__":
sys.exit(main())
Opinionated preferences for designing and publishing Rust library crates: API shape, errors, features, docs and release checks.
# Rust Library Crate taste of a maintainer who publishes reusable crates - Keep the public API small and re-export the important types from the crate root. Confidence: 0.85 - Define one error enum per crate with `thiserror`, and never return `anyhow::Error` from a library. Confidence: 0.90 - Mark public enums and config structs `#[non_exhaustive]` when new variants or fields are likely. Confidence: 0.80 - Accept flexible inputs like `impl AsRef<str>` or `impl Into<String>` and return concrete types. Confidence: 0.80 - Use the builder pattern for types with more than a few optional settings. Confidence: 0.80 - Put optional integrations behind additive cargo features; never make a feature remove functionality. Confidence: 0.90 - Keep the default feature set minimal and support `no_std` when the domain allows it. Confidence: 0.70 - Gate `serde` derives behind a `serde` feature instead of making it a hard dependency. Confidence: 0.85 - Declare `rust-version` in Cargo.toml and test the MSRV in CI. Confidence: 0.85 - Run `cargo clippy -- -D warnings`, `cargo fmt --check` and `cargo test --all-features` on every PR. Confidence: 0.90 - Check semver breakage with `cargo-semver-checks` before each release. Confidence: 0.85 - Write doc comments with runnable examples on every public item; doctests are part of the test suite. Confidence: 0.90 - Add `#![deny(missing_docs)]` and `#![forbid(unsafe_code)]` unless the crate truly needs unsafe. Confidence: 0.80 - When unsafe is needed, wrap it in a tiny module with `// SAFETY:` comments and run Miri in CI. Confidence: 0.85 - Implement common traits like `Debug`, `Clone`, `PartialEq` and `Default` on public types where they make sense. Confidence: 0.85 - Make public types `Send` and `Sync` when possible and assert it in a test. Confidence: 0.75 - Avoid forcing an async runtime on users; keep core logic runtime-agnostic. Confidence: 0.80 - Add property tests with `proptest` for parsers and encoders. Confidence: 0.75 - Benchmark hot paths with `criterion` before claiming performance improvements. Confidence: 0.75 - Release with `cargo-release` or release-plz and keep a CHANGELOG.md in Keep a Changelog format. Confidence: 0.80 - Dual-license under MIT OR Apache-2.0 to match the Rust ecosystem. Confidence: 0.80
Opinionated preferences for building and publishing TypeScript libraries to npm: exports maps, type checks, releases and package hygiene.
# TypeScript Library Publishing taste of a maintainer who ships small, well-typed npm packages - Publish ESM first and add a CommonJS build only when real consumers still need `require()`. Confidence: 0.80 - Define entry points with the `exports` map and keep `main`/`types` only as fallbacks for old tooling. Confidence: 0.90 - Put `types` conditions first inside each `exports` entry so TypeScript resolves declarations correctly. Confidence: 0.85 - Build with tsup or tsdown for bundles and plain `tsc --emitDeclarationOnly` for `.d.ts` files. Confidence: 0.75 - Turn on `strict`, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` in the library's own tsconfig. Confidence: 0.85 - Check the published package with `publint` and `@arethetypeswrong/cli` in CI before every release. Confidence: 0.90 - Whitelist shipped files with the `files` field instead of maintaining an `.npmignore`. Confidence: 0.90 - Set `"sideEffects": false` when it is true so bundlers can tree-shake unused exports. Confidence: 0.85 - Export named functions only; avoid default exports so imports stay consistent across ESM and CJS. Confidence: 0.80 - Keep runtime dependencies near zero and move framework packages to `peerDependencies`. Confidence: 0.90 - Declare a supported Node.js range in `engines` and test that range in a CI matrix. Confidence: 0.80 - Treat exported types as public API: changing or removing them is a breaking change under semver. Confidence: 0.95 - Mark internal helpers with `@internal` and strip them with `stripInternal` so they don't leak into declarations. Confidence: 0.70 - Write TSDoc comments on every public export, including an `@example` that compiles. Confidence: 0.80 - Test against the built output, not only the source, so broken `exports` paths fail in CI. Confidence: 0.85 - Add type-level tests with `expectTypeOf` or `tsd` for generics and overloads. Confidence: 0.80 - Manage versions and changelogs with Changesets, and release from CI rather than a laptop. Confidence: 0.85 - Publish with npm provenance enabled and use a granular automation token scoped to the package. Confidence: 0.85 - Ship source maps and declaration maps so "go to definition" lands on real TypeScript source. Confidence: 0.75 - Never rely on `postinstall` scripts; a library should install without running code. Confidence: 0.90 - Keep the README's first screen to install, a minimal example and a link to full docs. Confidence: 0.80
Opinionated preferences for building, testing and shipping fast, script-friendly command-line tools in Go.
# Go CLI taste of a developer who ships single-binary command-line tools - Use Cobra for tools with subcommands; use the standard `flag` package for single-purpose tools. Confidence: 0.80 - Keep `main.go` tiny: build the root command, run it, and map the returned error to an exit code. Confidence: 0.90 - Put command wiring in `cmd/` and real logic in `internal/` packages that know nothing about flags or the terminal. Confidence: 0.85 - Return errors from `RunE` instead of calling `os.Exit` or `log.Fatal` inside commands. Confidence: 0.90 - Exit with 0 on success, 1 for runtime failures and 2 for usage errors. Confidence: 0.85 - Write results to stdout and diagnostics to stderr; never mix progress output into data streams. Confidence: 0.95 - Offer `--output json` for scripting and keep the JSON shape stable across minor versions. Confidence: 0.85 - Detect a TTY before using colors, spinners or interactive prompts, and respect `NO_COLOR`. Confidence: 0.90 - Read configuration in a clear order: flags, then environment variables, then config file, then defaults. Confidence: 0.85 - Store config files under `os.UserConfigDir()` and caches under `os.UserCacheDir()`, not in the home directory root. Confidence: 0.80 - Pass `context.Context` through every operation and cancel it on SIGINT/SIGTERM with `signal.NotifyContext`. Confidence: 0.90 - Use `log/slog` for debug logging behind a `--verbose` flag; keep default output quiet. Confidence: 0.80 - Inject `io.Writer`s and the environment into commands so they can be tested without touching the real terminal. Confidence: 0.85 - Write table-driven tests for logic and golden-file tests for command output, with an `-update` flag to refresh goldens. Confidence: 0.85 - Build static binaries with `CGO_ENABLED=0` and `-trimpath` whenever the tool doesn't need cgo. Confidence: 0.85 - Embed version, commit and build date via `-ldflags` or `debug.ReadBuildInfo`, and expose them in a `version` command. Confidence: 0.90 - Release with GoReleaser: cross-compiled archives, checksums and a Homebrew tap from one tagged commit. Confidence: 0.80 - Ship shell completions for bash, zsh and fish generated from the command tree. Confidence: 0.80 - Make destructive commands ask for confirmation in a TTY and require `--yes` or `--force` in scripts. Confidence: 0.90 - Keep dependencies few and run `go vet`, `staticcheck` and `govulncheck` in CI. Confidence: 0.85 - Keep startup fast: no network calls or heavy initialization before a command actually needs them. Confidence: 0.80
Opinionated preferences for building framework-agnostic, accessible custom elements with the Web Components standards.
# Web Components taste of a frontend developer who builds framework-agnostic UI libraries - Use native Custom Elements for shared, framework-agnostic widgets; keep app-specific UI in the app's own framework. Confidence: 0.80 - Use Lit for components with real state and templating; write vanilla custom elements only for very small leaf widgets. Confidence: 0.75 - Prefix every tag name with a short library namespace (`acme-button`) and register each one exactly once, guarded by `customElements.get`. Confidence: 0.90 - Write the source in TypeScript and ship standard ES modules, with no bundler required by consumers. Confidence: 0.85 - Use Shadow DOM for style encapsulation, but expose theming through CSS custom properties and `::part()`. Confidence: 0.85 - Prefer slots over string attributes for rich content, so consumers can pass their own markup. Confidence: 0.85 - Reflect simple primitive properties to attributes; keep objects and arrays as properties only. Confidence: 0.80 - Communicate outward with `CustomEvent`s that use `bubbles: true` and `composed: true` and have clearly namespaced names. Confidence: 0.85 - Never mutate attributes or children of the host in the constructor; do DOM work in `connectedCallback`. Confidence: 0.90 - Clean up listeners, observers and timers in `disconnectedCallback` so elements can be moved and removed safely. Confidence: 0.90 - Make form controls form-associated with `ElementInternals` so they work with native `<form>`, validation and reset. Confidence: 0.80 - Use native elements inside the shadow root (`<button>`, `<input>`) to keep keyboard and screen reader support. Confidence: 0.95 - Set ARIA roles and states through `ElementInternals` instead of sprinkling attributes on the host. Confidence: 0.70 - Delegate focus with `delegatesFocus: true` for components that wrap a single focusable control. Confidence: 0.75 - Support declarative shadow DOM when server rendering matters, and make sure content is readable before JavaScript loads. Confidence: 0.65 - Publish a Custom Elements Manifest (`custom-elements.json`) to power docs, IDE autocompletion and framework wrappers. Confidence: 0.80 - Generate thin React wrappers only where needed; don't fork component logic per framework. Confidence: 0.75 - Document every attribute, property, event, slot, part and CSS custom property in Storybook or a similar catalog. Confidence: 0.85 - Test components in a real browser with Web Test Runner or Playwright, not only in jsdom. Confidence: 0.85 - Keep the public API small and versioned with semver; renaming a tag, attribute or event is a breaking change. Confidence: 0.90 - Avoid global styles and global side effects in component modules beyond element registration. Confidence: 0.90
Opinionated rules for storing, parsing, formatting and testing dates, times and time zones in application code.
# Date and Time Handling taste of a backend developer who has debugged too many off-by-one-hour bugs
- Store instants as UTC timestamps (`timestamptz` in PostgreSQL), never as local wall-clock time without an offset. Confidence: 0.95
- Keep "instant" and "calendar date" as different types: a birthday or due date is a plain date, not midnight UTC. Confidence: 0.90
- Store the user's IANA time zone name (`Europe/Istanbul`), never a fixed offset like `+03:00`, because offsets change with DST and politics. Confidence: 0.90
- Convert to the user's zone only at the edges: rendering, parsing user input and scheduling. Confidence: 0.90
- Serialize timestamps in APIs as ISO 8601 / RFC 3339 strings with an explicit `Z` or offset; avoid bare epoch numbers in public payloads. Confidence: 0.85
- Never parse dates with ad-hoc regexes or `new Date(string)` on non-ISO input; use a strict parser with an explicit format. Confidence: 0.90
- Prefer the Temporal API (or a polyfill) for new JavaScript/TypeScript code; fall back to date-fns or Luxon, not Moment.js. Confidence: 0.80
- Format for humans with `Intl.DateTimeFormat` and the user's locale instead of hand-built strings. Confidence: 0.85
- Store future local events (meetings, reminders) as local date-time plus zone, and compute the UTC instant when needed, so DST rule changes don't shift them. Confidence: 0.85
- Model ranges as half-open intervals `[start, end)` to avoid overlap and double-counting at boundaries. Confidence: 0.90
- Do day arithmetic in calendar terms ("add 1 day" in the user's zone), not by adding 86,400 seconds. Confidence: 0.85
- Use a monotonic clock (`performance.now()`, `time.monotonic()`) for measuring durations and timeouts, never wall-clock time. Confidence: 0.95
- Inject a clock dependency instead of calling `Date.now()` directly in business logic, so tests can freeze and advance time. Confidence: 0.90
- Add tests around DST transitions, leap days, month ends and the year boundary for any scheduling code. Confidence: 0.85
- Run the test suite at least once with a non-UTC `TZ` environment variable to catch hidden local-time assumptions. Confidence: 0.75
- Keep server, database and container clocks in UTC and synced with NTP. Confidence: 0.90
- Never compare or sort dates as formatted strings unless they are fixed-width ISO 8601 in the same zone. Confidence: 0.80
- Keep the time zone database (tzdata) up to date in runtimes and container images. Confidence: 0.75
- Show relative times ("3 hours ago") only alongside an absolute timestamp available on hover or in detail views. Confidence: 0.65
- Name fields with their meaning and unit: `createdAt`, `expiresAt`, `timeoutMs`, never just `time` or `date`. Confidence: 0.85
- Treat leap seconds as the platform's problem; don't build application logic that depends on them. Confidence: 0.70
Opinionated rules for designing, reviewing and maintaining relational database indexes based on real query patterns.
# Database Indexing taste of a backend engineer who indexes for real queries, not guesses - Design indexes from the actual slow query log and `EXPLAIN (ANALYZE, BUFFERS)` output, not from the schema alone. Confidence: 0.95 - Index every foreign key column that is used in joins or cascading deletes. Confidence: 0.90 - Order composite index columns by equality filters first, then range filters, then sort columns. Confidence: 0.90 - Prefer one well-chosen composite index over several single-column indexes the planner has to combine. Confidence: 0.85 - Drop indexes whose leading columns duplicate another index; `(a)` is redundant next to `(a, b)`. Confidence: 0.85 - Use covering indexes (`INCLUDE` columns) for hot read paths so queries can use index-only scans. Confidence: 0.80 - Use partial indexes for skewed data, such as `WHERE deleted_at IS NULL` or `WHERE status = 'pending'`. Confidence: 0.90 - Enforce uniqueness with unique indexes or constraints in the database, never only in application code. Confidence: 0.95 - Create indexes on large live tables with `CREATE INDEX CONCURRENTLY` (or the engine's online equivalent) in a migration of its own. Confidence: 0.95 - Never wrap indexed columns in functions in `WHERE` clauses; add an expression index like `lower(email)` when needed. Confidence: 0.85 - Avoid leading-wildcard `LIKE '%term'` on B-tree indexes; use trigram or full-text indexes for substring search. Confidence: 0.85 - Pick GIN for JSONB containment and arrays, BRIN for huge append-only time-series tables, B-tree for everything else. Confidence: 0.80 - Use keyset pagination on an indexed sort key instead of large `OFFSET` values. Confidence: 0.90 - Keep low-cardinality booleans out of standalone indexes; fold them into a partial or composite index instead. Confidence: 0.80 - Review index usage statistics monthly and remove indexes with zero scans after confirming replicas do not use them. Confidence: 0.75 - Budget write cost: every extra index slows inserts and updates, so write-heavy tables get the fewest indexes. Confidence: 0.85 - Keep table statistics fresh with autovacuum/analyze tuning on big, fast-changing tables. Confidence: 0.80 - Watch for index bloat and rebuild with `REINDEX CONCURRENTLY` when it degrades performance. Confidence: 0.70 - Name indexes predictably, for example `idx_<table>_<columns>` and `uq_<table>_<columns>`. Confidence: 0.75 - Add a query plan check to code review for any new query on a table above a million rows. Confidence: 0.70 - Test index changes on a production-sized copy or branch before shipping them. Confidence: 0.85 - Never add an index just because a column appears in a `WHERE` clause somewhere; measure first. Confidence: 0.80
Opinionated conventions for building Python command-line tools that are pleasant to use, easy to test and simple to install.
# Python CLI taste of a tooling developer who ships small, well-behaved command-line apps - Build the CLI with Typer for typed commands, or Click when fine control over parsing is needed; avoid hand-rolled `argparse` trees for multi-command tools. Confidence: 0.80 - Expose the command through `[project.scripts]` in `pyproject.toml` so it installs as a real executable. Confidence: 0.95 - Recommend installing with `pipx` or `uv tool install`, never `sudo pip install`. Confidence: 0.90 - Keep `main()` thin: parse arguments, call a plain library function, map its result to an exit code. Confidence: 0.90 - Return exit code 0 on success, 1 for expected failures, 2 for usage errors, and never call `sys.exit` deep inside library code. Confidence: 0.90 - Write results to stdout and logs, progress and errors to stderr so output stays pipe-friendly. Confidence: 0.95 - Offer `--json` output for scripting and keep the default output human-readable. Confidence: 0.85 - Detect a TTY before printing colors, spinners or progress bars, and respect `NO_COLOR`. Confidence: 0.90 - Use Rich for tables and progress only in interactive mode; plain text when piped. Confidence: 0.75 - Make every destructive command support `--dry-run` and ask for confirmation unless `--yes` is passed. Confidence: 0.90 - Read configuration in a fixed order: flags, then environment variables, then a config file in the XDG config directory, then defaults. Confidence: 0.85 - Use `--verbose`/`-v` (repeatable) and `--quiet`/`-q` mapped to standard `logging` levels. Confidence: 0.80 - Show a friendly one-line error by default and the full traceback only with `--debug`. Confidence: 0.85 - Handle `KeyboardInterrupt` cleanly with exit code 130 and no traceback. Confidence: 0.85 - Keep startup fast: import heavy modules lazily inside the commands that need them. Confidence: 0.80 - Provide `--version` that reads from `importlib.metadata`, not a hardcoded string. Confidence: 0.90 - Accept `-` as stdin/stdout for file arguments and use `pathlib.Path` everywhere. Confidence: 0.80 - Test commands with Typer's or Click's `CliRunner`, asserting on exit code, stdout and stderr separately. Confidence: 0.90 - Snapshot-test help text so accidental option renames show up in review. Confidence: 0.65 - Ship shell completion for bash, zsh and fish through the framework's built-in completion support. Confidence: 0.75 - Write help text with a short example for every command; examples beat long option descriptions. Confidence: 0.80 - Lock dependencies for releases but keep runtime requirements minimal, ideally a handful of packages. Confidence: 0.75
Opinionated Dockerfile conventions for small, reproducible, secure container images that build fast in CI.
# Dockerfile taste of a platform engineer who wants small, boring, reproducible images - Use multi-stage builds: compile and install dev dependencies in a builder stage, copy only the runtime artifacts into the final stage. Confidence: 0.95 - Pin base images to a specific version tag plus digest (`node:22.11-slim@sha256:...`), never `latest`. Confidence: 0.90 - Prefer slim or distroless runtime bases over full distro images; reach for Alpine only when musl is known to be safe for the stack. Confidence: 0.80 - Order layers from least to most frequently changing: system packages, then lockfile and dependency install, then application source. Confidence: 0.95 - Copy the lockfile alone before `COPY . .` so dependency layers stay cached when only source changes. Confidence: 0.95 - Keep a strict `.dockerignore` that excludes `.git`, `node_modules`, local env files, test output and build caches. Confidence: 0.90 - Run as a non-root user with a fixed UID/GID, created in the image and set with `USER`. Confidence: 0.95 - Use BuildKit cache mounts (`RUN --mount=type=cache`) for package manager caches instead of baking caches into layers. Confidence: 0.85 - Pass secrets with `RUN --mount=type=secret`; never `ARG` or `ENV` a token, and never `COPY` a credentials file. Confidence: 0.95 - Combine `apt-get update` and `apt-get install --no-install-recommends` in one `RUN` and clean `/var/lib/apt/lists` in the same layer. Confidence: 0.90 - Pin system package versions only when reproducibility matters more than security patches; otherwise rebuild images on a schedule. Confidence: 0.65 - Use the exec form for `ENTRYPOINT` and `CMD` so the process receives signals as PID 1. Confidence: 0.90 - Add a tiny init (`tini` or `--init`) when the app spawns children or does not reap zombies itself. Confidence: 0.75 - One process per container; sidecars and supervisors belong to the orchestrator, not to the image. Confidence: 0.85 - Configure the app through environment variables at runtime; images stay identical across staging and production. Confidence: 0.90 - Set `WORKDIR` explicitly and avoid `cd` inside `RUN` chains. Confidence: 0.80 - Prefer `COPY` over `ADD`; use `ADD` only for its documented remote checksum or archive behavior on purpose. Confidence: 0.85 - Add OCI labels (`org.opencontainers.image.source`, `revision`, `created`) from CI build args. Confidence: 0.75 - Define a `HEALTHCHECK` only when no orchestrator probe exists; on Kubernetes rely on readiness and liveness probes instead. Confidence: 0.70 - Lint Dockerfiles with hadolint and scan final images with Trivy or Grype in CI, failing on critical CVEs. Confidence: 0.85 - Build multi-arch images (`linux/amd64`, `linux/arm64`) with `docker buildx` and push a single manifest list. Confidence: 0.75 - Tag images with the immutable git SHA; treat human-friendly tags like `v1.4` as moving pointers. Confidence: 0.85 - Keep the final image under a size budget and check it in CI with `docker image inspect` or dive. Confidence: 0.65
Opinionated Node.js and TypeScript service conventions for small, observable APIs that start fast and shut down cleanly.
# Node.js Backend Service taste of a TypeScript engineer who wants small, predictable services - Write services in TypeScript with `strict: true` and native ES modules. Confidence: 0.90 - Pin the Node.js version to an active LTS release in `.nvmrc`, `engines` and the Docker base image. Confidence: 0.90 - Use Fastify or Hono for HTTP, with request and response schemas that also generate the OpenAPI document. Confidence: 0.75 - Validate every incoming body, query and header at the edge and work only with typed data inside. Confidence: 0.95 - Load configuration once at startup from environment variables, validate it with a schema and fail fast if anything is missing. Confidence: 0.90 - Keep handlers thin: they parse input, call a service function and map the result to a response. Confidence: 0.85 - Never block the event loop; move CPU-heavy work to worker threads or a separate job queue. Confidence: 0.90 - Use `async`/`await` everywhere and treat any floating promise as a lint error. Confidence: 0.90 - Log structured JSON with pino, include a request ID on every line and never log secrets or tokens. Confidence: 0.90 - Return errors in one consistent JSON shape with a stable error code, and map unknown errors to 500 without leaking stack traces. Confidence: 0.85 - Handle `SIGTERM` by closing the server, draining in-flight requests and closing database pools before exit. Confidence: 0.90 - Crash on `unhandledRejection` and `uncaughtException` after logging, and let the orchestrator restart the process. Confidence: 0.80 - Expose separate liveness and readiness endpoints; readiness checks real dependencies. Confidence: 0.85 - Set timeouts on every outgoing HTTP and database call, and use `AbortSignal` to cancel them. Confidence: 0.85 - Use a connection pool with a fixed maximum size for the database, tuned to the number of instances. Confidence: 0.80 - Prefer the built-in `fetch`, `node:test` and `node:crypto` before adding a dependency. Confidence: 0.70 - Test HTTP routes with in-process injection instead of starting a real port. Confidence: 0.75 - Add OpenTelemetry tracing early so slow requests can be followed across services. Confidence: 0.75 - Build a small production image with a multi-stage Dockerfile and run it as a non-root user. Confidence: 0.85 - Keep `package-lock.json` committed and install with `npm ci` in CI and Docker builds. Confidence: 0.90
Opinionated database backup conventions where every backup is encrypted, monitored and proven by regular restore drills.
# Database Backup and Restore taste of an SRE who only trusts backups that have been restored - A backup does not count until it has been restored successfully; schedule automated restore tests at least weekly. Confidence: 0.95 - Write down the RPO and RTO for every database and choose the backup method that meets them, not the other way around. Confidence: 0.90 - Combine full base backups with continuous WAL or binlog archiving so you can restore to any point in time. Confidence: 0.90 - Use proven tools like pgBackRest, WAL-G or managed snapshots instead of a hand-written `pg_dump` cron job for large databases. Confidence: 0.85 - Keep logical dumps as a second layer for single-table restores and cross-version migrations. Confidence: 0.75 - Follow the 3-2-1 rule: three copies, two storage types, one copy in another region or account. Confidence: 0.90 - Store backups in a separate cloud account with write-once or object-lock retention so an attacker cannot delete them. Confidence: 0.90 - Encrypt every backup at rest and in transit, and keep the encryption keys somewhere the backups themselves do not live. Confidence: 0.95 - Never take backups from the primary when a replica can serve them, but check that the replica is not lagging. Confidence: 0.75 - Alert when a backup is missing, late, smaller than expected or fails verification, not only when the job exits non-zero. Confidence: 0.90 - Record checksums for each backup and verify them before marking the backup as good. Confidence: 0.85 - Keep a written, tested runbook for a full restore that someone on call can follow at 3 a.m. Confidence: 0.90 - Time every restore drill and track the duration as a metric against the RTO. Confidence: 0.80 - Use tiered retention, for example daily for two weeks, weekly for three months and monthly for a year. Confidence: 0.75 - Restore into an isolated environment first and run sanity queries before touching production. Confidence: 0.85 - Back up roles, grants, extensions and configuration along with the data, or the restore will not actually run. Confidence: 0.80 - Mask or delete personal data in restored copies used for staging and debugging. Confidence: 0.85 - Treat backup deletion as a privileged action that needs two people. Confidence: 0.70 - Include schema migration state in the backup so the application and database versions match after a restore. Confidence: 0.70
Opinionated Kotlin coroutine conventions for Android and JVM backends with structured concurrency, clear dispatchers and testable flows.
# Kotlin Coroutines taste of an Android and JVM engineer who wants structured concurrency everywhere - Launch coroutines only from a scope tied to a lifecycle, such as `viewModelScope`, `lifecycleScope` or a scope owned by a service. Confidence: 0.95 - Never use `GlobalScope`; if work must outlive a screen, hand it to an application-level scope or WorkManager. Confidence: 0.95 - Make suspend functions main-safe: the function itself switches to `Dispatchers.IO` or `Default` with `withContext`, not the caller. Confidence: 0.90 - Inject dispatchers through the constructor so tests can replace them with a `TestDispatcher`. Confidence: 0.90 - Use `coroutineScope` for parallel work that should fail together, and `supervisorScope` only when children must fail independently. Confidence: 0.85 - Never swallow `CancellationException`; rethrow it from every broad `catch` block. Confidence: 0.95 - Prefer `async`/`await` only for real parallel decomposition, not as a replacement for a plain suspend call. Confidence: 0.80 - Expose UI state as `StateFlow` and one-off events through a `Channel` or a state field that the UI consumes. Confidence: 0.80 - Collect flows in the UI with `repeatOnLifecycle(Lifecycle.State.STARTED)` or `collectAsStateWithLifecycle`. Confidence: 0.90 - Use `stateIn` with `SharingStarted.WhileSubscribed(5_000)` so upstream work stops when nobody is watching. Confidence: 0.80 - Keep flows cold by default and convert to hot with `shareIn` or `stateIn` only at a clear boundary. Confidence: 0.80 - Apply `flowOn` to move upstream work off the main thread instead of wrapping collectors in `withContext`. Confidence: 0.80 - Wrap blocking Java APIs in `withContext(Dispatchers.IO)` and never call `runBlocking` in production code paths. Confidence: 0.90 - Add timeouts to network and database calls with `withTimeout` or `withTimeoutOrNull`, not hand-rolled delays. Confidence: 0.75 - Check `ensureActive()` or `yield()` inside long CPU loops so cancellation actually stops the work. Confidence: 0.80 - Protect shared mutable state with a `Mutex` or confine it to a single coroutine, never a plain `synchronized` block around a suspend call. Confidence: 0.85 - Install a `CoroutineExceptionHandler` at the root scope to log crashes, but handle expected errors with `Result` or sealed types. Confidence: 0.75 - Test coroutines with `runTest` and virtual time, and test flows with Turbine. Confidence: 0.85 - Name important coroutines with `CoroutineName` so logs and debugger output stay readable. Confidence: 0.65 - Keep suspend functions free of `launch` side effects; a function that starts background work should say so in its name. Confidence: 0.75
Opinionated rules for building web forms that are accessible, validate clearly and never lose what the user typed.
# Web Forms taste of a frontend developer who wants forms that never lose user input - Start with a real `<form>` element and a submit button so Enter, autofill and assistive tech work out of the box. Confidence: 0.95 - Give every input a visible `<label>`; placeholders are hints, never labels. Confidence: 0.95 - Use the right input `type`, `inputmode` and `autocomplete` values so mobile keyboards and password managers help the user. Confidence: 0.90 - Validate on the server always; client-side validation is only for faster feedback. Confidence: 0.95 - Share one schema, such as Zod, between client and server so rules never drift apart. Confidence: 0.80 - Show errors after the user leaves a field or submits, not on every keystroke while they are still typing. Confidence: 0.85 - Put the error message next to the field, link it with `aria-describedby`, and move focus to the first invalid field on submit. Confidence: 0.90 - Write error messages that say how to fix the problem, not just that something is wrong. Confidence: 0.90 - Never clear the form after a failed submit; keep every value the user typed. Confidence: 0.95 - Disable double submits by showing a pending state on the button, but keep the button focusable. Confidence: 0.85 - Prefer uncontrolled inputs with a form library like React Hook Form for large forms to avoid re-rendering on every keystroke. Confidence: 0.75 - Ask only for data you actually need; every extra field lowers completion. Confidence: 0.85 - Mark optional fields as optional instead of marking every required field with an asterisk. Confidence: 0.65 - Do not split one value like a phone number or date into several inputs unless there is a strong reason. Confidence: 0.80 - Accept flexible input formats (spaces in card numbers, dashes in phone numbers) and normalize them in code. Confidence: 0.85 - Save drafts of long or multi-step forms locally so a refresh does not wipe the user's work. Confidence: 0.75 - Make the success state clear and say what happens next. Confidence: 0.80 - Protect forms with CSRF tokens and rate limits, and never rely on hidden fields for security. Confidence: 0.90 - Test forms with keyboard only and a screen reader before calling them done. Confidence: 0.85
Opinionated AWS CDK conventions for infrastructure as code that stays safe to review, deploy and roll back.
# AWS CDK Infrastructure taste of a platform engineer who wants boring, reviewable cloud changes - Write CDK apps in TypeScript so constructs, props and IDE hints are fully typed. Confidence: 0.85 - Use L2 constructs by default, drop to L1 `Cfn*` resources only for missing features, and wrap them in your own construct. Confidence: 0.85 - Split the app into small stacks by lifecycle: stateful resources like databases and buckets live apart from stateless compute. Confidence: 0.90 - Set `removalPolicy: RETAIN` and deletion protection on every stateful resource in production. Confidence: 0.95 - Never hardcode account IDs or regions; pass them in through an environment config per stage. Confidence: 0.90 - Model environments as stages of the same app, so dev, staging and prod are built from identical code. Confidence: 0.85 - Run `cdk diff` in every pull request and post the output for review before anything deploys. Confidence: 0.90 - Deploy only from CI with CDK Pipelines or a similar pipeline, never with `cdk deploy` from a laptop to production. Confidence: 0.90 - Grant permissions with construct methods like `bucket.grantRead(fn)` instead of writing IAM policy JSON by hand. Confidence: 0.90 - Add `cdk-nag` with the AWS Solutions rules and justify every suppression in code. Confidence: 0.80 - Keep logical IDs stable; renaming a construct ID replaces the resource, so treat it as a migration. Confidence: 0.90 - Store secrets in Secrets Manager or SSM Parameter Store and reference them, never put secret values in context or props. Confidence: 0.95 - Tag every resource with owner, service and cost center through `Tags.of(app)`. Confidence: 0.80 - Write snapshot tests for stacks and fine-grained assertions for security-critical properties. Confidence: 0.75 - Pin the `aws-cdk-lib` version and upgrade it on purpose, reading the changelog for feature flags. Confidence: 0.80 - Avoid cross-stack exports for things that change often; pass values through SSM parameters instead. Confidence: 0.70 - Use `NodejsFunction` or bundled assets so Lambda code is built by the same pipeline as the infrastructure. Confidence: 0.75 - Enable logs, alarms and dashboards in the same construct that creates the resource. Confidence: 0.80 - Keep `cdk.context.json` committed so lookups are deterministic across machines. Confidence: 0.85