prompts.chatprompts.chatprompts.chat
TeamsBotsSkillsPromptsPromptmasters
BookFor KidsDevelopers
Login
CC0 2026 prompts.chat
DeepWikiHow to...DocsAPIPrivacyTermsSupportAboutGitHub
All Tags

Testing Prompts

57 prompts10 bots
Swift Package taste
Taste

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
Best PracticesiOSTooling+2
F@f
0
Refactoring taste
Taste

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.80
Best PracticesSoftwareRefactoring+2
F@f
0
Ruby Gem taste
Taste

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
Best PracticesSoftwareOpen Source+2
F@f
0
Python Complexity Hotspot Finder
Skill

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())
Best PracticesRefactoringEngineering+3
F@f
0
Transactional Email taste
Taste

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.75
Best PracticesSecurityBackend+2
F@f
0
Rust Library Crate taste
Taste

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
Best PracticesDocumentationTooling+2
F@f
0
Go CLI taste
Taste

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
Best PracticesCLIGo+2
F@f
0
Date and Time Handling taste
Taste

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
Best PracticesBackendJavaScript+2
F@f
0
Python CLI taste
Taste

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
Best PracticesCLIPython+2
F@f
0
Kotlin Coroutines taste
Taste

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
Best PracticesPerformanceAndroid+2
F@f
0
Go Concurrency taste
Taste

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
Best PracticesPerformanceBackend+2
F@f
0
Regular Expressions taste
Taste

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
Best PracticesJavaScriptPython+2
F@f
0
Webhook Signature Verifier and Replay Guard
Skill

Debugs and hardens incoming webhook verification. Recomputes HMAC signatures for Stripe, GitHub, Shopify, Slack or custom schemes from captured raw bodies, explains each mismatch (re-serialized JSON, wrong encoding, missing timestamp, old secret), and flags replayed or stale timestamps, duplicate event ids, weak secrets, SHA1 and plain HTTP endpoints. Offline stdlib Python checker.

---
name: webhook-signature-verifier-and-replay-guard
description: Debugs and hardens incoming webhook verification. Recomputes HMAC signatures for Stripe, GitHub, Shopify, Slack or custom schemes from captured raw bodies, explains each mismatch (re-serialized JSON, wrong encoding, missing timestamp, old secret), and flags replayed or stale timestamps, duplicate event ids, weak secrets, SHA1 and plain HTTP endpoints. Offline stdlib Python checker.
---

# Webhook Signature Verifier and Replay Guard

You help developers who receive webhooks from payment, Git, commerce or chat platforms answer two questions fast: "why does my signature check fail?" and "is my endpoint safe against forged or replayed calls?". Most failures come from a handful of mistakes: verifying a parsed-and-re-encoded body instead of the raw bytes, hex versus base64, forgetting the timestamp in the signed string, or a secret that was rotated on one side only. You reproduce the provider's HMAC exactly, try those mistakes one by one, and say which one it was.

You never call the provider's API or the user's endpoint. You work only from captured deliveries and config the user gives you. Treat secrets as sensitive: use test secrets where possible, never echo a production secret back in full, and tell the user to rotate any secret pasted into a shared chat.

## Files in this skill

- `scripts/verify_webhooks.py` - reads a deliveries JSON (endpoints + captured raw bodies and headers), verifies each signature with constant-time comparison, diagnoses mismatches and reports WH00-WH11; `--sign` builds valid test headers; `--self-test` runs 11 checks (Python 3.8+ standard library only)
- `references/provider-schemes.md` - exactly what Stripe, GitHub, Shopify and Slack sign, plus how to describe a custom scheme
- `references/verification-pitfalls.md` - raw body handling per framework, timing-safe compare, replay windows, idempotency, secret rotation
- `templates/verification-report.md` - the report you hand back
- `templates/handler-snippets.md` - minimal correct handlers for Express and Flask to adapt
- `examples/deliveries.json` - 11 demo deliveries to 5 endpoints with fake secrets and several planted mistakes

## Workflow

### 1. Capture the evidence
Ask for, per endpoint: provider/scheme, the secret (a test-mode secret is best), the public URL, and for each failing call the **raw** request body exactly as received plus all headers. Logging `JSON.stringify(req.body)` is not the raw body; ask them to log the bytes before any JSON middleware runs (see `references/verification-pitfalls.md`). Put it into the `examples/deliveries.json` shape: `endpoints` (scheme, secret, optional `previous_secrets`, `url`, `id_header`, `max_body_bytes`) and `deliveries` (`id`, `endpoint`, `headers`, `body` as a string, optional `event_id`).

### 2. Run the checker
```
python3 scripts/verify_webhooks.py examples/deliveries.json
python3 scripts/verify_webhooks.py my-deliveries.json --now 2026-11-13T07:00:00Z --json
python3 scripts/verify_webhooks.py --sign stripe --secret whsec_test_x --body-file body.json --timestamp 1794553200
python3 scripts/verify_webhooks.py --self-test
```
Use `--now` with the time the deliveries were captured, otherwise every old capture shows as a replay. Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, follow `references/provider-schemes.md` to rebuild the signed string by hand and compare.

### 3. Read the result
Each delivery gets a verdict: `accept`, `accept-duplicate(skip side effects)`, `accept-rotate-secret` or `reject`.
- High: WH01 signature mismatch (with the likely cause), WH02 missing signature or timestamp header, WH03 timestamp older than the tolerance (replay risk), WH09 endpoint not on HTTPS, WH00 bad input or unknown endpoint.
- Medium: WH04 duplicate event id, WH05 timestamp in the future beyond allowed skew (clock drift), WH06 SHA1-only signature, WH07 signed with a previous secret, WH08 short or low-entropy secret.
- Low: WH10 no event id to de-duplicate on, WH11 body larger than the configured limit.

### 4. Deliver
Fill `templates/verification-report.md`: per-delivery verdicts, the root cause of each mismatch in one sentence with the exact code fix, and a hardening checklist (raw body, constant-time compare, 5-minute window, idempotency store, rotation plan, HTTPS). If they want code, adapt `templates/handler-snippets.md` to their framework, then generate a test vector with `--sign` and re-run until every expected delivery is `accept`.

## Example result
On the demo file (now = 13 Nov 2026 07:00 UTC): D01 is valid and D02 is the same Stripe event again (skip side effects); D03 was signed over compact JSON but the app verified a pretty-printed copy; D04 carries a valid signature that is an hour old, so it is rejected as a replay; D06 is still signed with GitHub's previous secret; D07 has only the legacy SHA1 header; D08 compared a hex digest where Shopify sends base64; D10's Slack timestamp is 10 minutes in the future; and the contact form posts to plain HTTP with an 11-character secret. Result: 5 high, 5 medium, 2 low.

## Rules

- Always verify against the raw bytes and compare with a constant-time function; never compare signatures with `==`.
- Reject before doing work: signature and timestamp checks come before parsing, database writes or queueing.
- A valid signature does not make a delivery fresh or unique: check the timestamp window and de-duplicate on the event id.
- Do not weaken checks to "make it pass" (no skipping verification in production, no huge tolerances); fix the root cause.
- Provider details change; confirm header names and signed-string formats against the provider's current docs before shipping.

FILE:references/provider-schemes.md
# Provider signature schemes

All of these are HMAC over the **raw request body** with a shared secret. The differences are the header, the signed string, the hash and the encoding. Confirm against the provider's current documentation before shipping; names below are the widely used defaults.

| Scheme (`scheme`) | Header | Signed string | Hash | Encoding | Timestamp |
|---|---|---|---|---|---|
| `stripe` | `Stripe-Signature: t=<unix>,v1=<sig>[,v1=<sig2>]` | `<t>.<raw body>` | SHA-256 | hex | `t=` inside the header; default tolerance 300 s |
| `github` | `X-Hub-Signature-256: sha256=<sig>` | `<raw body>` | SHA-256 | hex | none (use `X-GitHub-Delivery` to de-duplicate) |
| `github-sha1` | `X-Hub-Signature: sha1=<sig>` | `<raw body>` | SHA-1 | hex | legacy, avoid |
| `shopify` | `X-Shopify-Hmac-Sha256: <sig>` | `<raw body>` | SHA-256 | base64 | none (de-duplicate on `X-Shopify-Webhook-Id`) |
| `slack` | `X-Slack-Signature: v0=<sig>` + `X-Slack-Request-Timestamp` | `v0:<ts>:<raw body>` | SHA-256 | hex | reject if older than 5 minutes |

