Opinionated test fixtures and seed data preferences: factories over giant fixture files, per-test isolation, deterministic data, a real database in tests and separate dev seeds that never touch production.
# Test Fixtures and Seed Data taste of a backend developer who wants tests that never flake - Use small factory functions with sensible defaults and per-test overrides instead of one huge shared fixture file. Confidence: 0.90 - Each test creates exactly the data it asserts on; never depend on rows another test or a global seed happened to insert. Confidence: 0.95 - Isolate tests with a transaction rolled back after each test, or truncate tables between tests when transactions are not possible. Confidence: 0.85 - Run integration tests against the same database engine as production in a container, not an in-memory substitute with different behavior. Confidence: 0.90 - Apply real migrations to the test database at the start of the run instead of a hand-maintained schema dump. Confidence: 0.85 - Make generated data deterministic: seed the fake-data library and freeze the clock so failures reproduce exactly. Confidence: 0.90 - Generate unique values (emails, slugs) with a sequence or random suffix so parallel tests never collide on unique constraints. Confidence: 0.85 - Keep factories next to the domain model and build valid objects by default; tests should opt in to invalid states explicitly. Confidence: 0.80 - Prefer building objects in memory for unit tests and persisting only in tests that actually need the database. Confidence: 0.80 - Name fixtures by intent, like paidCustomer or expiredSubscription, not user1 and user2. Confidence: 0.75 - Keep golden files and JSON fixtures small, reviewed and regenerated by a script, never edited by hand into drift. Confidence: 0.70 - Keep development seed data separate from test data; seeds exist to make the app usable locally, not to make tests pass. Confidence: 0.85 - Make seed scripts idempotent with upserts so running them twice is safe. Confidence: 0.90 - Guard seed and reset scripts so they refuse to run when the database URL points at production. Confidence: 1.00 - Never copy raw production data into dev or test; use synthetic data or an anonymized, masked snapshot. Confidence: 0.95 - Seed one realistic account per main role (admin, member, viewer) with documented local credentials. Confidence: 0.75 - Include awkward data in seeds: long names, Unicode, empty lists and many rows, so UI and pagination bugs show up early. Confidence: 0.75 - Stub external HTTP calls at the network boundary with recorded responses, and refresh recordings on a schedule. Confidence: 0.80 - Fail the test run on leaked data: assert tables are empty after the suite when using truncate isolation. Confidence: 0.60 - Keep the full integration suite under a few minutes in CI by parallelizing across database schemas or containers. Confidence: 0.70
Finds the test coverage gaps that matter in a Cobertura XML or LCOV report: files with the most missed lines, uncovered blocks, weak branch coverage, untested files and diff coverage of the lines changed in a pull request, then suggests the few tests worth writing first. Stdlib Python.
---
name: code-coverage-gap-finder
description: Finds the test coverage gaps that matter in a Cobertura XML or LCOV report: files with the most missed lines, uncovered blocks, weak branch coverage, untested files and diff coverage of the lines changed in a pull request, then suggests the few tests worth writing first. Stdlib Python.
---
# Code Coverage Gap Finder
You help developers and reviewers turn a coverage report into a short, useful list of tests to write. A single "coverage 51%" number tells a team almost nothing; what helps is knowing which files and which changed lines are not exercised by any test, where whole blocks or error paths are never run, and which gaps are risky enough to fix now. You read the report (and the diff of the change under review, if there is one), explain the numbers plainly, and propose a small, ranked set of concrete tests.
Coverage is a map of what tests execute, not proof that the code is correct. A line can be covered by a test that asserts nothing. Always say this when someone treats a high number as a quality guarantee, and never suggest tests that only exist to raise the number.
## Files in this skill
- `scripts/coverage_gaps.py` - reads Cobertura XML (coverage.py `coverage xml`, Jest/Vitest/istanbul `cobertura` reporter, gcovr, PHPUnit, coverlet, JaCoCo converted to Cobertura) or LCOV (`lcov.info`), and optionally a unified diff (`git diff`); prints totals, the files with the most missed lines with uncovered line ranges, diff coverage of changed lines and flags C01-C09; `--format text|md|json|csv`, thresholds, `--exclude`, `--strip-prefix`, `--fail-on`, `--self-test` runs 22 checks (Python 3.8+ standard library only)
- `references/coverage-metrics.md` - line, branch and diff coverage, how tools count them differently, and sensible targets
- `references/what-to-test-first.md` - how to rank gaps by risk and what a good test for each kind of gap looks like
- `templates/coverage-review.md` - a pull request or team review comment with numbers, the top gaps and the proposed tests
- `examples/coverage.xml` - a real coverage.py report (with `--branch`) of a small shop project: well-tested pricing, a partly tested discounts module, untested refunds and a new untested gift card module
- `examples/changes.diff` - the `git diff -U0` of the change under review (new discount helpers, new gift card file, one new test)
- `examples/lcov.info` - a small LCOV report from a JavaScript project
## Workflow
### 1. Get the report and the diff
Ask which language and test runner they use and produce a report in one of the two formats:
```
# Python (coverage.py)
coverage run --branch -m pytest && coverage xml -o coverage.xml
# JavaScript / TypeScript (Jest or Vitest with istanbul)
npx jest --coverage --coverageReporters=cobertura # or lcov -> coverage/lcov.info
npx vitest run --coverage --coverage.reporter=cobertura
# C / C++
gcovr --xml-pretty -o coverage.xml
# The change under review
git diff --no-color -U0 origin/main...HEAD > changes.diff
```
Branch data only appears when branch measurement is on (`--branch` for coverage.py). Paths in the diff must match the paths in the report; if the report stores `src/app/x.py` and the diff says `app/x.py`, use `--strip-prefix src`.
### 2. Run the analysis
```
python3 scripts/coverage_gaps.py coverage.xml
python3 scripts/coverage_gaps.py coverage.xml --diff changes.diff --min-diff 80 --format md > coverage-review.md
python3 scripts/coverage_gaps.py coverage/lcov.info --exclude "src/generated/*" --min-total 70
python3 scripts/coverage_gaps.py coverage.xml --format csv > coverage-by-file.csv
python3 scripts/coverage_gaps.py coverage.xml --diff changes.diff --fail-on high # CI gate
python3 scripts/coverage_gaps.py --self-test
```
Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable report or diff.
| Code | Severity | Gap |
|---|---|---|
| C01 | medium | total line coverage below `--min-total` (default 80%) |
| C02 | low | a file with at least `--min-lines` lines is below `--min-file` (default 60%) |
| C03 | medium / high | diff coverage of changed executable lines below `--min-diff` (high when below half of it) |
| C04 | medium | a changed source file is not in the report at all (new file never imported, or excluded) |
| C05 | low | an uncovered block of `--block` (default 15) or more consecutive lines in a partly tested file |
| C06 | low | branch coverage 25+ points below line coverage: lines run, but some if/else paths never do |
| C07 | medium | a file with at least `--min-lines` lines has no covered line at all |
| C08 | high | the report has no measured lines (tests did not run, or wrong paths) |
| C09 | info | the diff has no changed executable lines in the report (docs/config change, or path mismatch) |
### 3. Rank the gaps
Use `references/what-to-test-first.md`. Changed lines come first (C03/C04): they are the cheapest to test now and the most likely to hide new bugs. Then untested files that handle money, permissions, data deletion or external input (C07), then uncovered error paths and branches (C05/C06). Generated code, simple getters, logging and `if __name__ == "__main__"` blocks are low priority; suggest `--exclude` or a coverage config exclusion with a reason instead of tests.
### 4. Propose tests
For the top 3-5 gaps, open the uncovered line ranges and write concrete test ideas: the function, the input, the expected result or exception, and which uncovered lines or branch it will run. Prefer one meaningful assertion per behavior over many lines that only execute code. If the code is hard to test (hidden I/O, globals, time), say so and suggest a small refactor.
### 5. Report
Fill `templates/coverage-review.md` for a PR comment or a team review. Include the numbers, the top gaps, the proposed tests and an honest note on what coverage cannot tell.
## Rules
- Coverage numbers differ between tools (lines vs statements, with or without branches); compare runs only from the same tool and settings. coverage.py's own "Cover" column combines lines and branches, so it can differ from this script's line coverage.
- Never recommend tests without assertions, or excluding code from measurement just to hit a target.
- Do not shame a team for a low number; show the cheapest, highest-value next steps.
- Treat thresholds as team agreements, not universal truths; a 100% target is rarely worth its cost.
- Do not paste proprietary source code outside the conversation; line numbers and file names are enough for the report.
FILE:references/coverage-metrics.md
# Coverage metrics in plain words
## Line coverage
The share of executable lines that ran at least once during the tests. Blank lines, comments and most declarations do not count. Tools disagree on details: coverage.py counts statements, istanbul counts statements and lines separately, gcov counts lines. Always compare numbers from the same tool and settings.
## Branch coverage
The share of possible paths through decisions (`if`/`else`, loops entered or skipped, `&&`/`||` short circuits, `switch` cases, ternaries) that ran. A line with `if x:` is "covered" as soon as it runs once, but its branch is only fully covered when the tests make it both true and false. Branch coverage is usually lower than line coverage. A gap of 25 points or more (flag C06) often means error paths, edge cases or `else` cases are never tested.
In Cobertura XML a branch line looks like `<line number="12" hits="3" branch="true" condition-coverage="50% (1/2)"/>`; in LCOV each branch is a `BRDA:<line>,<block>,<branch>,<taken>` record where `-` means never evaluated.
## Diff coverage (patch coverage)
The share of changed executable lines in a pull request that the tests run. It answers "did this change come with tests?" and is fairer than a total number, because old untested code does not punish a new, well-tested change. Many teams gate PRs on diff coverage (for example 80%) and only watch the total.
Only added or modified lines count. Deleted lines, blank lines, comments and test files are ignored. A new source file that does not appear in the report at all (flag C04) usually means no test imports it, or it is excluded in the coverage configuration.
## Function coverage
The share of functions called at least once (LCOV `FN`/`FNDA`). A quick way to spot dead or untested functions; this script reports lines and branches only.
## Sensible targets
- New and changed code: 80-90% diff coverage with meaningful assertions.
- Whole project: a trend that goes up slowly matters more than a fixed number; 70-85% is common for application code.
- Critical modules (payments, permissions, data deletion, parsing external input): aim higher and test branches, not just lines.
- 100% is rarely worth the cost; the last few percent are often defensive code, generated code or platform-specific paths.
## What coverage cannot tell you
- Whether the assertions are right, or whether there are any assertions at all.
- Whether important combinations of inputs are tested (100% branch coverage can still miss a bug that needs two conditions at once).
- Whether integration with real databases, networks or browsers works.
- Mutation testing (for example mutmut, Stryker, PIT) is the next step when a team wants to know if tests would catch real bugs.
FILE:references/what-to-test-first.md
# What to test first
Rank each gap by **risk x likelihood of change / cost to test**. In practice this order works for most teams:
1. **Changed lines without tests (C03, C04).** The author has the context right now and the change is the most likely place for a new bug. Ask for tests in the same pull request.
2. **Untested code that moves money, controls access or deletes data (C07 in such files).** Refunds, payments, prices, discounts, permissions, account deletion, data export, migrations.
3. **Code that parses external input.** File uploads, CSV and JSON imports, webhooks, URL and form parameters, dates and time zones.
4. **Error paths and branches (C05, C06).** `except`/`catch` blocks, early returns, "not found" and "too small" cases, retries and timeouts. Bugs hide where tests never go.
5. **Large uncovered blocks in otherwise tested files (C05).** Often a forgotten feature flag path or a whole function nobody calls; sometimes dead code to delete instead of test.
6. **Everything else**, only when it is cheap.
## Usually not worth a test
- Generated code (protobuf, ORM migrations, API clients), vendored libraries.
- Trivial getters and setters, `__repr__`, simple data classes.
- `if __name__ == "__main__":` blocks and CLI wiring that is covered by an end-to-end test.
- Logging-only lines and debug helpers.
Exclude them with a reason (`# pragma: no cover` with a comment, `/* istanbul ignore next */`, or `omit`/`exclude` in the coverage config) rather than writing empty tests.
## What a good test for a gap looks like
- Names the behavior, not the line: `test_refund_is_zero_after_30_days`, not `test_line_12`.
- Sets up the smallest realistic input, calls the public function, and asserts the result or the exception.
- Covers both sides of the uncovered branch when the logic is important (`opened=True` and `opened=False`).
- Uses boundaries: 0, 1, the limit, limit + 1, empty, None, negative, very large.
- Avoids sleeping, real network calls and current time; inject a clock or a fake.
## Example from `examples/`
- `shop/gift_cards.py` is new in the change and has 0 covered lines: write tests for `redeem` (partial use, more than the balance, zero or negative amount) and `masked`, and for the invalid card number check in `__init__`.
- `shop/discounts.py` lines 29 and 36-41: `best_code` never sees an invalid code (line 29, the `continue`), and `code_expired` is never called. Two small tests cover both.
- `shop/refunds.py` has no tests at all and handles money: add tests for the 30-day limit, opened items (85%), damaged items and a return date before the order date.
FILE:templates/coverage-review.md
# Test coverage review: {{repository or PR title}}
**Report:** {{coverage tool, date, branch measurement on/off}}
**Change under review:** {{PR link or "whole project"}}
## Numbers
| Metric | Value | Target |
|---|---|---|
| Diff coverage (changed lines) | {{e.g. 30.0% (9/30)}} | {{80%}} |
| Line coverage (project) | {{e.g. 51.0%}} | {{80%}} |
| Branch coverage (project) | {{e.g. 40.9%}} | {{-}} |
## Gaps that matter most
1. **{{file}}** lines {{ranges}} - {{why it matters: new code / money / external input / error path}}
2. **{{file}}** lines {{ranges}} - {{why}}
3. **{{file}}** - {{why}}
## Tests I suggest
| # | Test | Covers | Effort |
|---|---|---|---|
| 1 | {{test name: input -> expected result}} | {{file:lines / branch}} | {{S/M/L}} |
| 2 | {{...}} | {{...}} | {{...}} |
| 3 | {{...}} | {{...}} | {{...}} |
## Not worth testing (exclude with a reason)
- {{file or block}} - {{generated / CLI wiring / logging}}
## Notes
- Coverage shows which code runs during tests, not whether the assertions are right.
- {{anything about flaky tests, missing branch data or path mismatches}}
FILE:examples/coverage.xml
<?xml version="1.0" ?>
<coverage version="7.18.0" timestamp="1796368012084" lines-valid="100" lines-covered="51" line-rate="0.51" branches-valid="44" branches-covered="18" branch-rate="0.4091" complexity="0">
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.18.0 -->
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
<sources>
<source>/home/dev/shop-api</source>
</sources>
<packages>
<package name="shop" line-rate="0.51" branch-rate="0.4091" complexity="0">
<classes>
<class name="__init__.py" filename="shop/__init__.py" complexity="0" line-rate="1" branch-rate="1">
<methods/>
<lines/>
</class>
<class name="cart.py" filename="shop/cart.py" complexity="0" line-rate="0.8333" branch-rate="0.625">
<methods/>
<lines>
<line number="2" hits="1"/>
<line number="3" hits="1"/>
<line number="6" hits="1"/>
<line number="7" hits="1"/>
<line number="8" hits="1"/>
<line number="9" hits="1"/>
<line number="11" hits="1"/>
<line number="12" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="13" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="12"/>
<line number="14" hits="1"/>
<line number="15" hits="1"/>
<line number="16" hits="1"/>
<line number="18" hits="1"/>
<line number="19" hits="0"/>
<line number="20" hits="0"/>
<line number="21" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="exit,22"/>
<line number="22" hits="0"/>
<line number="24" hits="1"/>
<line number="25" hits="1"/>
<line number="27" hits="1"/>
<line number="28" hits="1"/>
<line number="29" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="30" hits="1"/>
<line number="31" hits="1"/>
</lines>
</class>
<class name="discounts.py" filename="shop/discounts.py" complexity="0" line-rate="0.6667" branch-rate="0.5625">
<methods/>
<lines>
<line number="3" hits="1"/>
<line number="10" hits="1"/>
<line number="11" hits="1"/>
<line number="12" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="13"/>
<line number="13" hits="0"/>
<line number="14" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="15"/>
<line number="15" hits="0"/>
<line number="16" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="17" hits="1"/>
<line number="19" hits="1"/>
<line number="20" hits="1"/>
<line number="23" hits="1"/>
<line number="25" hits="1"/>
<line number="26" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="27" hits="1"/>
<line number="28" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="29"/>
<line number="29" hits="0"/>
<line number="30" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="31" hits="1"/>
<line number="32" hits="1"/>
<line number="35" hits="1"/>
<line number="36" hits="0"/>
<line number="37" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="38,39"/>
<line number="38" hits="0"/>
<line number="39" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="40,41"/>
<line number="40" hits="0"/>
<line number="41" hits="0"/>
</lines>
</class>
<class name="gift_cards.py" filename="shop/gift_cards.py" complexity="0" line-rate="0" branch-rate="0">
<methods/>
<lines>
<line number="4" hits="0"/>
<line number="5" hits="0"/>
<line number="6" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="7,8"/>
<line number="7" hits="0"/>
<line number="8" hits="0"/>
<line number="9" hits="0"/>
<line number="11" hits="0"/>
<line number="12" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="13,14"/>
<line number="13" hits="0"/>
<line number="14" hits="0"/>
<line number="15" hits="0"/>
<line number="16" hits="0"/>
<line number="18" hits="0"/>
<line number="19" hits="0"/>
</lines>
</class>
<class name="pricing.py" filename="shop/pricing.py" complexity="0" line-rate="0.8667" branch-rate="0.6667">
<methods/>
<lines>
<line number="3" hits="1"/>
<line number="6" hits="1"/>
<line number="7" hits="1" branch="true" condition-coverage="100% (2/2)"/>
<line number="8" hits="1"/>
<line number="9" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="10"/>
<line number="10" hits="0"/>
<line number="11" hits="1"/>
<line number="14" hits="1"/>
<line number="15" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="16"/>
<line number="16" hits="0"/>
<line number="17" hits="1"/>
<line number="20" hits="1"/>
<line number="21" hits="1"/>
<line number="22" hits="1"/>
<line number="23" hits="1"/>
</lines>
</class>
<class name="refunds.py" filename="shop/refunds.py" complexity="0" line-rate="0" branch-rate="0">
<methods/>
<lines>
<line number="2" hits="0"/>
<line number="5" hits="0"/>
<line number="6" hits="0"/>
<line number="7" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="8,9"/>
<line number="8" hits="0"/>
<line number="9" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="10,11"/>
<line number="10" hits="0"/>
<line number="11" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="12,13"/>
<line number="12" hits="0"/>
<line number="13" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="14,15"/>
<line number="14" hits="0"/>
<line number="15" hits="0"/>
<line number="18" hits="0"/>
<line number="19" hits="0"/>
<line number="25" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="26,27"/>
<line number="26" hits="0"/>
<line number="27" hits="0"/>
<line number="30" hits="0"/>
<line number="31" hits="0"/>
<line number="32" hits="0"/>
</lines>
</class>
</classes>
</package>
</packages>
</coverage>
FILE:examples/changes.diff
diff --git a/shop/discounts.py b/shop/discounts.py
index 7a2f304..81655b4 100644
--- a/shop/discounts.py
+++ b/shop/discounts.py
@@ -20,0 +21,21 @@ def apply_code(total_cents, code):
+
+
+def best_code(total_cents, codes):
+ """Pick the code that gives the lowest total; ties keep the first code."""
+ best, best_total = None, total_cents
+ for code in codes:
+ new_total, error = apply_code(total_cents, code)
+ if error:
+ continue
+ if new_total < best_total:
+ best, best_total = code, new_total
+ return best, best_total
+
+
+def code_expired(code, today, expiry):
+ end = expiry.get(code.strip().upper())
+ if end is None:
+ return False
+ if today > end:
+ return True
+ return False
diff --git a/shop/gift_cards.py b/shop/gift_cards.py
new file mode 100644
index 0000000..a6a7e76
--- /dev/null
+++ b/shop/gift_cards.py
@@ -0,0 +1,19 @@
+"""Gift card balances (new in this change)."""
+
+
+class GiftCard:
+ def __init__(self, number, balance_cents):
+ if len(number) != 16 or not number.isdigit():
+ raise ValueError("gift card number must be 16 digits")
+ self.number = number
+ self.balance = balance_cents
+
+ def redeem(self, amount_cents):
+ if amount_cents <= 0:
+ raise ValueError("amount must be positive")
+ used = min(amount_cents, self.balance)
+ self.balance -= used
+ return amount_cents - used
+
+ def masked(self):
+ return "**** **** **** " + self.number[-4:]
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/test_discounts.py b/tests/test_discounts.py
new file mode 100644
index 0000000..b62587b
--- /dev/null
+++ b/tests/test_discounts.py
@@ -0,0 +1,7 @@
+import unittest
+from shop.discounts import best_code
+
+
+class DiscountTest(unittest.TestCase):
+ def test_best_code(self):
+ self.assertEqual(best_code(5000, ["WELCOME10", "SAVE5"]), ("WELCOME10", 4500))
FILE:examples/lcov.info
TN:
SF:src/utils/slugify.js
FN:1,slugify
FNDA:6,slugify
DA:2,6
DA:3,6
DA:4,1
DA:5,5
DA:6,5
BRDA:3,0,0,1
BRDA:3,0,1,5
LF:5
LH:5
end_of_record
TN:
SF:src/utils/dates.js
FN:1,formatDate
FN:9,daysBetween
FNDA:3,formatDate
FNDA:0,daysBetween
DA:2,3
DA:3,3
DA:4,0
DA:5,3
DA:10,0
DA:11,0
DA:12,0
BRDA:3,0,0,0
BRDA:3,0,1,3
BRDA:11,1,0,-
BRDA:11,1,1,-
LF:7
LH:3
end_of_record
FILE:scripts/coverage_gaps.py
#!/usr/bin/env python3
"""coverage_gaps.py - find the coverage gaps that matter in a Cobertura XML or LCOV report.
Reads a coverage report (Cobertura XML from coverage.py `coverage xml`, Jest/Vitest/istanbul
`cobertura` reporter, PHPUnit, .NET coverlet, gcovr ...; or LCOV `lcov.info`), and optionally a
unified diff of the change under review. Prints totals, the files with the most missed lines,
uncovered line ranges, diff coverage of changed lines, and flags C01-C09.
Usage:
coverage_gaps.py REPORT [--diff changes.diff] [--format text|md|json|csv]
[--min-total 80] [--min-file 60] [--min-diff 80] [--min-lines 10]
[--block 15] [--top 10] [--exclude GLOB ...] [--strip-prefix PREFIX]
[--fail-on none|info|low|medium|high]
coverage_gaps.py --self-test
Exit: 0 ok, 1 flags at or above --fail-on, 2 unreadable input. Python 3.8+, standard library only.
"""
import argparse, csv, fnmatch, io, json, os, re, sys
import xml.etree.ElementTree as ET
SEV = {"info": 0, "low": 1, "medium": 2, "high": 3}
class FileCov:
def __init__(self, path):
self.path = path
self.lines = {} # line number -> hit count
self.branches = {} # line number -> (covered, total)
def add_line(self, n, hits):
self.lines[n] = max(self.lines.get(n, 0), hits)
def add_branch(self, n, covered, total):
c, t = self.branches.get(n, (0, 0))
self.branches[n] = (max(c, covered), max(t, total))
@property
def total(self): return len(self.lines)
@property
def covered(self): return sum(1 for h in self.lines.values() if h > 0)
@property
def missed_lines(self): return sorted(n for n, h in self.lines.items() if h == 0)
@property
def branch_total(self): return sum(t for _, t in self.branches.values())
@property
def branch_covered(self): return sum(c for c, _ in self.branches.values())
def pct(self):
return 100.0 * self.covered / self.total if self.total else None
def branch_pct(self):
return 100.0 * self.branch_covered / self.branch_total if self.branch_total else None
def norm_path(p, strip=""):
p = p.replace("\\", "/")
while p.startswith("./"):
p = p[2:]
if strip and p.startswith(strip):
p = p[len(strip):].lstrip("/")
return p
def parse_cobertura(text, strip=""):
root = ET.fromstring(text)
if root.tag != "coverage":
raise ValueError("not a Cobertura report (root element is <%s>)" % root.tag)
sources = [s.text.strip() for s in root.iter("source") if s.text and s.text.strip()]
files = {}
for cls in root.iter("class"):
fn = cls.get("filename")
if not fn:
continue
path = norm_path(fn, strip)
fc = files.setdefault(path, FileCov(path))
for ln in cls.iter("line"):
try:
n = int(ln.get("number")); hits = int(float(ln.get("hits", "0")))
except (TypeError, ValueError):
continue
fc.add_line(n, hits)
cond = ln.get("condition-coverage") # e.g. "50% (1/2)"
if ln.get("branch") == "true" and cond:
m = re.search(r"\((\d+)/(\d+)\)", cond)
if m:
fc.add_branch(n, int(m.group(1)), int(m.group(2)))
return files, sources
def parse_lcov(text, strip=""):
files, cur = {}, None
for raw in text.splitlines():
line = raw.strip()
if line.startswith("SF:"):
path = norm_path(line[3:], strip)
cur = files.setdefault(path, FileCov(path))
elif line.startswith("DA:") and cur is not None:
parts = line[3:].split(",")
try:
cur.add_line(int(parts[0]), int(float(parts[1])))
except (IndexError, ValueError):
continue
elif line.startswith("BRDA:") and cur is not None:
parts = line[5:].split(",")
if len(parts) == 4:
try:
n = int(parts[0])
except ValueError:
continue
taken = parts[3] not in ("-", "0")
c, t = cur.branches.get(n, (0, 0))
cur.branches[n] = (c + (1 if taken else 0), t + 1)
elif line == "end_of_record":
cur = None
if not files:
raise ValueError("no SF: records found; not an LCOV file?")
return files, []
def load_report(path, strip=""):
with open(path, encoding="utf-8", errors="replace") as fh:
text = fh.read()
head = text.lstrip()[:200]
if head.startswith("<"):
return parse_cobertura(text, strip)
return parse_lcov(text, strip)
def parse_diff(text, strip=""):
"""Return {path: set(added line numbers in the new file)} from a unified diff (git diff / git diff -U0)."""
changed, path, n = {}, None, None
for line in text.splitlines():
if line.startswith("+++ "):
p = line[4:].split("\t")[0].strip()
if p == "/dev/null":
path = None
continue
if p.startswith("b/"):
p = p[2:]
path = norm_path(p, strip)
changed.setdefault(path, set())
elif line.startswith("@@") and path is not None:
m = re.match(r"@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line)
n = int(m.group(1)) if m else None
elif path is not None and n is not None:
if line.startswith("+") and not line.startswith("+++"):
changed[path].add(n); n += 1
elif line.startswith("-") and not line.startswith("---"):
pass
elif line.startswith("\\"):
pass
else:
n += 1
return {p: s for p, s in changed.items() if s}
def ranges(nums):
out, start, prev = [], None, None
for x in sorted(nums):
if start is None:
start = prev = x
elif x == prev + 1:
prev = x
else:
out.append((start, prev)); start = prev = x
if start is not None:
out.append((start, prev))
return out
def fmt_ranges(rs, limit=8):
parts = ["%d" % a if a == b else "%d-%d" % (a, b) for a, b in rs]
more = len(parts) - limit
return ", ".join(parts[:limit]) + (" (+%d more)" % more if more > 0 else "")
def is_code_file(path):
return not re.search(r"\.(md|txt|json|ya?ml|toml|lock|cfg|ini|csv|svg|png|jpg|gif)$", path, re.I)
def is_test_file(path):
return bool(re.search(r"(^|/)(tests?|__tests__|spec)/|(^|/)test_[^/]+$|_test\.\w+$|\.(test|spec)\.\w+$", path))
def analyze(files, changed=None, opt=None):
o = dict(min_total=80.0, min_file=60.0, min_diff=80.0, min_lines=10, block=15, top=10, exclude=[])
o.update(opt or {})
files = {p: f for p, f in files.items() if not any(fnmatch.fnmatch(p, g) for g in o["exclude"])}
tot = sum(f.total for f in files.values()); cov = sum(f.covered for f in files.values())
btot = sum(f.branch_total for f in files.values()); bcov = sum(f.branch_covered for f in files.values())
rows = []
for p, f in sorted(files.items()):
rs = ranges(f.missed_lines)
biggest = max([b - a + 1 for a, b in rs], default=0)
rows.append(dict(file=p, lines=f.total, covered=f.covered, missed=f.total - f.covered,
pct=None if f.pct() is None else round(f.pct(), 1),
branch_pct=None if f.branch_pct() is None else round(f.branch_pct(), 1),
branches=f.branch_total, missed_ranges=rs, biggest_gap=biggest))
rows.sort(key=lambda r: (-r["missed"], r["file"]))
summary = dict(files=len(files), lines=tot, covered=cov,
line_pct=round(100.0 * cov / tot, 1) if tot else None,
branches=btot, branch_pct=round(100.0 * bcov / btot, 1) if btot else None)
flags = []
def flag(code, sev, msg, file=None):
flags.append(dict(code=code, severity=sev, file=file, message=msg))
if tot == 0:
flag("C08", "high", "the report contains no measured lines (wrong file, wrong paths, or tests did not run)")
elif summary["line_pct"] < o["min_total"]:
flag("C01", "medium", "total line coverage %.1f%% is below the %.0f%% target" % (summary["line_pct"], o["min_total"]))
for r in rows:
if r["lines"] >= o["min_lines"] and r["covered"] == 0:
flag("C07", "medium", "no line is covered (%d lines); the file may never be imported by tests" % r["lines"], r["file"])
elif r["lines"] >= o["min_lines"] and r["pct"] is not None and r["pct"] < o["min_file"]:
flag("C02", "low", "line coverage %.1f%% is below the per-file target %.0f%%" % (r["pct"], o["min_file"]), r["file"])
if r["biggest_gap"] >= o["block"] and r["covered"] > 0:
a, b = max(r["missed_ranges"], key=lambda x: x[1] - x[0])
flag("C05", "low", "uncovered block of %d lines (%d-%d)" % (b - a + 1, a, b), r["file"])
if r["branch_pct"] is not None and r["pct"] is not None and r["branches"] >= 4 and r["pct"] - r["branch_pct"] >= 25:
flag("C06", "low", "branch coverage %.1f%% is far below line coverage %.1f%%: lines run, but some if/else paths never do" % (r["branch_pct"], r["pct"]), r["file"])
diff = None
if changed is not None:
dfiles, dtot, dcov = [], 0, 0
for p, lines in sorted(changed.items()):
if any(fnmatch.fnmatch(p, g) for g in o["exclude"]) or not is_code_file(p):
continue
f = files.get(p)
if f is None:
if is_test_file(p):
continue
dfiles.append(dict(file=p, changed=len(lines), measurable=0, covered=0, pct=None, uncovered_ranges=[], in_report=False))
flag("C04", "medium", "changed file is not in the coverage report (new file without tests, or excluded from measurement)", p)
continue
meas = [n for n in lines if n in f.lines]
c = [n for n in meas if f.lines[n] > 0]
unc = ranges([n for n in meas if f.lines[n] == 0])
dtot += len(meas); dcov += len(c)
dfiles.append(dict(file=p, changed=len(lines), measurable=len(meas), covered=len(c),
pct=round(100.0 * len(c) / len(meas), 1) if meas else None, uncovered_ranges=unc, in_report=True))
diff = dict(files=dfiles, measurable=dtot, covered=dcov, pct=round(100.0 * dcov / dtot, 1) if dtot else None)
if diff["pct"] is not None and diff["pct"] < o["min_diff"]:
sev = "high" if diff["pct"] < o["min_diff"] / 2 else "medium"
flag("C03", sev, "diff coverage %.1f%% (%d of %d changed executable lines) is below the %.0f%% target" % (diff["pct"], dcov, dtot, o["min_diff"]))
if diff["measurable"] == 0 and not any(not d["in_report"] for d in dfiles):
flag("C09", "info", "no changed executable lines found in the report (docs/config-only change, or diff paths do not match report paths; try --strip-prefix)")
flags.sort(key=lambda x: (-SEV[x["severity"]], x["code"], x["file"] or ""))
return dict(summary=summary, files=rows, top=[r for r in rows if r["missed"]][:o["top"]], diff=diff, flags=flags, options=o)
def pct_s(v):
return " n/a" if v is None else "%5.1f%%" % v
def render_text(res):
s = res["summary"]; out = []
out.append("Coverage summary")
out.append(" Files %d, lines %d, covered %d -> line coverage %s" % (s["files"], s["lines"], s["covered"], pct_s(s["line_pct"]).strip()))
out.append(" Branches %d -> branch coverage %s" % (s["branches"], pct_s(s["branch_pct"]).strip()))
if res["diff"] is not None:
d = res["diff"]
out.append(" Diff coverage %s (%d of %d changed executable lines covered, %d files changed)" % (pct_s(d["pct"]).strip(), d["covered"], d["measurable"], len(d["files"])))
out.append("")
out.append("Files with the most missed lines (top %d)" % len(res["top"]))
for r in res["top"]:
out.append(" %-34s %s missed %3d/%-3d branch %s gaps %s" % (r["file"][:34], pct_s(r["pct"]), r["missed"], r["lines"], pct_s(r["branch_pct"]), fmt_ranges(r["missed_ranges"], 5)))
if res["diff"] is not None:
out.append("")
out.append("Changed lines")
for d in res["diff"]["files"]:
if not d["in_report"]:
out.append(" %-34s NOT IN REPORT (%d changed lines)" % (d["file"][:34], d["changed"]))
else:
out.append(" %-34s %s %d/%d covered uncovered %s" % (d["file"][:34], pct_s(d["pct"]), d["covered"], d["measurable"], fmt_ranges(d["uncovered_ranges"]) or "-"))
out.append("")
out.append("Findings (%d)" % len(res["flags"]))
for f in res["flags"]:
out.append(" [%s %s] %s%s" % (f["code"], f["severity"], (f["file"] + ": ") if f["file"] else "", f["message"]))
if not res["flags"]:
out.append(" none")
return "\n".join(out)
def render_md(res):
s = res["summary"]; out = ["# Coverage gaps", ""]
out.append("| Metric | Value |"); out.append("|---|---|")
out.append("| Line coverage | %s (%d/%d lines, %d files) |" % (pct_s(s["line_pct"]).strip(), s["covered"], s["lines"], s["files"]))
out.append("| Branch coverage | %s (%d branches) |" % (pct_s(s["branch_pct"]).strip(), s["branches"]))
if res["diff"] is not None:
d = res["diff"]
out.append("| Diff coverage | %s (%d/%d changed lines) |" % (pct_s(d["pct"]).strip(), d["covered"], d["measurable"]))
out += ["", "## Biggest gaps", "", "| File | Lines | Branches | Missed | Uncovered lines |", "|---|---|---|---|---|"]
for r in res["top"]:
if r["missed"]:
out.append("| `%s` | %s | %s | %d | %s |" % (r["file"], pct_s(r["pct"]).strip(), pct_s(r["branch_pct"]).strip(), r["missed"], fmt_ranges(r["missed_ranges"], 6)))
if res["diff"] is not None:
out += ["", "## Changed lines", "", "| File | Covered | Uncovered changed lines |", "|---|---|---|"]
for d in res["diff"]["files"]:
out.append("| `%s` | %s | %s |" % (d["file"], "not in report" if not d["in_report"] else "%d/%d" % (d["covered"], d["measurable"]), fmt_ranges(d["uncovered_ranges"]) or "-"))
out += ["", "## Findings", ""]
out += ["- **%s** (%s) %s%s" % (f["code"], f["severity"], ("`%s`: " % f["file"]) if f["file"] else "", f["message"]) for f in res["flags"]] or ["- none"]
return "\n".join(out)
def render_csv(res):
buf = io.StringIO(); w = csv.writer(buf, lineterminator="\n")
w.writerow(["file", "lines", "covered", "missed", "line_pct", "branch_pct", "biggest_gap", "uncovered_ranges"])
for r in sorted(res["files"], key=lambda r: r["file"]):
w.writerow([r["file"], r["lines"], r["covered"], r["missed"], "" if r["pct"] is None else r["pct"],
"" if r["branch_pct"] is None else r["branch_pct"], r["biggest_gap"], fmt_ranges(r["missed_ranges"], 1000)])
return buf.getvalue().rstrip("\n")
def to_json(res):
r = dict(res)
r["files"] = [dict(x, missed_ranges=[list(t) for t in x["missed_ranges"]]) for x in res["files"]]
r["top"] = [x["file"] for x in res["top"]]
if res["diff"] is not None:
r["diff"] = dict(res["diff"], files=[dict(x, uncovered_ranges=[list(t) for t in x["uncovered_ranges"]]) for x in res["diff"]["files"]])
return json.dumps(r, indent=2)
SAMPLE_XML = """<?xml version="1.0" ?>
<coverage version="7.4" line-rate="0.6" branch-rate="0.5">
<sources><source>/repo</source></sources>
<packages><package name="app"><classes>
<class name="a.py" filename="app/a.py"><lines>
<line number="1" hits="1"/><line number="2" hits="1"/><line number="3" hits="0"/>
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)"/><line number="5" hits="0"/>
</lines></class>
<class name="b.py" filename="app/b.py"><lines>
""" + "".join('<line number="%d" hits="0"/>' % i for i in range(1, 13)) + """
</lines></class>
</classes></package></packages>
</coverage>"""
SAMPLE_LCOV = """TN:
SF:src/x.js
DA:1,1
DA:2,0
DA:3,4
BRDA:3,0,0,1
BRDA:3,0,1,-
end_of_record
"""
SAMPLE_DIFF = """diff --git a/app/a.py b/app/a.py
--- a/app/a.py
+++ b/app/a.py
@@ -2,0 +3,3 @@ def f():
+ x = 1
+ if x:
+ return 2
diff --git a/app/new.py b/app/new.py
--- /dev/null
+++ b/app/new.py
@@ -0,0 +1,2 @@
+def g():
+ return 1
diff --git a/tests/test_a.py b/tests/test_a.py
--- a/tests/test_a.py
+++ b/tests/test_a.py
@@ -1,0 +2 @@
+ assert f() == 2
"""
def self_test():
checks = []
def ok(name, cond):
checks.append((name, bool(cond)))
files, _ = parse_cobertura(SAMPLE_XML)
ok("cobertura files", sorted(files) == ["app/a.py", "app/b.py"])
a = files["app/a.py"]
ok("cobertura line counts", (a.total, a.covered) == (5, 3))
ok("cobertura missed lines", a.missed_lines == [3, 5])
ok("cobertura branches", (a.branch_covered, a.branch_total) == (1, 2))
lf, _ = parse_lcov(SAMPLE_LCOV)
x = lf["src/x.js"]
ok("lcov lines", (x.total, x.covered) == (3, 2))
ok("lcov branches", (x.branch_covered, x.branch_total) == (1, 2))
ok("ranges", ranges([1, 2, 3, 7, 9, 10]) == [(1, 3), (7, 7), (9, 10)])
ok("fmt ranges", fmt_ranges([(1, 3), (7, 7)]) == "1-3, 7")
ch = parse_diff(SAMPLE_DIFF)
ok("diff added lines", ch.get("app/a.py") == {3, 4, 5})
ok("diff new file", ch.get("app/new.py") == {1, 2})
ok("diff strip prefix", parse_diff(SAMPLE_DIFF.replace("b/app/", "b/repo/app/"), "repo").get("app/a.py") == {3, 4, 5})
res = analyze(files, ch, dict(min_total=80, min_lines=10))
codes = {f["code"] for f in res["flags"]}
ok("total line pct", res["summary"]["line_pct"] == round(100 * 3 / 17, 1))
ok("C01 total below target", "C01" in codes)
ok("C07 untouched file", any(f["code"] == "C07" and f["file"] == "app/b.py" for f in res["flags"]))
ok("diff coverage 1 of 3", (res["diff"]["covered"], res["diff"]["measurable"]) == (1, 3))
ok("C03 diff below target", "C03" in codes)
ok("C04 new file not in report", any(f["code"] == "C04" and f["file"] == "app/new.py" for f in res["flags"]))
ok("test files ignored in diff", all(d["file"] != "tests/test_a.py" for d in res["diff"]["files"]))
ok("exclude glob", analyze(files, None, dict(exclude=["app/b.py"]))["summary"]["files"] == 1)
ok("empty report C08", any(f["code"] == "C08" for f in analyze({}, None)["flags"]))
ok("csv header", render_csv(res).splitlines()[0].startswith("file,lines,covered"))
ok("json roundtrip", json.loads(to_json(res))["summary"]["files"] == 2)
bad = [n for n, c in checks if not c]
if bad:
print("self-test FAILED: " + ", ".join(bad)); return 1
print("self-test OK: %d checks" % len(checks)); return 0
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("report", nargs="?")
ap.add_argument("--diff")
ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
ap.add_argument("--min-total", type=float, default=80.0)
ap.add_argument("--min-file", type=float, default=60.0)
ap.add_argument("--min-diff", type=float, default=80.0)
ap.add_argument("--min-lines", type=int, default=10, help="ignore smaller files for C02/C07")
ap.add_argument("--block", type=int, default=15, help="uncovered block size for C05")
ap.add_argument("--top", type=int, default=10)
ap.add_argument("--exclude", action="append", default=[])
ap.add_argument("--strip-prefix", default="")
ap.add_argument("--fail-on", choices=["none"] + list(SEV), default="none")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.report:
ap.print_usage(sys.stderr); return 2
try:
files, _ = load_report(a.report, a.strip_prefix)
changed = None
if a.diff:
with open(a.diff, encoding="utf-8", errors="replace") as fh:
changed = parse_diff(fh.read(), a.strip_prefix)
except (OSError, ValueError, ET.ParseError) as e:
print("error: %s" % e, file=sys.stderr); return 2
res = analyze(files, changed, dict(min_total=a.min_total, min_file=a.min_file, min_diff=a.min_diff,
min_lines=a.min_lines, block=a.block, top=a.top, exclude=a.exclude))
print({"text": render_text, "md": render_md, "json": to_json, "csv": render_csv}[a.format](res))
if a.fail_on != "none" and any(SEV[f["severity"]] >= SEV[a.fail_on] for f in res["flags"]):
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
Opinionated debugging preferences: reproduce first, shrink the failing case, read the real error, bisect, use debuggers and logs deliberately, and lock every fix in with a test.
# Debugging taste of an engineer who would rather prove a cause than guess one - Reproduce the bug reliably before changing any code; a fix for a bug you cannot reproduce is a guess. Confidence: 0.95 - Write down the exact steps, inputs, versions and environment that trigger the bug in the ticket before you start digging. Confidence: 0.85 - Read the full error message and the whole stack trace, starting from the first frame in your own code, before searching the web. Confidence: 0.90 - Shrink the failing case to the smallest input or code path that still fails; most causes become obvious once the noise is gone. Confidence: 0.90 - Turn the reproduction into a failing automated test first, then make it pass, and keep that test forever. Confidence: 0.90 - Use git bisect when something used to work; let the history find the breaking commit instead of reading diffs by hand. Confidence: 0.85 - Change one thing at a time and re-run; never stack several speculative fixes and hope one of them helped. Confidence: 0.90 - State a hypothesis out loud (or in the ticket) before each experiment, and note what result would disprove it. Confidence: 0.75 - Reach for a real debugger with breakpoints and watch expressions over adding a dozen print statements. Confidence: 0.70 - When printing is the right tool, log the values and their types with clear labels, and delete the temporary logs before merging. Confidence: 0.80 - Check your assumptions explicitly with assertions; the bug usually lives in the thing you were sure about. Confidence: 0.85 - Compare a working and a broken environment side by side (config, env vars, dependency versions, data) instead of staring at code. Confidence: 0.80 - Verify you are running the code you think you are running: clear caches, rebuild, and confirm the version or commit in the logs. Confidence: 0.85 - Look at the actual data in the database, queue or API response; do not debug from what the data is supposed to look like. Confidence: 0.85 - Treat flaky tests as real bugs, usually timing, ordering or shared state, and never just add retries to hide them. Confidence: 0.85 - For race conditions, add structured logs with timestamps and request or thread ids, then reconstruct the order of events. Confidence: 0.75 - Read the source of the library or framework when its behavior surprises you; docs describe intent, code describes reality. Confidence: 0.75 - Time-box solo debugging to about an hour, then explain the problem to a teammate or a rubber duck. Confidence: 0.70 - Fix the root cause rather than the symptom, and search the codebase for the same mistake in other places. Confidence: 0.85 - Never debug in production by editing live code; use feature flags, extra telemetry or a copy of the data instead. Confidence: 0.90 - Write a short note in the pull request on the cause, the fix and how it was verified, so the next person learns from it. Confidence: 0.80 - Add the missing log line, metric or error message that would have made this bug obvious, as part of the fix. Confidence: 0.80
Opinionated Bun preferences for TypeScript projects: runtime, package manager, bun:test, Bun.serve, env validation, single-file builds and Docker images.
# Bun Project taste of a TypeScript developer who wants one fast tool for everything - Use Bun as the runtime, package manager, test runner and bundler in new TypeScript projects instead of stitching together Node, npm, Jest and esbuild. Confidence: 0.85 - Pin the Bun version in package.json "packageManager" and in CI with oven-sh/setup-bun so every machine runs the same build. Confidence: 0.90 - Commit the text lockfile (bun.lock) and run bun install --frozen-lockfile in CI. Confidence: 0.95 - Write TypeScript directly and let Bun run it; keep tsc only for type checking with "noEmit": true. Confidence: 0.90 - Turn on "strict", "noUncheckedIndexedAccess" and "verbatimModuleSyntax" in tsconfig.json. Confidence: 0.85 - Use ES modules only; no CommonJS require in new code. Confidence: 0.90 - Serve HTTP with Bun.serve and its routes object for small services; reach for Hono when you need middleware and validation. Confidence: 0.80 - Read files with Bun.file and write with Bun.write instead of pulling in fs-extra. Confidence: 0.75 - Use the built-in bun:sqlite for local and embedded data before adding a native SQLite package. Confidence: 0.75 - Prefer Web standard APIs (fetch, Request, Response, URL, crypto.subtle) so code also runs on Node, Deno and edge runtimes. Confidence: 0.85 - Write tests with bun:test (describe, test, expect, mock) and keep them next to the code as *.test.ts. Confidence: 0.85 - Run bun test --coverage in CI and fail the job on new uncovered critical paths, not on a global percentage. Confidence: 0.70 - Load configuration from Bun's automatic .env loading plus a Zod schema that validates process.env at startup. Confidence: 0.85 - Never commit .env files; commit .env.example with every key and a comment. Confidence: 0.95 - Define scripts in package.json (dev, test, typecheck, lint, build) and call them with bun run so CI and humans use the same commands. Confidence: 0.90 - Use bun --watch for dev servers and bun --hot only when in-memory state must survive reloads. Confidence: 0.70 - Build single-file executables with bun build --compile for CLIs and small services shipped to servers. Confidence: 0.75 - Use Biome for linting and formatting to keep the toolchain as fast as the runtime. Confidence: 0.75 - Use Bun workspaces for monorepos and reference internal packages with "workspace:*". Confidence: 0.80 - Check a dependency for native addons or Node-only internals before adopting it, and keep a short list of known-incompatible packages in the README. Confidence: 0.70 - Ship Docker images from the official oven/bun slim image with a multi-stage build and a non-root user. Confidence: 0.80 - Keep Node compatibility as a fallback: run the test suite on Node once a week if the package is published to npm. Confidence: 0.65
Opinionated Pydantic v2 preferences for validating data at the edges of Python backends: separate input and output models, strict settings, discriminated unions and safe serialization.
# Pydantic Models taste of a Python backend developer who wants data checked at the edges - Use Pydantic v2 only and write new code against its API (model_validate, model_dump, field_validator), never the v1 compatibility layer. Confidence: 0.95 - Validate data at the boundaries (HTTP requests, queue messages, config, third-party responses) and pass typed models inward. Confidence: 0.90 - Keep separate models for input, output and storage (UserCreate, UserRead, UserRow) instead of one model with optional fields. Confidence: 0.90 - Set model_config = ConfigDict(extra="forbid") on request models so typos in payloads fail loudly. Confidence: 0.85 - Make value objects and events immutable with frozen=True. Confidence: 0.80 - Prefer precise types over plain str: EmailStr, HttpUrl, UUID, PositiveInt, constr with a pattern, Literal for small enums. Confidence: 0.85 - Use Annotated types with Field constraints and reuse them as named aliases (Slug = Annotated[str, Field(pattern=...)]). Confidence: 0.80 - Put single-field rules in field_validator and cross-field rules in model_validator(mode="after"); keep validators pure with no I/O. Confidence: 0.90 - Model variants with discriminated unions on a type field instead of trying each model in order. Confidence: 0.85 - Use timezone-aware datetimes only (AwareDatetime) and reject naive ones at the boundary. Confidence: 0.85 - Store money as Decimal with fixed places, never float. Confidence: 0.95 - Load settings with pydantic-settings from environment variables, with a prefix per service and SecretStr for secrets. Confidence: 0.90 - Never return ORM objects from an API directly; convert with model_validate(obj, from_attributes=True) into a response model. Confidence: 0.85 - Keep strict mode on for internal messages and allow lax coercion only on user-facing form input. Confidence: 0.70 - Use alias_generator with to_camel when the wire format is camelCase, and keep snake_case attributes in Python. Confidence: 0.80 - Serialize with model_dump(mode="json", exclude_none=True) for APIs so dates and decimals become stable strings. Confidence: 0.75 - Use TypeAdapter for validating plain lists, dicts and unions without wrapping them in a dummy model. Confidence: 0.80 - Export JSON Schema with model_json_schema and commit it, so API clients and docs stay in sync. Confidence: 0.70 - Return validation errors as a list of field paths and messages; never leak the raw exception text to clients. Confidence: 0.85 - Avoid heavy business logic and database calls inside models; models describe shape, services do work. Confidence: 0.85 - Test models with table-driven pytest cases for valid and invalid payloads, plus a few Hypothesis property tests for parsers. Confidence: 0.70 - Run mypy or pyright with the Pydantic plugin in CI so model fields and call sites are type-checked. Confidence: 0.80
Opinionated preferences for Zig projects: pinned toolchain, build.zig, explicit allocators, error handling, tests and cross-compilation.
# Zig Project taste of a systems developer who likes boring, explicit builds
- Pin the Zig version per project (a .zig-version file or mise/zigup) because the language still breaks between releases. Confidence: 0.90
- Drive everything through build.zig: build, test, run and install steps, with no Makefile or shell wrappers. Confidence: 0.90
- Declare dependencies in build.zig.zon with content hashes and fetch them with zig fetch --save. Confidence: 0.90
- Use b.standardTargetOptions and b.standardOptimizeOption so any target and release mode work from the command line. Confidence: 0.85
- Pass allocators explicitly into every function that allocates; never hide a global allocator. Confidence: 0.95
- Use std.testing.allocator in tests so leaks and double frees fail the test. Confidence: 0.90
- Pair every allocation with defer or errdefer on the very next line. Confidence: 0.90
- Prefer an ArenaAllocator for short-lived request or frame work instead of freeing many small objects. Confidence: 0.80
- Use the GeneralPurposeAllocator (DebugAllocator) in debug builds and check its leak report on exit. Confidence: 0.80
- Return error unions and propagate with try; reserve catch unreachable for cases you can prove. Confidence: 0.90
- Define small, specific error sets for public APIs instead of anyerror. Confidence: 0.80
- Write tests in the same file as the code with test blocks, and run them all with zig build test. Confidence: 0.90
- Keep comptime for real needs such as generics and lookup tables, not for clever metaprogramming. Confidence: 0.80
- Use slices and sentinel-terminated types instead of raw many-item pointers wherever possible. Confidence: 0.85
- Ship ReleaseSafe by default and use ReleaseFast only for measured hot paths. Confidence: 0.75
- Use @import("std").log with scoped loggers instead of std.debug.print in library code. Confidence: 0.75
- Wrap C libraries through @cImport in one small module and expose a Zig-style API from it. Confidence: 0.80
- Use zig cc and zig build to cross-compile C and Zig code from one machine instead of separate toolchains. Confidence: 0.85
- Run zig fmt in CI and fail the build when it would change any file. Confidence: 0.90
- Test in CI on Linux, macOS and Windows, plus at least one cross-compiled target. Confidence: 0.80
- Keep public library APIs in one root.zig and mark everything else non-pub. Confidence: 0.80
- Generate API docs with -femit-docs and publish them with each release. Confidence: 0.65
Opinionated conventions for publishing small, stable Java libraries with Maven: pinned plugins, tiny dependency trees, API compatibility checks and Central releases.
# Java Library taste of a developer who ships small, stable Maven artifacts - Target the oldest Java LTS your users still run (usually 17) and set it with maven.compiler.release, not source/target. Confidence: 0.90 - Use the Maven Wrapper (mvnw) and commit it so every build uses the same Maven version. Confidence: 0.90 - Pin every plugin version in pluginManagement; never rely on Maven's default plugin versions. Confidence: 0.95 - Keep runtime dependencies near zero; a library should not drag Guava or Commons into every consumer. Confidence: 0.85 - Mark compile-only and annotation-processor dependencies as provided or optional so they do not leak transitively. Confidence: 0.80 - Ship a module-info.java, or at least an Automatic-Module-Name in the manifest, so JPMS users get a stable module name. Confidence: 0.85 - Put everything not meant for users in an internal package and do not export it from the module. Confidence: 0.85 - Prefer immutable value types (records or final classes with builders) for the public API. Confidence: 0.85 - Never return null from public methods; return Optional for single values and empty collections for lists. Confidence: 0.85 - Throw unchecked exceptions with clear messages, and define one library-specific base exception type. Confidence: 0.75 - Annotate nullability with JSpecify (@NullMarked at package level) so Kotlin and static analysis tools see the contract. Confidence: 0.75 - Use SLF4J as the only logging dependency and never configure a logging backend inside the library. Confidence: 0.90 - Test with JUnit 5 and AssertJ, and keep unit tests runnable with a plain mvn verify and no network. Confidence: 0.90 - Run integration tests with the Failsafe plugin and Testcontainers instead of shared test databases. Confidence: 0.80 - Enforce formatting with Spotless (google-java-format or palantir-java-format) and fail CI on drift. Confidence: 0.80 - Run Error Prone or SpotBugs in CI and treat new warnings as build failures. Confidence: 0.70 - Use japicmp or revapi to block accidental binary-incompatible changes in minor and patch releases. Confidence: 0.85 - Follow semantic versioning strictly; breaking changes wait for a major version with a migration note. Confidence: 0.90 - Publish a BOM when the project has more than one artifact so users can align versions in one place. Confidence: 0.75 - Generate and publish sources and Javadoc jars, and write Javadoc for every public type and method. Confidence: 0.85 - Publish to Maven Central through the Central Portal with signed artifacts, released from CI, never from a laptop. Confidence: 0.85 - Make builds reproducible by setting project.build.outputTimestamp. Confidence: 0.70 - Test the library in CI on every supported Java version with a matrix build. Confidence: 0.85 - Keep a CHANGELOG.md with Added, Changed, Deprecated and Removed sections for each release. Confidence: 0.80 - Deprecate with @Deprecated(since, forRemoval) for at least one minor release before removing an API. Confidence: 0.80
Opinionated conventions for building and releasing Swift packages: Package.swift setup, strict concurrency, Swift Testing, DocC and semver.
# Swift Package taste of a developer who ships small, well-tested Swift libraries - Use Swift Package Manager as the only distribution method for new libraries, and skip CocoaPods and Carthage specs unless users ask. Confidence: 0.85 - Set the swift-tools-version to the oldest toolchain you really test on, and raise it on purpose in a minor release. Confidence: 0.80 - Declare explicit platform minimums in Package.swift (.iOS, .macOS, .watchOS, .tvOS, .visionOS) instead of relying on defaults. Confidence: 0.85 - Keep one focused library product per package; split optional integrations into separate targets users can opt into. Confidence: 0.80 - Use the standard layout (Sources/<Target>, Tests/<Target>Tests) and avoid custom path settings. Confidence: 0.90 - Enable Swift 6 language mode and strict concurrency checking, and mark public types Sendable where it is true. Confidence: 0.80 - Keep the public API small: default to internal, and make each public symbol a deliberate decision. Confidence: 0.90 - Prefer value types and protocols with small requirements over class hierarchies in public APIs. Confidence: 0.80 - Offer async/await APIs first, and add completion-handler or Combine wrappers only when users need them. Confidence: 0.75 - Avoid third-party dependencies in a library; when one is needed, use a version range from: a major version, never a branch or exact revision. Confidence: 0.85 - Write tests with Swift Testing (@Test, #expect) for new code and keep XCTest only where it is already used. Confidence: 0.75 - Run CI on macOS and Linux with swift build and swift test, plus xcodebuild for each Apple platform you claim to support. Confidence: 0.85 - Write DocC documentation for every public symbol and include at least one article showing the main use case. Confidence: 0.80 - Host the docs on the Swift Package Index and keep a .spi.yml so builds and documentation stay green there. Confidence: 0.70 - Follow semantic versioning with plain tags like 1.4.0, without a v prefix, so SPM resolves them. Confidence: 0.90 - Use @available and deprecation messages with a renamed: hint one minor release before removing an API. Confidence: 0.85 - Keep resources in a Resources folder declared with .process and access them only through Bundle.module. Confidence: 0.75 - Format with swift-format or SwiftFormat and lint with SwiftLint in CI, using a config committed to the repo. Confidence: 0.70 - Avoid build plugins and macros unless they remove real boilerplate, because they slow builds and need extra trust prompts. Confidence: 0.65 - Ship a privacy manifest (PrivacyInfo.xcprivacy) when the library touches required-reason APIs. Confidence: 0.75 - Keep Package.resolved out of library repositories, but commit it in apps and example projects. Confidence: 0.80 - Include a runnable example app or snippet in the README that compiles in CI. Confidence: 0.70 - Keep a CHANGELOG.md with Added, Changed, Deprecated and Fixed sections for every release. Confidence: 0.80
Opinionated habits for safe, incremental refactoring: characterization tests, small green steps, strangler fig and clean pull requests.
# Refactoring taste of an engineer who changes structure without changing behavior
- Never mix a refactor and a behavior change in the same commit; reviewers should be able to verify each one alone. Confidence: 0.95
- Get the code under characterization tests that pin today's behavior before touching legacy code, even if that behavior looks wrong. Confidence: 0.90
- Refactor in small steps that keep the build green, committing after each one instead of in one giant branch. Confidence: 0.90
- Use the IDE's automated refactorings (rename, extract function, move, inline) before editing by hand, because they are safer and faster. Confidence: 0.85
- Refactor the code you are about to change ("make the change easy, then make the easy change") rather than scheduling cleanup sprints. Confidence: 0.85
- Follow the rule of three: tolerate one duplication, and extract an abstraction only on the third real copy. Confidence: 0.80
- Prefer inlining a premature abstraction back to concrete code over adding more parameters and flags to keep it alive. Confidence: 0.80
- Replace boolean flag arguments with two well-named functions or an explicit options object. Confidence: 0.80
- Extract a function when you need a comment to explain what a block does, and use the comment as the function name. Confidence: 0.75
- Replace nested conditionals with guard clauses and early returns. Confidence: 0.85
- Introduce parameter objects or value types when the same three or more arguments travel together. Confidence: 0.70
- Push side effects (I/O, time, randomness) to the edges so the core logic becomes pure and easy to test. Confidence: 0.85
- Use the strangler fig pattern for large rewrites: route traffic piece by piece to the new code instead of a big-bang switch. Confidence: 0.90
- Put risky structural changes behind a feature flag or a parallel run that compares old and new results. Confidence: 0.75
- Use expand and contract for public interfaces: add the new API, migrate callers, then delete the old one in a later release. Confidence: 0.90
- Delete dead code instead of commenting it out; version control remembers it. Confidence: 0.95
- Run a codemod (jscodeshift, ts-morph, Comby, OpenRewrite) for mechanical changes across more than a handful of files. Confidence: 0.75
- Keep refactoring pull requests under about 400 changed lines, or split them into a reviewed series. Confidence: 0.70
- Put pure formatting or move-only changes in their own commit and add it to .git-blame-ignore-revs. Confidence: 0.80
- Use churn and complexity together to pick targets; refactor files that change often and are hard to read, not stable ugly ones. Confidence: 0.80
- Avoid renaming widely used concepts unless the team agrees on the new term and the whole codebase moves at once. Confidence: 0.65
- Write down why a refactor is happening in the PR description, with the problem it unblocks. Confidence: 0.85
- Stop when the code is clear enough for the next change; refactoring has no finish line and is not a goal by itself. Confidence: 0.80Opinionated conventions for building, testing and releasing small, dependable Ruby gems with clean gemspecs and safe publishing.
# Ruby Gem taste of a maintainer who ships small, dependable gems with boring releases - Scaffold new gems with `bundle gem <name> --test=rspec --ci=github --linter=rubocop` and keep the generated layout instead of inventing a custom one. Confidence: 0.80 - Keep the gemspec as the single source of truth for metadata, required Ruby version and runtime dependencies; the Gemfile only adds development tools. Confidence: 0.90 - Set `required_ruby_version` explicitly and support only Ruby versions that still receive security fixes. Confidence: 0.85 - Build `spec.files` from `git ls-files` filtered to `lib`, `sig`, `exe`, LICENSE, README and CHANGELOG so tests and fixtures never ship in the package. Confidence: 0.85 - Add as few runtime dependencies as possible and give each one a pessimistic constraint like `~> 2.3`, never an unbounded `>=`. Confidence: 0.90 - Do not commit `Gemfile.lock` for a library; let CI resolve fresh dependencies so breakage shows up early. Confidence: 0.65 - Namespace everything under one top-level module that matches the gem name, and never monkey-patch core classes from a library. Confidence: 0.95 - Use Zeitwerk for gems with many files, and plain `require_relative` for small ones. Confidence: 0.70 - Expose configuration through a `configure` block that yields a plain configuration object with documented defaults. Confidence: 0.80 - Define a base `<GemName>::Error < StandardError` and raise specific subclasses so callers can rescue the whole family. Confidence: 0.90 - Add `# frozen_string_literal: true` to every Ruby file. Confidence: 0.80 - Write tests in RSpec with `--require spec_helper`, random order and `disable_monkey_patching!` turned on. Confidence: 0.80 - Run CI on a matrix of all supported Rubies plus `head`, with `head` allowed to fail. Confidence: 0.85 - Enforce style with RuboCop (or Standard) in CI, and keep project-wide disables in `.rubocop.yml` instead of inline comments. Confidence: 0.75 - Ship RBS signatures in `sig/` for the public API, or at least YARD types, so editors and Steep can check callers. Confidence: 0.60 - Document every public method with YARD and keep a runnable quick-start example at the top of the README. Confidence: 0.80 - Follow Semantic Versioning strictly and keep `VERSION` in `lib/<gem>/version.rb` as the only place the version lives. Confidence: 0.95 - Maintain a CHANGELOG in Keep a Changelog format and update it in the same pull request as the change. Confidence: 0.85 - Deprecate before removing: warn through `Kernel#warn` with `category: :deprecated` for at least one minor release. Confidence: 0.85 - Publish from CI with RubyGems trusted publishing on a tagged release instead of running `gem push` from a laptop. Confidence: 0.85 - Require MFA for every owner by setting `rubygems_mfa_required` to "true" in the gemspec metadata. Confidence: 0.95 - Set `source_code_uri`, `changelog_uri` and `bug_tracker_uri` in the metadata so rubygems.org links back to the repository. Confidence: 0.75 - Keep optional integrations (Rails, Sidekiq) behind separate requires such as `require "<gem>/rails"` so they never load by default. Confidence: 0.80 - Test the packaged gem, not only the repo: build it in CI, install it into a clean bundle and run a smoke script. Confidence: 0.70
Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.
---
name: python-complexity-hotspot-finder
description: Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.
---
# Python Complexity Hotspot Finder
You help Python developers, tech leads and maintainers find the functions that are hardest to change safely and decide what to refactor first. Big if/elif ladders, deep nesting and functions with seven flags are where bugs hide and where new teammates get stuck, but not every complex function is worth touching. You combine complexity metrics with how often code actually changes, explain the results in plain language, and propose small, test-backed refactoring steps.
You read code locally and never upload it. Metrics are a guide, not a verdict: you say when a high number is fine (for example a flat lookup) and the team makes the final call.
## Files in this skill
- `scripts/complexity_hotspots.py` - walks files or folders (skips .git, venvs, build dirs), measures every function and method with the `ast` module: cyclomatic complexity, nesting depth, lines, parameters, returns; optional `--churn DAYS` adds git commit counts per file and ranks by `cc x (1 + churn)`; findings H01-H07; `--format text|md|json`, `--min-severity`, `--top N`, threshold flags; `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/complexity-metrics.md` - how each metric is counted, rough bands, what churn adds and what the numbers do not tell you
- `references/refactoring-recipes.md` - guard clauses, lookup tables, extract function, flag parameters, condition helpers, and what not to do
- `templates/hotspot-report.md` - the review you hand back
- `examples/billing.py` - a fictional billing module with a CC 22, 7-parameter pricing function; `examples/billing_refactored.py` - the same logic after refactoring (CC 5 at most)
## Workflow
### 1. Scope
Ask which package or folders matter, whether it is a git repository (for churn), what is changing soon (upcoming features touch which modules?), and whether there are tests. Exclude generated code, migrations and vendored libraries.
### 2. Run the scan
```
python3 scripts/complexity_hotspots.py src/
python3 scripts/complexity_hotspots.py src/ --churn 90 --top 15
python3 scripts/complexity_hotspots.py src/ --churn 90 --min-severity medium --format md > hotspots.md
python3 scripts/complexity_hotspots.py src/ --format json
python3 scripts/complexity_hotspots.py --self-test
```
Exit code 0 = nothing at or above `--min-severity`, 1 = findings, 2 = bad path or only unparsable files. Files with syntax errors are listed as PARSE ERROR and skipped.
| Code | Severity | Meaning |
|---|---|---|
| H01 | high | CC >= 15 (`--cc-high`) |
| H02 | medium | CC >= 10 (`--cc-warn`) |
| H03 | medium | nesting depth >= 4 |
| H04 | medium | 60+ lines |
| H05 | low | 6+ parameters (self/cls excluded) |
| H06 | low | 6+ return statements |
| H07 | high | hotspot: CC >= warn and file changed in 5+ commits in the churn window |
### 3. Interpret
- Rank by hotspot score when churn is available; a complex function nobody touches is low priority.
- Read the top 3-5 functions yourself before recommending anything. Check whether the complexity is accidental (copy-pasted branches, flags, deep nesting) or essential (real business rules).
- Flat dispatch functions (`invoice_status` with six early returns) are usually fine: say so.
- Check test coverage for each top hotspot; untested hotspots get characterization tests first.
### 4. Plan the refactor
For each top hotspot pick recipes from `references/refactoring-recipes.md`, list small steps (one commit each), estimate effort (S/M/L) and the expected CC afterwards. Never mix behavior changes with refactoring. Re-run the script after the change to show the before/after numbers.
### 5. Report
Fill `templates/hotspot-report.md`: summary, top hotspots table, a step-by-step plan for #1, what you leave alone on purpose and why, and the limits (per-file churn, renames).
## Example
```
python3 scripts/complexity_hotspots.py examples/billing.py
```
flags `calculate_invoice_total` with H01 (CC 22) and H05 (7 parameters) and `invoice_status` with H06 (6 returns, fine for a flat lookup). After extracting `tax_rate`, `line_total`, `apply_coupon` and `loyalty_discount` and moving rates into tables, `examples/billing_refactored.py` peaks at CC 5.
## Rules
- Measure first, then read the code; never recommend a refactor from numbers alone.
- Prefer small, reversible steps behind tests.
- Be honest about trade-offs: tables move complexity into data; helpers add jumps.
- Keep code on the user's machine.
FILE:references/complexity-metrics.md
# Complexity metrics: what they mean and how to read them
## Cyclomatic complexity (CC)
The number of independent paths through a function: 1 plus one for every decision point. `complexity_hotspots.py` counts:
| Construct | Adds |
|---|---|
| `if` / `elif` | 1 each (an `else` adds nothing) |
| `for`, `async for`, `while` | 1 |
| each `except` handler | 1 |
| `and` / `or` | 1 per extra operand (`a and b or c` adds 2) |
| comprehension (`for` part) and each of its `if` filters | 1 each |
| ternary `x if c else y` | 1 |
| `assert` | 1 |
| each `case` in `match` (Python 3.10+) | 1 |
Nested functions, classes and lambdas are measured on their own and do not add to the outer function.
### Rough bands (adjust with `--cc-warn` / `--cc-high`)
| CC | Reading |
|---|---|
| 1-5 | simple, easy to test |
| 6-10 | fine, keep an eye on it |
| 11-15 | hard to test fully; refactor when you next change it (H02) |
| 16+ | high risk; bugs hide here, plan a refactor (H01) |
CC is also the minimum number of test cases needed to cover every branch, which makes it a useful argument when talking to a team about test effort.
## Nesting depth
How many blocks deep the deepest statement sits (`if` inside `for` inside `try` = 3). An `elif` chain stays at the same depth. Depth 4+ (H03) usually means guard clauses or extracted helpers would help readability more than anything else.
## Length, parameters, returns
- **Lines** (H04, default 60): long functions mix several jobs. Length alone is weak; combined with high CC it is strong.
- **Parameters** (H05, default 6, `self`/`cls` excluded, `*args`/`**kwargs` counted): many flags often mean the function does several things; boolean flags are the strongest smell.
- **Returns** (H06, default 6): many exits are fine for a flat lookup (`invoice_status` style) but confusing in a long, nested function.
## Churn and hotspots (H07)
Complexity hurts only where people change code. With `--churn DAYS` the script counts how many commits touched each file in the last DAYS days (`git log --name-only`) and ranks by `score = cc x (1 + churn)`. A function with CC 12 in a file changed 30 times this quarter is a better refactoring target than a CC 25 parser nobody has touched in three years.
Limits: churn is per file, not per function; renames and big formatting commits inflate it; squash-merge workflows deflate it. Mention this when presenting results.
## What these numbers do not tell you
- Whether the code is correct or well tested; pair hotspots with coverage data if you have it.
- Domain complexity: some rules are genuinely complex, and a table-driven rewrite just moves the complexity into data (often still a win: data is easier to review and test).
- Readability of names and comments.
FILE:references/refactoring-recipes.md
# Refactoring recipes for complex Python functions
Always refactor behind tests. If the hotspot has no tests, first write characterization tests that pin today's behavior (including odd cases), then change structure in small commits, running tests after each step.
## 1. Guard clauses (fixes deep nesting, H03)
Return or `continue` early for the invalid or trivial cases instead of wrapping the main path in `if`.
```python
# before
for item in items:
if item.qty > 0:
if item.active:
process(item)
# after
for item in items:
if item.qty <= 0 or not item.active:
continue
process(item)
```
## 2. Lookup table instead of if/elif ladders (fixes H01/H02)
When branches only pick a value (a rate, a label, a handler), move the mapping into a dict.
```python
RATES = {("books", "EU"): 1.05, ("books", "*"): 1.08, ("*", "EU"): 1.2}
rate = RATES.get((cat, region), RATES.get((cat, "*"), 1.0))
```
For branches that run different code, map keys to functions: `HANDLERS[event.type](event)`.
## 3. Extract function (fixes H01, H04)
Give each job its own small, named function (`line_total`, `apply_coupon`, `loyalty_discount`). The parent becomes a readable sequence of steps, and each helper can be tested alone.
## 4. Replace boolean flag parameters (fixes H05)
`rush=False, gift_wrap=False, express=False` -> a small options set, an enum, or separate functions (`send_rush_order`). Group related parameters into a dataclass (`Address`, `PricingContext`).
## 5. Decompose complex conditions
`if customer.get("vip") or customer.get("orders", 0) > 20:` -> `if is_loyal(customer):`. The CC moves into a tiny, well-named function.
## 6. Polymorphism or `match` for type switches
A long `if kind == ...` over object types can become classes with a shared method, or a `match` statement that is easier to scan (CC stays similar but readability improves; say so honestly).
## 7. Split loops that do several things
One loop that filters, transforms, totals and logs -> a comprehension for filtering, a helper for transforming, `sum()` for totals.
## What not to do
- Do not chase a number: a flat 12-case lookup with CC 13 can be perfectly clear. Explain why you leave it.
- Do not refactor and change behavior in the same commit.
- Do not split a function into helpers that only make sense together and must be read in order; that adds jumps without reducing complexity.
- Do not refactor stable, untouched code just because it scores high; prioritize by churn and upcoming work.
FILE:templates/hotspot-report.md
# Complexity hotspot review: {{project}} ({{date}})
**Scope:** {{paths}} - {{function_count}} functions, average CC {{average_cc}}
**Thresholds:** CC warn {{cc_warn}} / high {{cc_high}}, depth {{max_depth}}, lines {{max_lines}}, params {{max_params}}; churn window {{churn_days}} days
## Summary
- {{one_sentence_overall_health}}
- Top risk: `{{top_function}}` ({{top_file}}) - {{why_it_matters}}
- Recommended next step: {{next_step}}
## Top hotspots
| Rank | Function | File | CC | Depth | Lines | Churn | Why it matters | Suggested refactor | Effort |
|---|---|---|---|---|---|---|---|---|---|
| 1 | | | | | | | | | S / M / L |
| 2 | | | | | | | | | |
| 3 | | | | | | | | | |
## Refactoring plan for the #1 hotspot
1. Characterization tests to add first: {{tests}}
2. Steps (one commit each): {{steps}}
3. Expected result: CC {{cc_before}} -> about {{cc_after}}, no behavior change
4. Risks and how we will check them: {{risks}}
## Left as is (on purpose)
- `{{function}}`: {{reason, e.g. flat lookup, stable for 2 years, scheduled for removal}}
## Notes and limits
- Churn is counted per file from git history; renames or formatting commits can inflate it.
- Metrics point to where to look; the team decides what to change.
FILE:examples/billing.py
"""Fictional billing module with typical hotspots (demo data for complexity_hotspots.py)."""
def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", rush=False, gift_wrap=False):
total = 0
for item in items:
if item.get("qty", 0) <= 0:
continue
price = item["price"] * item["qty"]
if item.get("category") == "books":
if region == "EU":
price = price * 1.05
elif region == "UK":
price = price
else:
price = price * 1.08
elif item.get("category") == "food":
if region == "EU" and not customer.get("business"):
price = price * 1.07
else:
price = price * 1.0
else:
if region == "EU":
price = price * 1.2
elif region == "UK":
price = price * 1.2
elif region == "US" and customer.get("state") in ("CA", "NY"):
price = price * 1.09
else:
price = price * 1.0
total += price
if coupon:
if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
total = total * (1 - coupon["value"] / 100)
elif coupon.get("type") == "fixed":
total = max(0, total - coupon["value"])
if customer.get("vip") or customer.get("orders", 0) > 20:
total = total * 0.95
if rush:
total += 15 if currency == "EUR" else 18
if gift_wrap:
total += 3
return round(total, 2)
def invoice_status(invoice, today):
if invoice["paid"]:
return "paid"
if invoice.get("disputed"):
return "disputed"
days = (today - invoice["due"]).days
if days <= 0:
return "open"
if days <= 30:
return "overdue"
if days <= 90:
return "late"
return "collections"
def format_amount(value, currency):
return "%s %.2f" % (currency, value)
FILE:examples/billing_refactored.py
"""The same billing logic after refactoring the hotspot (demo data for complexity_hotspots.py)."""
TAX_RATES = {
# (category, region) -> rate; "*" means any
("books", "EU"): 1.05, ("books", "UK"): 1.0, ("books", "*"): 1.08,
("food", "EU"): 1.07, ("food", "*"): 1.0,
("*", "EU"): 1.2, ("*", "UK"): 1.2, ("*", "*"): 1.0,
}
US_TAXED_STATES = {"CA": 1.09, "NY": 1.09}
RUSH_FEE = {"EUR": 15, "USD": 18}
GIFT_WRAP_FEE = 3
def tax_rate(category, region, customer):
if category == "food" and customer.get("business"):
return 1.0
if category not in ("books", "food") and region == "US":
return US_TAXED_STATES.get(customer.get("state"), 1.0)
key_category = category if category in ("books", "food") else "*"
return TAX_RATES.get((key_category, region), TAX_RATES[(key_category, "*")])
def line_total(item, region, customer):
return item["price"] * item["qty"] * tax_rate(item.get("category"), region, customer)
def apply_coupon(total, coupon):
if not coupon:
return total
if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
return total * (1 - coupon["value"] / 100)
if coupon.get("type") == "fixed":
return max(0, total - coupon["value"])
return total
def loyalty_discount(total, customer):
loyal = customer.get("vip") or customer.get("orders", 0) > 20
return total * 0.95 if loyal else total
def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", options=()):
subtotal = sum(line_total(i, region, customer) for i in items if i.get("qty", 0) > 0)
total = loyalty_discount(apply_coupon(subtotal, coupon), customer)
if "rush" in options:
total += RUSH_FEE.get(currency, 18)
if "gift_wrap" in options:
total += GIFT_WRAP_FEE
return round(total, 2)
FILE:scripts/complexity_hotspots.py
#!/usr/bin/env python3
"""complexity_hotspots.py - find Python functions that are hard to change safely.
Measures per function/method (standard library only, Python 3.8+):
cc cyclomatic complexity (1 + decision points: if/elif, for/while, except,
boolean operators, comprehension ifs, ternaries, match cases, assert)
depth deepest nesting of blocks inside the function
lines function length in source lines
params number of parameters (excluding self/cls)
returns number of return statements
Optional --churn adds how many commits touched each file in the last N days (git log),
and ranks hotspots by cc x (1 + churn).
Findings (severity):
H01 cc >= --cc-high (default 15) high
H02 cc >= --cc-warn (default 10) medium
H03 nesting depth >= --max-depth (4) medium
H04 lines >= --max-lines (60) medium
H05 params >= --max-params (6) low
H06 returns >= --max-returns (6) low
H07 hotspot: cc >= cc-warn and file churn >= --churn-min (5) high
Usage:
complexity_hotspots.py PATH [PATH ...] [--format text|md|json] [--min-severity low|medium|high]
[--churn DAYS] [--top N] [--cc-warn N] [--cc-high N] ...
complexity_hotspots.py --self-test
Exit codes: 0 no findings at or above min severity, 1 findings present, 2 usage/parse error.
"""
import argparse, ast, json, os, subprocess, sys
SEV = {"low": 1, "medium": 2, "high": 3}
SKIP_DIRS = {".git", ".venv", "venv", "env", "__pycache__", "node_modules", "build", "dist", ".tox", ".mypy_cache"}
class FuncVisitor(ast.NodeVisitor):
"""Computes metrics for one function body without descending into nested defs."""
BLOCKS = (ast.If, ast.For, ast.AsyncFor, ast.While, ast.Try, ast.With, ast.AsyncWith)
def __init__(self):
self.cc = 1
self.max_depth = 0
self.returns = 0
self._depth = 0
def generic_visit(self, node):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
return # nested definitions are measured separately (lambdas count as 0)
block = isinstance(node, self.BLOCKS) or type(node).__name__ in ("TryStar", "Match")
if isinstance(node, (ast.If, ast.For, ast.AsyncFor, ast.While, ast.IfExp, ast.Assert)):
self.cc += 1
elif isinstance(node, ast.ExceptHandler):
self.cc += 1
elif isinstance(node, ast.BoolOp):
self.cc += len(node.values) - 1
elif isinstance(node, ast.comprehension):
self.cc += 1 + len(node.ifs)
elif type(node).__name__ == "match_case":
self.cc += 1
elif isinstance(node, ast.Return):
self.returns += 1
if block:
# an elif is an If inside orelse; do not count it as deeper nesting
self._depth += 1
self.max_depth = max(self.max_depth, self._depth)
super().generic_visit(node)
if block:
self._depth -= 1
def visit_If(self, node):
self.cc += 1
self.visit(node.test)
self._depth += 1
self.max_depth = max(self.max_depth, self._depth)
for n in node.body:
self.visit(n)
self._depth -= 1
orelse = node.orelse
if len(orelse) == 1 and isinstance(orelse[0], ast.If):
self.visit_If(orelse[0]) # elif chain: same depth
else:
self._depth += 1
for n in orelse:
self.visit(n)
self._depth -= 1
def measure_function(node):
v = FuncVisitor()
for stmt in node.body:
v.visit(stmt)
args = node.args
names = [a.arg for a in getattr(args, "posonlyargs", []) + args.args + args.kwonlyargs]
if args.vararg: names.append(args.vararg.arg)
if args.kwarg: names.append(args.kwarg.arg)
params = len([n for n in names if n not in ("self", "cls")])
end = getattr(node, "end_lineno", node.lineno)
return {"cc": v.cc, "depth": v.max_depth, "lines": end - node.lineno + 1, "params": params, "returns": v.returns}
def analyze_source(src, filename="<string>"):
tree = ast.parse(src, filename=filename)
out = []
def walk(node, prefix):
for child in ast.iter_child_nodes(node):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
name = prefix + child.name
m = measure_function(child)
m.update({"file": filename, "function": name, "line": child.lineno})
out.append(m)
walk(child, name + ".")
elif isinstance(child, ast.ClassDef):
walk(child, prefix + child.name + ".")
else:
walk(child, prefix)
walk(tree, "")
return out
def iter_py_files(paths):
for p in paths:
if os.path.isfile(p):
if p.endswith(".py"): yield p
continue
for root, dirs, files in os.walk(p):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
for f in sorted(files):
if f.endswith(".py"):
yield os.path.join(root, f)
def git_churn(path, days):
"""Commits per file in the last `days` days, keyed by absolute path. Empty dict if not a git repo."""
base = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path)) or "."
try:
top = subprocess.run(["git", "-C", base, "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=True).stdout.strip()
log = subprocess.run(["git", "-C", top, "log", "--since=%d.days" % days, "--name-only", "--pretty=format:"],
capture_output=True, text=True, check=True).stdout
except (OSError, subprocess.CalledProcessError):
return {}
churn = {}
for line in log.splitlines():
line = line.strip()
if line.endswith(".py"):
k = os.path.normpath(os.path.join(top, line))
churn[k] = churn.get(k, 0) + 1
return churn
def findings_for(m, o):
f = []
if m["cc"] >= o.cc_high: f.append(("H01", "high", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_high)))
elif m["cc"] >= o.cc_warn: f.append(("H02", "medium", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_warn)))
if m["depth"] >= o.max_depth: f.append(("H03", "medium", "nesting depth %d >= %d" % (m["depth"], o.max_depth)))
if m["lines"] >= o.max_lines: f.append(("H04", "medium", "%d lines >= %d" % (m["lines"], o.max_lines)))
if m["params"] >= o.max_params: f.append(("H05", "low", "%d parameters >= %d" % (m["params"], o.max_params)))
if m["returns"] >= o.max_returns: f.append(("H06", "low", "%d return statements >= %d" % (m["returns"], o.max_returns)))
if m.get("churn") is not None and m["cc"] >= o.cc_warn and m["churn"] >= o.churn_min:
f.append(("H07", "high", "hotspot: complex (cc %d) and changed in %d commits recently" % (m["cc"], m["churn"])))
return f
def run(paths, o):
results, errors = [], []
churn = {}
if o.churn:
for p in paths:
churn.update(git_churn(p, o.churn))
for f in iter_py_files(paths):
try:
with open(f, encoding="utf-8") as fh:
ms = analyze_source(fh.read(), f)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append("%s: %s" % (f, e)); continue
for m in ms:
if o.churn:
m["churn"] = churn.get(os.path.normpath(os.path.abspath(f)), 0)
m["score"] = m["cc"] * (1 + m.get("churn", 0))
m["findings"] = [dict(code=c, severity=s, message=t) for c, s, t in findings_for(m, o)]
results.append(m)
results.sort(key=lambda m: (-m["score"], -m["cc"], m["file"], m["line"]))
return results, errors
def render(results, errors, o):
minsev = SEV[o.min_severity]
flagged = [m for m in results if any(SEV[x["severity"]] >= minsev for x in m["findings"])]
top = flagged[: o.top] if o.top else flagged
n = len(results)
avg = sum(m["cc"] for m in results) / n if n else 0
if o.format == "json":
return json.dumps({"functions": n, "average_cc": round(avg, 2), "flagged": len(flagged), "errors": errors,
"hotspots": top}, indent=2)
churn_col = o.churn is not None and o.churn > 0
if o.format == "md":
head = "| Rank | Function | File:line | CC | Depth | Lines | Params |" + (" Churn |" if churn_col else "") + " Findings |"
sep = "|---|---|---|---|---|---|---|" + ("---|" if churn_col else "") + "---|"
rows = [head, sep]
for i, m in enumerate(top, 1):
fs = "; ".join("%s %s" % (x["code"], x["message"]) for x in m["findings"])
rows.append("| %d | `%s` | %s:%d | %d | %d | %d | %d |%s %s |" % (i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"],
(" %d |" % m.get("churn", 0)) if churn_col else "", fs))
rows.append("")
rows.append("%d functions, average CC %.1f, %d flagged at %s+." % (n, avg, len(flagged), o.min_severity))
return "\n".join(rows)
lines = ["Complexity hotspots: %d functions, average CC %.1f, %d flagged (min severity %s)" % (n, avg, len(flagged), o.min_severity), ""]
for i, m in enumerate(top, 1):
extra = (" churn=%d" % m["churn"]) if "churn" in m else ""
lines.append("%2d. %s (%s:%d) cc=%d depth=%d lines=%d params=%d returns=%d%s score=%d" % (
i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"], m["returns"], extra, m["score"]))
for x in m["findings"]:
lines.append(" [%s] %s %s" % (x["severity"].upper(), x["code"], x["message"]))
if not top: lines.append("No functions above the thresholds.")
for e in errors: lines.append("PARSE ERROR " + e)
return "\n".join(lines)
def parser():
p = argparse.ArgumentParser(description="Find complex, frequently changed Python functions.")
p.add_argument("paths", nargs="*")
p.add_argument("--format", choices=["text", "md", "json"], default="text")
p.add_argument("--min-severity", choices=list(SEV), default="low")
p.add_argument("--churn", type=int, metavar="DAYS", help="add git churn for the last DAYS days")
p.add_argument("--churn-min", type=int, default=5)
p.add_argument("--top", type=int, default=0, help="show only the top N flagged functions")
p.add_argument("--cc-warn", type=int, default=10)
p.add_argument("--cc-high", type=int, default=15)
p.add_argument("--max-depth", type=int, default=4)
p.add_argument("--max-lines", type=int, default=60)
p.add_argument("--max-params", type=int, default=6)
p.add_argument("--max-returns", type=int, default=6)
p.add_argument("--self-test", action="store_true")
return p
def self_test():
o = parser().parse_args([])
def cc(src):
return {m["function"]: m for m in analyze_source(src)}
checks = []
def check(name, cond): checks.append((name, bool(cond)))
m = cc("def f():\n return 1\n")["f"]
check("straight-line function has cc 1", m["cc"] == 1 and m["depth"] == 0)
m = cc("def f(x):\n if x:\n return 1\n return 2\n")["f"]
check("one if gives cc 2", m["cc"] == 2 and m["returns"] == 2)
m = cc("def f(x):\n if x == 1:\n a = 1\n elif x == 2:\n a = 2\n elif x == 3:\n a = 3\n else:\n a = 0\n return a\n")["f"]
check("elif chain adds 1 each, depth stays 1", m["cc"] == 4 and m["depth"] == 1)
m = cc("def f(a, b, c):\n return a and b or c\n")["f"]
check("boolean operators add per operand", m["cc"] == 3)
m = cc("def f(xs):\n return [x for x in xs if x if x > 2]\n")["f"]
check("comprehension and its ifs count", m["cc"] == 4)
m = cc("def f():\n try:\n g()\n except ValueError:\n pass\n except KeyError:\n pass\n")["f"]
check("each except handler counts", m["cc"] == 3)
m = cc("def f(x):\n return 1 if x else 2\n")["f"]
check("ternary counts", m["cc"] == 2)
m = cc("def f(x):\n while x:\n for i in x:\n if i:\n with open(i) as h:\n pass\n")["f"]
check("nesting depth 4", m["depth"] == 4 and m["cc"] == 4)
r = cc("def outer():\n def inner(x):\n if x: return 1\n return inner\n")
check("nested function measured separately", r["outer"]["cc"] == 1 and r["outer.inner"]["cc"] == 2)
r = cc("class A:\n def m(self, a, b):\n pass\n")
check("method name and self excluded from params", r["A.m"]["params"] == 2)
r = cc("def f(a, b, c, d, e, f, *args, **kw):\n pass\n")
check("varargs counted as params", r["f"]["params"] == 8)
m = cc("def f(x):\n assert x\n return x\n")["f"]
check("assert counts", m["cc"] == 2)
if sys.version_info >= (3, 10):
m = cc("def f(x):\n match x:\n case 1:\n return 1\n case _:\n return 0\n")["f"]
check("match cases count", m["cc"] == 3)
else:
check("match cases count (skipped < 3.10)", True)
big = "def big(x):\n" + "".join(" if x == %d:\n return %d\n" % (i, i) for i in range(16)) + " return -1\n"
m = cc(big)["big"]
fs = [c for c, _, _ in findings_for(m, o)]
check("cc 17 gives H01 and many returns H06", m["cc"] == 17 and "H01" in fs and "H06" in fs and "H02" not in fs)
m = dict(cc=11, depth=1, lines=10, params=1, returns=1)
check("cc 11 gives H02 only", [c for c, _, _ in findings_for(m, o)] == ["H02"])
m = dict(cc=11, depth=1, lines=10, params=1, returns=1, churn=7)
check("complex + churn gives H07", "H07" in [c for c, _, _ in findings_for(m, o)])
m = dict(cc=3, depth=1, lines=10, params=1, returns=1, churn=40)
check("simple + churn is not a hotspot", findings_for(m, o) == [])
m = dict(cc=2, depth=5, lines=80, params=7, returns=1)
check("depth, length, params flagged", [c for c, _, _ in findings_for(m, o)] == ["H03", "H04", "H05"])
try:
analyze_source("def broken(:\n")
check("syntax error raised", False)
except SyntaxError:
check("syntax error raised", True)
ok = all(c for _, c in checks)
for n, c in checks:
print(("PASS " if c else "FAIL ") + n)
print("%d/%d checks passed" % (sum(c for _, c in checks), len(checks)))
return 0 if ok else 1
def main(argv=None):
o = parser().parse_args(argv)
if o.self_test:
return self_test()
if not o.paths:
parser().print_usage(sys.stderr); return 2
for p in o.paths:
if not os.path.exists(p):
print("no such path: " + p, file=sys.stderr); return 2
results, errors = run(o.paths, o)
print(render(results, errors, o))
if errors and not results:
return 2
minsev = SEV[o.min_severity]
return 1 if any(SEV[x["severity"]] >= minsev for m in results for x in m["findings"]) else 0
if __name__ == "__main__":
sys.exit(main())
Opinionated preferences for 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.75Opinionated preferences for designing and publishing Rust library crates: API shape, errors, features, docs and release checks.
# Rust Library Crate taste of a maintainer who publishes reusable crates - Keep the public API small and re-export the important types from the crate root. Confidence: 0.85 - Define one error enum per crate with `thiserror`, and never return `anyhow::Error` from a library. Confidence: 0.90 - Mark public enums and config structs `#[non_exhaustive]` when new variants or fields are likely. Confidence: 0.80 - Accept flexible inputs like `impl AsRef<str>` or `impl Into<String>` and return concrete types. Confidence: 0.80 - Use the builder pattern for types with more than a few optional settings. Confidence: 0.80 - Put optional integrations behind additive cargo features; never make a feature remove functionality. Confidence: 0.90 - Keep the default feature set minimal and support `no_std` when the domain allows it. Confidence: 0.70 - Gate `serde` derives behind a `serde` feature instead of making it a hard dependency. Confidence: 0.85 - Declare `rust-version` in Cargo.toml and test the MSRV in CI. Confidence: 0.85 - Run `cargo clippy -- -D warnings`, `cargo fmt --check` and `cargo test --all-features` on every PR. Confidence: 0.90 - Check semver breakage with `cargo-semver-checks` before each release. Confidence: 0.85 - Write doc comments with runnable examples on every public item; doctests are part of the test suite. Confidence: 0.90 - Add `#![deny(missing_docs)]` and `#![forbid(unsafe_code)]` unless the crate truly needs unsafe. Confidence: 0.80 - When unsafe is needed, wrap it in a tiny module with `// SAFETY:` comments and run Miri in CI. Confidence: 0.85 - Implement common traits like `Debug`, `Clone`, `PartialEq` and `Default` on public types where they make sense. Confidence: 0.85 - Make public types `Send` and `Sync` when possible and assert it in a test. Confidence: 0.75 - Avoid forcing an async runtime on users; keep core logic runtime-agnostic. Confidence: 0.80 - Add property tests with `proptest` for parsers and encoders. Confidence: 0.75 - Benchmark hot paths with `criterion` before claiming performance improvements. Confidence: 0.75 - Release with `cargo-release` or release-plz and keep a CHANGELOG.md in Keep a Changelog format. Confidence: 0.80 - Dual-license under MIT OR Apache-2.0 to match the Rust ecosystem. Confidence: 0.80
Opinionated preferences for building, testing and shipping fast, script-friendly command-line tools in Go.
# Go CLI taste of a developer who ships single-binary command-line tools - Use Cobra for tools with subcommands; use the standard `flag` package for single-purpose tools. Confidence: 0.80 - Keep `main.go` tiny: build the root command, run it, and map the returned error to an exit code. Confidence: 0.90 - Put command wiring in `cmd/` and real logic in `internal/` packages that know nothing about flags or the terminal. Confidence: 0.85 - Return errors from `RunE` instead of calling `os.Exit` or `log.Fatal` inside commands. Confidence: 0.90 - Exit with 0 on success, 1 for runtime failures and 2 for usage errors. Confidence: 0.85 - Write results to stdout and diagnostics to stderr; never mix progress output into data streams. Confidence: 0.95 - Offer `--output json` for scripting and keep the JSON shape stable across minor versions. Confidence: 0.85 - Detect a TTY before using colors, spinners or interactive prompts, and respect `NO_COLOR`. Confidence: 0.90 - Read configuration in a clear order: flags, then environment variables, then config file, then defaults. Confidence: 0.85 - Store config files under `os.UserConfigDir()` and caches under `os.UserCacheDir()`, not in the home directory root. Confidence: 0.80 - Pass `context.Context` through every operation and cancel it on SIGINT/SIGTERM with `signal.NotifyContext`. Confidence: 0.90 - Use `log/slog` for debug logging behind a `--verbose` flag; keep default output quiet. Confidence: 0.80 - Inject `io.Writer`s and the environment into commands so they can be tested without touching the real terminal. Confidence: 0.85 - Write table-driven tests for logic and golden-file tests for command output, with an `-update` flag to refresh goldens. Confidence: 0.85 - Build static binaries with `CGO_ENABLED=0` and `-trimpath` whenever the tool doesn't need cgo. Confidence: 0.85 - Embed version, commit and build date via `-ldflags` or `debug.ReadBuildInfo`, and expose them in a `version` command. Confidence: 0.90 - Release with GoReleaser: cross-compiled archives, checksums and a Homebrew tap from one tagged commit. Confidence: 0.80 - Ship shell completions for bash, zsh and fish generated from the command tree. Confidence: 0.80 - Make destructive commands ask for confirmation in a TTY and require `--yes` or `--force` in scripts. Confidence: 0.90 - Keep dependencies few and run `go vet`, `staticcheck` and `govulncheck` in CI. Confidence: 0.85 - Keep startup fast: no network calls or heavy initialization before a command actually needs them. Confidence: 0.80
Opinionated rules for storing, parsing, formatting and testing dates, times and time zones in application code.
# Date and Time Handling taste of a backend developer who has debugged too many off-by-one-hour bugs
- Store instants as UTC timestamps (`timestamptz` in PostgreSQL), never as local wall-clock time without an offset. Confidence: 0.95
- Keep "instant" and "calendar date" as different types: a birthday or due date is a plain date, not midnight UTC. Confidence: 0.90
- Store the user's IANA time zone name (`Europe/Istanbul`), never a fixed offset like `+03:00`, because offsets change with DST and politics. Confidence: 0.90
- Convert to the user's zone only at the edges: rendering, parsing user input and scheduling. Confidence: 0.90
- Serialize timestamps in APIs as ISO 8601 / RFC 3339 strings with an explicit `Z` or offset; avoid bare epoch numbers in public payloads. Confidence: 0.85
- Never parse dates with ad-hoc regexes or `new Date(string)` on non-ISO input; use a strict parser with an explicit format. Confidence: 0.90
- Prefer the Temporal API (or a polyfill) for new JavaScript/TypeScript code; fall back to date-fns or Luxon, not Moment.js. Confidence: 0.80
- Format for humans with `Intl.DateTimeFormat` and the user's locale instead of hand-built strings. Confidence: 0.85
- Store future local events (meetings, reminders) as local date-time plus zone, and compute the UTC instant when needed, so DST rule changes don't shift them. Confidence: 0.85
- Model ranges as half-open intervals `[start, end)` to avoid overlap and double-counting at boundaries. Confidence: 0.90
- Do day arithmetic in calendar terms ("add 1 day" in the user's zone), not by adding 86,400 seconds. Confidence: 0.85
- Use a monotonic clock (`performance.now()`, `time.monotonic()`) for measuring durations and timeouts, never wall-clock time. Confidence: 0.95
- Inject a clock dependency instead of calling `Date.now()` directly in business logic, so tests can freeze and advance time. Confidence: 0.90
- Add tests around DST transitions, leap days, month ends and the year boundary for any scheduling code. Confidence: 0.85
- Run the test suite at least once with a non-UTC `TZ` environment variable to catch hidden local-time assumptions. Confidence: 0.75
- Keep server, database and container clocks in UTC and synced with NTP. Confidence: 0.90
- Never compare or sort dates as formatted strings unless they are fixed-width ISO 8601 in the same zone. Confidence: 0.80
- Keep the time zone database (tzdata) up to date in runtimes and container images. Confidence: 0.75
- Show relative times ("3 hours ago") only alongside an absolute timestamp available on hover or in detail views. Confidence: 0.65
- Name fields with their meaning and unit: `createdAt`, `expiresAt`, `timeoutMs`, never just `time` or `date`. Confidence: 0.85
- Treat leap seconds as the platform's problem; don't build application logic that depends on them. Confidence: 0.70
Opinionated conventions for building Python command-line tools that are pleasant to use, easy to test and simple to install.
# Python CLI taste of a tooling developer who ships small, well-behaved command-line apps - Build the CLI with Typer for typed commands, or Click when fine control over parsing is needed; avoid hand-rolled `argparse` trees for multi-command tools. Confidence: 0.80 - Expose the command through `[project.scripts]` in `pyproject.toml` so it installs as a real executable. Confidence: 0.95 - Recommend installing with `pipx` or `uv tool install`, never `sudo pip install`. Confidence: 0.90 - Keep `main()` thin: parse arguments, call a plain library function, map its result to an exit code. Confidence: 0.90 - Return exit code 0 on success, 1 for expected failures, 2 for usage errors, and never call `sys.exit` deep inside library code. Confidence: 0.90 - Write results to stdout and logs, progress and errors to stderr so output stays pipe-friendly. Confidence: 0.95 - Offer `--json` output for scripting and keep the default output human-readable. Confidence: 0.85 - Detect a TTY before printing colors, spinners or progress bars, and respect `NO_COLOR`. Confidence: 0.90 - Use Rich for tables and progress only in interactive mode; plain text when piped. Confidence: 0.75 - Make every destructive command support `--dry-run` and ask for confirmation unless `--yes` is passed. Confidence: 0.90 - Read configuration in a fixed order: flags, then environment variables, then a config file in the XDG config directory, then defaults. Confidence: 0.85 - Use `--verbose`/`-v` (repeatable) and `--quiet`/`-q` mapped to standard `logging` levels. Confidence: 0.80 - Show a friendly one-line error by default and the full traceback only with `--debug`. Confidence: 0.85 - Handle `KeyboardInterrupt` cleanly with exit code 130 and no traceback. Confidence: 0.85 - Keep startup fast: import heavy modules lazily inside the commands that need them. Confidence: 0.80 - Provide `--version` that reads from `importlib.metadata`, not a hardcoded string. Confidence: 0.90 - Accept `-` as stdin/stdout for file arguments and use `pathlib.Path` everywhere. Confidence: 0.80 - Test commands with Typer's or Click's `CliRunner`, asserting on exit code, stdout and stderr separately. Confidence: 0.90 - Snapshot-test help text so accidental option renames show up in review. Confidence: 0.65 - Ship shell completion for bash, zsh and fish through the framework's built-in completion support. Confidence: 0.75 - Write help text with a short example for every command; examples beat long option descriptions. Confidence: 0.80 - Lock dependencies for releases but keep runtime requirements minimal, ideally a handful of packages. Confidence: 0.75
Opinionated Kotlin coroutine conventions for Android and JVM backends with structured concurrency, clear dispatchers and testable flows.
# Kotlin Coroutines taste of an Android and JVM engineer who wants structured concurrency everywhere - Launch coroutines only from a scope tied to a lifecycle, such as `viewModelScope`, `lifecycleScope` or a scope owned by a service. Confidence: 0.95 - Never use `GlobalScope`; if work must outlive a screen, hand it to an application-level scope or WorkManager. Confidence: 0.95 - Make suspend functions main-safe: the function itself switches to `Dispatchers.IO` or `Default` with `withContext`, not the caller. Confidence: 0.90 - Inject dispatchers through the constructor so tests can replace them with a `TestDispatcher`. Confidence: 0.90 - Use `coroutineScope` for parallel work that should fail together, and `supervisorScope` only when children must fail independently. Confidence: 0.85 - Never swallow `CancellationException`; rethrow it from every broad `catch` block. Confidence: 0.95 - Prefer `async`/`await` only for real parallel decomposition, not as a replacement for a plain suspend call. Confidence: 0.80 - Expose UI state as `StateFlow` and one-off events through a `Channel` or a state field that the UI consumes. Confidence: 0.80 - Collect flows in the UI with `repeatOnLifecycle(Lifecycle.State.STARTED)` or `collectAsStateWithLifecycle`. Confidence: 0.90 - Use `stateIn` with `SharingStarted.WhileSubscribed(5_000)` so upstream work stops when nobody is watching. Confidence: 0.80 - Keep flows cold by default and convert to hot with `shareIn` or `stateIn` only at a clear boundary. Confidence: 0.80 - Apply `flowOn` to move upstream work off the main thread instead of wrapping collectors in `withContext`. Confidence: 0.80 - Wrap blocking Java APIs in `withContext(Dispatchers.IO)` and never call `runBlocking` in production code paths. Confidence: 0.90 - Add timeouts to network and database calls with `withTimeout` or `withTimeoutOrNull`, not hand-rolled delays. Confidence: 0.75 - Check `ensureActive()` or `yield()` inside long CPU loops so cancellation actually stops the work. Confidence: 0.80 - Protect shared mutable state with a `Mutex` or confine it to a single coroutine, never a plain `synchronized` block around a suspend call. Confidence: 0.85 - Install a `CoroutineExceptionHandler` at the root scope to log crashes, but handle expected errors with `Result` or sealed types. Confidence: 0.75 - Test coroutines with `runTest` and virtual time, and test flows with Turbine. Confidence: 0.85 - Name important coroutines with `CoroutineName` so logs and debugger output stay readable. Confidence: 0.65 - Keep suspend functions free of `launch` side effects; a function that starts background work should say so in its name. Confidence: 0.75
Opinionated Go concurrency conventions for services where every goroutine has an owner, a context and a clean way to stop.
# Go Concurrency taste of a backend engineer who wants goroutines that never leak - Start a goroutine only when you know exactly how and when it will stop. Confidence: 0.95 - Pass a `context.Context` as the first argument to every function that blocks or does I/O, and honor its cancellation. Confidence: 0.95 - Use `errgroup.WithContext` to run related goroutines together so the first error cancels the rest. Confidence: 0.90 - Prefer plain synchronous APIs and let the caller add concurrency, instead of spawning goroutines inside library code. Confidence: 0.85 - Only the sender closes a channel, and only when no other sender can still write to it. Confidence: 0.90 - Use unbuffered channels by default; add a buffer only with a measured reason and a comment explaining its size. Confidence: 0.75 - Protect shared state with a `sync.Mutex` when it is simpler than a channel; channels are for passing ownership, not for every lock. Confidence: 0.85 - Keep the mutex right next to the fields it guards and never copy a struct that contains one. Confidence: 0.85 - Bound fan-out with a worker pool or `errgroup.SetLimit` instead of one goroutine per item. Confidence: 0.85 - Every `select` that waits on work also waits on `ctx.Done()`. Confidence: 0.90 - Use `time.NewTimer` or `context.WithTimeout` instead of `time.After` inside loops. Confidence: 0.75 - Use `sync.Once` or `sync.OnceValue` for lazy initialization, never a hand-rolled boolean flag. Confidence: 0.80 - Reach for `sync/atomic` types only for simple counters and flags, not for complex invariants. Confidence: 0.75 - Avoid `sync.Map` unless profiling shows lock contention on a read-heavy map. Confidence: 0.70 - Recover panics at goroutine boundaries in long-running servers and turn them into logged errors. Confidence: 0.75 - Run all tests with `-race` in CI, and treat any data race report as a release blocker. Confidence: 0.95 - Check for leaked goroutines in tests with `goleak`. Confidence: 0.70 - Make shutdown graceful: stop accepting work, drain in-flight jobs, then exit with a deadline. Confidence: 0.90 - Do not use `context.Value` for optional parameters; it is only for request-scoped data like trace IDs. Confidence: 0.85 - Document in the function comment whether a type is safe for concurrent use. Confidence: 0.80
Opinionated rules for writing regular expressions that stay readable, safe and well tested instead of turning into line noise.
# Regular Expressions taste of a developer who wants regexes people can still read - Reach for a real parser for HTML, JSON, CSV, URLs and email headers; a regex is the wrong tool there. Confidence: 0.95 - Prefer plain string methods like `startsWith`, `includes` or `split` when they do the job. Confidence: 0.85 - Anchor patterns with `^` and `$` (or `\A` and `\z`) when validating a whole value. Confidence: 0.90 - Use named capture groups instead of counting numbered groups. Confidence: 0.85 - Use non-capturing groups `(?:...)` when you only need grouping, not the captured value. Confidence: 0.75 - Write long patterns in verbose mode with comments, such as `re.VERBOSE` in Python or the `x` flag where supported. Confidence: 0.80 - Prefer specific character classes like `[^"]*` over a lazy `.*?` to make intent clear and matching faster. Confidence: 0.80 - Avoid nested quantifiers like `(a+)+`; they invite catastrophic backtracking and ReDoS. Confidence: 0.95 - Never run user-supplied patterns without a timeout or a linear-time engine like RE2. Confidence: 0.90 - Put a length limit on input before matching it against any non-trivial pattern. Confidence: 0.85 - Compile patterns once at module level and reuse them instead of rebuilding them in a loop. Confidence: 0.75 - Escape dynamic text with `re.escape` or an equivalent helper before putting it into a pattern. Confidence: 0.95 - Turn on the Unicode flag (`u` or `v` in JavaScript) when the input may contain non-ASCII text. Confidence: 0.80 - Remember that `\d` and `\w` can match non-ASCII digits and letters in some engines; use `[0-9]` when you mean ASCII. Confidence: 0.70 - Keep each regex to one job; two simple patterns beat one clever pattern. Confidence: 0.80 - Give every important pattern a table-driven test with strings that must match and strings that must not. Confidence: 0.90 - Add a comment with a real example input above any pattern longer than about twenty characters. Confidence: 0.80 - Do not validate email addresses with a giant regex; check for one `@` and send a confirmation email. Confidence: 0.85 - Use lookarounds sparingly; if a pattern needs several of them, split the logic into code. Confidence: 0.70 - Try patterns in a tester like regex101 with the right engine selected before shipping them. Confidence: 0.70
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())
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
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
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
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