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
Opinionated Go concurrency conventions for services where every goroutine has an owner, a context and a clean way to stop.
# Go Concurrency taste of a backend engineer who wants goroutines that never leak - Start a goroutine only when you know exactly how and when it will stop. Confidence: 0.95 - Pass a `context.Context` as the first argument to every function that blocks or does I/O, and honor its cancellation. Confidence: 0.95 - Use `errgroup.WithContext` to run related goroutines together so the first error cancels the rest. Confidence: 0.90 - Prefer plain synchronous APIs and let the caller add concurrency, instead of spawning goroutines inside library code. Confidence: 0.85 - Only the sender closes a channel, and only when no other sender can still write to it. Confidence: 0.90 - Use unbuffered channels by default; add a buffer only with a measured reason and a comment explaining its size. Confidence: 0.75 - Protect shared state with a `sync.Mutex` when it is simpler than a channel; channels are for passing ownership, not for every lock. Confidence: 0.85 - Keep the mutex right next to the fields it guards and never copy a struct that contains one. Confidence: 0.85 - Bound fan-out with a worker pool or `errgroup.SetLimit` instead of one goroutine per item. Confidence: 0.85 - Every `select` that waits on work also waits on `ctx.Done()`. Confidence: 0.90 - Use `time.NewTimer` or `context.WithTimeout` instead of `time.After` inside loops. Confidence: 0.75 - Use `sync.Once` or `sync.OnceValue` for lazy initialization, never a hand-rolled boolean flag. Confidence: 0.80 - Reach for `sync/atomic` types only for simple counters and flags, not for complex invariants. Confidence: 0.75 - Avoid `sync.Map` unless profiling shows lock contention on a read-heavy map. Confidence: 0.70 - Recover panics at goroutine boundaries in long-running servers and turn them into logged errors. Confidence: 0.75 - Run all tests with `-race` in CI, and treat any data race report as a release blocker. Confidence: 0.95 - Check for leaked goroutines in tests with `goleak`. Confidence: 0.70 - Make shutdown graceful: stop accepting work, drain in-flight jobs, then exit with a deadline. Confidence: 0.90 - Do not use `context.Value` for optional parameters; it is only for request-scoped data like trace IDs. Confidence: 0.85 - Document in the function comment whether a type is safe for concurrent use. Confidence: 0.80
Opinionated rules for writing regular expressions that stay readable, safe and well tested instead of turning into line noise.
# Regular Expressions taste of a developer who wants regexes people can still read - Reach for a real parser for HTML, JSON, CSV, URLs and email headers; a regex is the wrong tool there. Confidence: 0.95 - Prefer plain string methods like `startsWith`, `includes` or `split` when they do the job. Confidence: 0.85 - Anchor patterns with `^` and `$` (or `\A` and `\z`) when validating a whole value. Confidence: 0.90 - Use named capture groups instead of counting numbered groups. Confidence: 0.85 - Use non-capturing groups `(?:...)` when you only need grouping, not the captured value. Confidence: 0.75 - Write long patterns in verbose mode with comments, such as `re.VERBOSE` in Python or the `x` flag where supported. Confidence: 0.80 - Prefer specific character classes like `[^"]*` over a lazy `.*?` to make intent clear and matching faster. Confidence: 0.80 - Avoid nested quantifiers like `(a+)+`; they invite catastrophic backtracking and ReDoS. Confidence: 0.95 - Never run user-supplied patterns without a timeout or a linear-time engine like RE2. Confidence: 0.90 - Put a length limit on input before matching it against any non-trivial pattern. Confidence: 0.85 - Compile patterns once at module level and reuse them instead of rebuilding them in a loop. Confidence: 0.75 - Escape dynamic text with `re.escape` or an equivalent helper before putting it into a pattern. Confidence: 0.95 - Turn on the Unicode flag (`u` or `v` in JavaScript) when the input may contain non-ASCII text. Confidence: 0.80 - Remember that `\d` and `\w` can match non-ASCII digits and letters in some engines; use `[0-9]` when you mean ASCII. Confidence: 0.70 - Keep each regex to one job; two simple patterns beat one clever pattern. Confidence: 0.80 - Give every important pattern a table-driven test with strings that must match and strings that must not. Confidence: 0.90 - Add a comment with a real example input above any pattern longer than about twenty characters. Confidence: 0.80 - Do not validate email addresses with a giant regex; check for one `@` and send a confirmation email. Confidence: 0.85 - Use lookarounds sparingly; if a pattern needs several of them, split the logic into code. Confidence: 0.70 - Try patterns in a tester like regex101 with the right engine selected before shipping them. Confidence: 0.70
Opinionated asyncio conventions for Python services that stay fast, cancel cleanly and never block the event loop.
# Python Asyncio taste of a backend developer who never blocks the event loop - Use asyncio only for I/O-bound work like network calls and databases; CPU-heavy work goes to a process pool. Confidence: 0.90 - Start the program with a single `asyncio.run(main())` and never create or manage event loops by hand. Confidence: 0.90 - Use `asyncio.TaskGroup` for running tasks together so a failure cancels the siblings and nothing leaks. Confidence: 0.85 - Never fire and forget with `create_task` without keeping a reference; lost tasks get garbage collected and errors vanish. Confidence: 0.90 - Put a timeout on every network call with `asyncio.timeout()`; waiting forever is a bug. Confidence: 0.90 - Limit concurrency with a `Semaphore` instead of starting thousands of requests at once. Confidence: 0.85 - Never call blocking libraries like `requests` or `time.sleep` inside a coroutine. Confidence: 0.95 - Wrap unavoidable blocking calls in `asyncio.to_thread` and keep them short. Confidence: 0.80 - Use async-native clients such as `httpx` or `asyncpg`, and share one client per app instead of one per request. Confidence: 0.85 - Treat `CancelledError` as normal: clean up in `finally` and re-raise it, never swallow it. Confidence: 0.90 - Avoid `asyncio.gather` without `return_exceptions` for independent jobs where one failure should not hide the others. Confidence: 0.70 - Use `asyncio.Queue` with a fixed number of worker tasks for producer and consumer pipelines. Confidence: 0.80 - Close clients, sessions and connections with `async with` so shutdown is clean. Confidence: 0.85 - Turn on asyncio debug mode in development to catch slow callbacks and never-awaited coroutines. Confidence: 0.75 - Keep sync and async code paths separate instead of writing clever wrappers that run both. Confidence: 0.75 - Do not mix threads and the event loop unless you use `run_coroutine_threadsafe` on purpose. Confidence: 0.80 - Test async code with `pytest-asyncio` or `anyio` and give tests their own short timeouts. Confidence: 0.80 - Use `contextvars` for request IDs and tracing data instead of globals. Confidence: 0.75 - Consider `uvloop` only after measuring; the default loop is fast enough for most services. Confidence: 0.65 - Handle SIGTERM by cancelling the main task and waiting for workers to finish in-flight jobs. Confidence: 0.80
Opinionated conventions for versioning, changelogs and shipping releases so every deploy is predictable and easy to roll back.
# Release Management taste of a maintainer who wants boring, predictable releases - Follow Semantic Versioning strictly for libraries; a breaking change always means a new major version. Confidence: 0.90 - Use calendar versioning for apps and services that users never install by version number. Confidence: 0.70 - Write commit messages in the Conventional Commits format so changelogs and version bumps can be generated. Confidence: 0.75 - Keep a human-edited `CHANGELOG.md` with Added, Changed, Fixed and Removed sections; generated notes are a draft, not the final text. Confidence: 0.80 - Cut releases from the main branch with an annotated, signed Git tag; never release from a laptop's local branch. Confidence: 0.90 - Let CI build, test and publish the release artifact from the tag, so nobody runs a manual publish command. Confidence: 0.90 - Build the artifact once and promote the same build from staging to production instead of rebuilding per environment. Confidence: 0.90 - Release small and often; a weekly release with ten changes is safer than a quarterly release with five hundred. Confidence: 0.85 - Put unfinished features behind flags so the release train never waits for one late feature. Confidence: 0.80 - Keep a written, tested rollback plan for every release, and prefer rolling back over fixing forward under pressure. Confidence: 0.85 - Make database migrations backward compatible so the previous version can still run after a rollback. Confidence: 0.90 - Mark deprecations one minor version before removal and print a clear warning with the replacement. Confidence: 0.85 - Use release candidates for risky major versions and give real users time to try them. Confidence: 0.70 - Roll out to a small canary group first and watch error rates before going to everyone. Confidence: 0.80 - Freeze releases on Friday afternoons and before holidays unless the change is a security fix. Confidence: 0.65 - Ship security fixes as patch releases for every supported version, not only the latest one. Confidence: 0.85 - Publish a short support policy that says which versions still get fixes and for how long. Confidence: 0.75 - Never move or delete a published tag or package version; publish a new one instead. Confidence: 0.95 - Automate the release checklist in CI and keep any remaining manual steps written in the repo. Confidence: 0.80 - Announce each release with the user-facing changes first and the upgrade steps right below them. Confidence: 0.75
Opinionated conventions for using Zod to validate untrusted input and keep TypeScript types and runtime checks in sync.
# Zod Schema Validation taste of a TypeScript developer who trusts nothing from the outside - Validate every input that crosses a trust boundary with Zod: request bodies, query strings, env vars, webhooks and third-party API responses. Confidence: 0.95 - Define the schema first and infer the TypeScript type with `z.infer`, instead of writing the type and the schema twice. Confidence: 0.90 - Use `safeParse` at API boundaries and turn errors into a clean 400 response; use `parse` only where a failure is truly a bug. Confidence: 0.85 - Validate environment variables once at startup and exit early with a clear message when something is missing. Confidence: 0.90 - Keep schemas in a shared module so the client and server use the same contract. Confidence: 0.80 - Use `z.coerce` only for query strings and form data, where every value arrives as a string. Confidence: 0.80 - Prefer `z.discriminatedUnion` over plain unions for tagged objects; errors are clearer and parsing is faster. Confidence: 0.80 - Use `.strict()` on input schemas where unknown keys usually mean a client bug. Confidence: 0.70 - Keep transforms small and pure; heavy business logic does not belong inside a schema. Confidence: 0.80 - Put refinements that check more than one field on the object with `.superRefine` and a clear `path`. Confidence: 0.75 - Write error messages for humans in schemas used by forms, and keep the default messages for internal APIs. Confidence: 0.70 - Use branded types like `z.string().uuid().brand<"UserId">()` for IDs that must never be mixed up. Confidence: 0.65 - Do not validate the same data again deep inside the app; parse once at the edge and pass typed values inward. Confidence: 0.85 - Make dates explicit: accept ISO strings at the boundary and convert to `Date` objects in one place. Confidence: 0.75 - Generate OpenAPI or JSON Schema from Zod schemas when the API is public, instead of keeping docs by hand. Confidence: 0.70 - Avoid `z.any()` and `z.unknown()` in public schemas except for fields that are truly free-form. Confidence: 0.80 - Use `.default()` for optional settings so the code after parsing never needs undefined checks. Confidence: 0.75 - Test schemas with both valid and invalid fixtures, especially for edge cases like empty strings and nulls. Confidence: 0.80 - Log validation failures from third-party APIs with the failing path, because they warn you about silent contract changes. Confidence: 0.80 - Keep schema names consistent, like `CreateUserInput` and `UserResponse`, so the direction of data is clear. Confidence: 0.65
Opinionated HTTP caching and CDN conventions for fast web pages and APIs without stale content surprises.
# HTTP Caching taste of a web developer who wants fast pages without stale surprises - Decide the caching policy for every response on purpose; a missing `Cache-Control` header lets browsers and proxies guess. Confidence: 0.90 - Serve fingerprinted static assets with `Cache-Control: public, max-age=31536000, immutable`. Confidence: 0.95 - Put a content hash in asset file names instead of using query strings like `?v=2` for cache busting. Confidence: 0.85 - Send HTML documents with `no-cache` or a very short max-age so new deploys show up right away. Confidence: 0.85 - Use `private, no-store` for responses with personal or sensitive data, and never let a shared cache hold them. Confidence: 0.95 - Use `s-maxage` to give the CDN a different lifetime than the browser when the CDN can be purged and the browser cannot. Confidence: 0.80 - Add `stale-while-revalidate` for content that can be a few seconds old, so users rarely wait for the origin. Confidence: 0.80 - Use `stale-if-error` so the CDN keeps serving the last good copy when the origin is down. Confidence: 0.70 - Send strong `ETag` or `Last-Modified` validators so revalidation returns a cheap `304 Not Modified`. Confidence: 0.80 - Keep the `Vary` header minimal; varying on `User-Agent` or `Cookie` quietly destroys the CDN hit rate. Confidence: 0.85 - Never cache responses that set cookies at a shared cache. Confidence: 0.90 - Purge the CDN by tag or surrogate key after content changes instead of purging everything. Confidence: 0.75 - Cache API GET responses only when the data is truly shared, and say so explicitly in the response headers. Confidence: 0.80 - Do not cache error responses for long; a cached 500 or 404 can outlive the real problem. Confidence: 0.80 - Rely on HTTP caching headers instead of a service worker unless the app truly needs offline support. Confidence: 0.70 - Watch the CDN cache hit ratio as a key metric, and investigate when it drops after a deploy. Confidence: 0.75 - Test caching behavior with `curl -I` against the real CDN, not only in local development. Confidence: 0.80 - Document the cache rules per route in one place so nobody has to read headers in the browser to learn them. Confidence: 0.65 - Keep `Cache-Control` decisions in application code or edge config under version control, not only in a dashboard. Confidence: 0.75 - Prefer short cache times plus revalidation over long cache times plus emergency purges. Confidence: 0.70
Opinionated ESLint and Prettier conventions for JavaScript and TypeScript teams that want consistent code and no style debates.
# Linting and Formatting taste of a JavaScript developer who wants zero style debates - Let Prettier own all formatting and ESLint own only correctness, so the two tools never fight over the same rule. Confidence: 0.90 - Use the ESLint flat config (`eslint.config.js`) for new projects and skip the legacy `.eslintrc` formats. Confidence: 0.85 - Turn off every stylistic ESLint rule with `eslint-config-prettier` instead of tuning them one by one. Confidence: 0.85 - Keep the Prettier config tiny and close to defaults; arguing about semicolons is not worth a meeting. Confidence: 0.90 - Commit the formatter and linter configs to the repo and pin their versions so every machine gives the same result. Confidence: 0.90 - Enable `typescript-eslint` with type-aware rules for TypeScript code, even though it makes linting a bit slower. Confidence: 0.80 - Treat `no-floating-promises` and `no-misused-promises` as errors; unhandled promises are real bugs, not style. Confidence: 0.85 - Prefer a short list of rules set to `error` over a long list of `warn` rules that everyone learns to ignore. Confidence: 0.85 - Run the formatter on save in the editor so formatting never shows up as a separate task. Confidence: 0.85 - Run lint and format checks on staged files only in a pre-commit hook with `lint-staged`, and keep that hook fast. Confidence: 0.75 - Run `prettier --check` and `eslint --max-warnings=0` in CI so nothing unformatted or noisy reaches the main branch. Confidence: 0.90 - Land the first repo-wide format in a single dedicated commit and add it to `.git-blame-ignore-revs`. Confidence: 0.80 - Allow inline `eslint-disable` comments only for one specific rule, always with a short reason next to it. Confidence: 0.85 - Never disable a rule for the whole file just to get one tricky line through. Confidence: 0.75 - Keep import sorting automatic with a plugin, so import order never comes up in code review. Confidence: 0.70 - Add a `.editorconfig` for line endings, final newlines and indentation so non-JS files stay consistent too. Confidence: 0.70 - Ignore generated code and build output in both tools instead of fixing lint errors in files nobody writes by hand. Confidence: 0.85 - Review new lint rules as a team decision with a one-line reason in the config, not as a drive-by change. Confidence: 0.70 - Consider Biome for new small projects that want one fast tool for both linting and formatting. Confidence: 0.60 - Fix lint errors in the same pull request that adds them; a "clean up lint later" ticket never gets done. Confidence: 0.80
Opinionated conventions for modern, target-based CMake builds in portable C++ projects.
# CMake C++ Project taste of a systems developer who wants clean, portable builds - Require a modern CMake (3.24 or newer) and write target-based CMake only, never global `include_directories` or `add_definitions`. Confidence: 0.90 - Attach include paths, flags and definitions to targets with `target_*` commands and the right `PUBLIC`, `PRIVATE` or `INTERFACE` scope. Confidence: 0.90 - Always build out of source, in a `build/` directory that is gitignored. Confidence: 0.95 - Commit a `CMakePresets.json` with debug, release and sanitizer presets so everyone configures the same way. Confidence: 0.85 - Set the language standard with `target_compile_features(... cxx_std_20)` instead of raw `-std=` flags. Confidence: 0.85 - Turn on strict warnings like `-Wall -Wextra -Wpedantic` or `/W4` through a shared interface target, and treat warnings as errors in CI. Confidence: 0.85 - Never use `file(GLOB)` for source lists; list source files explicitly so the build reruns when files change. Confidence: 0.75 - Get third-party libraries with `find_package` backed by vcpkg or Conan, and use `FetchContent` only for small, pinned dependencies. Confidence: 0.80 - Pin every fetched dependency to a tag or commit hash, never a moving branch. Confidence: 0.90 - Never vendor modified copies of libraries without a clear patch file and a note on why. Confidence: 0.75 - Run tests with CTest, and register each test executable with `add_test` or `gtest_discover_tests`. Confidence: 0.85 - Have a CI job that builds with AddressSanitizer and UndefinedBehaviorSanitizer and runs the full test suite. Confidence: 0.85 - Export `compile_commands.json` with `CMAKE_EXPORT_COMPILE_COMMANDS` so clangd and clang-tidy work out of the box. Confidence: 0.90 - Format with a committed `.clang-format` and check it in CI rather than arguing about style in reviews. Confidence: 0.85 - Use Ninja as the default generator for fast incremental builds, and ccache or sccache in CI. Confidence: 0.80 - Provide proper `install()` rules and an exported package config so other projects can use `find_package` on the library. Confidence: 0.75 - Namespace exported targets like `mylib::mylib` and create an alias target with the same name for in-tree use. Confidence: 0.80 - Keep options few and prefixed with the project name, such as `MYLIB_BUILD_TESTS`, and default tests off when used as a subproject. Confidence: 0.75 - Avoid setting `CMAKE_CXX_FLAGS` directly in `CMakeLists.txt`; leave global flags to presets and toolchain files. Confidence: 0.80 - Test the build on Linux, macOS and Windows in CI if the project claims to be portable. Confidence: 0.80