## Notes per provider
- **Stripe**: during secret rolling the header can carry several `v1=` values; accept if any one matches. The endpoint secret starts with `whsec_` and the whole string (prefix included) is the HMAC key.
- **GitHub**: the secret is whatever you typed when creating the webhook. Ping events are signed too. Enable the SHA-256 header; the SHA-1 header exists only for old integrations.
- **Shopify**: the key is the app's API secret (or the webhook signing secret shown in the admin). The digest is base64, so comparing against a hex digest always fails.
- **Slack**: the body is usually `application/x-www-form-urlencoded`; sign the raw string, do not rebuild it from parsed form fields.

## Describing a custom scheme (`scheme: generic`)
Set these fields on the endpoint:
- `header` - header that carries the signature, e.g. `X-Signature`
- `alg` - `sha256`, `sha512` or `sha1`
- `enc` - `hex` or `base64`
- `prefix` - text before the digest in the header, e.g. `sha256=` (empty if none)
- `template` - signed string, using `{body}` and optionally `{ts}`, e.g. `{ts}.{body}`
- `ts_header` - header with the unix timestamp, if the scheme has one
- `id_header` - header with a unique delivery id, for de-duplication

Any field can also override a named scheme (for example a self-hosted GitLab-style proxy that re-signs with a different header).

FILE:references/verification-pitfalls.md
# Verification pitfalls and hardening

## 1. Use the raw body (the cause of most mismatches)
JSON middleware parses the body; re-encoding it changes whitespace, key order or number formatting, so the HMAC no longer matches.
- **Express**: mount `express.raw({ type: 'application/json' })` on the webhook route (before `express.json()`), verify `req.body` (a Buffer), then `JSON.parse` it yourself.
- **Next.js route handlers**: `const raw = await req.text()` before anything else.
- **Flask**: `request.get_data(cache=True, as_text=False)`; do not use `request.json` for verification.
- **Django**: `request.body` (bytes) before touching `request.POST`.
- **FastAPI/Starlette**: `await request.body()`.
- **Go**: read `r.Body` once with `io.ReadAll`, verify, then unmarshal from the same bytes.
- Proxies, API gateways and serverless adapters may re-encode bodies (base64 in AWS API Gateway events: decode first) or add a trailing newline.

## 2. Compare in constant time
Use `hmac.compare_digest` (Python), `crypto.timingSafeEqual` (Node, equal-length Buffers), `hmac.Equal` (Go), `MessageDigest.isEqual` (Java). Plain `==` leaks timing and invites forgery attempts.

## 3. Freshness and replay
- If the scheme signs a timestamp, reject deliveries older than the tolerance (300 s is the common default) **even when the signature is valid**: an attacker who captured one request can resend it.
- Allow a small future skew (about 60 s) and keep server clocks on NTP; large future offsets mean a clock problem.
- Schemes without a signed timestamp (GitHub, Shopify) rely on de-duplication only.

## 4. Idempotency
Providers retry on timeouts and non-2xx responses, so the same event arrives more than once. Store the event or delivery id (or a SHA-256 of the raw body) with a unique constraint and a TTL longer than the provider's retry window (often 3 days); on a repeat, return 200 without re-running side effects. Respond within a few seconds and do slow work in a queue.

## 5. Secrets and rotation
- Generate at least 32 random bytes (`python3 -c "import secrets; print(secrets.token_hex(32))"`); one secret per endpoint and environment.
- Rotation: add the new secret as primary and keep the old one in `previous_secrets` for a short overlap, accept either, then remove the old one. A delivery that only matches the old secret (WH07) means the sender has not switched yet.
- Load secrets from a secret manager or environment, strip whitespace, and never log them.

## 6. Transport and limits
- HTTPS only: the HMAC proves origin but does not hide customer data.
- Cap body size and reject before parsing; return 401/403 for bad signatures without details, and log the reason internally.
- Optional extra layer: allow-list the provider's published IP ranges, but never instead of signature checks.

FILE:templates/verification-report.md
# Webhook verification report

**Endpoints checked:** [names]  **Deliveries:** [n]  **Captured at:** [time, used as --now]
**Verdict:** [All good / Fix before go-live / Under attack or misconfigured]
**Findings:** [h] high, [m] medium, [l] low (`verify_webhooks.py` output attached)

## Deliveries
| Delivery | Endpoint | Verdict | Root cause (one sentence) |
|---|---|---|---|
| [D01] | [billing-stripe] | [accept / reject / duplicate / rotate] | [e.g. verified pretty-printed JSON instead of raw body] |

## Fixes, in order
1. [Code fix with file/line, e.g. mount express.raw() on /hooks/stripe before express.json()]
2. [...]
3. [...]

## Hardening checklist
- [ ] Verify the raw body bytes, then parse
- [ ] Constant-time comparison
- [ ] Timestamp window [300] s, future skew [60] s, NTP on all hosts
- [ ] Idempotency store keyed on [event id header], TTL [3 days]
- [ ] One random secret (32+ bytes) per endpoint and environment; rotation plan with overlap
- [ ] HTTPS only, body size limit, 401 without details on failure
- [ ] Alert when the failure rate on an endpoint jumps

## Test vectors used
[--sign commands and the headers they produced, with test secrets only]

FILE:templates/handler-snippets.md
# Minimal correct handlers (adapt names, keep the order of checks)

## Node.js / Express (Stripe-style `t=...,v1=...`)
```js
const crypto = require('crypto');
const express = require('express');
const app = express();
const SECRET = process.env.WEBHOOK_SECRET;      // never hard-code
const TOLERANCE = 300;                          // seconds
const seen = new Set();                         // use a DB table with a unique key in production

app.post('/hooks/stripe', express.raw({ type: 'application/json' }), (req, res) => {
  const header = req.get('Stripe-Signature') || '';
  const parts = Object.fromEntries(header.split(',').map(p => p.split('=')));
  const t = Number(parts.t);
  const sigs = header.split(',').filter(p => p.startsWith('v1=')).map(p => p.slice(3));
  if (!t || sigs.length === 0) return res.sendStatus(401);
  if (Math.abs(Date.now() / 1000 - t) > TOLERANCE) return res.sendStatus(401);
  const expected = crypto.createHmac('sha256', SECRET).update(`t.`).update(req.body).digest('hex');
  const ok = sigs.some(s => s.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)));
  if (!ok) return res.sendStatus(401);
  const event = JSON.parse(req.body.toString('utf8'));
  if (seen.has(event.id)) return res.sendStatus(200);   // duplicate: no side effects
  seen.add(event.id);
  // enqueue(event) and return quickly
  res.sendStatus(200);
});
app.use(express.json());                        // other routes after the raw webhook route
```

## Python / Flask (GitHub `X-Hub-Signature-256`)
```python
import hashlib, hmac, json, os
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = os.environ["WEBHOOK_SECRET"].strip().encode()
seen = set()  # replace with a table that has a UNIQUE constraint on delivery_id

@app.post("/hooks/github")
def github_hook():
    raw = request.get_data(cache=True)                 # raw bytes, before request.json
    header = request.headers.get("X-Hub-Signature-256", "")
    if not header.startswith("sha256="):
        abort(401)
    expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(header[7:], expected):
        abort(401)
    delivery = request.headers.get("X-GitHub-Delivery")
    if delivery in seen:
        return "", 200                                  # duplicate retry
    seen.add(delivery)
    event = json.loads(raw)
    # enqueue(event) and return quickly
    return "", 200
```

## Checklist when porting to another stack
Read raw bytes -> check header present -> check timestamp window (if signed) -> HMAC with the right hash/encoding -> constant-time compare (any of several signatures) -> de-duplicate -> parse -> enqueue -> 2xx fast.

FILE:examples/deliveries.json
{
  "now": "2026-11-13T07:00:00Z",
  "tolerance_seconds": 300,
  "future_skew_seconds": 60,
  "_note": "Demo data only: every secret below is a fake test value. Bodies are the RAW request bodies exactly as received.",
  "endpoints": {
    "billing-stripe": {
      "scheme": "stripe",
      "secret": "whsec_demo_4b9e2c7a1f6d3085e2a9c4b7d1f0e6a3",
      "url": "https://api.acme-demo.test/hooks/stripe",
      "max_body_bytes": 65536
    },
    "ci-github": {
      "scheme": "github",
      "secret": "gh_demo_secret_9c1e7a3f5b2d8064aa71c3e9f2b5d708",
      "previous_secrets": [
        "gh_demo_old_secret_2f8a6c4e0b1d9375"
      ],
      "url": "https://api.acme-demo.test/hooks/github",
      "id_header": "X-GitHub-Delivery"
    },
    "orders-shopify": {
      "scheme": "shopify",
      "secret": "shpss_demo_e3a1c9f7b5d2084b6e2c9a7f1d3b5e80",
      "url": "https://api.acme-demo.test/hooks/shopify",
      "id_header": "X-Shopify-Webhook-Id"
    },
    "ops-slack": {
      "scheme": "slack",
      "secret": "slack_demo_8f2c6a0e4b9d1735c2e8a6f0b4d9c173",
      "url": "https://api.acme-demo.test/hooks/slack"
    },
    "contact-form": {
      "scheme": "generic",
      "header": "X-Form-Signature",
      "alg": "sha256",
      "enc": "hex",
      "prefix": "",
      "template": "{body}",
      "secret": "formhook123",
      "url": "http://forms.acme-demo.test/hook"
    }
  },
  "deliveries": [
    {
      "id": "D01",
      "endpoint": "billing-stripe",
      "event_id": "evt_3Qx1",
      "headers": {
        "Stripe-Signature": "t=1794553160,v1=5ac4a493d3abba1d31c6979909abe3f96f880b5d5567f64e2e1292578d05a6c8"
      },
      "body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}"
    },
    {
      "id": "D02",
      "endpoint": "billing-stripe",
      "event_id": "evt_3Qx1",
      "headers": {
        "Stripe-Signature": "t=1794553160,v1=5ac4a493d3abba1d31c6979909abe3f96f880b5d5567f64e2e1292578d05a6c8"
      },
      "body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}"
    },
    {
      "id": "D03",
      "endpoint": "billing-stripe",
      "event_id": "evt_3Qx2",
      "headers": {
        "Stripe-Signature": "t=1794553170,v1=b20e8ff57bb1b1d93f8793c15a2217b54e0e012b3800a1faa32a613e4fbcb5d2"
      },
      "body": "{\n  \"id\": \"evt_3Qx1\",\n  \"type\": \"invoice.paid\",\n  \"data\": {\n    \"object\": {\n      \"id\": \"in_901\",\n      \"amount_paid\": 4900,\n      \"currency\": \"usd\",\n      \"customer\": \"cus_77\"\n    }\n  }\n}"
    },
    {
      "id": "D04",
      "endpoint": "billing-stripe",
      "event_id": "evt_2Zk9",
      "headers": {
        "Stripe-Signature": "t=1794549600,v1=647af93a8d457b8daee20995225aae284f5ea56cfe075c38cb465fe41ff99bfb"
      },
      "body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}"
    },
    {
      "id": "D05",
      "endpoint": "ci-github",
      "headers": {
        "X-Hub-Signature-256": "sha256=646c0de3d17073a243c74ed3340c018acbea30805a870eff1d6847b4333a5963",
        "X-GitHub-Delivery": "a1b2-0001"
      },
      "body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}"
    },
    {
      "id": "D06",
      "endpoint": "ci-github",
      "headers": {
        "X-Hub-Signature-256": "sha256=f728095add7f5315c2eda1d4f6e36040f898f4d0c2d71a42e8154ec05b1f16da",
        "X-GitHub-Delivery": "a1b2-0002"
      },
      "body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}"
    },
    {
      "id": "D07",
      "endpoint": "ci-github",
      "headers": {
        "X-Hub-Signature": "sha1=ca66729dfe67d043208370a5b228586808eaa8ce",
        "X-GitHub-Delivery": "a1b2-0003"
      },
      "body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}"
    },
    {
      "id": "D08",
      "endpoint": "orders-shopify",
      "headers": {
        "X-Shopify-Hmac-Sha256": "651b34b52d6af57f77251cb9e652c7e409bf05c04695478629ec8104f4bf6992",
        "X-Shopify-Webhook-Id": "wh-5501"
      },
      "body": "{\"id\":820012,\"email\":\"buyer@example.test\",\"total_price\":\"58.00\",\"currency\":\"EUR\",\"line_items\":[{\"sku\":\"TEA-250\",\"quantity\":2}]}"
    },
    {
      "id": "D09",
      "endpoint": "orders-shopify",
      "headers": {
        "X-Shopify-Hmac-Sha256": "ZRs0tS1q9X93JRy55lLH5Am/BcBGlUeGKeyBBPS/aZI=",
        "X-Shopify-Webhook-Id": "wh-5502"
      },
      "body": "{\"id\":820012,\"email\":\"buyer@example.test\",\"total_price\":\"58.00\",\"currency\":\"EUR\",\"line_items\":[{\"sku\":\"TEA-250\",\"quantity\":2}]}"
    },
    {
      "id": "D10",
      "endpoint": "ops-slack",
      "headers": {
        "X-Slack-Signature": "v0=675094d734821c12a58309211f8d66c58fffbbf86f25ba8424acb5cffd228fe6",
        "X-Slack-Request-Timestamp": "1794553800"
      },
      "body": "token=demo&team_id=T000&command=%2Fdeploy&text=shop-api+staging&user_name=dev-ana"
    },
    {
      "id": "D11",
      "endpoint": "contact-form",
      "headers": {
        "X-Form-Signature": "50c78cd627e684b0c1c024f1dfe22cc321a4afb6d25aed29aad8f1c6c2c66dce"
      },
      "body": "{\"form\":\"contact\",\"name\":\"Sam\",\"message\":\"Please call me back\"}"
    }
  ]
}

FILE:scripts/verify_webhooks.py
#!/usr/bin/env python3
"""Webhook signature verifier and replay guard (offline, Python 3.8+ standard library only).

Reads a JSON file with endpoint configs and captured deliveries (raw body + headers),
recomputes each HMAC signature, checks timestamps, duplicates and config hygiene, and
explains the most likely cause of every mismatch.

Usage:
  verify_webhooks.py deliveries.json [--now 2026-11-13T10:00:00Z] [--json]
  verify_webhooks.py --sign SCHEME --secret S --body-file body.txt [--timestamp 1794560400]
  verify_webhooks.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, base64, hashlib, hmac, json, math, sys
from collections import Counter
from datetime import datetime, timezone

SCHEMES = {
    # header, algorithm, encoding, prefix, signed-string template, timestamp header
    "github":  {"header": "X-Hub-Signature-256", "alg": "sha256", "enc": "hex", "prefix": "sha256=", "template": "{body}", "ts_header": None},
    "github-sha1": {"header": "X-Hub-Signature", "alg": "sha1", "enc": "hex", "prefix": "sha1=", "template": "{body}", "ts_header": None},
    "shopify": {"header": "X-Shopify-Hmac-Sha256", "alg": "sha256", "enc": "base64", "prefix": "", "template": "{body}", "ts_header": None},
    "slack":   {"header": "X-Slack-Signature", "alg": "sha256", "enc": "hex", "prefix": "v0=", "template": "v0:{ts}:{body}", "ts_header": "X-Slack-Request-Timestamp"},
    "stripe":  {"header": "Stripe-Signature", "alg": "sha256", "enc": "hex", "prefix": "", "template": "{ts}.{body}", "ts_header": None},
}
SEV_ORDER = {"high": 0, "medium": 1, "low": 2, "info": 3}


def scheme_for(ep):
    base = dict(SCHEMES.get(ep.get("scheme", "generic"), {}))
    for k in ("header", "alg", "enc", "prefix", "template", "ts_header"):
        if k in ep:
            base[k] = ep[k]
    missing = [k for k in ("header", "alg", "enc", "template") if not base.get(k)]
    if missing:
        raise ValueError("endpoint %r: generic scheme needs %s" % (ep.get("name"), ", ".join(missing)))
    base.setdefault("prefix", "")
    base.setdefault("ts_header", None)
    return base


def digest(secret, msg, alg, enc):
    mac = hmac.new(secret.encode("utf-8"), msg.encode("utf-8"), getattr(hashlib, alg)).digest()
    return mac.hex() if enc == "hex" else base64.b64encode(mac).decode("ascii")


def signed_string(sch, body, ts):
    return sch["template"].replace("{ts}", str(ts or "")).replace("{body}", body)


def sign(scheme_name, secret, body, ts=None):
    sch = scheme_for({"scheme": scheme_name})
    sig = digest(secret, signed_string(sch, body, ts), sch["alg"], sch["enc"])
    if scheme_name == "stripe":
        return {sch["header"]: "t=%s,v1=%s" % (ts, sig)}
    out = {sch["header"]: sch["prefix"] + sig}
    if sch["ts_header"]:
        out[sch["ts_header"]] = str(ts)
    return out


def get_header(headers, name):
    for k, v in headers.items():
        if k.lower() == name.lower():
            return v
    return None


def parse_stripe(value):
    ts, sigs = None, []
    for part in value.split(","):
        k, _, v = part.strip().partition("=")
        if k == "t":
            ts = v
        elif k == "v1":
            sigs.append(v)
    return ts, sigs


def entropy_bits(secret):
    if not secret:
        return 0.0
    counts = Counter(secret)
    h = -sum(c / len(secret) * math.log2(c / len(secret)) for c in counts.values())
    return h * len(secret)


def diagnose(sch, ep, body, ts, received):
    """Try the usual mistakes and return a human explanation, or None."""
    secret = ep["secret"]
    alg, enc = sch["alg"], sch["enc"]
    tries = []
    for old in ep.get("previous_secrets", []):
        tries.append(("WH07", "matches a PREVIOUS secret: the sender still signs with the old secret (finish the rotation)", old, signed_string(sch, body, ts), enc))
    try:
        obj = json.loads(body)
        tries.append(("WH01", "matches the body re-serialized as compact JSON: the sender or your framework parsed and re-encoded the payload before signing/verifying; always use the raw bytes", secret, signed_string(sch, json.dumps(obj, separators=(",", ":")), ts), enc))
        tries.append(("WH01", "matches the body re-serialized with default json.dumps spacing: verify against the raw request body, not a parsed object", secret, signed_string(sch, json.dumps(obj), ts), enc))
    except ValueError:
        pass
    tries.append(("WH01", "matches the body with a trailing newline stripped/added: a proxy or test tool changed the body", secret, signed_string(sch, body.rstrip("\n") if body.endswith("\n") else body + "\n", ts), enc))
    if "{ts}" in sch["template"]:
        tries.append(("WH01", "matches HMAC over the body alone: the timestamp prefix is missing from the signed string", secret, body, enc))
    if secret.startswith("whsec_"):
        tries.append(("WH01", "matches when the 'whsec_' prefix is removed from the secret: check how the secret is loaded", secret[len("whsec_"):], signed_string(sch, body, ts), enc))
    tries.append(("WH01", "matches with a trimmed secret: the stored secret has stray whitespace", secret.strip(), signed_string(sch, body, ts), enc))
    other = "base64" if enc == "hex" else "hex"
    tries.append(("WH01", "matches with %s encoding instead of %s: wrong digest encoding" % (other, enc), secret, signed_string(sch, body, ts), other))
    for code, why, sec, msg, e in tries:
        if sec == secret and msg == signed_string(sch, body, ts) and e == enc:
            continue
        cand = digest(sec, msg, alg, e)
        if any(hmac.compare_digest(cand, r) for r in received):
            return code, why
    return None


def check_delivery(d, ep, now, tolerance, skew, seen_ids):
    findings = []
    def add(code, sev, msg):
        findings.append({"code": code, "severity": sev, "delivery": d.get("id"), "endpoint": ep.get("name"), "message": msg})
    try:
        sch = scheme_for(ep)
    except ValueError as e:
        add("WH00", "high", str(e))
        return findings, None
    headers = d.get("headers", {})
    body = d.get("body")
    if not isinstance(body, str):
        add("WH00", "high", "body must be the raw request body as a string (not parsed JSON)")
        return findings, None
    raw = get_header(headers, sch["header"])
    if raw is None:
        if ep.get("scheme") == "github" and get_header(headers, "X-Hub-Signature"):
            add("WH06", "medium", "only legacy X-Hub-Signature (HMAC-SHA1) present; enable and verify X-Hub-Signature-256")
        add("WH02", "high", "missing signature header %s: reject with 401 before doing any work" % sch["header"])
        return findings, False
    ts = None
    if ep.get("scheme") == "stripe":
        ts, received = parse_stripe(raw)
        if not ts or not received:
            add("WH02", "high", "Stripe-Signature header has no t= or v1= part")
            return findings, False
    else:
        if sch["prefix"] and not raw.startswith(sch["prefix"]):
            add("WH01", "high", "signature does not start with %r (wrong scheme or algorithm?)" % sch["prefix"])
            return findings, False
        received = [raw[len(sch["prefix"]):]]
        if sch["ts_header"]:
            ts = get_header(headers, sch["ts_header"])
            if ts is None:
                add("WH02", "high", "missing timestamp header %s" % sch["ts_header"])
                return findings, False
    if sch["alg"] in ("sha1", "md5"):
        add("WH06", "medium", "weak HMAC algorithm %s: prefer SHA-256 if the provider supports it" % sch["alg"].upper())
    expected = digest(ep["secret"], signed_string(sch, body, ts), sch["alg"], sch["enc"])
    valid = any(hmac.compare_digest(expected, r) for r in received)
    if not valid:
        hint = diagnose(sch, ep, body, ts, received)
        if hint and hint[0] == "WH07":
            add("WH07", "medium", hint[1])
            valid = None  # authentic but signed with the old secret
        elif hint:
            add("WH01", "high", "signature mismatch; likely cause: " + hint[1])
        else:
            add("WH01", "high", "signature mismatch; no common mistake reproduces it: wrong secret for this endpoint, or the body was modified in transit")
    if ts is not None:
        try:
            tsv = int(ts)
        except ValueError:
            add("WH00", "high", "timestamp %r is not unix seconds" % ts)
            tsv = None
        if tsv is not None and now is not None:
            age = now - tsv
            if age > tolerance:
                add("WH03", "high", "timestamp is %d s old (tolerance %d s): possible replay, reject even if the signature is valid" % (age, tolerance))
            elif age < -skew:
                add("WH05", "medium", "timestamp is %d s in the future (allowed skew %d s): check server clocks (NTP)" % (-age, skew))
    event_id = d.get("event_id") or get_header(headers, ep.get("id_header", "X-Webhook-Id") or "") or get_header(headers, "X-GitHub-Delivery")
    if event_id:
        key = (ep.get("name"), event_id)
        if key in seen_ids:
            add("WH04", "medium", "duplicate event id %s (first seen in delivery %s): process idempotently, do not run side effects twice" % (event_id, seen_ids[key]))
        else:
            seen_ids[key] = d.get("id")
    else:
        add("WH10", "low", "no event/delivery id: cannot de-duplicate retries; store a hash of the body or ask the provider for an id header")
    limit = ep.get("max_body_bytes")
    if limit and len(body.encode("utf-8")) > limit:
        add("WH11", "low", "body is %d bytes, above max_body_bytes %d" % (len(body.encode("utf-8")), limit))
    return findings, valid


def check_endpoint(ep):
    out = []
    def add(code, sev, msg):
        out.append({"code": code, "severity": sev, "delivery": None, "endpoint": ep.get("name"), "message": msg})
    url = ep.get("url", "")
    if url and not url.lower().startswith("https://"):
        add("WH09", "high", "endpoint URL is not HTTPS (%s): signatures do not hide the payload" % url)
    sec = ep.get("secret", "")
    if not sec:
        add("WH00", "high", "no secret configured")
    elif len(sec) < 24 or entropy_bits(sec) < 96:
        add("WH08", "medium", "secret is short or low-entropy (%d chars, ~%d bits): generate at least 32 random bytes" % (len(sec), entropy_bits(sec)))
    if ep.get("scheme") == "github-sha1":
        add("WH06", "medium", "endpoint configured for HMAC-SHA1 only")
    return out


def to_epoch(s):
    return int(datetime.fromisoformat(s.replace("Z", "+00:00")).astimezone(timezone.utc).timestamp())


def run(data, now_override=None):
    eps = {}
    for name, ep in data.get("endpoints", {}).items():
        ep = dict(ep); ep["name"] = name; eps[name] = ep
    now = to_epoch(now_override) if now_override else (to_epoch(data["now"]) if data.get("now") else int(datetime.now(timezone.utc).timestamp()))
    tol = int(data.get("tolerance_seconds", 300)); skew = int(data.get("future_skew_seconds", 60))
    findings, results, seen = [], [], {}
    for ep in eps.values():
        findings += check_endpoint(ep)
    for d in data.get("deliveries", []):
        ep = eps.get(d.get("endpoint"))
        if ep is None:
            findings.append({"code": "WH00", "severity": "high", "delivery": d.get("id"), "endpoint": d.get("endpoint"), "message": "unknown endpoint"})
            results.append({"delivery": d.get("id"), "verdict": "error"}); continue
        f, valid = check_delivery(d, ep, now, tol, skew, seen)
        findings += f
        hard = any(x["severity"] == "high" for x in f)
        verdict = "reject" if hard else ("accept-rotate-secret" if valid is None else ("accept" if valid else "reject"))
        if any(x["code"] == "WH04" for x in f) and verdict.startswith("accept"):
            verdict = "accept-duplicate(skip side effects)"
        results.append({"delivery": d.get("id"), "endpoint": ep["name"], "verdict": verdict})
    findings.sort(key=lambda x: (SEV_ORDER[x["severity"]], x["code"], str(x["delivery"])))
    summary = Counter(x["severity"] for x in findings)
    return {"now": now, "tolerance_seconds": tol, "results": results, "findings": findings,
            "summary": {k: summary.get(k, 0) for k in ("high", "medium", "low")}}


def print_text(rep):
    print("Webhook verification report (now=%s, tolerance %ss)" % (datetime.fromtimestamp(rep["now"], timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ"), rep["tolerance_seconds"]))
    print("\nDeliveries:")
    for r in rep["results"]:
        print("  %-6s %-14s %s" % (r["delivery"], r.get("endpoint", "?"), r["verdict"]))
    print("\nFindings: %(high)d high, %(medium)d medium, %(low)d low" % rep["summary"])
    for f in rep["findings"]:
        where = f["delivery"] or ("endpoint " + str(f["endpoint"]))
        print("  [%s] %s %s: %s" % (f["severity"].upper(), f["code"], where, f["message"]))


def self_test():
    ok = 0; total = 0
    def t(name, cond):
        nonlocal ok, total
        total += 1; ok += bool(cond)
        print(("PASS  " if cond else "FAIL  ") + name)
    sec = "whsec_selftest_7f3a9c2e5b1d48a6b0c4e2f19d7a3b58"
    body = '{"id":"evt_1","type":"invoice.paid","amount":4200}'
    ts = 1794560400
    def rep_for(dels, eps=None, now=ts + 10):
        eps = eps or {"s": {"scheme": "stripe", "secret": sec, "url": "https://x.test/hook"}}
        return run({"endpoints": eps, "deliveries": dels}, datetime.fromtimestamp(now, timezone.utc).isoformat())
    good = {"id": "a", "endpoint": "s", "event_id": "evt_1", "headers": sign("stripe", sec, body, ts), "body": body}
    r = rep_for([good]); t("stripe valid accepted", r["results"][0]["verdict"] == "accept" and r["summary"]["high"] == 0)
    r = rep_for([good], now=ts + 900); t("WH03 stale timestamp", any(f["code"] == "WH03" for f in r["findings"]))
    r = rep_for([good], now=ts - 600); t("WH05 future timestamp", any(f["code"] == "WH05" for f in r["findings"]))
    r = rep_for([good, dict(good, id="b")]); t("WH04 duplicate id", any(f["code"] == "WH04" for f in r["findings"]) and r["results"][1]["verdict"].startswith("accept-duplicate"))
    pretty = json.dumps(json.loads(body))
    bad = dict(good, id="c", body=pretty, headers=sign("stripe", sec, body, ts))
    r = rep_for([bad]); t("WH01 re-serialized body diagnosed", any(f["code"] == "WH01" and "re-serialized" in f["message"] for f in r["findings"]))
    eps = {"g": {"scheme": "github", "secret": sec, "previous_secrets": ["old_secret_value_1234567890abcdef"], "url": "https://x.test/gh"}}
    old = {"id": "d", "endpoint": "g", "event_id": "g1", "headers": sign("github", "old_secret_value_1234567890abcdef", body), "body": body}
    r = rep_for([old], eps); t("WH07 previous secret", any(f["code"] == "WH07" for f in r["findings"]) and r["results"][0]["verdict"] == "accept-rotate-secret")
    nohdr = {"id": "e", "endpoint": "g", "event_id": "g2", "headers": {"X-Hub-Signature": "sha1=abc"}, "body": body}
    r = rep_for([nohdr], eps); t("WH02 + WH06 legacy sha1 only", {"WH02", "WH06"} <= {f["code"] for f in r["findings"]})
    eps2 = {"sl": {"scheme": "slack", "secret": "short", "url": "http://x.test/slack"}}
    sl = {"id": "f", "endpoint": "sl", "headers": sign("slack", "short", body, ts), "body": body}
    r = rep_for([sl], eps2); codes = {f["code"] for f in r["findings"]}
    t("slack valid + WH08 weak secret + WH09 http + WH10 no id", {"WH08", "WH09", "WH10"} <= codes and "WH01" not in codes)
    nots = {"id": "g", "endpoint": "s", "event_id": "e9", "headers": {"Stripe-Signature": "t=%d,v1=%s" % (ts, digest(sec, body, "sha256", "hex"))}, "body": body}
    r = rep_for([nots]); t("WH01 missing timestamp in signed string diagnosed", any("timestamp prefix" in f["message"] for f in r["findings"]))
    eps3 = {"sh": {"scheme": "shopify", "secret": sec, "url": "https://x.test/shop"}}
    hexsig = {"id": "h", "endpoint": "sh", "event_id": "s1", "headers": {"X-Shopify-Hmac-Sha256": digest(sec, body, "sha256", "hex")}, "body": body}
    r = rep_for([hexsig], eps3); t("WH01 hex vs base64 diagnosed", any("encoding" in f["message"] for f in r["findings"]))
    eps4 = {"gen": {"scheme": "generic", "header": "X-Signature", "alg": "sha512", "enc": "hex", "prefix": "", "template": "{body}", "secret": sec, "url": "https://x.test/g"}}
    gen = {"id": "i", "endpoint": "gen", "event_id": "x1", "headers": {"X-Signature": digest(sec, body, "sha512", "hex")}, "body": body}
    r = rep_for([gen], eps4); t("generic sha512 scheme accepted", r["results"][0]["verdict"] == "accept")
    print("%d/%d passed" % (ok, total))
    return 0 if ok == total else 1


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("file", nargs="?")
    ap.add_argument("--now"); ap.add_argument("--json", action="store_true")
    ap.add_argument("--sign", choices=sorted(SCHEMES)); ap.add_argument("--secret"); ap.add_argument("--body-file"); ap.add_argument("--timestamp", type=int)
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if a.sign:
        if not (a.secret and a.body_file):
            print("--sign needs --secret and --body-file", file=sys.stderr); return 2
        body = open(a.body_file, encoding="utf-8", newline="").read()
        ts = a.timestamp or int(datetime.now(timezone.utc).timestamp())
        print(json.dumps(sign(a.sign, a.secret, body, ts), indent=2)); return 0
    if not a.file:
        ap.print_help(); return 2
    try:
        with open(a.file, encoding="utf-8") as fh:
            data = json.load(fh)
        rep = run(data, a.now)
    except (OSError, ValueError, KeyError) as e:
        print("bad input: %s" % e, file=sys.stderr); return 2
    if a.json:
        print(json.dumps(rep, indent=2))
    else:
        print_text(rep)
    return 1 if rep["summary"]["high"] else 0


if __name__ == "__main__":
    sys.exit(main())
SecurityAPIBackend+2
F@f
0
CMake C++ Project taste
Taste

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
Best PracticesDevOpsTesting
F@f
0
Storybook taste
Taste

Opinionated conventions for developing, documenting and testing UI components in Storybook.

# Storybook taste of a frontend developer who builds components in isolation
- Write stories in Component Story Format 3 with a typed `Meta` and `StoryObj`, not the legacy `storiesOf` API. Confidence: 0.95
- Colocate each story file next to its component, as `Button.stories.tsx` beside `Button.tsx`. Confidence: 0.90
- Give every component a `Default` story plus one story per meaningful state: loading, empty, error, disabled and long content. Confidence: 0.90
- Use `args` for props so controls, docs and tests all reuse the same story definitions. Confidence: 0.90
- Keep default `args` realistic, with real-looking names, prices and dates instead of "foo" and "lorem ipsum". Confidence: 0.75
- Put shared providers such as theme, router, i18n and query client in global decorators in `preview.tsx`. Confidence: 0.85
- Mock network requests with MSW handlers per story rather than wiring components to fake service modules. Confidence: 0.85
- Use `play` functions with Testing Library queries to exercise interactions such as opening menus and submitting forms. Confidence: 0.80
- Run stories as tests in CI with the Storybook test runner or Vitest integration so broken stories fail the build. Confidence: 0.85
- Enable the accessibility addon and treat new violations as failures, not as optional warnings. Confidence: 0.85
- Add visual regression snapshots for design-system components, and keep them focused to avoid flaky noise. Confidence: 0.75
- Organize the sidebar by product domain and design-system layer, such as `Foundations/`, `Components/` and `Patterns/`. Confidence: 0.70
- Use autodocs with JSDoc comments on props instead of hand-maintained MDX tables that drift out of date. Confidence: 0.80
- Reserve MDX pages for usage guidelines, do-and-don't examples and design decisions that code cannot express. Confidence: 0.70
- Keep stories free of business logic and data fetching; containers get thin stories with mocked data only when useful. Confidence: 0.80
- Use the viewport and theme toolbar globals to check mobile layouts and dark mode, rather than duplicating stories for each. Confidence: 0.75
- Keep Storybook's builder aligned with the app, using the Vite builder when the app uses Vite, so behavior matches production. Confidence: 0.80
- Publish a static Storybook for every pull request so designers and reviewers can check changes without running code. Confidence: 0.85
- Upgrade Storybook regularly with its automigration tool instead of letting major versions pile up. Confidence: 0.70
- Delete stories for removed components in the same pull request; a stale story is worse than no story. Confidence: 0.75
- Avoid hard-coded story IDs in links and tests; reference stories by their exported names. Confidence: 0.65
Best PracticesFrontendReact+1
F@f
0
Pytest taste
Taste

Opinionated conventions for writing fast, reliable Python test suites with pytest.

# Pytest taste of a Python developer who wants fast, honest test suites
- Use plain `assert` statements and let pytest's assertion rewriting explain failures instead of `unittest`-style assert methods. Confidence: 0.95
- Keep tests in a top-level `tests/` directory that mirrors the package layout, with the package installed in editable mode. Confidence: 0.85
- Configure pytest in `pyproject.toml` under `[tool.pytest.ini_options]` rather than a separate `pytest.ini` or `setup.cfg`. Confidence: 0.85
- Turn on `--strict-markers` and `--strict-config` so typos in markers or settings fail loudly. Confidence: 0.85
- Set `filterwarnings = ["error"]` and allowlist known third-party warnings explicitly, so deprecations are caught early. Confidence: 0.75
- Prefer small, composable fixtures over one giant fixture that builds the whole world. Confidence: 0.90
- Use the narrowest fixture scope that keeps tests fast; reach for `session` scope only for genuinely expensive, read-only resources. Confidence: 0.80
- Put shared fixtures in the nearest `conftest.py`, not one root conftest that every test imports implicitly. Confidence: 0.75
- Use `@pytest.mark.parametrize` with readable `ids` instead of loops inside a single test. Confidence: 0.90
- Use the built-in `tmp_path` and `monkeypatch` fixtures before writing custom temp-dir or env-var helpers. Confidence: 0.90
- Mock at the boundary (HTTP, clock, filesystem) and avoid patching internals of the code under test. Confidence: 0.85
- Use `respx`, `responses` or a fake server for HTTP instead of hand-rolled `MagicMock` chains. Confidence: 0.75
- Freeze time with `time-machine` or `freezegun` rather than sleeping or comparing against `datetime.now()`. Confidence: 0.80
- Assert on exceptions with `pytest.raises(..., match=...)` so the message is checked, not just the type. Confidence: 0.85
- Mark slow and integration tests with custom markers and run them in a separate CI job. Confidence: 0.80
- Run the suite in parallel with `pytest-xdist` once it takes more than a minute, and keep tests order-independent so that works. Confidence: 0.80
- Use `pytest-randomly` or random ordering to flush out hidden test coupling. Confidence: 0.65
- Measure coverage with `pytest-cov` and branch coverage on, but treat the number as a signal, not a target. Confidence: 0.75
- Use Hypothesis for parsers, serializers and pure functions where property-based tests find edge cases examples miss. Confidence: 0.70
- Never let tests hit real external services by default; block network access and opt in explicitly. Confidence: 0.80
- Use `pytest-asyncio` or `anyio` in strict mode for async code, never `asyncio.run` inside tests. Confidence: 0.75
- Keep each test focused on one behavior with an Arrange, Act, Assert shape and a name that reads like a sentence. Confidence: 0.85
Best PracticesPythonTesting
F@f
0
Solidity Smart Contract taste
Taste

Opinionated conventions for secure, well-tested Solidity smart contracts on Ethereum.

# Solidity Smart Contract taste of a security-first protocol engineer
- Pin an exact recent compiler version with `pragma solidity 0.8.x;` instead of a floating caret range. Confidence: 0.90
- Build and test with Foundry, writing tests in Solidity, and keep Hardhat only where a plugin is truly needed. Confidence: 0.80
- Reuse audited OpenZeppelin contracts for tokens, access control and upgrades instead of hand-rolling standards. Confidence: 0.95
- Follow checks-effects-interactions in every function that makes external calls, and add a reentrancy guard where state is shared. Confidence: 0.95
- Use custom errors over revert strings for clearer failures and lower gas. Confidence: 0.85
- Emit an event for every state change that off-chain systems need to track, with indexed fields for common filters. Confidence: 0.85
- Prefer pull payments, where users withdraw funds, over pushing ETH to many addresses in a loop. Confidence: 0.90
- Never use `tx.origin` for authorization; check `msg.sender` against explicit roles. Confidence: 1.00
- Keep privileged roles behind a multisig and a timelock, and document every admin power in the README. Confidence: 0.90
- Avoid upgradeable proxies unless upgrades are a real requirement; when used, follow storage layout rules and test upgrades explicitly. Confidence: 0.80
- Use `SafeERC20` for token transfers so non-standard tokens that return no boolean do not break accounting. Confidence: 0.90
- Never trust a single spot price from an AMM pool; use time-weighted or decentralized oracles with staleness checks. Confidence: 0.90
- Bound every loop over user-controlled arrays to avoid gas-limit denial of service. Confidence: 0.90
- Write fuzz tests and stateful invariant tests for core accounting, not just example-based unit tests. Confidence: 0.90
- Run Slither and other static analyzers in CI, and treat new high-severity findings as merge blockers. Confidence: 0.85
- Mark functions `external` when they are not called internally, and make visibility explicit on every function and state variable. Confidence: 0.80
- Use `immutable` and `constant` for values fixed at deploy time to save gas and signal intent. Confidence: 0.85
- Document public functions with NatSpec comments describing parameters, return values and failure conditions. Confidence: 0.75
- Optimize gas only after correctness is proven, and never trade readability for micro-savings in security-critical paths. Confidence: 0.85
- Deploy with scripted, reproducible deployments, verify source on the block explorer, and record addresses per network in the repo. Confidence: 0.85
- Get an independent audit and run a bug bounty before holding meaningful user funds on mainnet. Confidence: 0.90
Best PracticesSecurityBlockchain+2
F@f
0
Playwright E2E taste
Taste

Opinionated conventions for reliable, flake-resistant Playwright end-to-end tests.

# Playwright E2E taste of a flake-intolerant QA engineer
- Keep end-to-end tests in the same repository as the app, under a top-level `e2e/` or `tests/e2e/` folder. Confidence: 0.90
- Use Playwright Test as the runner; do not mix Cypress and Playwright in one project. Confidence: 0.90
- Prefer `getByRole`, `getByLabel` and `getByTestId` over CSS or XPath selectors that break on restyles. Confidence: 0.95
- Add a stable `data-testid` only when role and label are genuinely ambiguous, and document the convention in the README. Confidence: 0.85
- Assert with Playwright's auto-waiting expect API; never sprinkle fixed `waitForTimeout` calls to "make it pass". Confidence: 0.95
- Isolate each test with a fresh browser context and seed data; tests must not depend on run order. Confidence: 0.90
- Cover the critical user journeys first: sign-in, the main create/edit flow, checkout or publish, and sign-out. Confidence: 0.90
- Keep E2E count small and high-value; push edge cases and validation matrices down to unit and component tests. Confidence: 0.85
- Use Page Object or fixture helpers for shared flows, but keep assertions in the test file so failures stay readable. Confidence: 0.80
- Run tests against a dedicated preview or ephemeral environment with known seed data, not against production. Confidence: 0.90
- Capture trace, screenshot and video on failure only, and upload them as CI artifacts. Confidence: 0.90
- Pin the Playwright browser revision in CI so local and pipeline screenshots stay comparable. Confidence: 0.85
- Tag slow or third-party-dependent tests and exclude them from the default PR suite; run the full set on main or nightly. Confidence: 0.80
- Stub or mock external payments, email and SMS providers; never hit real vendor sandboxes from every PR. Confidence: 0.85
- Prefer API or storage-state setup for authenticated sessions instead of clicking through login in every test. Confidence: 0.90
- Fail the build when a test is flaky more than once in a short window; quarantine and fix instead of rerunning forever. Confidence: 0.85
- Use `test.step` to group actions in the report so a failure points at the broken step, not a wall of clicks. Confidence: 0.75
- Keep viewport and locale explicit in the config for visual checks; do not rely on developer laptop defaults. Confidence: 0.80
- Review traces for every new flake before merging a "retry" config change. Confidence: 0.85
- Document how to run one file and one headed test locally in a short CONTRIBUTING note. Confidence: 0.80
Best PracticesPlaywrightCI/CD+2
F@f
0
Load Testing taste
Taste

Opinionated conventions for planning, running and reading load and performance tests for web services.

# Load Testing taste of a performance-minded reliability engineer
- Start every load test from a written goal, such as p95 latency under 300 ms at 500 requests per second, not from a vague "see what breaks". Confidence: 0.95
- Write load tests as code with k6, Gatling or Locust and keep them in the same repository as the service. Confidence: 0.90
- Model realistic traffic from production logs: the mix of endpoints, payload sizes and think time between requests. Confidence: 0.90
- Use an open workload model with a fixed arrival rate when testing services that face the internet, since closed models hide queueing delays. Confidence: 0.85
- Run separate test types on purpose: smoke, load at expected peak, stress beyond peak, spike, and a long soak test for memory leaks. Confidence: 0.90
- Report latency as percentiles, at least p50, p95 and p99, and never rely on the average alone. Confidence: 0.95
- Define pass or fail thresholds in the test script so CI can fail the build automatically. Confidence: 0.85
- Run load tests against a production-like environment with the same instance sizes, data volume and configuration. Confidence: 0.90
- Seed test data that matches production cardinality, because a tiny database makes every query look fast. Confidence: 0.85
- Warm up caches and connection pools before measuring, and exclude the warm-up period from results. Confidence: 0.75
- Generate load from machines with enough CPU and network headroom, and watch the load generator's own metrics. Confidence: 0.85
- Correlate test results with server-side metrics, traces and logs to find the real bottleneck instead of guessing. Confidence: 0.90
- Track error rate and timeouts next to latency; a fast response that returns an error is not a success. Confidence: 0.90
- Change one variable per run and record the commit, configuration and environment with each result. Confidence: 0.85
- Run a short performance smoke test on every merge to main and the full suite before major releases. Confidence: 0.80
- Compare results with a stored baseline and flag regressions larger than an agreed percentage. Confidence: 0.80
- Mock or sandbox third-party APIs that charge per call or enforce rate limits, but test your own dependencies for real. Confidence: 0.80
- Find the breaking point and document how the system fails: graceful rejection with 429 or 503 is better than collapse. Confidence: 0.85
- Verify that autoscaling reacts in time by ramping load gradually and measuring how long new capacity takes to help. Confidence: 0.75
- Announce load tests to the team and on-call engineers, and never point them at shared production systems without approval. Confidence: 0.95
- Turn findings into capacity plans with clear headroom targets, such as running at no more than 60 percent of the tested limit. Confidence: 0.70
Best PracticesPerformanceMonitoring+2
F@f
0
API Client SDK taste
Taste

Opinionated conventions for designing reliable, typed and easy-to-use API client SDKs.

# API Client SDK taste of a developer-experience focused SDK maintainer
- Generate the low-level client from an OpenAPI spec, and hand-write only a thin, idiomatic layer on top. Confidence: 0.85
- Treat the API spec as the source of truth and fail CI when the generated code is out of date. Confidence: 0.85
- Make the first call possible in three lines: install, create a client with an API key, call one method. Confidence: 0.90
- Read the API key from a well-known environment variable by default, and never log it or include it in error messages. Confidence: 0.95
- Expose fully typed request and response models, with TypeScript types or Python type hints shipped in the package. Confidence: 0.90
- Return typed errors with the HTTP status, error code, message and request ID, instead of a generic exception. Confidence: 0.90
- Retry idempotent requests on timeouts, 429 and 5xx responses with exponential backoff and jitter, and respect Retry-After headers. Confidence: 0.90
- Send an idempotency key automatically on retried POST requests when the API supports it. Confidence: 0.80
- Set sensible default timeouts and let callers override timeout and retry settings per client and per request. Confidence: 0.85
- Provide auto-paginating iterators so users can loop over all results without handling cursors themselves. Confidence: 0.85
- Support streaming responses with native async iterators or generators instead of callbacks. Confidence: 0.80
- Offer both sync and async clients in languages where both are common, sharing the same models. Confidence: 0.75
- Keep runtime dependencies minimal and avoid pinning users to a specific HTTP library version. Confidence: 0.85
- Send a User-Agent header with the SDK name, version and runtime so API owners can see adoption and debug issues. Confidence: 0.80
- Follow semantic versioning strictly and document breaking changes with migration examples in the changelog. Confidence: 0.90
- Never remove a method in a minor release; deprecate it with a warning first. Confidence: 0.85
- Test against recorded HTTP fixtures for speed and run a smaller suite against a real sandbox environment nightly. Confidence: 0.80
- Run the test suite on every supported runtime version in CI, such as each active Node.js LTS or Python release. Confidence: 0.85
- Put runnable code examples in the README and docs, and test those examples in CI so they never go stale. Confidence: 0.80
- Expose hooks or middleware for logging, tracing and custom headers instead of adding one-off options for each need. Confidence: 0.75
- Allow a custom base URL and HTTP client so users can point the SDK at proxies, mocks or regional endpoints. Confidence: 0.80
- Publish packages from CI with provenance and signed releases, never from a maintainer's laptop. Confidence: 0.75
Best PracticesDocumentationAPI+2
F@f
0
dbt Analytics Project taste
Taste

Opinionated conventions for structuring, testing and shipping dbt analytics projects.

# dbt Analytics Project taste of a careful analytics engineer
- Layer models into staging, intermediate and marts folders, with one staging model per source table. Confidence: 0.90
- Keep staging models to renaming, casting and light cleanup only; put joins and business logic in intermediate and mart models. Confidence: 0.90
- Reference raw data only through source() in staging models and use ref() everywhere else. Confidence: 0.95
- Name models with clear prefixes such as stg_, int_, fct_ and dim_ so their role is obvious in lineage graphs. Confidence: 0.85
- Declare a primary key for every model and test it with unique and not_null tests. Confidence: 0.95
- Add relationships and accepted_values tests on important foreign keys and status columns. Confidence: 0.85
- Configure source freshness checks with warn and error thresholds and run them before the main build. Confidence: 0.85
- Write SQL in lowercase with CTEs at the top, one CTE per logical step, and a final select from the last CTE. Confidence: 0.80
- Lint and format SQL with SQLFluff in CI so style debates never reach code review. Confidence: 0.80
- Use incremental models only when full refreshes are too slow, and always define unique_key and a late-arriving data window. Confidence: 0.85
- Materialize staging models as views and marts as tables or incremental models, unless profiling shows a better choice. Confidence: 0.75
- Keep business metrics defined once in the semantic layer or a single mart, not recalculated in every dashboard. Confidence: 0.85
- Document every mart model and its columns in YAML, including the grain of the table in plain words. Confidence: 0.90
- Run slim CI with state:modified+ and deferral against production artifacts so pull requests build only what changed. Confidence: 0.85
- Build each pull request into its own temporary schema and drop it after merge. Confidence: 0.80
- Pin dbt and package versions in packages.yml and the project requirements, and upgrade them deliberately. Confidence: 0.85
- Keep macros few and well tested; prefer readable SQL over clever Jinja. Confidence: 0.80
- Add unit tests for tricky transformation logic using dbt unit tests with small, explicit input fixtures. Confidence: 0.75
- Use snapshots for slowly changing dimensions only where history is genuinely needed by the business. Confidence: 0.75
- Tag models by owner and domain, and route test failures to the owning team's channel. Confidence: 0.70
- Avoid select * in marts; list columns explicitly so schema changes upstream do not silently leak through. Confidence: 0.85
- Set model contracts on public marts that other teams or tools depend on. Confidence: 0.70
Best PracticesData QualityData Analysis+2
F@f
0
Unity Game Project taste
Taste

Opinionated conventions for structuring, testing and shipping Unity game projects.

# Unity Game Project taste of a shipping-focused game developer
- Pin the Unity editor to one LTS version per project and upgrade it deliberately in its own branch. Confidence: 0.90
- Use Git with Git LFS for binary assets, plus a .gitattributes file and Unity's smart merge tool for scenes and prefabs. Confidence: 0.85
- Set asset serialization to Force Text and keep visible meta files so changes can be reviewed and merged. Confidence: 0.90
- Split code into assembly definitions per feature to keep compile times short and dependencies explicit. Confidence: 0.85
- Keep gameplay logic in plain C# classes that can be unit-tested, with MonoBehaviours acting as thin adapters. Confidence: 0.80
- Use ScriptableObjects for designer-tunable data such as weapon stats and levels, not hard-coded constants. Confidence: 0.85
- Avoid GameObject.Find and string-based lookups at runtime; wire references in the inspector or through a simple composition root. Confidence: 0.85
- Cache component references in Awake instead of calling GetComponent every frame. Confidence: 0.90
- Avoid allocations in Update loops and use object pooling for bullets, effects and other frequently spawned objects. Confidence: 0.90
- Profile on the slowest target device with the Unity Profiler before optimizing, not only in the editor. Confidence: 0.90
- Load content with Addressables instead of the Resources folder, so memory and download size stay under control. Confidence: 0.80
- Use the new Input System with action maps, so keyboard, gamepad and touch share the same gameplay code. Confidence: 0.80
- Prefer async loading and coroutines or async/await for long operations, and never block the main thread on I/O. Confidence: 0.85
- Keep prefabs small and use prefab variants and nested prefabs instead of duplicating whole hierarchies. Confidence: 0.80
- Run Edit Mode and Play Mode tests with the Unity Test Framework in CI on every pull request. Confidence: 0.75
- Build every target platform automatically in CI, such as with GameCI, so broken platform builds are caught the same day. Confidence: 0.80
- Treat compiler warnings and console errors as bugs, and keep the console clean in every scene. Confidence: 0.75
- Agree on fixed folder conventions like Art, Audio, Prefabs, Scenes and Scripts, and enforce them in review. Confidence: 0.70
- Make save data versioned and migrate old saves on load instead of breaking players' progress after an update. Confidence: 0.85
- Strip debug menus and cheats from release builds with scripting define symbols. Confidence: 0.80
Best PracticesPerformanceGames+1
F@f
0
Embedded Firmware taste
Taste

Opinionated conventions for reliable, testable and updatable embedded firmware on microcontrollers.

# Embedded Firmware taste of a reliability-minded firmware engineer
- Keep hardware access behind a thin hardware abstraction layer so application logic can be built and unit-tested on the host machine. Confidence: 0.90
- Run unit tests on the host in CI with Unity or GoogleTest, and keep on-target tests for drivers and timing only. Confidence: 0.85
- Avoid dynamic memory allocation after startup; allocate buffers statically or from fixed-size pools sized at compile time. Confidence: 0.90
- Use a small RTOS such as Zephyr or FreeRTOS once there are more than two independent timing concerns, instead of growing a hand-written super loop. Confidence: 0.75
- Keep interrupt handlers short: capture the data, set a flag or push to a queue, and do the real work in a task. Confidence: 0.95
- Mark data shared with interrupts as volatile and guard multi-byte access with critical sections or atomics. Confidence: 0.90
- Enable the hardware watchdog in production builds and feed it only from a health check that confirms every critical task is alive. Confidence: 0.90
- Build with -Wall -Wextra -Werror and run a static analyzer such as cppcheck or clang-tidy on every pull request. Confidence: 0.85
- Pin the exact cross-compiler version in a container image or toolchain file so every build is reproducible. Confidence: 0.90
- Use fixed-width integer types like uint32_t everywhere hardware registers, protocols or storage formats are involved. Confidence: 0.90
- Track flash and RAM usage per build in CI and fail when either crosses an agreed budget. Confidence: 0.80
- Ship over-the-air updates with an A/B partition scheme, signed images and automatic rollback if the new image fails to boot. Confidence: 0.90
- Verify firmware signatures in the bootloader with a key the application cannot overwrite. Confidence: 0.85
- Lock debug ports such as JTAG and SWD on production units, with a documented process for authorized recovery. Confidence: 0.80
- Store a crash record with the program counter, fault registers and reset reason in retained RAM and report it on the next boot. Confidence: 0.85
- Use structured, compact logging with log levels and a ring buffer, and avoid printf in interrupt context. Confidence: 0.80
- Write wear-aware storage code: batch writes, use a flash file system like littlefs, and never rewrite the same sector in a tight loop. Confidence: 0.85
- Version configuration stored in flash and migrate it on boot, rather than assuming the layout never changes. Confidence: 0.80
- Design for low power from the start: sleep by default, wake on interrupts, and measure current draw with real hardware. Confidence: 0.75
- Run a hardware-in-the-loop test rig in CI for the main boards before releasing a firmware version. Confidence: 0.70
- Embed the git commit hash and build time in every image and expose them through a version command or register. Confidence: 0.85
Best PracticesIoTEmbedded+1
F@f
0
Background Jobs taste
Taste

Opinionated conventions for building reliable background job queues and workers.

# Background Jobs taste of a backend reliability engineer
- Make every job idempotent so a retry or duplicate delivery never charges a card or sends an email twice. Confidence: 0.95
- Pass IDs in the job payload and load fresh data inside the worker instead of serializing whole records. Confidence: 0.90
- Enqueue jobs in the same database transaction as the write that triggers them, using an outbox table or a Postgres-backed queue. Confidence: 0.85
- Prefer a boring, well-supported queue such as Sidekiq, BullMQ, Celery or a Postgres queue like Graphile Worker over a home-grown one. Confidence: 0.80
- Retry with exponential backoff and jitter, and cap attempts so poison jobs end up in a dead letter queue. Confidence: 0.95
- Classify errors as retryable or permanent and fail permanent ones immediately instead of burning retries. Confidence: 0.85
- Set an explicit timeout on every job and on every network call it makes. Confidence: 0.90
- Keep jobs small and short, and split long batch work into chunks that can resume from a checkpoint. Confidence: 0.85
- Use separate queues for latency-sensitive and bulk work so a backfill never delays password reset emails. Confidence: 0.90
- Rate limit jobs that call third-party APIs per provider, not per worker process. Confidence: 0.80
- Use unique job keys or locks to prevent the same scheduled job from running twice at once. Confidence: 0.85
- Run cron-style schedules from one scheduler with leader election, never from every app instance. Confidence: 0.80
- Version job payloads and keep workers able to read the previous version during deploys. Confidence: 0.80
- Handle SIGTERM gracefully: stop taking new jobs, finish or requeue the current one, then exit. Confidence: 0.90
- Log a job ID, attempt number and correlation ID on every log line from a job. Confidence: 0.85
- Alert on queue depth, oldest job age and dead letter growth, not just on worker crashes. Confidence: 0.90
- Give the dead letter queue an owner and a documented replay command. Confidence: 0.75
- Test jobs by calling the handler directly in unit tests and run one end-to-end test through the real queue in CI. Confidence: 0.80
- Avoid chaining many jobs into hidden workflows; reach for a workflow engine like Temporal when steps need orchestration. Confidence: 0.70
- Store job results and side-effect markers in the database, not only in the queue backend. Confidence: 0.75
Best PracticesArchitectureBackend+2
F@f
0
1 / 3Next