Estimates what employee turnover really costs per team: recruiting, interviews, vacancy, ramp-up, onboarding and offboarding from a simple CSV, flags hot spots, and tests whether a retention program pays for itself with savings and break-even scenarios. Stdlib Python.
---
name: employee-turnover-cost-calculator
description: Estimates what employee turnover really costs per team: recruiting, interviews, vacancy, ramp-up, onboarding and offboarding from a simple CSV, flags hot spots, and tests whether a retention program pays for itself with savings and break-even scenarios. Stdlib Python.
---
# Employee Turnover Cost Calculator
You help business managers, founders and HR leads put a credible number on employee turnover. "People keep leaving" rarely wins a budget discussion; "Sales turnover cost us about 150,000 last year, and a 25,000 retention program breaks even if it keeps 1.4 people" does. You turn a few numbers per team into a transparent cost estimate, show which part of the cost dominates, and help decide whether a retention investment is worth it.
The numbers are estimates built from stated assumptions, not accounting facts. You always show the assumptions, round sensibly and invite the user to replace defaults with their own data. You never ask for or handle personal data about individual employees: team-level aggregates are enough.
## Files in this skill
- `scripts/turnover_cost.py` - reads a team CSV and an assumptions JSON, computes cost per leaver (recruiting, interviewing, vacancy, ramp-up, onboarding, offboarding), annual and regrettable cost per team and in total; flags T01-T04 and invalid rows (E01); `--reduce-pct` savings scenario, `--program-cost` break-even for a retention program; `--format text|md|csv|json`; `--self-test` runs 22 checks (Python 3.8+ standard library only)
- `references/cost-model.md` - every cost component, the formulas, typical ranges and where to get the inputs
- `references/retention-levers.md` - what usually drives turnover per situation and which retention actions fit, with rough costs
- `templates/turnover-cost-brief.md` - a one-page brief for leadership
- `examples/teams.csv` + `examples/assumptions.json` - a fictional 93-person company with six teams
## Workflow
### 1. Gather inputs
Ask for, per team or role: average headcount over the last 12 months, number of leavers (voluntary and involuntary, or say which), how many were regrettable (people you wanted to keep), average salary, typical time to fill a role (calendar days), months until a new hire is fully productive, and the main hiring channel. Then confirm the assumptions: currency, employer overhead on salary, agency fees or job-ad costs, interview hours per hire, onboarding and offboarding costs, how much work is lost while a seat is empty, and productivity during ramp-up. Use the defaults in `examples/assumptions.json` only when the user has no better number, and say so.
### 2. Run the calculation
```
python3 scripts/turnover_cost.py teams.csv --assumptions assumptions.json
python3 scripts/turnover_cost.py teams.csv --assumptions assumptions.json --reduce-pct 20 --program-cost 25000
python3 scripts/turnover_cost.py teams.csv --assumptions assumptions.json --format md > turnover.md
python3 scripts/turnover_cost.py teams.csv --assumptions assumptions.json --format csv
python3 scripts/turnover_cost.py --self-test
```
Exit code 0 = no flags, 1 = flags or invalid rows, 2 = unreadable input or missing columns.
| Code | Meaning |
|---|---|
| T01 | turnover rate at or above `high_turnover_pct` (default 25%) |
| T02 | more than half of the team's leavers (2 or more) were regrettable |
| T03 | cost per leaver at or above 50% of annual salary |
| T04 | time to fill at or above `slow_fill_days` (default 60) |
| E01 | invalid row (non-numeric, regrettable > leavers, unknown hiring channel, implausible numbers) |
### 3. Interpret
- Look at both the total and the mix: high-volume, low-cost turnover (warehouse, support) and low-volume, high-cost turnover (engineering, sales) need different responses.
- Check which component dominates (`By part`): ramp-up and vacancy usually outweigh recruiting fees, which is why "cheaper recruiting" rarely fixes the problem.
- Regrettable cost is the number to act on; some turnover is healthy.
- Run a sensitivity check: re-run with ramp-up loss and vacancy cost 20-30% lower; if the conclusion still holds, it is robust.
### 4. Decide on retention actions
Use `references/retention-levers.md` to match the likely drivers (pay, manager quality, workload, growth, schedule) to actions, estimate their yearly cost, and use `--program-cost` to show the break-even reduction. Prefer a pilot in the team with the highest regrettable cost and a measurable target (for example "cut Sales leavers from 4 to 2 within 12 months").
### 5. Report
Fill `templates/turnover-cost-brief.md`: the headline number with assumptions, the team table, the top two hot spots, the proposed action with its break-even, and how to measure progress.
## Example
```
python3 scripts/turnover_cost.py examples/teams.csv --assumptions examples/assumptions.json --reduce-pct 20 --program-cost 25000
```
Result: about EUR 540k per year for 31 leavers (33.3% turnover, avg EUR 17.4k per leaver), EUR 298k of it regrettable. Engineering (EUR 184k, 59% of salary per leaver, slow to fill) and Sales (EUR 153k, 40% turnover) are the hot spots; a EUR 25k program breaks even at 4.6% less turnover, and a 20% reduction would save about EUR 108k.
## Limits
- Estimates only; hidden costs (lost customers, team morale, knowledge loss) are not included and usually make the real cost higher.
- Team averages hide individual differences; do not use the output to judge individual employees.
- Vacancy and ramp-up assumptions drive most of the result: agree them with finance before presenting.
FILE:references/cost-model.md
# Turnover cost model
All amounts per leaver unless stated. The script uses exactly these formulas.
| Component | Formula | Typical range | Where to get the input |
|---|---|---|---|
| Recruiting | agency fee % x salary, or fixed channel cost (job ads, referral bonus) | agency 15-30% of salary; job boards 300-2,000; referral bonus 500-3,000 | finance, recruiting invoices |
| Interviewing | interview hours per hire x loaded hourly cost of interviewers | 8-25 hours | hiring managers, ATS stages |
| Vacancy | working days empty (calendar days x 5/7) x daily loaded pay x vacancy cost % | 30-80% of daily pay, depending on how much work is covered by others or overtime | time-to-fill from ATS; ask managers how much work is really lost |
| Ramp-up | ramp months / 12 x loaded salary x productivity loss % | 1-2 months for hourly roles, 3-6 for skilled roles, 6-9 for senior or sales roles with long cycles; average loss 40-60% over the ramp | managers |
| Onboarding | fixed: equipment, licences, training, buddy time, admin | 500-4,000 | IT, HR |
| Offboarding | fixed: exit admin, access removal, handover time, final pay processing | 200-1,000 | HR, IT |
Loaded salary = salary x (1 + employer overhead %). Overhead covers employer taxes, benefits and pension contributions (often 15-35%).
Daily loaded pay = loaded salary / working days per year (around 220).
Turnover rate = leavers in 12 months / average headcount over the same months.
## Cross-check
Total cost per leaver usually lands between 20% and 60% of annual salary for most roles, and can exceed 100% for senior, specialist or quota-carrying roles once lost revenue is included. If the result is far outside that range, check the inputs (monthly vs annual salary, days vs months).
## What is not included
- Lost revenue or customers (sales roles, account managers): add separately if the business can estimate it.
- Overtime and burnout of remaining colleagues, and knock-on resignations.
- Knowledge loss and mistakes made by new hires.
- Severance and legal costs for involuntary exits.
Mention these as reasons the real cost is likely higher, without inventing numbers.
## Data hygiene
- Use team-level aggregates; never collect names or reasons for individual leavers in this calculation.
- Count interns, fixed-term contracts that ended as planned, and internal transfers separately or exclude them.
- Twelve months is the standard window; for small teams (under 10 people) one leaver swings the rate a lot, so look at two or three years.
FILE:references/retention-levers.md
# Retention levers
Match the likely driver to an action. Ask exit and stay interview themes (aggregated) before choosing.
| Likely driver | Signals | Actions | Rough yearly cost |
|---|---|---|---|
| Pay below market | offers from competitors, leavers get 15%+ raises | market pay review for the at-risk roles, clear salary bands, retention bonus for critical people | 3-8% of the affected payroll |
| Manager relationship | turnover concentrated under one or two managers | manager training, regular 1:1s, skip-level conversations, coaching | 1,000-3,000 per manager |
| Workload and burnout | overtime, sick leave rising, leavers mention stress | hire ahead of demand, cut low-value work, protect focus time, fair on-call rotas | varies; often cheaper than one leaver |
| No growth path | good people leave after 18-30 months | career ladders, internal mobility, learning budget, stretch projects | 500-2,000 per person |
| Schedule and flexibility | hourly roles, parents, long commutes | predictable shifts published early, shift swapping, hybrid days where possible | low |
| Bad hiring fit | many leavers in the first 90 days | clearer job previews, structured interviews, better onboarding and a buddy | 500-1,500 per hire |
| Recognition | leavers mention feeling invisible | regular, specific recognition; transparent promotion criteria | low |
## Running a pilot
1. Pick the team with the highest regrettable cost.
2. Choose one or two actions that fit its driver.
3. Set a target in leavers (not only percent) and a review date (6 and 12 months).
4. Compare with a similar team that did not get the action, if possible.
5. Re-run the calculator with the new numbers and report the saving against the program cost.
## Break-even reasoning
Program break-even (leavers avoided) = program cost / average cost per leaver. If keeping one or two people pays for the program, it is usually worth piloting even with uncertain assumptions.
FILE:templates/turnover-cost-brief.md
# Turnover cost brief: {company or department}, {period}
## Headline
Turnover cost us an estimated **{currency} {annual_cost}** in the last 12 months: {leavers} leavers, {turnover_pct}% turnover, about {currency} {avg_cost_per_leaver} per leaver. **{currency} {regrettable_cost}** of it came from people we wanted to keep.
## Where it hurts
| Team | Leavers | Turnover | Cost per leaver | Annual cost | Why |
|---|---|---|---|---|---|
| {team} | {n} | {pct}% | {cost} ({pct_salary}% of salary) | {annual} | {flags in plain words} |
Biggest cost component: {ramp-up / vacancy / recruiting} ({share}% of the total).
## Proposal
{Action, team, owner}. Cost: {currency} {program_cost} per year. It breaks even if it prevents **{break_even_leavers} leavers** ({break_even_pct}% less turnover). A {reduce_pct}% reduction would save about {currency} {annual_saving} ({net} net).
## How we will measure it
- Leavers and regrettable leavers per quarter in {team}
- Time to fill and 90-day attrition of new hires
- Review on {date}; stop or scale based on the result
## Assumptions
{overhead %, channel costs, interview hours, vacancy %, ramp months and loss %, onboarding/offboarding costs}. Not included: lost revenue, overtime, knowledge loss, severance, so the real cost is likely higher.
FILE:examples/teams.csv
team,role,avg_headcount,leavers_12m,regrettable_leavers,avg_salary,time_to_fill_days,ramp_months,hiring_channel
Customer Support,Support Agent,24,9,4,38000,35,2,job_board
Engineering,Software Engineer,18,4,3,78000,62,4,agency
Sales,Account Executive,10,4,2,62000,48,5,agency
Warehouse,Picker and Packer,30,13,3,31000,14,1,job_board
Finance,Accountant,5,1,1,58000,55,3,referral
Marketing,Content Marketer,6,0,0,52000,40,3,job_board
FILE:examples/assumptions.json
{
"currency": "EUR",
"working_days_per_year": 220,
"employer_overhead_pct": 22,
"hiring_channels": {
"agency": {"fee_pct_of_salary": 20, "fixed_cost": 0},
"job_board": {"fee_pct_of_salary": 0, "fixed_cost": 900},
"referral": {"fee_pct_of_salary": 0, "fixed_cost": 1500}
},
"interview_hours_per_hire": 14,
"interviewer_hourly_cost": 55,
"onboarding_cost_per_hire": 1800,
"offboarding_cost_per_leaver": 400,
"vacancy_cost_pct_of_daily_pay": 60,
"ramp_productivity_loss_pct": 50,
"high_turnover_pct": 25,
"slow_fill_days": 60
}
FILE:scripts/turnover_cost.py
#!/usr/bin/env python3
"""turnover_cost.py - estimate what employee turnover costs a business, per team and in total (standard library only).
Input: a CSV with one row per team or role (see examples/teams.csv) and an assumptions JSON (examples/assumptions.json).
Per leaver the cost is the sum of:
recruiting agency fee (% of salary) or fixed channel cost (job ads, referral bonus)
interviewing interview hours x interviewer hourly cost
vacancy days the seat is empty (time_to_fill_days converted to working days) x daily pay x vacancy_cost_pct
ramp-up ramp_months / 12 x loaded salary x ramp_productivity_loss_pct
onboarding fixed onboarding cost (equipment, training, admin)
offboarding fixed offboarding cost (exit admin, access removal, handover)
Loaded salary = avg_salary x (1 + employer_overhead_pct / 100).
Flags: T01 turnover rate >= high_turnover_pct, T02 more than half of 2+ leavers were regrettable,
T03 cost per leaver >= 50% of salary, T04 time to fill >= slow_fill_days, E01 invalid row.
Scenarios: --reduce-pct P shows the saving if turnover fell by P percent; --program-cost C (per year) shows
whether a retention program pays for itself and the break-even reduction.
Usage:
python3 turnover_cost.py teams.csv --assumptions assumptions.json [--format text|md|csv|json]
[--reduce-pct 20] [--program-cost 15000]
python3 turnover_cost.py --self-test
Exit code: 0 = no flags, 1 = flags present (T01-T04) or invalid rows, 2 = bad input file.
"""
import argparse, csv, io, json, sys
REQUIRED = ["team", "role", "avg_headcount", "leavers_12m", "regrettable_leavers", "avg_salary", "time_to_fill_days", "ramp_months", "hiring_channel"]
DEFAULTS = {"currency": "EUR", "working_days_per_year": 220, "employer_overhead_pct": 20, "hiring_channels": {},
"interview_hours_per_hire": 12, "interviewer_hourly_cost": 50, "onboarding_cost_per_hire": 1500,
"offboarding_cost_per_leaver": 300, "vacancy_cost_pct_of_daily_pay": 50, "ramp_productivity_loss_pct": 50,
"high_turnover_pct": 25, "slow_fill_days": 60}
def load_assumptions(path):
a = dict(DEFAULTS)
if path:
with open(path, encoding="utf-8") as fh:
a.update(json.load(fh))
return a
def parse_rows(text):
reader = csv.DictReader(io.StringIO(text))
missing = [c for c in REQUIRED if c not in (reader.fieldnames or [])]
if missing:
raise ValueError("missing columns: " + ", ".join(missing))
return list(reader)
def money(x):
return round(x + 0.0, 2)
def cost_row(row, a):
"""Return the cost breakdown and flags for one CSV row, or raise ValueError for invalid data."""
try:
hc = float(row["avg_headcount"]); leavers = int(row["leavers_12m"]); regret = int(row["regrettable_leavers"])
salary = float(row["avg_salary"]); fill = float(row["time_to_fill_days"]); ramp = float(row["ramp_months"])
except (TypeError, ValueError):
raise ValueError("non-numeric value")
if hc <= 0 or salary <= 0 or leavers < 0 or regret < 0 or fill < 0 or ramp < 0:
raise ValueError("values must be positive (headcount and salary > 0)")
if regret > leavers:
raise ValueError("regrettable_leavers > leavers_12m")
if leavers > hc * 3:
raise ValueError("leavers_12m more than 3x headcount - check the data")
channel = (row.get("hiring_channel") or "").strip()
ch = a["hiring_channels"].get(channel)
if ch is None:
raise ValueError("unknown hiring_channel %r" % channel)
loaded = salary * (1 + a["employer_overhead_pct"] / 100.0)
daily = loaded / a["working_days_per_year"]
working_days_vacant = fill * 5.0 / 7.0
parts = {
"recruiting": salary * ch.get("fee_pct_of_salary", 0) / 100.0 + ch.get("fixed_cost", 0),
"interviewing": a["interview_hours_per_hire"] * a["interviewer_hourly_cost"],
"vacancy": working_days_vacant * daily * a["vacancy_cost_pct_of_daily_pay"] / 100.0,
"ramp_up": ramp / 12.0 * loaded * a["ramp_productivity_loss_pct"] / 100.0,
"onboarding": float(a["onboarding_cost_per_hire"]),
"offboarding": float(a["offboarding_cost_per_leaver"]),
}
per_leaver = sum(parts.values())
rate = 100.0 * leavers / hc
flags = []
if rate >= a["high_turnover_pct"]:
flags.append("T01 turnover %.1f%% >= %s%%" % (rate, a["high_turnover_pct"]))
if leavers >= 2 and regret / leavers > 0.5:
flags.append("T02 %d of %d leavers regrettable" % (regret, leavers))
if per_leaver >= 0.5 * salary:
flags.append("T03 cost per leaver %.0f%% of salary" % (100 * per_leaver / salary))
if fill >= a["slow_fill_days"]:
flags.append("T04 time to fill %g days >= %s" % (fill, a["slow_fill_days"]))
return {"team": row["team"], "role": row["role"], "avg_headcount": hc, "leavers_12m": leavers, "regrettable_leavers": regret,
"turnover_pct": round(rate, 1), "avg_salary": salary, "cost_per_leaver": money(per_leaver),
"cost_per_leaver_pct_salary": round(100 * per_leaver / salary, 1),
"breakdown_per_leaver": {k: money(v) for k, v in parts.items()},
"annual_cost": money(per_leaver * leavers), "regrettable_cost": money(per_leaver * regret), "flags": flags}
def analyze(rows, a, reduce_pct=None, program_cost=None):
teams, errors = [], []
for i, row in enumerate(rows, start=2):
try:
teams.append(cost_row(row, a))
except ValueError as e:
errors.append({"line": i, "team": row.get("team", ""), "error": "E01 " + str(e)})
total = sum(t["annual_cost"] for t in teams)
leavers = sum(t["leavers_12m"] for t in teams)
hc = sum(t["avg_headcount"] for t in teams)
summary = {"currency": a["currency"], "teams": len(teams), "avg_headcount": hc, "leavers_12m": leavers,
"turnover_pct": round(100.0 * leavers / hc, 1) if hc else 0.0, "annual_cost": money(total),
"regrettable_cost": money(sum(t["regrettable_cost"] for t in teams)),
"avg_cost_per_leaver": money(total / leavers) if leavers else 0.0,
"cost_by_part": {k: money(sum(t["breakdown_per_leaver"][k] * t["leavers_12m"] for t in teams)) for k in ["recruiting", "interviewing", "vacancy", "ramp_up", "onboarding", "offboarding"]}}
if reduce_pct is not None:
summary["scenario"] = {"reduce_pct": reduce_pct, "leavers_avoided": round(leavers * reduce_pct / 100.0, 1), "annual_saving": money(total * reduce_pct / 100.0)}
if program_cost is not None:
be = 100.0 * program_cost / total if total else None
summary["program"] = {"program_cost": money(program_cost), "break_even_reduce_pct": round(be, 1) if be is not None else None,
"break_even_leavers_avoided": round(program_cost / summary["avg_cost_per_leaver"], 1) if leavers else None}
if reduce_pct is not None:
summary["program"]["net_saving_at_reduce_pct"] = money(total * reduce_pct / 100.0 - program_cost)
teams.sort(key=lambda t: -t["annual_cost"])
return {"summary": summary, "teams": teams, "errors": errors}
def fmt_money(x, cur):
return "%s %s" % (cur, "{:,.0f}".format(x))
def render(res, fmt):
s, cur = res["summary"], res["summary"]["currency"]
if fmt == "json":
return json.dumps(res, indent=2)
if fmt == "csv":
out = io.StringIO(); w = csv.writer(out, lineterminator="\n")
w.writerow(["team", "role", "avg_headcount", "leavers_12m", "turnover_pct", "cost_per_leaver", "cost_per_leaver_pct_salary", "annual_cost", "regrettable_cost", "flags"])
for t in res["teams"]:
w.writerow([t["team"], t["role"], t["avg_headcount"], t["leavers_12m"], t["turnover_pct"], t["cost_per_leaver"], t["cost_per_leaver_pct_salary"], t["annual_cost"], t["regrettable_cost"], "; ".join(t["flags"])])
return out.getvalue().rstrip("\n")
L = []
md = fmt == "md"
L.append(("## " if md else "") + "Turnover cost: %s per year (%d leavers, %.1f%% turnover, avg %s per leaver)" % (fmt_money(s["annual_cost"], cur), s["leavers_12m"], s["turnover_pct"], fmt_money(s["avg_cost_per_leaver"], cur)))
L.append(("- " if md else " ") + "Regrettable leavers cost: %s" % fmt_money(s["regrettable_cost"], cur))
L.append(("- " if md else " ") + "By part: " + ", ".join("%s %s" % (k, fmt_money(v, cur)) for k, v in s["cost_by_part"].items()))
if "scenario" in s:
sc = s["scenario"]
L.append(("- " if md else " ") + "Scenario: %g%% less turnover avoids %.1f leavers and saves %s per year" % (sc["reduce_pct"], sc["leavers_avoided"], fmt_money(sc["annual_saving"], cur)))
if "program" in s:
p = s["program"]
line = "Retention program %s/year breaks even at %.1f%% less turnover (%.1f leavers avoided)" % (fmt_money(p["program_cost"], cur), p["break_even_reduce_pct"], p["break_even_leavers_avoided"])
if "net_saving_at_reduce_pct" in p:
line += "; net %s at the scenario" % fmt_money(p["net_saving_at_reduce_pct"], cur)
L.append(("- " if md else " ") + line)
L.append("")
if md:
L.append("| Team | Role | Headcount | Leavers | Turnover | Cost per leaver | % of salary | Annual cost | Flags |")
L.append("|---|---|---|---|---|---|---|---|---|")
for t in res["teams"]:
L.append("| %s | %s | %g | %d | %.1f%% | %s | %.1f%% | %s | %s |" % (t["team"], t["role"], t["avg_headcount"], t["leavers_12m"], t["turnover_pct"], fmt_money(t["cost_per_leaver"], cur), t["cost_per_leaver_pct_salary"], fmt_money(t["annual_cost"], cur), "<br>".join(t["flags"]) or "-"))
else:
for t in res["teams"]:
L.append("%-18s %-20s hc %-5g leavers %-3d turnover %5.1f%% per leaver %-12s (%5.1f%% of salary) annual %s" % (t["team"], t["role"], t["avg_headcount"], t["leavers_12m"], t["turnover_pct"], fmt_money(t["cost_per_leaver"], cur), t["cost_per_leaver_pct_salary"], fmt_money(t["annual_cost"], cur)))
for f in t["flags"]:
L.append(" " + f)
for e in res["errors"]:
L.append(("- " if md else "") + "line %d %s: %s" % (e["line"], e["team"], e["error"]))
return "\n".join(L)
def self_test():
T = []
def check(name, cond): T.append((name, bool(cond)))
a = dict(DEFAULTS); a.update({"employer_overhead_pct": 0, "working_days_per_year": 200, "hiring_channels": {"fixed": {"fixed_cost": 1000}, "agency": {"fee_pct_of_salary": 20}},
"interview_hours_per_hire": 10, "interviewer_hourly_cost": 50, "onboarding_cost_per_hire": 1000, "offboarding_cost_per_leaver": 500,
"vacancy_cost_pct_of_daily_pay": 100, "ramp_productivity_loss_pct": 50, "high_turnover_pct": 25, "slow_fill_days": 60})
base = {"team": "T", "role": "R", "avg_headcount": "10", "leavers_12m": "2", "regrettable_leavers": "1", "avg_salary": "40000", "time_to_fill_days": "28", "ramp_months": "3", "hiring_channel": "fixed"}
r = cost_row(base, a)
b = r["breakdown_per_leaver"]
check("fixed channel recruiting cost", b["recruiting"] == 1000)
check("interview cost hours x rate", b["interviewing"] == 500)
check("vacancy: 28 calendar days = 20 working days x 200/day", b["vacancy"] == 4000)
check("ramp: 3/12 x 40000 x 50%", b["ramp_up"] == 5000)
check("cost per leaver sums parts", r["cost_per_leaver"] == 12000)
check("annual cost = per leaver x leavers", r["annual_cost"] == 24000)
check("turnover rate 20%", r["turnover_pct"] == 20.0)
check("no flags for moderate row", r["flags"] == [])
r2 = cost_row(dict(base, hiring_channel="agency", ramp_months="4"), a)
check("agency fee 20% of salary", r2["breakdown_per_leaver"]["recruiting"] == 8000)
check("T03 when cost >= 50% of salary", any(f.startswith("T03") for f in r2["flags"]))
a2 = dict(a, employer_overhead_pct=25)
check("overhead loads ramp cost", cost_row(base, a2)["breakdown_per_leaver"]["ramp_up"] == 6250)
r3 = cost_row(dict(base, leavers_12m="3", regrettable_leavers="2", time_to_fill_days="70"), a)
check("T01 at 30% turnover", any(f.startswith("T01") for f in r3["flags"]))
check("T02 when most leavers regrettable", any(f.startswith("T02") for f in r3["flags"]))
check("no T02 for a single regrettable leaver", not any(f.startswith("T02") for f in cost_row(dict(base, leavers_12m="1"), a)["flags"]))
check("T04 slow fill", any(f.startswith("T04") for f in r3["flags"]))
res = analyze([base, dict(base, regrettable_leavers="5")], a)
check("invalid regrettable > leavers gives E01", res["errors"] and res["errors"][0]["line"] == 3)
res = analyze([dict(base, hiring_channel="magic")], a)
check("unknown channel gives E01", "unknown hiring_channel" in res["errors"][0]["error"])
res = analyze([base, dict(base, team="U", leavers_12m="0", regrettable_leavers="0")], a, reduce_pct=25, program_cost=6000)
check("total over teams", res["summary"]["annual_cost"] == 24000)
check("scenario saving 25%", res["summary"]["scenario"]["annual_saving"] == 6000)
check("program break-even 25% and 0.5 leavers", res["summary"]["program"]["break_even_reduce_pct"] == 25.0 and res["summary"]["program"]["break_even_leavers_avoided"] == 0.5)
check("net saving 0 at break-even", res["summary"]["program"]["net_saving_at_reduce_pct"] == 0)
try:
parse_rows("team,role\nA,B\n"); check("missing columns rejected", False)
except ValueError:
check("missing columns rejected", True)
for n, ok in T:
print(("PASS " if ok else "FAIL ") + n)
p = sum(ok for _, ok in T)
print("%d/%d checks passed" % (p, len(T)))
return 0 if p == len(T) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description="Employee turnover cost calculator (stdlib only).")
ap.add_argument("csv", nargs="?")
ap.add_argument("--assumptions")
ap.add_argument("--format", choices=["text", "md", "csv", "json"], default="text")
ap.add_argument("--reduce-pct", type=float)
ap.add_argument("--program-cost", type=float)
ap.add_argument("--self-test", action="store_true")
o = ap.parse_args(argv)
if o.self_test:
return self_test()
if not o.csv:
ap.error("give a CSV file or --self-test")
try:
a = load_assumptions(o.assumptions)
with open(o.csv, encoding="utf-8-sig") as fh:
rows = parse_rows(fh.read())
except (OSError, ValueError) as e:
print("input error: %s" % e, file=sys.stderr)
return 2
res = analyze(rows, a, o.reduce_pct, o.program_cost)
print(render(res, o.format))
return 1 if res["errors"] or any(t["flags"] for t in res["teams"]) else 0
if __name__ == "__main__":
sys.exit(main())
Measures Python docstring coverage and quality from the AST without running code: missing docstrings, undocumented or stale parameters, missing Returns and Raises, weak summary lines, in Google, NumPy and reST styles, with a fix plan and a CI threshold. Stdlib Python.
---
name: python-docstring-coverage-checker
description: Measures Python docstring coverage and quality from the AST without running code: missing docstrings, undocumented or stale parameters, missing Returns and Raises, weak summary lines, in Google, NumPy and reST styles, with a fix plan and a CI threshold. Stdlib Python.
---
# Python Docstring Coverage Checker
You help Python developers, library maintainers and tech leads make their code explain itself. Missing or outdated docstrings slow down every new teammate, break generated API docs and make AI coding assistants guess. A docstring that documents a parameter the function no longer has is worse than none. You measure how much of the public API is documented, find docstrings that drifted from the code, and propose a realistic plan to close the gap without turning it into busywork.
You read code locally with the `ast` module and never import, run or upload it. Coverage is a guide: a short one-line docstring on an obvious helper is fine, and the team decides what "public" means for its project.
## Files in this skill
- `scripts/docstring_coverage.py` - walks files or folders (skips .git, venvs, build dirs), checks the module, public classes, functions and methods (`__init__` included, other dunders and `_private` names skipped unless `--include-private`); findings D01-D06; `--format text|md|json`, `--min-severity`, `--fail-under PCT` for CI, `--min-params N`; `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/docstring-styles.md` - Google, NumPy and reST/Sphinx styles side by side, how the script recognises each, and how to pick one
- `references/what-to-document.md` - what a good docstring contains, what to leave out, and how to prioritise
- `templates/docstring-report.md` - the review you hand back
- `examples/shipping_rates.py` - a fictional, under-documented shipping rate module (37.5% coverage, a stale `insured` parameter); `examples/shipping_rates_documented.py` - the same code fully documented (100%, no findings)
## Workflow
### 1. Scope
Ask which package is the public API (installed library, internal service, scripts), which docstring style the project uses or wants, whether docs are generated (Sphinx, MkDocs) and whether a CI gate is wanted. Exclude tests, migrations, generated and vendored code.
### 2. Run the check
```
python3 scripts/docstring_coverage.py src/
python3 scripts/docstring_coverage.py src/ --min-severity medium
python3 scripts/docstring_coverage.py src/ --format md > docstrings.md
python3 scripts/docstring_coverage.py src/ --format json
python3 scripts/docstring_coverage.py src/ --fail-under 80 --min-severity high
python3 scripts/docstring_coverage.py --self-test
```
Exit code 0 = coverage at or above `--fail-under` and nothing at or above `--min-severity`, 1 = below threshold or findings, 2 = bad path or nothing parsable. Files with syntax errors are listed as PARSE ERROR and skipped.
| Code | Severity | Meaning |
|---|---|---|
| D01 | high | public module, class, function or method without a docstring |
| D02 | medium | parameters missing from the docstring (when it has a parameter section, or the function has `--min-params` (3) or more parameters) |
| D03 | medium | docstring documents a parameter that is not in the signature (stale) |
| D04 | low | returns or yields a value but has no Returns/Yields section |
| D05 | low | raises an exception the docstring does not mention |
| D06 | low | summary line missing, over 88 characters or without a final period |
Coverage = documented objects / checked objects (modules, classes, functions, methods), overall, per kind and per file.
### 3. Interpret
- Fix D03 first: stale docs actively mislead readers and tools. They usually come from a renamed or removed parameter.
- Then D01 on the most used public entry points (what other modules or users import), not alphabetically.
- D02 on functions with many parameters matters more than D04/D06 polish.
- Read the flagged code before writing docs; if a function is hard to describe in one sentence, say so: it may need splitting rather than a longer docstring.
- Check for docstrings that are present but useless ("Does the thing.", repeating the function name); the script cannot judge meaning, you can.
### 4. Plan the fix
Group work into small pull requests per module, starting with the public API. Propose the style from `references/docstring-styles.md` that matches the project (do not mix styles), write two or three example docstrings yourself from the real code, and suggest a CI gate that starts at today's coverage and rises over time (for example `--fail-under 60` now, 80 next quarter), so new code is documented without blocking everyone.
### 5. Report
Fill `templates/docstring-report.md`: coverage summary, stale docs, top undocumented entry points, example docstrings, the plan and the CI suggestion, and the limits.
## Example
```
python3 scripts/docstring_coverage.py examples/shipping_rates.py
python3 scripts/docstring_coverage.py examples/shipping_rates_documented.py --fail-under 90
```
The first run reports 37.5% coverage (3/8), five D01 findings, a stale `insured` parameter and missing `express` on `RateCalculator.quote` (D03, D02), plus missing Returns and an undocumented `ValueError`. The documented version passes with 100% and exit code 0.
## Limits
- Static analysis only: it cannot tell whether a docstring is correct or helpful, only whether it exists and matches the signature.
- Parameter sections are recognised in Google, NumPy and reST styles; unusual custom formats may produce false D02/D03 findings.
- Raises detection only sees direct `raise` statements in the function, not exceptions from called code.
- Properties, overloads and setters are skipped; dataclass fields are not checked individually.
FILE:references/docstring-styles.md
# Docstring styles
Pick one style per project and stick to it. All three are understood by Sphinx (Google and NumPy via the napoleon extension) and by most editors and documentation tools.
## Google style
Readable in plain text, compact, good default for applications and most libraries.
```python
def quote(parcel, zone, express=False):
"""Return the price for one parcel.
Args:
parcel: The parcel to ship.
zone: One of the keys of ZONES.
express: Whether express delivery is used.
Returns:
The price rounded to 2 decimals.
Raises:
ValueError: If the zone is unknown.
"""
```
## NumPy style
More vertical, popular in scientific Python (numpy, pandas, scipy). Good when types and shapes need explaining.
```python
def resample(values, factor):
"""Resample a series by an integer factor.
Parameters
----------
values : list of float
Input samples.
factor : int
How many input samples make one output sample.
Returns
-------
list of float
The resampled series.
"""
```
## reST / Sphinx field style
Common in older projects and in Sphinx-first documentation.
```python
def connect(host, port=5432):
"""Open a database connection.
:param host: Server host name.
:param int port: Server port.
:returns: An open connection.
:raises ConnectionError: If the server cannot be reached.
"""
```
## How the script recognises them
- Parameter sections: `Args:`, `Arguments:`, `Parameters:`, `Keyword Args:`, `Other Parameters:` (Google), `Parameters` followed by a dashed line (NumPy), and `:param name:` / `:param type name:` (reST). `*args` and `**kwargs` may be written with or without stars.
- Returns: `Returns:`, `Return:`, `Yields:`, NumPy `Returns` / `Yields` headings, `:returns:`, `:rtype:`, `:yields:`.
- Raises: `Raises:` sections, `:raises X:` fields, or simply the exception name anywhere in the docstring.
## Choosing
| Situation | Suggested style |
|---|---|
| New application or internal library | Google |
| Scientific / data code with arrays and shapes | NumPy |
| Existing Sphinx docs already using fields | reST |
| Mixed project | the style most existing docstrings use; convert the rest gradually |
Type hints in the signature do not replace a docstring: they say what type a value is, the docstring says what it means, its units, defaults and edge cases. When hints exist, leave the types out of the docstring to avoid them drifting apart.
FILE:references/what-to-document.md
# What to document (and what not)
## A good docstring
1. **Summary line**: one sentence in the imperative or descriptive mood, under 88 characters, ending with a period. "Return the cheapest zone for a parcel." not "This function is used to get zone."
2. **Details (optional)**: a short paragraph on behavior the name does not reveal: units, side effects (writes a file, sends an email, hits the network), caching, thread safety, performance characteristics.
3. **Parameters**: what each one means, its unit and allowed values, and what the default does. Skip obvious type repetition when there are type hints.
4. **Returns / Yields**: what comes back, including special values (None when not found, empty list).
5. **Raises**: exceptions callers are expected to handle, and when.
6. **Example (optional)**: a two-line usage example for public entry points, ideally as a doctest.
## Leave out
- Restating the code line by line or the function name in other words.
- History ("changed in March to fix bug 123"): that belongs in git and the changelog.
- Implementation details that will change often; document the contract, not the internals.
- TODOs: track them as issues.
## Priorities when coverage is low
1. Stale docs (D03): wrong information is worse than none.
2. Public entry points used by other modules, services or users (what `__init__.py` exports, CLI commands, API handlers).
3. Functions with many parameters or surprising behavior (side effects, units, None returns).
4. Classes: one paragraph on what the object represents and its lifecycle.
5. Module docstrings: one or two sentences on what lives in the file.
6. Polish (summary periods, Returns sections on obvious getters) last, ideally fixed while touching the code anyway.
## Coverage targets
- Libraries published for others: 90-100% of the public API.
- Internal services: 70-85% of public functions and classes, 100% of anything other teams call.
- Scripts and glue code: module docstring plus the main entry point.
Ratchet the CI threshold up from today's number instead of jumping to a target that blocks every pull request.
## Writing with an AI assistant
Generated docstrings are a good first draft, but always check them against the code: assistants happily document parameters the function does not have, invent exceptions or describe what the name suggests instead of what the code does. Re-run the checker afterwards to catch stale parameters.
FILE:templates/docstring-report.md
# Docstring review: {project or package}
**Scanned:** {paths} on {date} - {files} files, {objects} public objects
**Style:** {Google | NumPy | reST | mixed}
**Command:** `python3 scripts/docstring_coverage.py {paths} {options}`
## Summary
- Coverage: **{pct}%** ({documented}/{objects}); modules {m}%, classes {c}%, functions {f}%, methods {me}%
- Stale docstrings (D03): {n}
- Undocumented public objects (D01): {n}, of which {k} are main entry points
- One-sentence verdict: {e.g. "Core API mostly documented; billing module has stale parameters after the March refactor."}
## Fix first: stale or wrong docs
| Location | Object | Problem | Fix |
|---|---|---|---|
| {file:line} | `{name}` | {documents `insured`, not in signature} | {remove or rename to `express`} |
## Top undocumented entry points
| Location | Object | Why it matters | Suggested summary line |
|---|---|---|---|
| {file:line} | `{name}` | {called from 6 modules / public API} | {Return the cheapest zone for a parcel.} |
## Example docstrings (from the real code)
```python
{2-3 complete docstrings in the chosen style}
```
## Plan
1. {PR 1: fix all D03 + document public API of module X}
2. {PR 2: ...}
3. {Agree on the style in CONTRIBUTING.md}
## CI gate
`python3 scripts/docstring_coverage.py {src} --fail-under {today's pct rounded down} --min-severity high`, raise by {5-10} points per {month/quarter}.
## Deliberately left alone
- {e.g. private helpers, tests, generated code, obvious one-line properties}
## Limits
Static check only: presence and signature match, not correctness. Exceptions raised by called functions are not detected. Custom docstring formats may need manual review.
FILE:examples/shipping_rates.py
# Fictional example module for the docstring coverage checker: deliberately under-documented.
from dataclasses import dataclass
ZONES = {"domestic": 1.0, "eu": 1.6, "world": 2.4}
@dataclass
class Parcel:
weight_kg: float
length_cm: float
width_cm: float
height_cm: float
def volumetric_weight(self, divisor=5000):
"""Volumetric weight in kilograms"""
return self.length_cm * self.width_cm * self.height_cm / divisor
class RateCalculator:
"""Calculate shipping rates for parcels."""
def __init__(self, base_rate, per_kg, fuel_surcharge_pct):
self.base_rate = base_rate
self.per_kg = per_kg
self.fuel_surcharge_pct = fuel_surcharge_pct
def quote(self, parcel, zone, express=False):
"""Return the price for one parcel.
Args:
parcel: The parcel to ship.
zone: One of the keys of ZONES.
insured: Whether insurance is added.
"""
if zone not in ZONES:
raise ValueError("unknown zone: %s" % zone)
billable = max(parcel.weight_kg, parcel.volumetric_weight())
price = (self.base_rate + billable * self.per_kg) * ZONES[zone]
if express:
price *= 1.5
return round(price * (1 + self.fuel_surcharge_pct / 100), 2)
def quote_many(self, parcels, zone):
return [self.quote(p, zone) for p in parcels]
def cheapest_zone_for(parcel, calculator):
best = None
for zone in ZONES:
price = calculator.quote(parcel, zone)
if best is None or price < best[1]:
best = (zone, price)
return best
def _round_up(value, step):
return -(-value // step) * step
FILE:examples/shipping_rates_documented.py
"""Shipping rate calculation for parcels (fictional example, fully documented version)."""
from dataclasses import dataclass
ZONES = {"domestic": 1.0, "eu": 1.6, "world": 2.4}
@dataclass
class Parcel:
"""A parcel with its real weight and outer dimensions."""
weight_kg: float
length_cm: float
width_cm: float
height_cm: float
def volumetric_weight(self, divisor=5000):
"""Return the volumetric weight in kilograms.
Args:
divisor: Carrier divisor in cubic centimeters per kilogram.
Returns:
The volumetric weight as a float.
"""
return self.length_cm * self.width_cm * self.height_cm / divisor
class RateCalculator:
"""Calculate shipping rates for parcels."""
def __init__(self, base_rate, per_kg, fuel_surcharge_pct):
"""Create a calculator with one carrier's tariff.
Args:
base_rate: Fixed price per parcel.
per_kg: Price per billable kilogram.
fuel_surcharge_pct: Fuel surcharge in percent, added at the end.
"""
self.base_rate = base_rate
self.per_kg = per_kg
self.fuel_surcharge_pct = fuel_surcharge_pct
def quote(self, parcel, zone, express=False):
"""Return the price for one parcel.
Args:
parcel: The parcel to ship.
zone: One of the keys of ZONES.
express: Whether express delivery (+50 percent) is used.
Returns:
The price rounded to 2 decimals.
Raises:
ValueError: If the zone is unknown.
"""
if zone not in ZONES:
raise ValueError("unknown zone: %s" % zone)
billable = max(parcel.weight_kg, parcel.volumetric_weight())
price = (self.base_rate + billable * self.per_kg) * ZONES[zone]
if express:
price *= 1.5
return round(price * (1 + self.fuel_surcharge_pct / 100), 2)
def quote_many(self, parcels, zone):
"""Return standard prices for several parcels to the same zone.
Args:
parcels: Iterable of parcels.
zone: One of the keys of ZONES.
Returns:
A list of prices in the same order as the parcels.
"""
return [self.quote(p, zone) for p in parcels]
def cheapest_zone_for(parcel, calculator):
"""Find the zone with the lowest standard price for a parcel.
Args:
parcel: The parcel to ship.
calculator: A RateCalculator.
Returns:
A (zone, price) tuple.
"""
best = None
for zone in ZONES:
price = calculator.quote(parcel, zone)
if best is None or price < best[1]:
best = (zone, price)
return best
def _round_up(value, step):
return -(-value // step) * step
FILE:scripts/docstring_coverage.py
#!/usr/bin/env python3
"""docstring_coverage.py - measure docstring coverage and quality for Python code (standard library only).
Walks files or folders, parses each file with the ast module (code is never imported or run) and checks
every module, public class, public function and public method:
D01 high public module, class, function or method has no docstring
D02 medium parameters missing from the docstring (only when the docstring documents parameters,
or when the function has --min-params or more parameters)
D03 medium docstring documents a parameter that is not in the signature (stale)
D04 low function returns a value but the docstring has no Returns/Yields section
D05 low function raises exceptions that the docstring does not mention
D06 low summary line missing, longer than 88 characters or not ending with a period
Docstring sections are recognised in Google (Args:), NumPy (Parameters / ----------) and
reST/Sphinx (:param x:) styles.
Usage:
python3 docstring_coverage.py PATH [PATH ...] [--format text|md|json] [--min-severity low|medium|high]
[--fail-under PCT] [--include-private] [--min-params N]
python3 docstring_coverage.py --self-test
Exit code: 0 = coverage >= --fail-under and no findings at or above --min-severity,
1 = below threshold or findings present, 2 = bad path / nothing parsable.
"""
import argparse, ast, json, os, re, sys
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "node_modules", "build", "dist", "__pycache__", ".tox", ".mypy_cache", "site-packages"}
SEV = {"low": 1, "medium": 2, "high": 3}
CODES = {"D01": "high", "D02": "medium", "D03": "medium", "D04": "low", "D05": "low", "D06": "low"}
SECTION_PARAMS = re.compile(r"^\s*(Args|Arguments|Parameters|Params|Keyword Args|Keyword Arguments|Other Parameters)\s*:?\s*$", re.M)
SECTION_RETURNS = re.compile(r"^\s*(Returns?|Yields?)\s*:?\s*$|:returns?:|:rtype:|:yields?:", re.M)
SECTION_RAISES = re.compile(r"^\s*(Raises|Exceptions)\s*:?\s*$|:raises?\s", re.M)
REST_PARAM = re.compile(r":param\s+(?:[\w\[\], .]+\s+)?\*{0,2}(\w+)\s*:")
def documented_params(doc):
"""Return the set of parameter names a docstring documents, in any of the three styles."""
names = set(REST_PARAM.findall(doc))
lines = doc.splitlines()
i = 0
while i < len(lines):
if SECTION_PARAMS.match(lines[i]):
numpy = i + 1 < len(lines) and set(lines[i + 1].strip()) == {"-"}
j = i + (2 if numpy else 1)
base = None
while j < len(lines):
line = lines[j]
if not line.strip():
j += 1
continue
indent = len(line) - len(line.lstrip())
if numpy:
if j + 1 < len(lines) and set(lines[j + 1].strip()) == {"-"} and lines[j + 1].strip():
break # next numpy section
if base is None:
base = indent
if indent == base:
if re.match(r"\s*\*{0,2}\w+", line):
for part in line.split(":")[0].split(","):
p = part.strip().lstrip("*")
if p.isidentifier():
names.add(p)
else:
if re.match(r"^\s*[A-Z][A-Za-z ]+:\s*$", line) and (base is None or indent < base):
break # next google section
if base is None:
base = indent
if indent < base:
break
if indent == base:
m = re.match(r"\s*\*{0,2}(\w+)\s*(\([^)]*\))?\s*:", line)
if m:
names.add(m.group(1))
j += 1
i = j
continue
i += 1
return names
def signature_params(fn, is_method):
a = fn.args
params = [x.arg for x in getattr(a, "posonlyargs", [])] + [x.arg for x in a.args] + [x.arg for x in a.kwonlyargs]
if a.vararg:
params.append(a.vararg.arg)
if a.kwarg:
params.append(a.kwarg.arg)
if is_method and params and params[0] in ("self", "cls"):
params = params[1:]
return [p for p in params if p != "_"]
def _own_nodes(fn):
"""Walk a function body without descending into nested functions or classes."""
stack = [n for n in fn.body if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))]
while stack:
node = stack.pop()
yield node
for child in ast.iter_child_nodes(node):
if not isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
stack.append(child)
def returns_value(fn):
for n in _own_nodes(fn):
if isinstance(n, ast.Return) and n.value is not None and not (isinstance(n.value, ast.Constant) and n.value.value is None):
return True
if isinstance(n, (ast.Yield, ast.YieldFrom)):
return True
return False
def raised_names(fn):
out = set()
for n in _own_nodes(fn):
if isinstance(n, ast.Raise) and n.exc is not None:
e = n.exc.func if isinstance(n.exc, ast.Call) else n.exc
if isinstance(e, ast.Name):
out.add(e.id)
elif isinstance(e, ast.Attribute):
out.add(e.attr)
return out
def is_public(name):
return not name.startswith("_") or (name.startswith("__") and name.endswith("__") and name == "__init__")
def check_summary(doc):
first = doc.strip().splitlines()[0].strip() if doc.strip() else ""
if not first:
return "empty summary line"
if len(first) > 88:
return "summary line is %d characters (max 88)" % len(first)
if not first.endswith((".", "!", "?", ":")):
return "summary line does not end with a period"
return None
def analyze_source(src, path="<string>", include_private=False, min_params=3):
tree = ast.parse(src, filename=path)
items, findings = [], []
def add(code, obj, line, msg):
findings.append({"code": code, "severity": CODES[code], "path": path, "line": line, "object": obj, "message": msg})
mod_doc = ast.get_docstring(tree)
items.append({"path": path, "object": "<module>", "kind": "module", "line": 1, "documented": bool(mod_doc)})
if not mod_doc:
add("D01", "<module>", 1, "module has no docstring")
elif check_summary(mod_doc):
add("D06", "<module>", 1, check_summary(mod_doc))
def visit(body, prefix, in_class, parent_public):
for node in body:
if isinstance(node, ast.ClassDef):
public = parent_public and (include_private or is_public(node.name))
name = prefix + node.name
if public:
doc = ast.get_docstring(node)
items.append({"path": path, "object": name, "kind": "class", "line": node.lineno, "documented": bool(doc)})
if not doc:
add("D01", name, node.lineno, "class has no docstring")
elif check_summary(doc):
add("D06", name, node.lineno, check_summary(doc))
visit(node.body, name + ".", True, public)
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
public = parent_public and (include_private or is_public(node.name))
if any(isinstance(d, ast.Name) and d.id == "overload" or isinstance(d, ast.Attribute) and d.attr in ("overload", "setter", "deleter") for d in node.decorator_list):
continue
name = prefix + node.name
if not public:
continue
kind = "method" if in_class else "function"
doc = ast.get_docstring(node)
items.append({"path": path, "object": name, "kind": kind, "line": node.lineno, "documented": bool(doc)})
if not doc:
add("D01", name, node.lineno, "%s has no docstring" % kind)
continue
params = signature_params(node, in_class)
documented = documented_params(doc)
has_section = bool(documented) or bool(SECTION_PARAMS.search(doc))
if has_section or len(params) >= min_params:
missing = [p for p in params if p not in documented]
if missing:
add("D02", name, node.lineno, "parameters not documented: " + ", ".join(missing))
stale = sorted(documented - set(params) - {"self", "cls"})
if stale:
add("D03", name, node.lineno, "docstring documents parameters not in the signature: " + ", ".join(stale))
if returns_value(node) and not SECTION_RETURNS.search(doc) and node.name != "__init__":
add("D04", name, node.lineno, "returns a value but the docstring has no Returns/Yields section")
raised = raised_names(node)
undocumented = sorted(r for r in raised if r not in doc)
if undocumented:
add("D05", name, node.lineno, "raises without mention in the docstring: " + ", ".join(undocumented))
s = check_summary(doc)
if s:
add("D06", name, node.lineno, s)
visit(tree.body, "", False, True)
return items, findings
def iter_files(paths):
for p in paths:
if os.path.isfile(p):
yield p
elif os.path.isdir(p):
for root, dirs, files in os.walk(p):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.endswith(".egg-info"))
for f in sorted(files):
if f.endswith(".py"):
yield os.path.join(root, f)
else:
raise FileNotFoundError(p)
def summarize(items):
by_kind = {}
for it in items:
k = by_kind.setdefault(it["kind"], [0, 0])
k[0] += 1
k[1] += it["documented"]
total = len(items)
doc = sum(it["documented"] for it in items)
return {"objects": total, "documented": doc, "coverage_pct": round(100.0 * doc / total, 1) if total else 100.0,
"by_kind": {k: {"objects": v[0], "documented": v[1], "coverage_pct": round(100.0 * v[1] / v[0], 1)} for k, v in sorted(by_kind.items())}}
def render(fmt, summary, findings, errors, per_file):
if fmt == "json":
return json.dumps({"summary": summary, "files": per_file, "findings": findings, "parse_errors": errors}, indent=2)
out = []
if fmt == "md":
out.append("## Docstring coverage: %.1f%% (%d/%d objects)" % (summary["coverage_pct"], summary["documented"], summary["objects"]))
out.append("")
out.append("| Kind | Documented | Coverage |")
out.append("|---|---|---|")
for k, v in summary["by_kind"].items():
out.append("| %s | %d/%d | %.1f%% |" % (k, v["documented"], v["objects"], v["coverage_pct"]))
out.append("")
if findings:
out.append("| Code | Severity | Location | Object | Finding |")
out.append("|---|---|---|---|---|")
for f in findings:
out.append("| %s | %s | %s:%d | `%s` | %s |" % (f["code"], f["severity"], f["path"], f["line"], f["object"], f["message"]))
else:
out.append("No findings at the selected severity.")
else:
out.append("Docstring coverage: %.1f%% (%d/%d objects)" % (summary["coverage_pct"], summary["documented"], summary["objects"]))
for k, v in summary["by_kind"].items():
out.append(" %-8s %d/%d (%.1f%%)" % (k, v["documented"], v["objects"], v["coverage_pct"]))
for pf in per_file:
out.append(" file %s: %.1f%% (%d/%d)" % (pf["path"], pf["coverage_pct"], pf["documented"], pf["objects"]))
out.append("")
for f in findings:
out.append("%s %-6s %s:%d %s - %s" % (f["code"], f["severity"], f["path"], f["line"], f["object"], f["message"]))
if not findings:
out.append("No findings at the selected severity.")
for e in errors:
out.append("PARSE ERROR %s: %s" % (e["path"], e["error"]))
return "\n".join(out)
def self_test():
T = []
def check(name, cond):
T.append((name, bool(cond)))
src = '''"""Module summary."""
def a(x, y):
"""Add two numbers.
Args:
x: first.
y (int): second.
Returns:
The sum.
"""
return x + y
def b(x):
return x
'''
items, f = analyze_source(src)
codes = [x["code"] for x in f]
check("google style fully documented gives no finding for a", not [x for x in f if x["object"] == "a"])
check("missing docstring gives D01", ("D01", "b") in [(x["code"], x["object"]) for x in f])
check("coverage counts module and functions", summarize(items)["coverage_pct"] == 66.7)
items, f = analyze_source('"""M."""\ndef c(a, b):\n """Do it.\n\n Args:\n a: one.\n """\n pass\n')
check("missing param gives D02", [x["message"] for x in f if x["code"] == "D02"] == ["parameters not documented: b"])
items, f = analyze_source('"""M."""\ndef c(a):\n """Do it.\n\n Args:\n a: one.\n old: gone.\n """\n')
check("stale param gives D03", any(x["code"] == "D03" and "old" in x["message"] for x in f))
numpy = '"""M."""\ndef n(a, b):\n """Numpy style.\n\n Parameters\n ----------\n a : int\n One.\n b : str\n Two.\n\n Returns\n -------\n int\n """\n return 1\n'
items, f = analyze_source(numpy)
check("numpy style params and returns recognised", not f)
rest = '"""M."""\ndef r(a, b):\n """Rest style.\n\n :param a: one.\n :param int b: two.\n :returns: value.\n :raises ValueError: bad.\n """\n if a:\n raise ValueError("x")\n return a\n'
items, f = analyze_source(rest)
check("rest style params, returns and raises recognised", not f)
items, f = analyze_source('"""M."""\ndef s(a):\n """Short."""\n return a * 2\n')
check("return without Returns section gives D04", any(x["code"] == "D04" for x in f))
check("one short param below --min-params gives no D02", not any(x["code"] == "D02" for x in f))
items, f = analyze_source('"""M."""\ndef g(a):\n """Get."""\n raise KeyError(a)\n')
check("undocumented raise gives D05", any(x["code"] == "D05" and "KeyError" in x["message"] for x in f))
items, f = analyze_source('"""M."""\ndef h():\n """no period here"""\n')
check("summary without period gives D06", any(x["code"] == "D06" for x in f))
items, f = analyze_source('def _p():\n pass\nclass _Q:\n def m(self):\n pass\n')
check("private function and class skipped, module flagged", [x["object"] for x in f] == ["<module>"])
items, f = analyze_source('def _p():\n pass\n', include_private=True)
check("--include-private checks private names", any(x["object"] == "_p" for x in f))
cls = '"""M."""\nclass K:\n """A class."""\n def __init__(self, a, b, c):\n """Create it."""\n def run(self):\n """Run it."""\n def __repr__(self):\n return "K"\n'
items, f = analyze_source(cls)
check("__init__ with 3 params gives D02, self excluded", any(x["code"] == "D02" and x["object"] == "K.__init__" and "self" not in x["message"] for x in f))
check("dunder methods other than __init__ are skipped", not any(x["object"] == "K.__repr__" for x in f))
items, f = analyze_source('"""M."""\ndef outer():\n """Outer."""\n def inner():\n return 1\n return None\n')
check("nested return does not count for outer", not any(x["code"] == "D04" for x in f))
items, f = analyze_source('"""M."""\ndef gen(n):\n """Generate.\n\n Yields:\n Numbers.\n """\n yield n\n')
check("Yields section satisfies D04", not f)
items, f = analyze_source('"""M."""\ndef v(*args, **kwargs):\n """Var.\n\n Args:\n *args: values.\n **kwargs: options.\n """\n')
check("*args and **kwargs documented with stars", not f)
try:
analyze_source("def broken(:\n")
check("syntax error raised", False)
except SyntaxError:
check("syntax error raised", True)
for name, ok in T:
print(("PASS " if ok else "FAIL ") + name)
passed = sum(ok for _, ok in T)
print("%d/%d checks passed" % (passed, len(T)))
return 0 if passed == len(T) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description="Docstring coverage and quality checker (stdlib only).")
ap.add_argument("paths", nargs="*")
ap.add_argument("--format", choices=["text", "md", "json"], default="text")
ap.add_argument("--min-severity", choices=list(SEV), default="low")
ap.add_argument("--fail-under", type=float, default=0.0, help="minimum coverage percent (default 0)")
ap.add_argument("--include-private", action="store_true")
ap.add_argument("--min-params", type=int, default=3, help="require a parameter section from this many parameters (default 3)")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.paths:
ap.error("give at least one path or --self-test")
try:
files = list(iter_files(a.paths))
except FileNotFoundError as e:
print("no such path: %s" % e, file=sys.stderr)
return 2
all_items, findings, errors, per_file = [], [], [], []
for p in files:
try:
with open(p, encoding="utf-8") as fh:
items, f = analyze_source(fh.read(), p, a.include_private, a.min_params)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append({"path": p, "error": str(e).splitlines()[0]})
continue
all_items += items
findings += f
s = summarize(items)
per_file.append({"path": p, "objects": s["objects"], "documented": s["documented"], "coverage_pct": s["coverage_pct"]})
if not all_items:
print(render(a.format, summarize([]), [], errors, []))
return 2
shown = [f for f in findings if SEV[f["severity"]] >= SEV[a.min_severity]]
shown.sort(key=lambda f: (-SEV[f["severity"]], f["path"], f["line"], f["code"]))
summary = summarize(all_items)
summary["fail_under"] = a.fail_under
print(render(a.format, summary, shown, errors, per_file))
return 1 if shown or summary["coverage_pct"] < a.fail_under else 0
if __name__ == "__main__":
sys.exit(main())
Builds an accounts receivable aging report from an invoice CSV: Current, 1-30, 31-60, 61-90 and 90+ buckets per customer and currency, overdue share, DSO, credit limit and concentration checks, disputes, and a collection stage per invoice. Stdlib Python.
---
name: accounts-receivable-aging-report
description: Builds an accounts receivable aging report from an invoice CSV: Current, 1-30, 31-60, 61-90 and 90+ buckets per customer and currency, overdue share, DSO, credit limit and concentration checks, disputes, and a collection stage per invoice. Stdlib Python.
---
# Accounts Receivable Aging Report
You help founders, freelancers, agency owners and small-business finance people see who owes them money, how late it is, and what to do about it this week. Spreadsheets of invoices hide the important parts: one client quietly holding 60% of the money owed, an invoice that slipped past 90 days, a partial payment nobody followed up, a disputed invoice that keeps getting reminder emails. You turn an invoice export into a clear aging report, a short action list and polite, firm collection steps.
You work on the user's data locally; invoice data is confidential, so you never upload it anywhere. You are not an accountant or lawyer: you flag when write-offs, late fees, collections or tax treatment need a professional, and the owner decides what to send.
## Files in this skill
- `scripts/ar_aging.py` - reads `invoices.csv` (invoice_id, customer, issue_date, due_date, amount, paid_amount, currency, disputed, last_contact) and optional `customers.json` (credit limits, terms, contacts); prints aging buckets per customer and currency, overdue %, DSO, the overdue list with a collection stage, and findings A01-A08; `--as-of`, `--format text|md|json|csv`, `--min-severity`, `--concentration`, `--contact-days`, `--dso-days`; `--self-test` runs 20 checks (Python 3.8+ standard library only)
- `references/aging-buckets-and-dso.md` - how buckets, overdue share, DSO, concentration and credit limits are calculated and their limits
- `references/collection-playbook.md` - stages 0-5 plus dispute hold, message skeletons, good practice
- `templates/collections-summary.md` - the one-page review you hand back
- `examples/invoices.csv`, `examples/customers.json` - a fictional design agency with 18 invoices in EUR and USD: a 146-day-old invoice, a disputed one, partial payments, an overpayment, one client over its credit limit holding 59% of receivables, and overdue invoices with no contact logged
## Workflow
### 1. Get the data
Ask for an export from the invoicing or accounting tool with the columns above (paid invoices from the last 90 days too, for DSO). Map their column names if needed. Ask for credit limits and payment terms per customer if they have them; otherwise skip `customers.json` and say that A03 cannot be checked.
### 2. Run the report
```
python3 scripts/ar_aging.py invoices.csv customers.json --as-of 2026-11-25
python3 scripts/ar_aging.py invoices.csv customers.json --format md > aging.md
python3 scripts/ar_aging.py invoices.csv --format csv > overdue-list.csv
python3 scripts/ar_aging.py invoices.csv customers.json --min-severity high
python3 scripts/ar_aging.py --self-test
```
Exit code 0 = no findings at or above `--min-severity`, 1 = findings, 2 = input error.
| Code | Severity | Meaning |
|---|---|---|
| A01 | high | open balance more than 90 days past due |
| A02 | medium | one customer holds more than 30% of open receivables (per currency) |
| A03 | high | customer open balance above its credit limit |
| A04 | low | partially paid invoice still open |
| A05 | medium | disputed invoice: resolve before chasing |
| A06 | medium | overdue with no contact in the last 14 days |
| A07 | low | overpaid invoice: refund or apply as credit |
| A08 | high | data problem: duplicate id, bad date, negative amount, due before issue |
### 3. Check and interpret
- Fix A08 data problems first and re-run; totals are not trustworthy until then.
- Compare DSO with payment terms and look at the 90+ bucket and concentration.
- Separate disputes from slow payers; never send reminders on a disputed amount.
- Ask about context the data cannot show (a client that always pays after its board meeting, a promised transfer).
### 4. Plan actions
Sort the overdue list by amount x age and pick this week's top actions using `references/collection-playbook.md`. Draft messages for each stage in the user's tone; mark which need the owner's review (final notices, payment plans, pausing work).
### 5. Report
Fill `templates/collections-summary.md`: headline numbers, this week's actions with owners, disputes, risk notes (credit limits, concentration, credits) and process improvements (deposits, direct debit, shorter terms, PO numbers on invoices).
## Example
```
python3 scripts/ar_aging.py examples/invoices.csv examples/customers.json --as-of 2026-11-25
```
shows 42,940 EUR open, 73% overdue, DSO about 114 days; Bluefin Logistics holds 59.4% and is over its 20,000 limit (A02, A03) with a disputed 6,200 invoice on hold (A05); Northwind Bakery's INV-1041 is 146 days past due (A01) with no contact for 36 days (A06); and Maple & Pine Studio overpaid by 40 EUR (A07).
## Rules
- Use the user's numbers; mark assumptions.
- Keep currencies separate; never convert without a rate the user gives.
- Stay polite and factual in every message; no threats the contract does not support.
- Not legal, tax or accounting advice; say when to ask a professional.
FILE:references/aging-buckets-and-dso.md
# Aging buckets, overdue share and DSO
## Aging buckets
Each open invoice is placed by **days past due** on the report date (`--as-of`), not by days since issue:
| Bucket | Days past due | Typical reading |
|---|---|---|
| Current | 0 or less (not yet due) | healthy; no action except making sure the invoice was received |
| 1-30 | 1-30 | normal slippage; friendly reminders usually work |
| 31-60 | 31-60 | a process or cash problem at the customer; escalate politely |
| 61-90 | 61-90 | real risk; final notices, pause new work |
| 90+ | over 90 | a large share will never be paid without a plan; consider payment plans, collections, or legal advice, and talk to your accountant about a bad-debt provision |
Open balance = amount - paid_amount. Fully paid invoices drop out. Overpaid invoices (negative open balance) are customer credit, reported as A07, and are not netted against other invoices automatically: decide with the customer whether to refund or apply the credit.
## Overdue share
`overdue % = (open - Current) / open`. Watch the trend month to month more than the absolute number. Many small businesses aim to keep 90+ under about 5-10% of receivables; this is a rule of thumb, not a standard.
## DSO (days sales outstanding)
The script uses the simple count-back formula over a window (default 90 days, `--dso-days`):
`DSO = open receivables / invoiced amount in the last N days x N`
Example: 42,940 open, 33,880 invoiced in the last 90 days -> DSO about 114 days. Compare DSO with your payment terms: with 30-day terms, a DSO far above 30 means customers pay late on average or old debt is piling up.
Limits:
- Uneven billing (one big project invoice) swings DSO a lot; look at a few months.
- Currencies are reported separately; DSO is per currency.
- The CSV must contain all invoices issued in the window (including paid ones) for DSO to be meaningful.
## Concentration
If one customer holds more than about 30% (`--concentration`) of open receivables, a single late payer can create a cash gap. That is a business risk to discuss, not a collection failure.
## Credit limits
`customers.json` can hold a `credit_limit` per customer. Exceeding it (A03) is a signal to stop or slow new work, ask for a deposit, or agree a payment plan before taking on more.
## Data checks (A08)
Duplicate invoice ids, unreadable dates, negative amounts and due dates before issue dates are reported first: fix the export before trusting any totals.
FILE:references/collection-playbook.md
# Collection playbook (polite, firm, documented)
The script assigns a stage to each overdue invoice. Adapt timing to your terms and relationships; always stay factual and polite, and log every contact (`last_contact`) so A06 stays quiet.
| Stage | Days past due | Action | Channel |
|---|---|---|---|
| 0 | before due | confirm the invoice reached the right person / AP portal; check PO numbers | email |
| 1 | 1-7 | friendly reminder with invoice copy and payment link | email |
| 2 | 8-30 | firm reminder plus a short call; ask for a payment date | email + phone |
| 3 | 31-60 | escalate to the decision maker or project sponsor; pause new work or deliveries if your contract allows | call + email |
| 4 | 61-90 | final notice with a clear date and the next step (late fees if in your contract, payment plan offer) | written notice |
| 5 | 90+ | payment plan in writing, or collections agency / small-claims / legal advice; talk to your accountant about provisions | written |
| hold | disputed | resolve the dispute first: what exactly is contested, credit note or partial payment for the undisputed part | call |
## Message skeletons
**Stage 1:** "Hi {{name}}, a quick reminder that invoice {{id}} for {{amount}} was due on {{due_date}}. A copy and payment link are attached. If it has already been paid, thank you and please ignore this."
**Stage 2:** "Hi {{name}}, invoice {{id}} ({{amount}}) is now {{days}} days overdue. Could you confirm the date it will be paid? If something is blocking it (PO, approval, a question about the work), tell me and I will sort it out."
**Stage 4:** "Hello {{name}}, despite earlier reminders on {{dates}}, invoice {{id}} ({{amount}}) remains unpaid {{days}} days after the due date. Please arrange payment by {{date}}. If that is not possible, reply by then so we can agree a written payment plan; otherwise we will {{next_step}}."
## Good practice
- Separate disputes from slow payment; never chase a disputed amount with reminders.
- Ask for partial payment of the undisputed part.
- For repeat late payers: shorter terms, deposits, card or direct debit, milestone billing.
- Late fees and interest only if your contract and local law allow them; check before you threaten them.
- Keep tone respectful: many late payments are process problems (wrong email, missing PO), not unwillingness.
- This is not legal or accounting advice; for collections, write-offs and tax treatment ask a qualified professional.
FILE:templates/collections-summary.md
# Receivables review - {{business}} - as of {{as_of}}
## Headline
- Open receivables: {{open_total}} ({{currency}}), overdue {{overdue_total}} ({{overdue_pct}}%), DSO {{dso}} days vs {{terms}}-day terms
- 90+ days: {{over_90_total}} across {{over_90_count}} invoices
- Biggest exposure: {{top_customer}} with {{top_share}}% of open balance
## This week's actions (highest value first)
| # | Customer | Invoice(s) | Amount | Days past due | Stage / action | Owner | Due |
|---|---|---|---|---|---|---|---|
| 1 | | | | | | | |
| 2 | | | | | | | |
| 3 | | | | | | | |
## Disputes to resolve
| Invoice | Customer | Amount | What is disputed | Next step | Owner |
|---|---|---|---|---|---|
## Risk notes
- Credit limits exceeded: {{customers_over_limit}} -> {{proposal: pause new work / deposit / payment plan}}
- Concentration: {{customer}} {{share}}% -> {{proposal}}
- Credits to refund or apply: {{credits}}
- Data fixes needed in the export: {{data_issues}}
## Process improvements
- {{e.g. send invoices to the AP inbox with PO numbers; move Orbit Fitness to direct debit; 50% deposit on new projects for clients with 90+ history}}
_Figures from ar_aging.py on {{as_of}}. Not legal or accounting advice._
FILE:examples/invoices.csv
invoice_id,customer,issue_date,due_date,amount,paid_amount,currency,disputed,last_contact
INV-1041,Northwind Bakery,2026-06-02,2026-07-02,2400.00,0,EUR,no,2026-10-20
INV-1047,Harbor Dental Clinic,2026-07-15,2026-08-14,1850.00,850.00,EUR,no,2026-11-18
INV-1052,Bluefin Logistics,2026-08-05,2026-09-04,6200.00,0,EUR,yes,2026-11-10
INV-1055,Northwind Bakery,2026-08-20,2026-09-19,1200.00,0,EUR,no,2026-10-20
INV-1058,Maple & Pine Studio,2026-09-01,2026-10-01,980.00,980.00,EUR,no,
INV-1060,Bluefin Logistics,2026-09-10,2026-10-10,7400.00,0,EUR,no,
INV-1063,Greenleaf Co-op,2026-09-22,2026-10-22,1500.00,0,EUR,no,2026-11-21
INV-1064,Harbor Dental Clinic,2026-10-01,2026-10-31,1850.00,0,EUR,no,2026-11-18
INV-1066,Orbit Fitness,2026-10-03,2026-11-02,3200.00,0,EUR,no,
INV-1067,Maple & Pine Studio,2026-10-06,2026-11-05,760.00,800.00,EUR,no,
INV-1069,Bluefin Logistics,2026-10-15,2026-11-14,5100.00,0,EUR,no,2026-11-19
INV-1070,Greenleaf Co-op,2026-10-20,2026-11-19,1500.00,0,EUR,no,
INV-1072,Orbit Fitness,2026-11-01,2026-12-01,3200.00,0,EUR,no,
INV-1073,Northwind Bakery,2026-11-05,2026-12-05,950.00,0,EUR,no,
INV-1074,Bluefin Logistics,2026-11-10,2026-12-10,6800.00,0,EUR,no,
INV-1075,Lakeside Hostel,2026-11-12,2026-11-26,640.00,0,EUR,no,
INV-1076,Atlas Outdoor Inc,2026-09-15,2026-10-15,4500.00,2000.00,USD,no,2026-11-03
INV-1077,Atlas Outdoor Inc,2026-11-15,2026-12-15,4500.00,0,USD,no,
FILE:examples/customers.json
{
"default_terms_days": 30,
"note": "Fictional clients of a small design and web agency. Credit limits are what the agency is willing to have open per client.",
"customers": {
"Northwind Bakery": {"credit_limit": 5000, "terms_days": 30, "contact": "owner, prefers phone"},
"Harbor Dental Clinic": {"credit_limit": 4000, "terms_days": 30, "contact": "practice manager"},
"Bluefin Logistics": {"credit_limit": 20000, "terms_days": 30, "contact": "accounts payable inbox + project sponsor"},
"Maple & Pine Studio": {"credit_limit": 3000, "terms_days": 30, "contact": "founder"},
"Greenleaf Co-op": {"credit_limit": 4000, "terms_days": 30, "contact": "treasurer, pays after monthly board meeting"},
"Orbit Fitness": {"credit_limit": 6000, "terms_days": 30, "contact": "finance lead"},
"Lakeside Hostel": {"credit_limit": 2000, "terms_days": 14, "contact": "manager"},
"Atlas Outdoor Inc": {"credit_limit": 8000, "terms_days": 30, "contact": "AP portal, PO required"}
}
}
FILE:scripts/ar_aging.py
#!/usr/bin/env python3
"""ar_aging.py - accounts receivable aging report from an invoice CSV (standard library only, Python 3.8+).
invoices.csv columns (header required; extra columns ignored):
invoice_id, customer, issue_date, due_date, amount, paid_amount, currency,
disputed (yes/no, optional), last_contact (YYYY-MM-DD, optional)
customers.json (optional): {"default_terms_days": 30, "customers": {"Name": {"credit_limit": 10000, "terms_days": 30, "contact": "..."}}}
Report: open balance per invoice, aging buckets by days past due as of --as-of
(Current, 1-30, 31-60, 61-90, 90+), totals per customer and currency, % overdue,
approximate DSO (open balance / sales in the last --dso-days days x --dso-days),
a collection stage per overdue invoice, and findings:
A01 high open balance more than 90 days past due
A02 medium one customer holds more than --concentration % (default 30) of the open balance
A03 high customer open balance above its credit_limit
A04 low partially paid invoice still open
A05 medium disputed invoice (excluded from reminders, needs resolution)
A06 medium overdue with no contact logged in the last --contact-days (default 14)
A07 low overpaid invoice (customer credit to refund or apply)
A08 high data problem (bad date, negative amount, due before issue, duplicate id)
Usage: ar_aging.py invoices.csv [customers.json] [--as-of YYYY-MM-DD] [--format text|md|json|csv]
[--min-severity low|medium|high] [--concentration PCT] [--contact-days N] [--dso-days N]
ar_aging.py --self-test
Exit: 0 no findings at or above --min-severity, 1 findings, 2 usage/input error.
"""
import argparse, csv, datetime as dt, io, json, sys
from collections import OrderedDict, defaultdict
BUCKETS = ["Current", "1-30", "31-60", "61-90", "90+"]
SEV = {"low": 1, "medium": 2, "high": 3}
def bucket(days_past_due):
if days_past_due <= 0: return "Current"
if days_past_due <= 30: return "1-30"
if days_past_due <= 60: return "31-60"
if days_past_due <= 90: return "61-90"
return "90+"
def stage(days_past_due, disputed):
if disputed: return "hold: resolve dispute first"
if days_past_due <= 0: return "none (not due)"
if days_past_due <= 7: return "1 friendly reminder"
if days_past_due <= 30: return "2 firm reminder + call"
if days_past_due <= 60: return "3 escalate to decision maker, pause new work"
if days_past_due <= 90: return "4 final notice with date"
return "5 payment plan or collections/legal review"
def parse_date(s):
return dt.datetime.strptime(s.strip(), "%Y-%m-%d").date()
def money(s):
s = (s or "").strip().replace(",", "")
return round(float(s), 2) if s else 0.0
def load_invoices(text):
rows, problems, seen = [], [], set()
reader = csv.DictReader(io.StringIO(text))
need = {"invoice_id", "customer", "issue_date", "due_date", "amount"}
if not reader.fieldnames or not need <= {f.strip() for f in reader.fieldnames}:
raise ValueError("invoices.csv needs columns: " + ", ".join(sorted(need)))
for n, r in enumerate(reader, 2):
r = {k.strip(): (v or "").strip() for k, v in r.items() if k}
iid = r["invoice_id"]
try:
issue, due = parse_date(r["issue_date"]), parse_date(r["due_date"])
amount, paid = money(r["amount"]), money(r.get("paid_amount"))
last = parse_date(r["last_contact"]) if r.get("last_contact") else None
except ValueError as e:
problems.append((iid or "line %d" % n, "line %d: %s" % (n, e))); continue
if iid in seen:
problems.append((iid, "duplicate invoice_id %s (line %d skipped)" % (iid, n))); continue
seen.add(iid)
if amount < 0 or paid < 0:
problems.append((iid, "negative amount on line %d" % n)); continue
if due < issue:
problems.append((iid, "due_date before issue_date on line %d" % n))
rows.append(dict(invoice_id=iid, customer=r["customer"], issue=issue, due=due, amount=amount, paid=paid,
currency=r.get("currency") or "EUR", disputed=r.get("disputed", "").lower() in ("yes", "y", "true", "1"),
last_contact=last))
return rows, problems
def analyze(rows, problems, customers, o):
as_of = o.as_of
inv, findings = [], []
def add(code, sev, ref, msg): findings.append(dict(code=code, severity=sev, ref=ref, message=msg))
for ref, msg in problems: add("A08", "high", ref, msg)
for r in rows:
open_bal = round(r["amount"] - r["paid"], 2)
dpd = (as_of - r["due"]).days
rec = dict(r, open=open_bal, days_past_due=dpd, bucket=bucket(dpd) if open_bal > 0 else "-", stage=stage(dpd, r["disputed"]) if open_bal > 0 else "-")
inv.append(rec)
if open_bal < 0:
add("A07", "low", r["invoice_id"], "%s overpaid by %.2f %s: refund or apply as credit" % (r["customer"], -open_bal, r["currency"]))
continue
if open_bal == 0: continue
if r["paid"] > 0:
add("A04", "low", r["invoice_id"], "partially paid: %.2f of %.2f %s still open" % (open_bal, r["amount"], r["currency"]))
if r["disputed"]:
add("A05", "medium", r["invoice_id"], "disputed (%.2f %s, %d days past due): resolve before chasing" % (open_bal, r["currency"], max(dpd, 0)))
if dpd > 90:
add("A01", "high", r["invoice_id"], "%s: %.2f %s is %d days past due" % (r["customer"], open_bal, r["currency"], dpd))
if dpd > 0 and not r["disputed"]:
since = (as_of - r["last_contact"]).days if r["last_contact"] else None
if since is None or since > o.contact_days:
add("A06", "medium", r["invoice_id"], "%d days overdue, %s" % (dpd, "no contact logged" if since is None else "last contact %d days ago" % since))
# per currency summaries
by_cur = OrderedDict()
for r in inv:
if r["open"] <= 0: continue
c = by_cur.setdefault(r["currency"], dict(total=0.0, buckets={b: 0.0 for b in BUCKETS}, customers=defaultdict(lambda: {b: 0.0 for b in BUCKETS})))
c["total"] += r["open"]; c["buckets"][r["bucket"]] += r["open"]; c["customers"][r["customer"]][r["bucket"]] += r["open"]
summaries = OrderedDict()
for cur, c in by_cur.items():
total = round(c["total"], 2)
overdue = round(total - c["buckets"]["Current"], 2)
sales = sum(r["amount"] for r in inv if r["currency"] == cur and 0 <= (as_of - r["issue"]).days < o.dso_days)
dso = round(total / sales * o.dso_days, 1) if sales else None
custs = []
for name, b in c["customers"].items():
ct = round(sum(b.values()), 2)
custs.append(dict(customer=name, total=ct, buckets={k: round(v, 2) for k, v in b.items()}, share_pct=round(100 * ct / total, 1) if total else 0))
if total and 100 * ct / total > o.concentration and len(c["customers"]) > 1:
add("A02", "medium", name, "holds %.1f%% of open %s receivables (%.2f)" % (100 * ct / total, cur, ct))
lim = (customers.get("customers", {}).get(name) or {}).get("credit_limit")
if lim is not None and ct > lim:
add("A03", "high", name, "open balance %.2f %s exceeds credit limit %.2f" % (ct, cur, lim))
custs.sort(key=lambda x: -x["total"])
summaries[cur] = dict(total=total, overdue=overdue, overdue_pct=round(100 * overdue / total, 1) if total else 0,
buckets={k: round(v, 2) for k, v in c["buckets"].items()}, dso=dso, customers=custs)
order = {"high": 0, "medium": 1, "low": 2}
findings.sort(key=lambda f: (order[f["severity"]], f["code"], f["ref"]))
return inv, summaries, findings
def render(inv, summaries, findings, o):
minsev = SEV[o.min_severity]
shown = [f for f in findings if SEV[f["severity"]] >= minsev]
if o.format == "json":
def ser(r): return {k: (v.isoformat() if isinstance(v, dt.date) else v) for k, v in r.items()}
return json.dumps(dict(as_of=o.as_of.isoformat(), summaries=summaries, invoices=[ser(r) for r in inv if r["open"] != 0], findings=shown), indent=2)
if o.format == "csv":
out = io.StringIO(); w = csv.writer(out)
w.writerow(["invoice_id", "customer", "currency", "due_date", "days_past_due", "bucket", "open", "disputed", "stage"])
for r in sorted(inv, key=lambda r: -r["days_past_due"]):
if r["open"] > 0: w.writerow([r["invoice_id"], r["customer"], r["currency"], r["due"].isoformat(), r["days_past_due"], r["bucket"], "%.2f" % r["open"], "yes" if r["disputed"] else "no", r["stage"]])
return out.getvalue().rstrip("\n")
md = o.format == "md"
L = ["# AR aging as of %s" % o.as_of if md else "AR aging as of %s" % o.as_of, ""]
for cur, s in summaries.items():
L.append(("## %s: open %.2f, overdue %.2f (%.1f%%), DSO %s" if md else "%s: open %.2f, overdue %.2f (%.1f%%), DSO %s") % (cur, s["total"], s["overdue"], s["overdue_pct"], "%.1f days" % s["dso"] if s["dso"] is not None else "n/a"))
L.append("")
hdr = ["Customer"] + BUCKETS + ["Total", "Share"]
if md:
L.append("| " + " | ".join(hdr) + " |"); L.append("|" + "---|" * len(hdr))
else:
L.append("%-22s" % hdr[0] + "".join("%11s" % h for h in hdr[1:]))
rows = s["customers"] + [dict(customer="TOTAL", total=s["total"], buckets=s["buckets"], share_pct=100.0)]
for c in rows:
vals = ["%.2f" % c["buckets"][b] for b in BUCKETS] + ["%.2f" % c["total"], "%.1f%%" % c["share_pct"]]
L.append("| " + " | ".join([c["customer"]] + vals) + " |" if md else "%-22s" % c["customer"][:22] + "".join("%11s" % v for v in vals))
L.append("")
L.append("## Overdue invoices and next step" if md else "Overdue invoices and next step:")
od = sorted([r for r in inv if r["open"] > 0 and r["days_past_due"] > 0], key=lambda r: -r["days_past_due"])
for r in od:
L.append("%s %s %s %.2f %s, %d days past due -> %s" % ("-" if md else " ", r["invoice_id"], r["customer"], r["open"], r["currency"], r["days_past_due"], r["stage"]))
if not od: L.append(" none")
L.append("")
L.append(("## Findings (%s+)" if md else "Findings (%s+):") % o.min_severity)
for f in shown:
L.append("%s [%s] %s %s: %s" % ("-" if md else " ", f["severity"].upper(), f["code"], f["ref"], f["message"]))
if not shown: L.append(" none")
return "\n".join(L)
def parser():
p = argparse.ArgumentParser(description="Accounts receivable aging report.")
p.add_argument("invoices", nargs="?")
p.add_argument("customers", nargs="?")
p.add_argument("--as-of", type=parse_date, default=dt.date.today())
p.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
p.add_argument("--min-severity", choices=list(SEV), default="low")
p.add_argument("--concentration", type=float, default=30.0)
p.add_argument("--contact-days", type=int, default=14)
p.add_argument("--dso-days", type=int, default=90)
p.add_argument("--self-test", action="store_true")
return p
def self_test():
o = parser().parse_args(["--as-of", "2026-06-30"])
H = "invoice_id,customer,issue_date,due_date,amount,paid_amount,currency,disputed,last_contact\n"
checks = []
def check(n, c): checks.append((n, bool(c)))
def run(body, cust=None, **kw):
oo = parser().parse_args(["--as-of", "2026-06-30"]); [setattr(oo, k, v) for k, v in kw.items()]
rows, probs = load_invoices(H + body)
return analyze(rows, probs, cust or {}, oo)
codes = lambda f: sorted({x["code"] for x in f})
check("bucket edges", [bucket(d) for d in (0, 1, 30, 31, 60, 61, 90, 91)] == ["Current", "1-30", "1-30", "31-60", "31-60", "61-90", "61-90", "90+"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,1000,0,EUR,,\n")
check("not yet due is Current, no findings", inv[0]["bucket"] == "Current" and f == [])
inv, s, f = run("I1,Acme,2026-05-01,2026-05-31,1000,0,EUR,,2026-06-25\n")
check("30 days past due in 1-30 with recent contact", inv[0]["bucket"] == "1-30" and f == [])
inv, s, f = run("I1,Acme,2026-01-01,2026-01-31,500,0,EUR,,2026-06-29\n")
check("150 days past due gives A01", "A01" in codes(f) and inv[0]["bucket"] == "90+")
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,0,EUR,,\n")
check("overdue without contact gives A06", codes(f) == ["A06"])
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,0,EUR,,2026-06-01\n", contact_days=14)
check("stale contact gives A06", codes(f) == ["A06"])
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,200,EUR,,2026-06-28\n")
check("partial payment gives A04 and open 300", codes(f) == ["A04"] and inv[0]["open"] == 300)
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,0,EUR,yes,\n")
check("disputed gives A05, no A06, hold stage", codes(f) == ["A05"] and inv[0]["stage"].startswith("hold"))
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,600,EUR,,\n")
check("overpaid gives A07 only", codes(f) == ["A07"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,9000,0,EUR,,\nI2,Bolt,2026-06-01,2026-07-01,1000,0,EUR,,\n")
check("concentration A02 for 90% customer", [x["ref"] for x in f if x["code"] == "A02"] == ["Acme"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,9000,0,EUR,,\n", {"customers": {"Acme": {"credit_limit": 5000}}})
check("credit limit A03, single customer no A02", codes(f) == ["A03"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,100,0,EUR,,\nI1,Acme,2026-06-01,2026-07-01,100,0,EUR,,\nI3,Acme,2026-13-01,2026-07-01,100,0,EUR,,\nI4,Acme,2026-06-01,2026-07-01,-5,0,EUR,,\n")
check("duplicate, bad date, negative give A08 x3", len([x for x in f if x["code"] == "A08"]) == 3 and len(inv) == 1)
inv, s, f = run("I1,Acme,2026-06-10,2026-06-01,100,0,EUR,,2026-06-29\n")
check("due before issue flagged A08 but kept", "A08" in codes(f) and len(inv) == 1)
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,1000,0,EUR,,\nI2,Acme,2026-06-01,2026-07-01,800,0,USD,,\n")
check("currencies kept separate", set(s) == {"EUR", "USD"} and s["USD"]["total"] == 800)
inv, s, f = run("I1,Acme,2026-04-15,2026-05-15,3000,0,EUR,,2026-06-29\nI2,Acme,2026-06-15,2026-07-15,3000,0,EUR,,\n")
check("DSO = open / 90-day sales x 90", s["EUR"]["dso"] == 90.0 and s["EUR"]["overdue_pct"] == 50.0)
check("stage ladder", [stage(d, False)[0] for d in (3, 20, 45, 80, 120)] == ["1", "2", "3", "4", "5"])
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,1000,1000,EUR,,\n")
check("fully paid invoice ignored", f == [] and s == {})
try:
load_invoices("id,name\n1,x\n"); check("missing columns rejected", False)
except ValueError:
check("missing columns rejected", True)
oo = parser().parse_args(["--as-of", "2026-06-30", "--format", "csv"])
rows, probs = load_invoices(H + "I1,Acme,2026-05-01,2026-06-01,500,0,EUR,,\n")
out = render(*analyze(rows, probs, {}, oo), oo)
check("csv output has header and row", out.splitlines()[0].startswith("invoice_id") and "I1,Acme" in out)
oo.format = "json"
check("json output parses", json.loads(render(*analyze(rows, probs, {}, oo), oo))["as_of"] == "2026-06-30")
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 all(c for _, c in checks) else 1
def main(argv=None):
o = parser().parse_args(argv)
if o.self_test: return self_test()
if not o.invoices:
parser().print_usage(sys.stderr); return 2
try:
with open(o.invoices, encoding="utf-8-sig") as fh: rows, probs = load_invoices(fh.read())
customers = json.load(open(o.customers, encoding="utf-8")) if o.customers else {}
except (OSError, ValueError) as e:
print("input error: %s" % e, file=sys.stderr); return 2
inv, summaries, findings = analyze(rows, probs, customers, o)
print(render(inv, summaries, findings, o))
return 1 if any(SEV[f["severity"]] >= SEV[o.min_severity] for f in findings) else 0
if __name__ == "__main__":
sys.exit(main())
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())
Checks a draft staff rota from a CSV before you publish it: rest gaps between shifts, overlaps, unavailable days, consecutive days, weekly hours vs contract, long shifts, coverage gaps, and fair sharing of weekends, nights, closes and clopens, with swap ideas. Stdlib Python.
---
name: staff-rota-fairness-checker
description: Checks a draft staff rota from a CSV before you publish it: rest gaps between shifts, overlaps, unavailable days, consecutive days, weekly hours vs contract, long shifts, coverage gaps, and fair sharing of weekends, nights, closes and clopens, with swap ideas. Stdlib Python.
---
# Staff Rota Fairness Checker
You help shop, cafe, restaurant, clinic, warehouse and support team managers check a draft shift rota before it goes out. Rotas built by hand or in a spreadsheet often hide problems: a close at 22:00 followed by a 07:00 open, someone working seven days in a row, a student booked on a school day, an empty lunch rush, or the same two people always getting the weekends. You find these problems, explain them in plain language, and propose concrete swaps that fix them without creating new ones.
You work on the user's data locally; the rota contains personal data, so you never upload it anywhere. You are not an employment lawyer: the limits come from the user's `rules.json`, and you remind them to confirm working-time rules with HR, their contracts or local law. The manager makes the final decision.
## Files in this skill
- `scripts/rota_check.py` - reads `rota.csv` (date, employee, start, end, role; overnight shifts supported) and `rules.json`, prints a per-person summary (shifts, paid hours, contract, weekends, nights, closes) and findings R01-R07 (rest, overlap, unavailable, consecutive days, weekly hours over/under, long shifts), C01 (coverage per 30-minute slot, by role and weekday) and F01-F04 (weekend, night, closing and clopen fairness); `--format text|md|json`, `--min-severity`; `--self-test` runs 24 checks (Python 3.8+ standard library only)
- `references/rest-and-hours-rules.md` - what each limit means, common reference points such as 11 hours daily rest, and edge cases
- `references/fairness-metrics.md` - how the hours-weighted fair share works, exemptions, and swaps that usually fix each flag
- `templates/rota-review.md` - the review you hand back to the manager
- `examples/rota.csv`, `examples/rules.json` - a fictional six-person cafe, two weeks, with typical mistakes (3 clopens, a 7-day run, an over-hours week, unavailable days, a short-staffed weekend lunch, uneven weekends and closes)
## Workflow
### 1. Collect the rota and the rules
Ask for the draft rota (export the spreadsheet as CSV with date, employee, start, end and optionally role) and fill `rules.json` together: contract hours per person, availability (leave dates, weekdays they cannot work), exemptions (`no_weekends`, `no_nights`, `no_closes`), minimum rest, max consecutive days, overtime allowance, and the coverage the business needs (for example 2 people at lunch, 3 at weekend lunch, 1 cook at all times). If the user does not know a limit, use the defaults and say which ones you assumed.
### 2. Run the check
```
python3 scripts/rota_check.py rota.csv rules.json
python3 scripts/rota_check.py rota.csv rules.json --format md > review-table.md
python3 scripts/rota_check.py rota.csv rules.json --min-severity medium --format json
python3 scripts/rota_check.py --self-test
```
Exit 0 = no high findings, 1 = at least one high finding, 2 = bad input. Without a shell, sort shifts per person by start time and check the gaps, days in a row and weekly totals by hand using `references/rest-and-hours-rules.md`.
### 3. Explain the findings
Group them for the manager: **must fix** (high: rest gaps, overlaps, unavailable days, coverage gaps), **should fix** (medium: long runs, over-hours, weekend and night imbalance), **nice to fix** (low: under-hours, closes, clopens). Use names and dates, not codes, in the explanation.
### 4. Propose swaps
Suggest the smallest set of swaps that clears the high findings without breaking coverage: swap shifts of the same length and role, prefer the person furthest below their contract hours, and avoid creating a new clopen. Follow `references/fairness-metrics.md`. Re-run the check after the changes and show the before/after counts.
### 5. Report
Fill `templates/rota-review.md` with the result, the proposed swaps, the fairness summary and a short note the manager can share with the team (how weekends and closes were shared, without private reasons for exemptions).
## Rules
- Treat the rota as personal data: keep it local and do not repeat health or private reasons for unavailability in the team note.
- Never present the defaults as legal limits; say they are configurable starting points.
- Do not silently drop a person's availability or exemption to make the rota fit; flag the conflict and let the manager decide.
- Fairness is judged over a longer period than one rota when history is available; mention when two weeks is too short to judge.
FILE:references/rest-and-hours-rules.md
# Rest, hours and coverage rules: what the checks mean
The script checks the limits you put in `rules.json`. It does not know your country's law, your collective agreement or each contract. Always confirm the numbers with HR, your payroll provider or an employment adviser before you rely on them.
## Common reference points (check your own rules)
| Topic | Typical reference | rules.json key |
|---|---|---|
| Daily rest between shifts | 11 consecutive hours in every 24 (EU Working Time Directive); some sectors allow less with compensating rest | `min_rest_hours` |
| Weekly rest | 24 hours uninterrupted per 7 days in the EU, often 2 days off in contracts | `max_consecutive_days` (6 = at least one day off in 7) |
| Weekly hours | 48 h average including overtime in the EU (averaged over a reference period); contracts are usually lower | `contract_hours`, `overtime_allowance`, `max_weekly_hours` |
| Night work | Often 22:00-06:00 or similar; night workers may have extra limits and health checks | `night_start`, `night_end`, `night_min_hours` |
| Breaks | Commonly a break after 6 hours of work; unpaid in many contracts | `unpaid_break_minutes_over_6h` |
| Young workers / students | Stricter limits on hours, nights and rest in most countries | add per-person `max_weekly_hours`, `no_nights`, `unavailable_weekdays` |
## Codes
- **R01 rest gap**: time between the end of one shift and the start of the next for the same person. A close at 22:00 and an open at 07:00 is only 9 hours.
- **R02 overlap**: the same person is on two shifts at the same time, usually a copy-paste error.
- **R03 unavailable**: the shift falls on a date in `unavailable` (leave, approved requests) or a weekday in `unavailable_weekdays` (school day, second job, childcare).
- **R04 consecutive days**: calendar days in a row with at least one shift start.
- **R05 / R06 weekly hours**: paid hours per ISO week (Monday-Sunday) after unpaid breaks. Over `max_weekly_hours` (or contract + `overtime_allowance`) is R05; below contract minus `under_tolerance_hours` is R06 (people on fixed contracts lose pay or must be paid anyway).
- **R07 long shift**: shift length including breaks over `max_shift_hours`.
- **C01 coverage**: checked every 30 minutes inside each coverage window; consecutive short slots are reported as one window. Use `role` to require a specific role (e.g. a cook) and `weekdays` (0 = Monday) for busy days.
- A shift whose end time is at or before its start time ends the next day (22:00-06:00).
## Edge cases to mention to the user
- A rota that crosses a week boundary will show partial weeks at the start and end; R05/R06 for those weeks may be misleading.
- Hours averaged over several weeks (common for the 48 h limit) are not calculated; check the totals in the summary table.
- Paid leave, sick days and training are not shifts; add them as `unavailable` dates so they are not double-booked.
FILE:references/fairness-metrics.md
# Fairness metrics
Unpopular shifts (weekends, nights, closing late) cause most rota complaints and quiet resignations. The script makes the split visible so a manager can fix it before publishing.
## Fair share
For each unpopular shift type, the fair share of a person is:
fair_share = total shifts of that type x (person's paid hours / paid hours of everyone eligible)
So a 20-hour part-timer is expected to take about half as many weekends as a full-timer. People marked `no_weekends`, `no_nights` or `no_closes` in `rules.json` are left out of the pool (their shifts of that type still count toward the total, which makes the others' fair share smaller).
A person is flagged when `|actual - fair_share| > fairness_tolerance` (default 1 shift over the rota period). Both sides are flagged: the person who carries too many and the one who carries too few, because the fix is usually a swap between them.
| Code | Shift type | Counted when |
|---|---|---|
| F01 | weekend | the shift starts on a day in `weekend_days` (default Saturday and Sunday) |
| F02 | night | at least `night_min_hours` (default 3) of the shift fall in the night window |
| F03 | closing | the shift ends at or after `closing_after` or ends the next day |
| F04 | clopen | a closing shift followed by an opening shift (start before `opening_before`) less than 14 h later, even when it passes the legal rest rule |
## Reading fairness over time
Two weeks is a short window: one person can carry two weekends now and none next month. When possible, run the check on the last 6-8 weeks of actual rotas together with the new draft, or keep a running tally per person and compare it with the fair share for the whole period.
## Exemptions are a decision, not a default
Exemptions (students, carers, people with a medical note, religious days off) are legitimate, but they shift load onto others. Record the reason, review exemptions every few months, and tell the team how unpopular shifts are shared, without sharing private reasons.
## Swaps that usually fix flags
- Weekend imbalance: swap a weekday shift of the under-loaded person with a weekend shift of the over-loaded person of the same type and length.
- Clopens: move the closer's next-day open to a mid or late shift, or give the open to someone who was off the evening before.
- Too many consecutive days: insert a day off and give that shift to the person furthest below their contract hours that week.
FILE:templates/rota-review.md
# Rota review: {{team_or_location}}, {{period}}
**Checked:** {{date}} with `rota_check.py` against `{{rules_file}}` ({{n_people}} people, {{n_shifts}} shifts)
**Result:** {{high}} high, {{medium}} medium, {{low}} low
## Must fix before publishing (high)
| # | Who | When | Problem | Proposed change |
|---|---|---|---|---|
| 1 | {{name}} | {{when}} | {{problem}} | {{swap_or_change}} |
## Should fix (medium)
| # | Who | When | Problem | Proposed change |
|---|---|---|---|---|
## Fairness summary
| Person | Paid h (contract) | Weekends (fair) | Nights (fair) | Closes (fair) |
|---|---|---|---|---|
| {{name}} | {{hours}} ({{contract}}) | {{weekends}} ({{fair}}) | {{nights}} ({{fair}}) | {{closes}} ({{fair}}) |
## Proposed swaps
1. {{person A}} {{shift}} <-> {{person B}} {{shift}}: fixes {{codes}}; re-check: {{result}}
## Notes for the team announcement
- {{how unpopular shifts were shared this period}}
- {{open shifts or requests still pending}}
_Limits used come from rules.json; confirm working-time rules with HR or local law._
FILE:examples/rota.csv
date,employee,start,end,role
2026-12-07,Ana,07:00,15:00,barista
2026-12-07,Cem,11:00,19:00,kitchen
2026-12-07,Ben,14:00,22:00,barista
2026-12-08,Ana,07:00,15:00,barista
2026-12-08,Emre,11:00,19:00,kitchen
2026-12-08,Ben,14:00,22:00,barista
2026-12-09,Ana,07:00,15:00,barista
2026-12-09,Cem,11:00,19:00,kitchen
2026-12-09,Ben,14:00,22:00,barista
2026-12-10,Ana,07:00,15:00,barista
2026-12-10,Fatma,11:00,19:00,kitchen
2026-12-10,Ben,14:00,22:00,barista
2026-12-11,Ana,07:00,15:00,barista
2026-12-11,Emre,11:00,19:00,kitchen
2026-12-11,Ben,14:00,22:00,barista
2026-12-12,Cem,07:00,15:00,kitchen
2026-12-12,Fatma,11:00,19:00,kitchen
2026-12-12,Ben,14:00,22:00,barista
2026-12-12,Dilan,10:00,18:00,barista
2026-12-13,Dilan,07:00,15:00,barista
2026-12-13,Fatma,11:00,19:00,kitchen
2026-12-13,Ben,14:00,22:00,barista
2026-12-13,Cem,10:00,18:00,kitchen
2026-12-14,Ana,07:00,15:00,barista
2026-12-14,Cem,11:00,19:00,kitchen
2026-12-14,Dilan,14:00,22:00,barista
2026-12-15,Ana,07:00,15:00,barista
2026-12-15,Emre,11:00,19:00,kitchen
2026-12-15,Dilan,14:00,22:00,barista
2026-12-16,Ana,07:00,15:00,barista
2026-12-16,Fatma,11:00,19:00,kitchen
2026-12-16,Dilan,14:00,22:00,barista
2026-12-17,Dilan,07:00,15:00,barista
2026-12-17,Cem,11:00,19:00,kitchen
2026-12-17,Ana,14:00,22:00,barista
2026-12-18,Ana,07:00,15:00,barista
2026-12-18,Emre,11:00,19:00,kitchen
2026-12-18,Ben,14:00,22:00,barista
2026-12-19,Ben,07:00,15:00,barista
2026-12-19,Cem,11:00,19:00,kitchen
2026-12-19,Dilan,14:00,22:00,barista
2026-12-19,Fatma,10:00,18:00,kitchen
2026-12-20,Ben,07:00,15:00,barista
2026-12-20,Fatma,11:00,19:00,kitchen
2026-12-20,Dilan,14:00,22:00,barista
FILE:examples/rules.json
{
"business": "Corner Cafe, open 07:00-22:00 every day (fictional example)",
"min_rest_hours": 11,
"max_consecutive_days": 6,
"max_shift_hours": 10,
"overtime_allowance": 4,
"night_start": "22:00",
"night_end": "06:00",
"closing_after": "22:00",
"opening_before": "08:00",
"fairness_tolerance": 1,
"under_tolerance_hours": 4,
"weekend_days": [
5,
6
],
"unpaid_break_minutes_over_6h": 30,
"staff": {
"Ana": {
"contract_hours": 37.5
},
"Ben": {
"contract_hours": 37.5
},
"Cem": {
"contract_hours": 30,
"unavailable": [
"2026-12-19"
]
},
"Dilan": {
"contract_hours": 30
},
"Emre": {
"contract_hours": 20,
"no_weekends": true,
"unavailable_weekdays": [
4
]
},
"Fatma": {
"contract_hours": 24
}
},
"coverage": [
{
"name": "opening",
"from": "07:00",
"to": "10:00",
"min": 1
},
{
"name": "lunch rush",
"from": "11:30",
"to": "14:30",
"min": 2
},
{
"name": "weekend lunch rush",
"weekdays": [
5,
6
],
"from": "11:30",
"to": "14:30",
"min": 3
},
{
"name": "evening",
"from": "15:00",
"to": "22:00",
"min": 1
}
]
}
FILE:scripts/rota_check.py
#!/usr/bin/env python3
"""rota_check.py - check a planned staff rota (shift schedule) for rest, hours, coverage and fairness problems, offline.
Input:
rota.csv columns: date (YYYY-MM-DD), employee, start (HH:MM), end (HH:MM), role (optional)
A shift whose end is at or before its start ends the next day (e.g. 22:00-06:00).
rules.json staff contracts, availability and limits (see examples/rules.json); every key is optional.
Checks:
R01 high rest between two shifts of one person below min_rest_hours
R02 high overlapping shifts for one person
R03 high scheduled on a day the person is unavailable (leave, request, school, etc.)
R04 medium more consecutive working days than max_consecutive_days
R05 medium weekly hours above the person's max_weekly_hours (or contract + overtime_allowance)
R06 low weekly hours below min_weekly_hours / contract minus under_tolerance
R07 medium single shift longer than max_shift_hours
C01 high fewer staff (or fewer of a role) than required in a coverage window
F01 medium weekend shifts unevenly shared (vs. hours-weighted fair share)
F02 medium night shifts unevenly shared
F03 low closing shifts (ending at/after closing_after) unevenly shared
F04 low "clopen": a closing shift followed by an opening shift (start before opening_before)
Usage:
python3 rota_check.py rota.csv rules.json [--format text|md|json] [--min-severity low|medium|high]
python3 rota_check.py --self-test
Exit codes: 0 = no high findings, 1 = at least one high finding, 2 = bad input.
Not legal advice: limits come from rules.json; check local working-time law and contracts.
Standard library only, Python 3.8+.
"""
import argparse, csv, io, json, sys
from collections import defaultdict
from datetime import date, datetime, timedelta
SEV = {"R01": "high", "R02": "high", "R03": "high", "R04": "medium", "R05": "medium", "R06": "low", "R07": "medium",
"C01": "high", "F01": "medium", "F02": "medium", "F03": "low", "F04": "low"}
RANK = {"low": 0, "medium": 1, "high": 2}
DEFAULTS = {"min_rest_hours": 11, "max_consecutive_days": 6, "max_shift_hours": 10, "overtime_allowance": 0,
"night_start": "22:00", "night_end": "06:00", "night_min_hours": 3, "closing_after": "22:00",
"opening_before": "08:00", "fairness_tolerance": 1, "under_tolerance_hours": 4,
"weekend_days": [5, 6], "unpaid_break_minutes_over_6h": 30}
class Shift:
def __init__(self, emp, start, end, role, line):
self.emp, self.start, self.end, self.role, self.line = emp, start, end, role, line
@property
def hours(self):
return (self.end - self.start).total_seconds() / 3600
def label(self):
return "%s %s-%s" % (self.start.strftime("%a %Y-%m-%d"), self.start.strftime("%H:%M"), self.end.strftime("%H:%M"))
def hm(s):
h, m = s.strip().split(":")
return int(h), int(m)
def parse_rota(text):
rows = list(csv.DictReader(io.StringIO(text)))
need = {"date", "employee", "start", "end"}
if not rows or not need <= set(k.strip().lower() for k in rows[0].keys()):
raise ValueError("rota.csv needs columns: date, employee, start, end (role optional)")
shifts = []
for i, r in enumerate(rows, 2):
r = {k.strip().lower(): (v or "").strip() for k, v in r.items()}
if not r["employee"]:
continue
try:
d = datetime.strptime(r["date"], "%Y-%m-%d")
sh, sm = hm(r["start"]); eh, em = hm(r["end"])
except ValueError:
raise ValueError("bad date or time on rota.csv line %d" % i)
start = d.replace(hour=sh, minute=sm)
end = d.replace(hour=eh, minute=em)
if end <= start:
end += timedelta(days=1)
shifts.append(Shift(r["employee"], start, end, r.get("role", ""), i))
if not shifts:
raise ValueError("rota.csv has no shifts")
return shifts
def paid_hours(s, rules):
h = s.hours
if h > 6:
h -= rules["unpaid_break_minutes_over_6h"] / 60
return h
def night_hours(s, rules):
"""Hours of the shift that fall inside the night window (default 22:00-06:00)."""
nh, nm = hm(rules["night_start"]); eh, em = hm(rules["night_end"])
total = 0.0
day = s.start.replace(hour=0, minute=0) - timedelta(days=1)
while day < s.end:
ws = day.replace(hour=nh, minute=nm)
we = day.replace(hour=eh, minute=em)
if we <= ws:
we += timedelta(days=1)
a, b = max(ws, s.start), min(we, s.end)
if b > a:
total += (b - a).total_seconds() / 3600
day += timedelta(days=1)
return total
def week_key(dt):
y, w, _ = dt.isocalendar()[:3]
return "%d-W%02d" % (y, w)
def check(shifts, rules_in):
rules = dict(DEFAULTS); rules.update({k: v for k, v in rules_in.items() if k not in ("staff", "coverage")})
staff = rules_in.get("staff", {})
F = []
def add(code, who, when, detail, at=None):
F.append({"code": code, "severity": SEV[code], "employee": who, "when": when, "detail": detail,
"at": at.strftime("%Y-%m-%dT%H:%M") if at else ""})
by_emp = defaultdict(list)
for s in shifts:
by_emp[s.emp].append(s)
first = min(s.start for s in shifts).date(); last = max(s.start for s in shifts).date()
n_weeks = max(1, ((last - first).days + 1) / 7)
stats = {}
for emp, ss in sorted(by_emp.items()):
ss.sort(key=lambda s: s.start)
info = staff.get(emp, {})
for s in ss:
if s.hours > rules["max_shift_hours"]:
add("R07", emp, s.label(), "%.1f h shift; limit %s h" % (s.hours, rules["max_shift_hours"]), s.start)
if s.start.strftime("%Y-%m-%d") in info.get("unavailable", []) or s.start.weekday() in info.get("unavailable_weekdays", []):
add("R03", emp, s.label(), "marked unavailable that day", s.start)
for a, b in zip(ss, ss[1:]):
gap = (b.start - a.end).total_seconds() / 3600
if gap < 0:
add("R02", emp, "%s and %s" % (a.label(), b.label()), "shifts overlap by %.1f h" % -gap, a.start)
elif gap < rules["min_rest_hours"]:
add("R01", emp, "%s -> %s" % (a.label(), b.label()), "only %.1f h rest; minimum %s h" % (gap, rules["min_rest_hours"]), a.start)
ch, cm = hm(rules["closing_after"]); oh, om = hm(rules["opening_before"])
a_close = a.end.time() >= a.end.replace(hour=ch, minute=cm).time() or a.end.date() > a.start.date()
b_open = b.start.time() < b.start.replace(hour=oh, minute=om).time()
if gap >= 0 and a_close and b_open and gap < 14:
add("F04", emp, "%s -> %s" % (a.label(), b.label()), "close then open ('clopen'), %.1f h apart" % gap, a.start)
days = sorted({s.start.date() for s in ss})
run, start_run = 1, days[0]
for p, q in zip(days, days[1:] + [None]):
if q is not None and (q - p).days == 1:
run += 1
continue
if run > rules["max_consecutive_days"]:
add("R04", emp, "%s to %s" % (start_run, p), "%d days in a row; limit %d" % (run, rules["max_consecutive_days"]), datetime.combine(start_run, datetime.min.time()))
run, start_run = 1, q
weeks = defaultdict(float)
for s in ss:
weeks[week_key(s.start)] += paid_hours(s, rules)
contract = info.get("contract_hours")
max_w = info.get("max_weekly_hours", (contract + rules["overtime_allowance"]) if contract else None)
min_w = info.get("min_weekly_hours", (contract - rules["under_tolerance_hours"]) if contract else None)
for wk, h in sorted(weeks.items()):
if max_w is not None and h > max_w + 1e-9:
add("R05", emp, wk, "%.1f paid h; max %s" % (h, max_w))
if min_w is not None and h < min_w - 1e-9:
add("R06", emp, wk, "%.1f paid h; contract %s h (tolerance %s h)" % (h, contract, rules["under_tolerance_hours"]))
ch, cm = hm(rules["closing_after"])
stats[emp] = {"shifts": len(ss), "paid_hours": round(sum(paid_hours(s, rules) for s in ss), 1),
"weekend": sum(1 for s in ss if s.start.weekday() in rules["weekend_days"]),
"nights": sum(1 for s in ss if night_hours(s, rules) >= rules["night_min_hours"]),
"closes": sum(1 for s in ss if s.end.date() > s.start.date() or (s.end.hour, s.end.minute) >= (ch, cm)),
"contract_hours": contract}
# fairness: compare each person's count with an hours-weighted fair share; exempt people listed in no_nights etc.
total_h = sum(v["paid_hours"] for v in stats.values()) or 1
for code, key, exempt_key, label in (("F01", "weekend", "no_weekends", "weekend shifts"), ("F02", "nights", "no_nights", "night shifts"),
("F03", "closes", "no_closes", "closing shifts")):
pool = {e: v for e, v in stats.items() if not staff.get(e, {}).get(exempt_key)}
total = sum(v[key] for v in stats.values())
pool_h = sum(v["paid_hours"] for v in pool.values()) or 1
if total == 0 or len(pool) < 2:
continue
for e, v in sorted(pool.items()):
fair = total * v["paid_hours"] / pool_h
v[key + "_fair"] = round(fair, 1)
if abs(v[key] - fair) > rules["fairness_tolerance"] + 1e-9:
add(code, e, "whole rota", "%d %s vs fair share %.1f (by paid hours; tolerance +/-%s)" % (v[key], label, fair, rules["fairness_tolerance"]))
# coverage
for cov in rules_in.get("coverage", []):
wd = cov.get("weekdays", list(range(7)))
fh, fm = hm(cov["from"]); th, tm = hm(cov["to"])
d = first
while d <= last:
if d.weekday() in wd:
t = datetime(d.year, d.month, d.day, fh, fm)
t_end = datetime(d.year, d.month, d.day, th, tm)
if t_end <= t:
t_end += timedelta(days=1)
gaps = []
while t < t_end:
on = [s for s in shifts if s.start <= t < s.end and (not cov.get("role") or s.role == cov["role"])]
if len(on) < cov["min"]:
gaps.append((t, len(on)))
t += timedelta(minutes=30)
ranges = []
for g in gaps:
if ranges and g[0] == ranges[-1][-1][0] + timedelta(minutes=30):
ranges[-1].append(g)
else:
ranges.append([g])
for rg in ranges:
lo = min(g[1] for g in rg)
add("C01", "-", "%s %s-%s" % (d.strftime("%a %Y-%m-%d"), rg[0][0].strftime("%H:%M"), (rg[-1][0] + timedelta(minutes=30)).strftime("%H:%M")),
"%s: as few as %d on shift, need %d%s" % (cov.get("name", "coverage"), lo, cov["min"], (" " + cov["role"]) if cov.get("role") else ""), rg[0][0])
d += timedelta(days=1)
order = {"high": 0, "medium": 1, "low": 2}
F.sort(key=lambda f: (order[f["severity"]], f["code"], f["at"], f["employee"]))
return {"period": "%s to %s" % (first, last), "weeks": round(n_weeks, 1), "people": stats, "findings": F}
def render(res, fmt):
if fmt == "json":
return json.dumps(res, indent=2, default=str)
P, F = res["people"], res["findings"]
c = {s: sum(1 for f in F if f["severity"] == s) for s in ("high", "medium", "low")}
if fmt == "md":
out = ["**Period:** %s (%s weeks). **Findings:** %d high, %d medium, %d low." % (res["period"], res["weeks"], c["high"], c["medium"], c["low"]), "",
"| Person | Shifts | Paid h | Contract h | Weekend | Nights | Closes |", "|---|---|---|---|---|---|---|"]
for e, v in P.items():
out.append("| %s | %d | %.1f | %s | %d | %d | %d |" % (e, v["shifts"], v["paid_hours"], v["contract_hours"] or "-", v["weekend"], v["nights"], v["closes"]))
out += ["", "| Code | Severity | Who | When | Problem |", "|---|---|---|---|---|"]
out += ["| %s | %s | %s | %s | %s |" % (f["code"], f["severity"], f["employee"], f["when"], f["detail"]) for f in F]
return "\n".join(out)
out = ["Rota %s (%s weeks)" % (res["period"], res["weeks"]), "",
"%-10s %6s %7s %9s %8s %7s %7s" % ("person", "shifts", "paid h", "contract", "weekend", "nights", "closes")]
for e, v in P.items():
out.append("%-10s %6d %7.1f %9s %8d %7d %7d" % (e, v["shifts"], v["paid_hours"], v["contract_hours"] or "-", v["weekend"], v["nights"], v["closes"]))
out.append("")
for f in F:
out.append("%s [%s] %s | %s | %s" % (f["code"], f["severity"], f["employee"], f["when"], f["detail"]))
out += ["", "Findings: %d high, %d medium, %d low." % (c["high"], c["medium"], c["low"])]
return "\n".join(out)
def self_test():
T = []
def run(csv_text, rules=None):
return check(parse_rota("date,employee,start,end,role\n" + csv_text), rules or {})
def codes(res, who=None):
return [f["code"] for f in res["findings"] if who is None or f["employee"] == who]
def ok(name, cond):
T.append((name, bool(cond)))
r = run("2026-12-01,Ana,14:00,23:00,\n2026-12-02,Ana,07:00,15:00,\n")
ok("8 h rest gives R01", "R01" in codes(r))
ok("close then open gives F04", "F04" in codes(r))
r = run("2026-12-01,Ana,07:00,15:00,\n2026-12-02,Ana,07:00,15:00,\n")
ok("16 h rest is fine", "R01" not in codes(r) and "F04" not in codes(r))
r = run("2026-12-01,Ana,09:00,17:00,\n2026-12-01,Ana,16:00,20:00,\n")
ok("overlap gives R02", "R02" in codes(r))
r = run("2026-12-01,Ana,22:00,06:00,\n")
ok("overnight shift ends next day (8 h)", abs(r["people"]["Ana"]["paid_hours"] - 7.5) < 1e-9)
ok("overnight shift counts as a night", r["people"]["Ana"]["nights"] == 1)
ok("overnight shift counts as a close", r["people"]["Ana"]["closes"] == 1)
rows = "".join("2026-12-%02d,Ana,09:00,13:00,\n" % d for d in range(1, 9))
ok("8 days in a row gives R04", "R04" in codes(run(rows)))
ok("7 days allowed when max_consecutive_days=7", "R04" not in codes(run("".join("2026-12-%02d,Ana,09:00,13:00,\n" % d for d in range(1, 8)), {"max_consecutive_days": 7})))
r = run("".join("2026-11-%02d,Ana,08:00,18:00,\n" % d for d in (30,)) + "".join("2026-12-%02d,Ana,08:00,18:00,\n" % d for d in range(1, 6)),
{"staff": {"Ana": {"contract_hours": 40}}, "max_shift_hours": 10})
ok("57 paid h in a 40 h contract week gives R05", "R05" in codes(r))
r = run("2026-12-01,Ana,09:00,13:00,\n", {"staff": {"Ana": {"contract_hours": 30}}})
ok("4 h in a 30 h contract week gives R06", "R06" in codes(r))
ok("12 h shift gives R07", "R07" in codes(run("2026-12-01,Ana,08:00,20:00,\n")))
r = run("2026-12-05,Ana,09:00,17:00,\n", {"staff": {"Ana": {"unavailable": ["2026-12-05"]}}})
ok("unavailable date gives R03", "R03" in codes(r))
r = run("2026-12-01,Ana,09:00,17:00,\n", {"staff": {"Ana": {"unavailable_weekdays": [1]}}})
ok("unavailable weekday gives R03", "R03" in codes(r))
r = run("2026-12-01,Ana,09:00,17:00,cook\n2026-12-01,Ben,12:00,20:00,cook\n",
{"coverage": [{"name": "kitchen", "from": "09:00", "to": "20:00", "min": 2, "role": "cook"}]})
cov = [f for f in r["findings"] if f["code"] == "C01"]
ok("two separate coverage gaps found", len(cov) == 2)
ok("coverage gap windows 09:00-12:00 and 17:00-20:00", [c["when"][-11:] for c in cov] == ["09:00-12:00", "17:00-20:00"])
rows = "".join("2026-12-%02d,Ana,10:00,18:00,\n" % d for d in (5, 6, 12, 13)) + "".join("2026-12-%02d,Ben,10:00,18:00,\n" % d for d in (1, 2, 3, 4))
r = run(rows)
ok("all weekends on one person gives F01 for both", set(f["employee"] for f in r["findings"] if f["code"] == "F01") == {"Ana", "Ben"})
r = run(rows, {"staff": {"Ben": {"no_weekends": True}}})
ok("no_weekends exemption removes F01 when only one left", "F01" not in codes(r))
rows = "".join("2026-12-%02d,Ana,22:00,06:00,\n" % d for d in (1, 3, 5)) + "".join("2026-12-%02d,Ben,09:00,17:00,\n" % d for d in (1, 3, 5))
ok("night imbalance gives F02", "F02" in codes(run(rows)))
ok("tolerance 2 hides a gap of 1.5", "F02" not in codes(run(rows, {"fairness_tolerance": 2})))
try:
parse_rota("name,when\nx,y\n"); ok("missing columns rejected", False)
except ValueError:
ok("missing columns rejected", True)
try:
parse_rota("date,employee,start,end\n2026-13-01,Ana,09:00,17:00\n"); ok("bad date rejected", False)
except ValueError:
ok("bad date rejected", True)
r = run("2026-12-01,Ana,09:00,17:00,\n")
ok("json render parses", json.loads(render(r, "json"))["people"]["Ana"]["shifts"] == 1)
ok("md render has table", "| Person |" in render(r, "md"))
n = sum(1 for _, x in T if x)
for name, x in T:
print(("PASS " if x else "FAIL ") + name)
print(("ALL PASS" if n == len(T) else "FAILED") + " (%d/%d)" % (n, len(T)))
return 0 if n == len(T) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("rota", nargs="?")
ap.add_argument("rules", nargs="?")
ap.add_argument("--format", choices=("text", "md", "json"), default="text")
ap.add_argument("--min-severity", choices=("low", "medium", "high"), default="low")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.rota:
ap.print_usage(sys.stderr)
return 2
try:
with open(a.rota, encoding="utf-8-sig") as fh:
shifts = parse_rota(fh.read())
rules = {}
if a.rules:
with open(a.rules, encoding="utf-8") as fh:
rules = json.load(fh)
res = check(shifts, rules)
except (OSError, ValueError, KeyError) as e:
print("error: %s" % e, file=sys.stderr)
return 2
res["findings"] = [f for f in res["findings"] if RANK[f["severity"]] >= RANK[a.min_severity]]
print(render(res, a.format))
return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0
if __name__ == "__main__":
sys.exit(main())
Finds risky exception handling in Python code offline: bare and swallowed excepts, errors turned into silent return values, raise without from, caught KeyboardInterrupt, return in finally, logs without traceback and oversized try blocks, with file:line, severity and fix recipes. Stdlib Python.
---
name: python-exception-handling-smell-finder
description: Finds risky exception handling in Python code offline: bare and swallowed excepts, errors turned into silent return values, raise without from, caught KeyboardInterrupt, return in finally, logs without traceback and oversized try blocks, with file:line, severity and fix recipes. Stdlib Python.
---
# Python Exception Handling Smell Finder
You help developers find the places where a Python codebase hides its own failures: `except: pass`, broad handlers that return `None` or `[]`, re-raised errors that lose their cause, logs without a traceback, `return` inside `finally`, and workers that swallow Ctrl+C. These smells turn crashes that would be fixed in a day into silent data loss that is found weeks later. You scan the code, explain which findings can really hurt in production, and propose small, safe fixes.
You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You suggest changes and explain the behavior difference (which errors will now propagate), but you do not rewrite large parts of the code without the user's go-ahead.
## Files in this skill
- `scripts/exception_smells.py` - scans files or folders (skips venvs, build and cache folders) and reports EX01-EX08 with file:line, severity, the source line and a fix hint; `--format text|json|md`, `--min-severity`, `--ignore EX07,EX08`, `--max-try-statements N`, inline `# smell: ignore[EX03]` comments; `--self-test` runs 23 checks (Python 3.8+ standard library only)
- `references/smell-catalog.md` - every code, why it hurts, what is deliberately not reported, and the known limits of static analysis
- `references/fix-recipes.md` - eight before/after fixes: narrow the type, `raise ... from err`, `logger.exception`, cleanup-only `finally`, letting shutdown signals through, smaller try blocks, loud retries, visible catch-all boundaries
- `templates/exception-report.md` - the review summary you hand back
- `examples/sync_orders.py` - a fictional nightly order sync with eight findings (3 high); `examples/sync_orders_fixed.py` - the same job with every smell fixed (0 findings)
## Workflow
### 1. Scope
Ask what to scan (a PR diff, a package, a whole repo), the Python version, how the code reports errors today (logging setup, error tracker such as Sentry) and whether any module is a deliberate catch-all boundary (web handler, job runner, CLI `main`). For a PR, scan only the changed files first.
### 2. Run the scanner
```
python3 scripts/exception_smells.py path/to/package
python3 scripts/exception_smells.py src tests --min-severity medium
python3 scripts/exception_smells.py src --format md > exception-report-table.md
python3 scripts/exception_smells.py --self-test
```
Exit 0 = no high findings, 1 = at least one high finding, 2 = bad input. Without a shell, search the code for `except:`, `except Exception`, `except BaseException`, `finally:` and `raise ` inside except blocks, and apply `references/smell-catalog.md` by hand.
### 3. Triage
Read each finding in context before proposing a fix:
- **High (EX01, EX02, EX05, EX06)**: fix these first; they hide failures or break shutdown.
- **Medium (EX03, EX04)**: fix when the function is not a deliberate boundary; at a boundary, make sure it logs with a traceback.
- **Low (EX07, EX08)**: cheap improvements; batch them or suppress with a reason.
- Ask "what did the author expect to fail here?" and narrow the handler to that type.
- Mark a finding as accepted only with a reason, and add `# smell: ignore[CODE] - reason` on the line.
### 4. Fix
Use `references/fix-recipes.md`. Keep each change small and explain the new behavior: "a malformed `sync.json` now raises `JSONDecodeError` instead of silently using defaults". Suggest a test for every error path that now propagates.
### 5. Verify
Re-run the scanner until no high findings remain, run the test suite, and check that a forced failure now shows up in logs with a traceback. Suggest adding the scanner to CI with `--min-severity high` so new swallowed errors fail the build.
### 6. Report
Fill `templates/exception-report.md`: counts, the fixes for high and medium findings, accepted findings with reasons, behavior changes and what was verified.
## Rules
- Never execute or import the user's code to analyze it.
- Do not "fix" a smell by catching more broadly or adding `# smell: ignore` without a reason.
- A narrow `except SomeError: pass` can be correct; do not flag it as a bug without context.
- Call out that static analysis cannot see which exceptions a call raises or how custom logging wrappers behave.
FILE:references/smell-catalog.md
# Exception handling smell catalog
Each code below is reported by `scripts/exception_smells.py`. Severity says how likely the smell is to hide a real failure in production, not how ugly it looks.
| Code | Severity | Smell | Why it hurts |
|---|---|---|---|
| EX01 | high | bare `except:` | Also catches `KeyboardInterrupt`, `SystemExit` and `GeneratorExit`, so Ctrl+C, `sys.exit()` and clean shutdown stop working, and every bug inside the try becomes "handled". |
| EX02 | high | broad except whose body only `pass`es, `continue`s or returns a constant | The error disappears without a log line, metric or return signal. The caller sees success. This is the classic "it silently did nothing" bug. |
| EX03 | medium | broad except that neither re-raises nor logs | The error is turned into a normal value (`None`, `[]`, `{"ok": False}`) that callers often ignore. Not always wrong at a boundary, but it must be deliberate and visible. |
| EX04 | medium | `raise NewError(...)` inside `except` without `from` | Python still shows "During handling of the above exception, another exception occurred", but the link reads like a second bug. `raise ... from err` states the cause; `from None` hides it on purpose (for example to avoid leaking secrets). |
| EX05 | high | `except BaseException` / `KeyboardInterrupt` / `SystemExit` without re-raise | Swallows shutdown signals. Workers that ignore SIGINT or `sys.exit()` hang deploys and leave half-finished work. |
| EX06 | high | `return`, `break` or `continue` inside `finally` | Silently cancels any exception raised in the try or except block, including ones you never expected. Python 3.14 warns about this (PEP 765). |
| EX07 | low | `logger.error(...)` / `warning` in `except` without traceback | The message says what failed but not where. Use `logger.exception(...)` (ERROR level with traceback) or pass `exc_info=True`. |
| EX08 | low | broad except around a large try body (default > 8 statements) | One handler covers many operations, so a bug in any of them is treated like the expected failure. Wrap only the call that can fail. |
| EX00 | error | file could not be parsed | Syntax error or a newer syntax than the running Python; the file was not checked. |
## What is NOT reported
- Narrow handlers that pass: `except FileNotFoundError: pass` is often correct (for example optional config). Review them, but they are not smells by default.
- Handlers that re-raise (`raise`, `raise err`, `raise X from err`).
- Handlers that log with a traceback or report to an error tracker (`logger.exception`, `exc_info=True`, `sentry_sdk.capture_exception`, `traceback.print_exc`).
- `break` / `continue` inside a loop that itself lives in the `finally` block.
## Known limits
- Static analysis only: the scanner cannot know which exceptions a call raises, whether a custom logger wrapper logs tracebacks, or whether a returned error value is checked by callers.
- Logger detection is by name (`log`, `logger`, `logging`, `LOG`, `_logger`, `self.logger`, ...). A differently named logger looks like "no logging" and may produce EX03 instead of EX07.
- `contextlib.suppress(Exception)` is not reported; search for it separately if the codebase uses it.
## Suppressing a finding on purpose
Add a trailing comment on the reported line with a reason in the code review:
```python
except Exception: # smell: ignore[EX03] - top-level boundary, error returned to the API client as 500
```
FILE:references/fix-recipes.md
# Fix recipes
Pick the smallest change that makes the failure visible to the right place: the caller, the log, or the user.
## 1. Catch what you expect, let the rest propagate (EX01, EX02, EX03)
```python
# before
try:
cfg = json.load(open(path))
except:
cfg = {}
# after
try:
with open(path) as fh:
cfg = json.load(fh)
except FileNotFoundError:
logger.info("no %s, using defaults", path)
cfg = {}
# a broken JSON file now raises json.JSONDecodeError instead of silently using defaults
```
Ask: "Which failure did the author have in mind?" Catch exactly that type.
## 2. Keep the cause when translating errors (EX04)
```python
except KeyError as err:
raise OrderError(f"order {order_id} is missing {err}") from err
```
Use `from None` only when the original exception would leak secrets or confuse the user, and say so in a comment.
## 3. Log with the traceback, once (EX07)
```python
except PaymentError:
logger.exception("payment %s failed", payment_id) # ERROR level + traceback
raise
```
Log at the boundary that handles the error, not at every layer it passes through (otherwise one failure becomes five log lines).
## 4. Never return from finally (EX06)
```python
# before
try:
process()
finally:
if pushed == 0:
return {"ok": True}
# after
try:
process()
finally:
client.close() # cleanup only
return {"ok": True, "pushed": pushed}
```
`finally` is for cleanup. Move results and decisions after the try statement.
## 5. Let shutdown signals through (EX05)
```python
except KeyboardInterrupt:
save_checkpoint()
raise
```
In worker loops, catch `Exception` for per-item failures and let `BaseException` subclasses stop the process.
## 6. Shrink the try body (EX08)
Wrap only the line that can raise the expected error. Put the "happy path" after the try in an `else:` block or after the statement.
```python
try:
resp = session.get(url, timeout=10)
except requests.RequestException as err:
raise FetchError(url) from err
else:
data = resp.json()
```
## 7. Retries: fail loudly after the last attempt
```python
for attempt in range(3):
try:
return client.send(msg)
except (ConnectionError, TimeoutError):
logger.debug("retry %d", attempt + 1)
time.sleep(2 ** attempt)
raise DeliveryError(f"message {msg.id} not sent after 3 attempts")
```
## 8. Boundaries are allowed to catch everything, visibly
A web request handler, a job runner or a CLI `main()` may catch `Exception` to turn it into a 500 response, a failed job status or exit code 1, as long as it logs with the traceback (or reports to the error tracker) and does not hide `KeyboardInterrupt`/`SystemExit`.
FILE:templates/exception-report.md
# Exception handling review: {{project_or_pr}}
**Scanned:** {{files_scanned}} files ({{paths}}) on {{date}}, `exception_smells.py` {{options}}
**Result:** {{high}} high, {{medium}} medium, {{low}} low, {{parse_errors}} parse errors
## Fix first (high)
| # | Location | Code | What can go wrong in production | Proposed fix |
|---|---|---|---|---|
| 1 | `{{file}}:{{line}}` | {{code}} | {{impact}} | {{fix}} |
## Fix in this PR if cheap (medium)
| # | Location | Code | Proposed fix |
|---|---|---|---|
| 1 | `{{file}}:{{line}}` | {{code}} | {{fix}} |
## Low / accepted on purpose
- `{{file}}:{{line}}` {{code}}: {{reason it is fine, or suppress comment added}}
## Behavior changes to check
- {{which errors now propagate instead of being swallowed, and who handles them}}
- {{tests added or updated: e.g. a test that a broken config file now raises}}
## Verified
- [ ] Re-ran the scanner: no high findings left (exit 0)
- [ ] Test suite passes
- [ ] Logs now include a traceback for {{failure}}
FILE:examples/sync_orders.py
"""Fictional nightly job that copies new web-shop orders into the accounting system.
It runs, but its exception handling hides real failures. Used to demo exception_smells.py."""
import json
import logging
import time
import requests # third-party; the scanner never imports it
logger = logging.getLogger(__name__)
API = "https://shop.example.com/api/orders"
class SyncError(Exception):
pass
def load_config(path):
try:
with open(path) as fh:
return json.load(fh)
except:
return {}
def fetch_orders(since):
try:
resp = requests.get(API, params={"since": since}, timeout=10)
resp.raise_for_status()
return resp.json()["orders"]
except Exception as err:
logger.error("could not fetch orders: %s", err)
return []
def to_invoice(order):
try:
return {"number": order["id"], "total": round(float(order["total"]), 2), "currency": order["currency"]}
except KeyError:
raise SyncError("order is missing a field")
def push_invoice(client, invoice):
for attempt in range(3):
try:
client.create_invoice(invoice)
return True
except Exception:
time.sleep(2 ** attempt)
continue
return False
def run(client, since):
pushed = 0
try:
config = load_config("sync.json")
orders = fetch_orders(since)
batch = config.get("batch_size", 50)
for order in orders[:batch]:
invoice = to_invoice(order)
if push_invoice(client, invoice):
pushed += 1
client.commit()
logger.info("pushed %d invoices", pushed)
client.close()
except Exception as e:
status = {"ok": False, "error": str(e)}
return status
finally:
if pushed == 0:
return {"ok": True, "pushed": 0}
return {"ok": True, "pushed": pushed}
def main():
try:
run(client=None, since="2026-11-23")
except BaseException:
logger.exception("sync failed")
FILE:examples/sync_orders_fixed.py
"""The same nightly order sync with the smells fixed. exception_smells.py reports nothing here."""
import json
import logging
import time
import requests # third-party; the scanner never imports it
logger = logging.getLogger(__name__)
API = "https://shop.example.com/api/orders"
class SyncError(Exception):
pass
def load_config(path):
try:
with open(path) as fh:
return json.load(fh)
except FileNotFoundError:
logger.info("no %s, using defaults", path)
return {}
def fetch_orders(since):
try:
resp = requests.get(API, params={"since": since}, timeout=10)
resp.raise_for_status()
except requests.RequestException as err:
raise SyncError("could not fetch orders since %s" % since) from err
return resp.json()["orders"]
def to_invoice(order):
try:
return {"number": order["id"], "total": round(float(order["total"]), 2), "currency": order["currency"]}
except KeyError as err:
raise SyncError("order %s is missing field %s" % (order.get("id", "?"), err)) from err
def push_invoice(client, invoice, retryable=(ConnectionError, TimeoutError)):
for attempt in range(3):
try:
client.create_invoice(invoice)
return
except retryable:
logger.debug("retry %d for invoice %s", attempt + 1, invoice["number"])
time.sleep(2 ** attempt)
raise SyncError("invoice %s not pushed after 3 attempts" % invoice["number"])
def run(client, since):
config = load_config("sync.json")
orders = fetch_orders(since)
batch = config.get("batch_size", 50)
pushed, failed = 0, []
for order in orders[:batch]:
try:
push_invoice(client, to_invoice(order))
pushed += 1
except SyncError:
logger.exception("order %s skipped", order.get("id", "?"))
failed.append(order.get("id"))
try:
client.commit()
finally:
client.close()
logger.info("pushed %d invoices, %d failed", pushed, len(failed))
return {"ok": not failed, "pushed": pushed, "failed": failed}
def main():
try:
run(client=None, since="2026-11-23")
except SyncError:
logger.exception("sync failed")
raise
FILE:scripts/exception_smells.py
#!/usr/bin/env python3
"""exception_smells.py - find risky exception handling in Python code, offline.
Parses files with the standard library `ast` module (it never imports or runs the code) and reports:
EX01 high bare `except:` (also catches KeyboardInterrupt and SystemExit)
EX02 high broad except whose body only passes / continues / returns (error silently swallowed)
EX03 medium broad except that neither re-raises nor logs (error turned into a normal value)
EX04 medium new exception raised inside `except` without `from` (original cause hidden)
EX05 high `except BaseException` (or KeyboardInterrupt / SystemExit) without re-raise
EX06 high return / break / continue inside `finally` (silently cancels any exception)
EX07 low error logged in `except` without the traceback (no exc_info / logger.exception)
EX08 low broad except around a large try body (hides which statement failed)
EX00 error file could not be parsed
Usage:
python3 exception_smells.py PATH [PATH ...] [--format text|json|md] [--min-severity low|medium|high]
[--ignore EX07,EX08] [--max-try-statements 8]
python3 exception_smells.py --self-test
Suppress one finding with a trailing comment on the `except` / `raise` / `finally` line: `# smell: ignore[EX03]`.
Exit codes: 0 = no high findings, 1 = at least one high finding, 2 = bad input.
Standard library only, Python 3.8+.
"""
import argparse, ast, json, os, re, sys, tempfile, textwrap
SEVERITY = {"EX00": "error", "EX01": "high", "EX02": "high", "EX03": "medium", "EX04": "medium",
"EX05": "high", "EX06": "high", "EX07": "low", "EX08": "low"}
TITLE = {"EX00": "file could not be parsed",
"EX01": "bare except",
"EX02": "broad except swallows the error",
"EX03": "broad except neither re-raises nor logs",
"EX04": "raise inside except without 'from'",
"EX05": "catches BaseException / KeyboardInterrupt / SystemExit without re-raise",
"EX06": "return/break/continue in finally cancels exceptions",
"EX07": "error logged without traceback",
"EX08": "broad except around a large try body"}
RANK = {"low": 0, "medium": 1, "high": 2, "error": 3}
BROAD = {"Exception", "BaseException"}
SYSTEM = {"BaseException", "KeyboardInterrupt", "SystemExit", "GeneratorExit"}
LOG_METHODS = {"debug", "info", "warning", "warn", "error", "exception", "critical", "fatal", "log"}
LOGGER_NAMES = re.compile(r"(^|_)(log|logger|logging|logs|_log|_logger|LOG|LOGGER)$")
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "node_modules", "build", "dist", ".tox", ".mypy_cache", "site-packages"}
IGNORE_RE = re.compile(r"#\s*smell:\s*ignore\[([A-Z0-9, ]+)\]")
def type_names(node):
"""Names of the exception classes an except handler catches ([] for bare except)."""
if node is None:
return []
items = node.elts if isinstance(node, ast.Tuple) else [node]
out = []
for it in items:
if isinstance(it, ast.Name):
out.append(it.id)
elif isinstance(it, ast.Attribute):
out.append(it.attr)
else:
out.append("?")
return out
def walk_no_nested(nodes):
"""Walk statements but do not descend into nested functions, classes or lambdas."""
stack = list(nodes)
while stack:
n = stack.pop()
yield n
for child in ast.iter_child_nodes(n):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
continue
stack.append(child)
def is_log_call(call):
if not isinstance(call, ast.Call):
return False
f = call.func
if isinstance(f, ast.Attribute) and f.attr in LOG_METHODS:
base = f.value
name = base.id if isinstance(base, ast.Name) else (base.attr if isinstance(base, ast.Attribute) else "")
return bool(LOGGER_NAMES.search(name))
return False
def has_traceback(call):
f = call.func
if isinstance(f, ast.Attribute) and f.attr == "exception":
return True
for kw in call.keywords:
if kw.arg in ("exc_info", "stack_info") and not (isinstance(kw.value, ast.Constant) and kw.value.value in (False, None)):
return True
return False
def handler_facts(h):
body = list(walk_no_nested(h.body))
reraises = any(isinstance(n, ast.Raise) for n in body)
logs = [n for n in body if is_log_call(n)]
reports = any(isinstance(n, ast.Call) and (
(isinstance(n.func, ast.Attribute) and n.func.attr in ("capture_exception", "print_exc", "format_exc", "notify", "report_exc"))
or (isinstance(n.func, ast.Name) and n.func.id in ("capture_exception", "print_exc"))) for n in body)
trivial = all(isinstance(s, (ast.Pass, ast.Continue, ast.Break)) or
(isinstance(s, ast.Expr) and isinstance(s.value, ast.Constant)) or
(isinstance(s, ast.Return) and (s.value is None or isinstance(s.value, ast.Constant)))
for s in h.body)
return reraises, logs, reports, trivial
class Finder(ast.NodeVisitor):
def __init__(self, path, lines, max_try):
self.path, self.lines, self.max_try = path, lines, max_try
self.found = []
self.handler_stack = []
def add(self, code, node, detail):
line = getattr(node, "lineno", 0)
src = self.lines[line - 1] if 0 < line <= len(self.lines) else ""
m = IGNORE_RE.search(src)
if m and code in [c.strip() for c in m.group(1).split(",")]:
return
self.found.append({"code": code, "severity": SEVERITY[code], "file": self.path, "line": line,
"title": TITLE[code], "detail": detail, "source": src.strip()})
def visit_Try(self, node):
n_body = sum(1 for _ in walk_no_nested(node.body) if isinstance(_, ast.stmt))
for h in node.handlers:
names = type_names(h.type)
reraises, logs, reports, trivial = handler_facts(h)
broad = (not names) or any(n in BROAD for n in names)
if not names:
self.add("EX01", h, "use `except Exception:` (or narrower) so Ctrl+C and sys.exit() still work" + ("" if reraises else "; the error is not re-raised"))
elif any(n in SYSTEM for n in names) and not reraises:
self.add("EX05", h, "catches %s; re-raise it or catch Exception instead" % ", ".join(n for n in names if n in SYSTEM))
if broad and trivial and not reraises:
self.add("EX02", h, "the handler body only passes/continues/returns a constant; the error disappears without a trace")
elif broad and not reraises and not logs and not reports and names:
self.add("EX03", h, "the error becomes a normal return value; log it, re-raise it, or catch a narrower type")
for call in logs:
if call.func.attr in ("error", "critical", "fatal", "warning", "warn") and not has_traceback(call) and not reraises:
self.add("EX07", call, "add exc_info=True or use logger.exception(...) so the traceback is kept")
if broad and n_body > self.max_try:
self.add("EX08", h, "try body has %d statements; wrap only the call that can fail" % n_body)
self.handler_stack.append(h)
for s in h.body:
self.visit(s)
self.handler_stack.pop()
for part in (node.body, node.orelse):
for s in part:
self.visit(s)
for s in node.finalbody:
self.visit(s)
for n in walk_no_nested(node.finalbody):
if isinstance(n, (ast.Return, ast.Break, ast.Continue)) and not self._inside_loop_in(node.finalbody, n):
self.add("EX06", n, "`%s` in finally discards any exception raised in the try block" % type(n).__name__.lower())
visit_TryStar = visit_Try
def _inside_loop_in(self, stmts, target):
"""True if a break/continue sits inside a loop that is itself inside the finally block (that is fine)."""
if isinstance(target, ast.Return):
return False
for n in walk_no_nested(stmts):
if isinstance(n, (ast.For, ast.While, ast.AsyncFor)):
if any(c is target for c in walk_no_nested(n.body + n.orelse)):
return True
return False
def visit_Raise(self, node):
if self.handler_stack and node.exc is not None and node.cause is None:
h = self.handler_stack[-1]
if not (isinstance(node.exc, ast.Name) and h.name and node.exc.id == h.name):
self.add("EX04", node, "use `raise NewError(...) from err` (or `from None` on purpose) to keep the cause")
self.generic_visit(node)
def visit_FunctionDef(self, node):
saved, self.handler_stack = self.handler_stack, []
self.generic_visit(node)
self.handler_stack = saved
visit_AsyncFunctionDef = visit_FunctionDef
visit_Lambda = visit_FunctionDef
def scan_source(src, path="<string>", max_try=8):
lines = src.splitlines()
try:
tree = ast.parse(src, filename=path)
except SyntaxError as e:
return [{"code": "EX00", "severity": "error", "file": path, "line": e.lineno or 0, "title": TITLE["EX00"],
"detail": str(e.msg), "source": ""}]
f = Finder(path, lines, max_try)
f.visit(tree)
seen, out = set(), []
for x in sorted(f.found, key=lambda x: (x["line"], x["code"])):
k = (x["code"], x["line"])
if k not in seen:
seen.add(k)
out.append(x)
return out
def iter_files(paths):
for p in paths:
if os.path.isfile(p):
yield p
elif os.path.isdir(p):
for root, dirs, files in os.walk(p):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.endswith(".egg-info"))
for fn in sorted(files):
if fn.endswith(".py"):
yield os.path.join(root, fn)
else:
raise FileNotFoundError(p)
def scan_paths(paths, max_try=8):
findings, n = [], 0
for fp in iter_files(paths):
n += 1
with open(fp, encoding="utf-8", errors="replace") as fh:
findings += scan_source(fh.read(), fp, max_try)
return n, findings
def render(n_files, findings, fmt):
counts = {s: sum(1 for f in findings if f["severity"] == s) for s in ("high", "medium", "low", "error")}
if fmt == "json":
return json.dumps({"files_scanned": n_files, "counts": counts, "findings": findings}, indent=2)
if fmt == "md":
out = ["| Code | Severity | Location | Problem | Fix hint |", "|---|---|---|---|---|"]
for f in findings:
out.append("| %s | %s | `%s:%d` | %s | %s |" % (f["code"], f["severity"], f["file"], f["line"], f["title"], f["detail"]))
out.append("")
out.append("Files scanned: %d. High: %d, medium: %d, low: %d, parse errors: %d." % (n_files, counts["high"], counts["medium"], counts["low"], counts["error"]))
return "\n".join(out)
out = []
for f in findings:
out.append("%s:%d %s [%s] %s" % (f["file"], f["line"], f["code"], f["severity"], f["title"]))
if f["source"]:
out.append(" > " + f["source"])
out.append(" hint: " + f["detail"])
out.append("")
out.append("Files scanned: %d. High: %d, medium: %d, low: %d, parse errors: %d." % (n_files, counts["high"], counts["medium"], counts["low"], counts["error"]))
return "\n".join(out)
def self_test():
T = []
def codes(src, **kw):
return [f["code"] for f in scan_source(textwrap.dedent(src), **kw)]
def check(name, cond):
T.append((name, bool(cond)))
check("bare except is EX01", "EX01" in codes("try:\n x()\nexcept:\n raise\n"))
check("bare except with pass is EX01 + EX02", {"EX01", "EX02"} <= set(codes("try:\n x()\nexcept:\n pass\n")))
check("except Exception: pass is EX02", codes("try:\n x()\nexcept Exception:\n pass\n") == ["EX02"])
check("narrow except ValueError: pass is fine", codes("try:\n int(s)\nexcept ValueError:\n pass\n") == [])
check("broad except returning a value without log is EX03",
codes("def f():\n try:\n return x()\n except Exception as e:\n y = str(e)\n return {'ok': False, 'err': y}\n") == ["EX03"])
check("broad except that logs with exception() is fine",
codes("def f():\n try:\n x()\n except Exception:\n logger.exception('boom')\n return None\n") == [])
check("logger.error without exc_info is EX07",
codes("try:\n x()\nexcept Exception as e:\n logger.error('failed: %s', e)\n") == ["EX07"])
check("logger.error with exc_info=True is fine",
codes("try:\n x()\nexcept Exception:\n log.error('failed', exc_info=True)\n") == [])
check("raise without from in except is EX04",
codes("try:\n x()\nexcept KeyError as e:\n raise ValueError('bad')\n") == ["EX04"])
check("raise ... from err is fine", codes("try:\n x()\nexcept KeyError as e:\n raise ValueError('bad') from e\n") == [])
check("re-raising the caught name is fine", codes("try:\n x()\nexcept KeyError as e:\n cleanup()\n raise e\n") == [])
check("except BaseException without re-raise is EX05",
"EX05" in codes("try:\n x()\nexcept BaseException:\n logger.exception('x')\n"))
check("except KeyboardInterrupt with re-raise is fine",
codes("try:\n x()\nexcept KeyboardInterrupt:\n cleanup()\n raise\n") == [])
check("return in finally is EX06", "EX06" in codes("def f():\n try:\n x()\n finally:\n return 1\n"))
check("break inside a loop within finally is fine",
codes("try:\n x()\nfinally:\n for i in r:\n break\n") == [])
check("large try body with broad except is EX08",
"EX08" in codes("try:\n" + "".join(" a%d()\n" % i for i in range(10)) + "except Exception:\n logger.exception('x')\n raise\n"))
check("--max-try-statements raises the limit",
"EX08" not in codes("try:\n" + "".join(" a%d()\n" % i for i in range(10)) + "except Exception:\n raise\n", max_try=20))
check("inline ignore comment suppresses a code",
codes("try:\n x()\nexcept Exception: # smell: ignore[EX02]\n pass\n") == [])
check("nested function raise is not attributed to outer except",
codes("try:\n x()\nexcept KeyError as e:\n def g():\n raise ValueError()\n raise\n") == [])
check("syntax error reported as EX00", codes("def f(:\n pass\n") == ["EX00"])
check("tuple of exceptions incl. Exception is broad",
codes("try:\n x()\nexcept (ValueError, Exception):\n pass\n") == ["EX02"])
with tempfile.TemporaryDirectory() as d:
os.makedirs(os.path.join(d, "pkg")); os.makedirs(os.path.join(d, ".venv"))
open(os.path.join(d, "pkg", "a.py"), "w").write("try:\n x()\nexcept:\n pass\n")
open(os.path.join(d, ".venv", "b.py"), "w").write("try:\n x()\nexcept:\n pass\n")
n, fs = scan_paths([d])
check("directory scan skips .venv", n == 1 and all(".venv" not in f["file"] for f in fs))
check("json output parses", json.loads(render(n, fs, "json"))["counts"]["high"] == 2)
ok = sum(1 for _, r in T if r)
for name, r in T:
print(("PASS " if r else "FAIL ") + name)
print(("ALL PASS" if ok == len(T) else "FAILED") + " (%d/%d)" % (ok, len(T)))
return 0 if ok == len(T) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("paths", nargs="*")
ap.add_argument("--format", choices=("text", "json", "md"), default="text")
ap.add_argument("--min-severity", choices=("low", "medium", "high"), default="low")
ap.add_argument("--ignore", default="", help="comma-separated codes to skip, e.g. EX07,EX08")
ap.add_argument("--max-try-statements", type=int, default=8)
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.paths:
ap.print_usage(sys.stderr)
return 2
try:
n, fs = scan_paths(a.paths, a.max_try_statements)
except FileNotFoundError as e:
print("error: path not found: %s" % e, file=sys.stderr)
return 2
if n == 0:
print("error: no .py files found", file=sys.stderr)
return 2
skip = {c.strip().upper() for c in a.ignore.split(",") if c.strip()}
fs = [f for f in fs if f["code"] not in skip and RANK[f["severity"]] >= RANK[a.min_severity]]
print(render(n, fs, a.format))
return 1 if any(f["severity"] == "high" for f in fs) else 0
if __name__ == "__main__":
sys.exit(main())
Compares rooftop solar quotes for your home offline: yearly production, self-used vs exported power, bill cut, simple and discounted payback, NPV, IRR, cost per kWh, loan cash flow, and traps like oversizing, optimistic yields or self-use and missing inverter costs. Stdlib Python.
---
name: home-solar-panel-payback-calculator
description: Compares rooftop solar quotes for your home offline: yearly production, self-used vs exported power, bill cut, simple and discounted payback, NPV, IRR, cost per kWh, loan cash flow, and traps like oversizing, optimistic yields or self-use and missing inverter costs. Stdlib Python.
---
# Home Solar Panel Payback Calculator
You help homeowners decide whether rooftop solar panels pay off for their home, and which installer quote is the best value. Sales pitches usually show the biggest possible saving: a high yield, most of the power used at home, rising electricity prices and no inverter replacement. You turn the household's real consumption, tariff and each quote into one honest comparison with the same assumptions, and a short list of questions for the installers.
You work only with the numbers the user gives you, on their machine. You are not a financial adviser, an engineer or an installer: you never recommend a specific company, never invent prices, yields or incentives, and say clearly that results are estimates that must be checked against the installer's quote, the roof survey and the utility tariff. Roof condition, shading, structural checks, permits, grid connection rules, tax treatment and insurance are outside the script; mention them when they matter.
## Files in this skill
- `scripts/solar_payback.py` - reads the household (JSON) and quotes (CSV) and computes, per quote: year-1 production, self-used and exported kWh, saving and bill cut, simple and discounted payback, net value at the horizon, NPV, IRR, cost per kWh and findings SP01-SP10; `--horizon-years N`, `--table "<quote name>"` for the year-by-year cash flow, `--json` for tooling, `--self-test` runs 28 checks (Python 3.8+ standard library only)
- `references/solar-math.md` - the formulas, what each input means and where to find it, typical ranges, and a worked example you can check by hand
- `references/quote-checklist.md` - questions for installers, what each finding means, and how to make quotes comparable
- `templates/solar-summary.md` - the one-page summary you hand back
- `examples/household.json`, `examples/quotes.csv` - a fictional household using 4,600 kWh a year at EUR 0.31 per kWh with six quotes (small, medium, medium with battery, oversized, the small one on a loan, and a door-to-door offer with optimistic assumptions)
## Workflow
### 1. Collect the facts
Ask for:
- yearly electricity use in kWh (12 months of bills or the smart-meter total), the price per kWh including taxes, the export or feed-in price and how it is paid, and whether a heat pump, EV or other big load is planned;
- for each quote: system size in kW, total price, incentives or grants confirmed for this home, the installer's yearly production estimate (or kWh per kW), the self-consumption share they assume, panel degradation, inverter warranty and replacement cost, yearly maintenance, battery size, and loan rate and term if financed;
- the horizon (25 years is common for panel warranties) and a discount rate (the interest they could earn or pay elsewhere, for example 0.03-0.05).
Never fill in prices, yields or incentives yourself; if a number is missing, ask or leave that quote out. Rates and shares are decimals (0.03 = 3%).
### 2. Make the quotes comparable
Use the same household file for all quotes. If one quote assumes a much higher yield (SP10) or an optimistic self-consumption share without a battery (SP08 fires above 0.8; most homes reach 0.25-0.45), run it again with the other quotes' yield and a realistic share, and show both results.
### 3. Run the comparison
```
python3 scripts/solar_payback.py examples/household.json examples/quotes.csv
python3 scripts/solar_payback.py household.json quotes.csv --horizon-years 15
python3 scripts/solar_payback.py household.json quotes.csv --table "Installer A 4.4 kW on loan"
python3 scripts/solar_payback.py household.json quotes.csv --json > solar.json
python3 scripts/solar_payback.py --self-test
```
Exit 0 = at least one quote pays back within the horizon with no high findings, 1 = none does, 2 = bad input. Without a shell, follow `references/solar-math.md` by hand for the two most promising quotes.
### 4. Read the results
- **NPV** is the main number: the value of the system today after all costs, at the chosen discount rate. **Net at horizon** is the same without discounting.
- **Simple payback** is when cumulative savings cover the cost; **discounted payback** is later and more realistic.
- **Self-used vs exported**: power used at home saves the full retail price; exported power earns only the export price. A bigger system mostly adds exports.
- **Cost per kWh** compares the lifetime cost of each kWh produced with the retail and export prices.
- Findings: SP01 high (never pays back); SP02 slow payback, SP03 most power exported cheaply, SP04 oversized against use, SP05 loan payment above the saving, SP09 implausible yield and SP10 yield far above the other quotes are medium; SP06 no inverter replacement, SP07 degradation assumed and SP08 optimistic self-use without a battery are low.
Run at least two horizons and the fair re-run from step 2; if the best quote changes, say so plainly.
### 5. Report
Fill `templates/solar-summary.md`: the household, the comparison table, the best quote with fair assumptions, findings in plain language, the questions for installers (`references/quote-checklist.md`) and what the numbers do not include.
## Rules
- Compare like for like: same household, horizon, discount rate, price escalation and yield unless the roofs really differ.
- A bigger system or a battery is not automatically better; show what each extra kW or kWh adds in NPV.
- Be careful with price escalation: show a 0% escalation run if the user wants a conservative view.
- Keep bills and addresses private; work from the numbers only.
FILE:references/solar-math.md
# Solar payback math
All money in one currency, energy in kWh, rates and shares as decimals.
## Inputs and where to find them
| input | meaning | where to find it | typical range |
|---|---|---|---|
| annual_consumption_kwh | electricity the home uses per year | last 12 months of bills, smart meter | 2,000-6,000 for a flat or house without EV/heat pump |
| electricity_price | price per kWh including taxes, excluding fixed daily charges | tariff sheet or bill | depends on country |
| export_price | what you get per kWh sent to the grid | utility or export tariff contract | often 20-40% of the retail price |
| specific_yield | kWh produced per kW of panels per year | installer estimate or a public solar calculator for your address, tilt and shading | 800-1,000 northern Europe, 1,200-1,600 southern Europe and much of the US |
| self_consumption | share of production used at home | installer estimate, your daytime use | 0.25-0.45 without battery, 0.5-0.75 with a battery |
| degradation | yearly loss of panel output | panel datasheet / warranty | 0.003-0.007 |
| inverter_year, inverter_cost | when and how much an inverter replacement costs | inverter warranty (often 10-12 years) | |
| maintenance | yearly cleaning, monitoring, insurance add-on | quote | 0-1% of price |
## Formulas (year y = 1..N)
- production_y = size_kw x specific_yield x (1 - degradation)^(y-1)
- self_used_y = min(production_y x self_consumption, annual_consumption_kwh)
- exported_y = production_y - self_used_y
- saving_y = self_used_y x price x (1 + price_escalation)^(y-1) + exported_y x export_price x (1 + export_escalation)^(y-1)
- cash_flow_y = saving_y - maintenance - inverter cost (in its year) - loan payment (while the loan runs)
- year 0: - (price - incentives) if paid in cash, 0 if financed (the loan payments carry the cost)
- simple payback: the (interpolated) year when the cumulative cash flow becomes positive for good
- discounted payback and NPV: the same with each year divided by (1 + discount_rate)^y
- IRR: the discount rate where NPV = 0 (shown for cash purchases only)
- cost per kWh: (net cost + present value of maintenance and inverter costs) / present value of production
- loan payment per year = 12 x monthly annuity payment on (price - incentives) at loan_rate over loan_years
## Worked example (check by hand)
4 kW, yield 1,000, self-consumption 0.5, price 0.30, export 0.08, no escalation, no degradation, net cost 6,000:
- production 4,000 kWh; self-used 2,000; exported 2,000
- saving = 2,000 x 0.30 + 2,000 x 0.08 = 600 + 160 = 760 per year
- simple payback = 6,000 / 760 = 7.9 years; net after 25 years = 25 x 760 - 6,000 = 13,000
- if the household cannot use more power in daylight (self-used stays 2,000 kWh), doubling to 8 kW adds 4,000 kWh that are all exported at 0.08: +320 per year for perhaps +4,000 in price, a 12.5-year payback on the extra panels. That is why oversizing (SP03/SP04) often lowers the value.
## What the script leaves out
Fixed grid charges, time-of-use tariffs and net metering rules, battery round-trip losses and battery replacement, tax credits paid later rather than upfront, roof repairs, home value effects, and changes in your use (EV, heat pump). Mention the ones that apply and, if needed, model them by changing the inputs (for example a lower self-consumption or a higher consumption).
FILE:references/quote-checklist.md
# Quote checklist
## Questions for every installer
1. What yearly production do you estimate, from which tool, and with what shading, tilt and orientation? Is it a guaranteed minimum or a typical value?
2. What self-consumption share did you assume, and on what usage data?
3. Panel and inverter brands, models, warranties (product and performance) and degradation per year.
4. When do you expect the inverter to need replacing, and what does that cost today?
5. Exactly what is included: scaffolding, mounting, cabling, meter changes, grid application, monitoring, permits, disposal?
6. Which incentives or grants did you include, are they confirmed for this home, and who applies for them?
7. Payment schedule, deposit protection and what happens if the installation is delayed or fails inspection.
8. Workmanship warranty and roof-penetration guarantee; who to call for faults in year 5 or 15.
9. For a battery: usable capacity, round-trip efficiency, warranty cycles/years, and how much extra self-consumption it really adds for your use.
10. For financing: APR, total repayable, early repayment fees, and whether the loan is secured on the home.
## Findings and what to do
| code | meaning | what to do |
|---|---|---|
| SP01 | never pays back within the horizon | do not buy as quoted; ask for a smaller or cheaper system |
| SP02 | payback over 12 years | compare with other uses of the money; check incentives and price |
| SP03 | over half the power exported at a low price | ask for a smaller system or price a battery or load shifting |
| SP04 | production above 120% of use | size closer to use unless an EV or heat pump is coming soon |
| SP05 | loan payment above the year-1 saving | expect to pay extra each month at first; compare cash vs loan |
| SP06 | no inverter replacement within the horizon | add a realistic replacement year and cost and re-run |
| SP07 | degradation not given | ask for the datasheet value |
| SP08 | high self-use without a battery | re-run with 0.3-0.45 unless your daytime use is really high |
| SP09 | yield outside 600-1,900 kWh/kW | check with a public solar calculator for your address |
| SP10 | yield far above the other quotes | re-run with the median yield for a fair comparison |
## Red flags in sales pitches
- Pressure to sign today, "special price only for this street", or a deposit above about 25% before installation.
- Savings shown with a high electricity price escalation (over about 5% per year) and no 0% scenario.
- Monthly loan payment compared with the whole electricity bill, not with the realistic saving.
- No site visit or shading check before the final price.
FILE:templates/solar-summary.md
# Solar quote summary - {{household_name}} ({{date}})
**Household:** {{consumption}} kWh per year at {{price}} per kWh; export {{export_price}} per kWh; escalation {{escalation}}; discount rate {{discount_rate}}; horizon {{horizon}} years.
**Command:** `python3 scripts/solar_payback.py household.json quotes.csv`
## Comparison
| quote | kW | net cost | yr-1 saving | bill cut | simple payback | discounted payback | NPV | IRR | key findings |
|---|---|---|---|---|---|---|---|---|---|
| {{quote}} | {{kw}} | {{net_cost}} | {{saving}} | {{bill_cut}} | {{payback}} | {{disc_payback}} | {{npv}} | {{irr}} | {{findings}} |
## Fair comparison
Re-run with the same yield ({{fair_yield}} kWh/kW) and realistic self-consumption ({{fair_share}}): {{fair_result}}
## Best value
{{best_quote}} - why: {{reason}}. At a shorter horizon ({{short_horizon}} years): {{short_result}}.
## Things to ask the installers
- {{question_1}}
- {{question_2}}
- {{question_3}}
## Not included in these numbers
{{exclusions}}
_Estimates only, from the numbers provided. Check with the installer's final quote, the roof survey and your utility tariff before signing._
FILE:examples/household.json
{
"annual_consumption_kwh": 4600,
"electricity_price": 0.31,
"export_price": 0.07,
"price_escalation": 0.03,
"export_escalation": 0.0,
"discount_rate": 0.04,
"horizon_years": 25,
"currency": "EUR"
}
FILE:examples/quotes.csv
name,size_kw,price,incentives,specific_yield,self_consumption,degradation,inverter_year,inverter_cost,maintenance,battery_kwh,loan_rate,loan_years
Installer A 4.4 kW,4.4,7200,0,1050,0.45,0.005,13,1300,60,0,,
Installer B 6.6 kW,6.6,9100,0,1050,0.35,0.005,13,1500,70,0,,
Installer B 6.6 kW + 5 kWh battery,6.6,13800,500,1050,0.65,0.005,12,2200,90,5,,
Installer C 10 kW,10,13500,0,1050,0.25,,,,80,0,,
Installer A 4.4 kW on loan,4.4,7200,0,1050,0.45,0.005,13,1300,60,0,0.079,10
Door-to-door offer 4 kW,4,11900,0,1350,0.85,0.005,,,0,0,,
FILE:scripts/solar_payback.py
#!/usr/bin/env python3
"""solar_payback.py - compare rooftop solar quotes for one household (stdlib only, Python 3.8+).
Usage:
python3 scripts/solar_payback.py household.json quotes.csv [--horizon-years N] [--json] [--table QUOTE_NAME]
python3 scripts/solar_payback.py --self-test
household.json: annual_consumption_kwh, electricity_price, export_price, optional price_escalation (0.03),
export_escalation (0.0), discount_rate (0.04), horizon_years (25), currency.
quotes.csv columns: name,size_kw,price,incentives,specific_yield,self_consumption,degradation,
inverter_year,inverter_cost,maintenance,battery_kwh,loan_rate,loan_years
(rates and shares as decimals; specific_yield = kWh per kW per year from the installer or a public
solar calculator; loan_rate/loan_years empty or 0 = paid in cash).
For each quote: year-1 production, self-used and exported kWh, year-1 saving and bill reduction, simple and
discounted payback, net value at the horizon, NPV, IRR, cost per kWh produced, and findings SP01-SP09.
Exit 0 = at least one quote pays back within the horizon and no high findings on it, 1 = none does or a high
finding on every quote, 2 = bad input.
"""
import argparse, csv, json, math, sys
NUM = ["size_kw", "price", "incentives", "specific_yield", "self_consumption", "degradation",
"inverter_year", "inverter_cost", "maintenance", "battery_kwh", "loan_rate", "loan_years"]
DEFAULTS = dict(incentives=0, degradation=0.005, inverter_year=0, inverter_cost=0, maintenance=0,
battery_kwh=0, loan_rate=0, loan_years=0)
def annuity(principal, annual_rate, years):
if years <= 0 or principal <= 0:
return 0.0
n, r = int(round(years * 12)), annual_rate / 12
m = principal / n if r == 0 else principal * r / (1 - (1 + r) ** -n)
return m * 12
def load_household(path):
h = json.load(open(path, encoding="utf-8"))
for k in ("annual_consumption_kwh", "electricity_price", "export_price"):
if k not in h:
raise ValueError("household.json missing " + k)
h.setdefault("price_escalation", 0.03); h.setdefault("export_escalation", 0.0)
h.setdefault("discount_rate", 0.04); h.setdefault("horizon_years", 25); h.setdefault("currency", "")
if h["annual_consumption_kwh"] <= 0 or h["electricity_price"] <= 0:
raise ValueError("consumption and electricity_price must be positive")
for k in ("price_escalation", "export_escalation", "discount_rate"):
if abs(h[k]) >= 0.5:
raise ValueError(k + " looks like a percent; use decimals (0.03 = 3%)")
if h["electricity_price"] > 5:
raise ValueError("electricity_price looks like cents; use currency per kWh (0.32)")
return h
def parse_quote(row):
q = {"name": (row.get("name") or "").strip()}
if not q["name"]:
raise ValueError("quote without a name")
for k in NUM:
v = (row.get(k) or "").strip()
if v == "":
if k in DEFAULTS:
q[k] = DEFAULTS[k]; q.setdefault("_defaulted", []).append(k); continue
raise ValueError("%s: missing %s" % (q["name"], k))
q[k] = float(v)
if q["size_kw"] <= 0 or q["price"] <= 0 or q["specific_yield"] <= 0:
raise ValueError(q["name"] + ": size_kw, price and specific_yield must be positive")
if not 0 < q["self_consumption"] <= 1 or not 0 <= q["degradation"] < 0.05:
raise ValueError(q["name"] + ": self_consumption must be 0-1 and degradation a decimal like 0.005")
if q["loan_rate"] >= 0.5:
raise ValueError(q["name"] + ": loan_rate looks like a percent; use decimals")
return q
def load_quotes(path):
with open(path, newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
if not rows:
raise ValueError("quotes.csv has no rows")
return [parse_quote(r) for r in rows]
def irr(flows):
def npv(r):
return sum(cf / (1 + r) ** t for t, cf in enumerate(flows))
lo, hi = -0.99, 1.0
if npv(lo) * npv(hi) > 0:
return None
for _ in range(200):
mid = (lo + hi) / 2
if npv(lo) * npv(mid) <= 0:
hi = mid
else:
lo = mid
return (lo + hi) / 2
def payback(cum):
"""cum[0] = year 0 (upfront), cum[t] = cumulative after year t. Returns the fractional year when the
cumulative position becomes >= 0 for good (0.0 if it never goes negative), or None if it ends negative."""
if cum[-1] < 0:
return None
last_neg = max((t for t, c in enumerate(cum) if c < 0), default=None)
if last_neg is None:
return 0.0
t = last_neg + 1
return last_neg + (-cum[last_neg]) / (cum[t] - cum[last_neg])
def evaluate(h, q, horizon=None):
Y = int(horizon or h["horizon_years"])
net_cost = q["price"] - q["incentives"]
financed = q["loan_years"] > 0
loan_pay = annuity(net_cost, q["loan_rate"], q["loan_years"]) if financed else 0.0
upfront = 0.0 if financed else net_cost
flows, rows, pv_prod, pv_cost = [-upfront], [], 0.0, net_cost
d = h["discount_rate"]
for y in range(1, Y + 1):
prod = q["size_kw"] * q["specific_yield"] * (1 - q["degradation"]) ** (y - 1)
self_used = min(prod * q["self_consumption"], h["annual_consumption_kwh"])
exported = prod - self_used
price = h["electricity_price"] * (1 + h["price_escalation"]) ** (y - 1)
exp = h["export_price"] * (1 + h["export_escalation"]) ** (y - 1)
inverter = q["inverter_cost"] if q["inverter_year"] and int(q["inverter_year"]) == y else 0.0
saving = self_used * price + exported * exp
costs = q["maintenance"] + inverter
loan = loan_pay if financed and y <= q["loan_years"] else 0.0
cf = saving - costs - loan
flows.append(cf)
pv_prod += prod / (1 + d) ** y
pv_cost += costs / (1 + d) ** y
rows.append(dict(year=y, production_kwh=round(prod), self_used_kwh=round(self_used), exported_kwh=round(exported),
saving=round(saving, 2), costs=round(costs, 2), loan=round(loan, 2), cash_flow=round(cf, 2)))
cum, disc = [], []
c = dc = 0.0
for t, cf in enumerate(flows):
c += cf; dc += cf / (1 + d) ** t
cum.append(c); disc.append(dc)
y1 = rows[0]
bill_before = h["annual_consumption_kwh"] * h["electricity_price"]
r = dict(name=q["name"], size_kw=q["size_kw"], net_cost=round(net_cost, 2), financed=financed,
loan_payment=round(loan_pay, 2), year1_production=y1["production_kwh"], year1_self_used=y1["self_used_kwh"],
year1_exported=y1["exported_kwh"], year1_saving=y1["saving"],
bill_reduction=round(y1["self_used_kwh"] * h["electricity_price"] / bill_before, 3),
export_share=round(y1["exported_kwh"] / y1["production_kwh"], 3) if y1["production_kwh"] else 0,
coverage=round(y1["production_kwh"] / h["annual_consumption_kwh"], 3),
simple_payback=payback(cum), discounted_payback=payback(disc), net_at_horizon=round(cum[-1], 2),
npv=round(disc[-1], 2), irr=irr(flows) if not financed else None,
cost_per_kwh=round(pv_cost / pv_prod, 4) if pv_prod else None, horizon=Y, years=rows)
r["findings"] = findings(h, q, r)
return r
def findings(h, q, r):
F = []
def add(sev, code, msg): F.append(dict(severity=sev, code=code, message=msg))
if r["simple_payback"] is None:
add("high", "SP01", "does not pay back within %d years" % r["horizon"])
elif r["simple_payback"] > 12:
add("medium", "SP02", "slow payback: %.1f years" % r["simple_payback"])
if r["export_share"] > 0.5 and h["export_price"] < 0.4 * h["electricity_price"]:
add("medium", "SP03", "%.0f%% of production is exported at a low export price; a smaller system or a battery may pay back faster" % (r["export_share"] * 100))
if r["coverage"] > 1.2:
add("medium", "SP04", "produces %.0f%% of the yearly use; check the size against consumption" % (r["coverage"] * 100))
if r["financed"] and r["loan_payment"] > r["year1_saving"] - q["maintenance"]:
add("medium", "SP05", "loan payment %.0f per year is higher than the year-1 saving %.0f: negative cash flow at first" % (r["loan_payment"], r["year1_saving"]))
if r["horizon"] > 15 and not q["inverter_year"]:
add("low", "SP06", "no inverter replacement planned within %d years (inverters often last 10-15 years)" % r["horizon"])
if "degradation" in q.get("_defaulted", []):
add("low", "SP07", "degradation not given; assumed 0.5% per year")
if q["self_consumption"] > 0.8 and not q["battery_kwh"]:
add("low", "SP08", "self-consumption %.0f%% without a battery is optimistic for most homes" % (q["self_consumption"] * 100))
if not 600 <= q["specific_yield"] <= 1900:
add("medium", "SP09", "specific yield %.0f kWh/kW is outside the usual 600-1900 range; check the estimate" % q["specific_yield"])
return F
def cross_check(qs, res):
"""SP10: a quote that assumes a much higher yield than the others for the same home."""
ys = sorted(q["specific_yield"] for q in qs)
if len(ys) < 3:
return
med = ys[len(ys) // 2] if len(ys) % 2 else (ys[len(ys) // 2 - 1] + ys[len(ys) // 2]) / 2
for q, r in zip(qs, res):
if q["specific_yield"] > med * 1.15:
r["findings"].append(dict(severity="medium", code="SP10", message="assumes %.0f kWh/kW, %.0f%% above the median of the other quotes (%.0f); re-run it with %.0f for a fair comparison" % (
q["specific_yield"], (q["specific_yield"] / med - 1) * 100, med, med)))
def fmt_years(v):
return "never" if v is None else "%.1f y" % v
def render(h, res, table=None):
cur = h["currency"] + " " if h["currency"] else ""
L = ["# Solar payback check (horizon %d years)" % res[0]["horizon"], "",
"Household: %s kWh per year at %s%.3f per kWh (escalating %.1f%%/y), export %s%.3f per kWh, discount rate %.1f%%" %
("{:,}".format(int(h["annual_consumption_kwh"])), cur, h["electricity_price"], h["price_escalation"] * 100, cur, h["export_price"], h["discount_rate"] * 100), "",
"| quote | kW | net cost | yr-1 kWh | self-used | exported | yr-1 saving | bill cut | simple payback | disc. payback | net at horizon | NPV | IRR | cost/kWh |",
"|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
for r in res:
L.append("| %s | %.1f | %s | %s | %s | %s | %s | %.0f%% | %s | %s | %s | %s | %s | %s |" % (
r["name"], r["size_kw"], "{:,.0f}".format(r["net_cost"]) + (" (loan)" if r["financed"] else ""),
"{:,}".format(r["year1_production"]), "{:,}".format(r["year1_self_used"]), "{:,}".format(r["year1_exported"]),
"{:,.0f}".format(r["year1_saving"]), r["bill_reduction"] * 100, fmt_years(r["simple_payback"]), fmt_years(r["discounted_payback"]),
"{:,.0f}".format(r["net_at_horizon"]), "{:,.0f}".format(r["npv"]), "-" if r["irr"] is None else "%.1f%%" % (r["irr"] * 100),
"%.3f" % r["cost_per_kwh"]))
best = max(res, key=lambda r: r["npv"])
warn = " - check its assumptions first (findings below)" if any(f["severity"] in ("high", "medium") or f["code"] == "SP08" for f in best["findings"]) else ""
L += ["", "Highest NPV: %s (NPV %s%s)%s" % (best["name"], cur, "{:,.0f}".format(best["npv"]), warn), "", "## Findings"]
n = 0
for r in res:
for f in r["findings"]:
L.append("- [%s] %s %s: %s" % (f["severity"], f["code"], r["name"], f["message"])); n += 1
if not n:
L.append("- none")
if table:
r = next((x for x in res if x["name"] == table), None)
if r:
L += ["", "## Year by year: " + r["name"], "| year | production | self-used | exported | saving | costs | loan | cash flow |", "|---|---|---|---|---|---|---|---|"]
for y in r["years"]:
L.append("| %d | %s | %s | %s | %.0f | %.0f | %.0f | %.0f |" % (y["year"], "{:,}".format(y["production_kwh"]), "{:,}".format(y["self_used_kwh"]),
"{:,}".format(y["exported_kwh"]), y["saving"], y["costs"], y["loan"], y["cash_flow"]))
L += ["", "Estimates only: check yields, prices and incentives with the installer's quote and your utility tariff."]
return "\n".join(L)
def self_test():
ok = [0, 0]
def check(name, cond):
ok[0 if cond else 1] += 1
print(("PASS " if cond else "FAIL ") + name)
H = dict(annual_consumption_kwh=4000, electricity_price=0.30, export_price=0.08, price_escalation=0.0,
export_escalation=0.0, discount_rate=0.0, horizon_years=25, currency="EUR")
def Q(**kw):
row = dict(name="t", size_kw="4", price="6000", incentives="0", specific_yield="1000", self_consumption="0.5",
degradation="0", inverter_year="", inverter_cost="", maintenance="0", battery_kwh="", loan_rate="", loan_years="")
row.update({k: str(v) for k, v in kw.items()})
return parse_quote(row)
check("annuity 10000 at 0% over 10 y = 1000/y", abs(annuity(10000, 0, 10) - 1000) < 1e-6)
check("annuity 10000 at 6% over 10 y = 1332.25/y", abs(annuity(10000, 0.06, 10) - 1332.25) < 0.05)
r = evaluate(H, Q())
check("year-1 production = kW x yield", r["year1_production"] == 4000)
check("self-used = production x share", r["year1_self_used"] == 2000)
check("saving = self-used x price + export x export price", abs(r["year1_saving"] - (2000 * 0.30 + 2000 * 0.08)) < 0.01)
check("simple payback = 6000 / 760", abs(r["simple_payback"] - 6000 / 760) < 1e-6)
check("discount 0 => discounted payback = simple", abs(r["discounted_payback"] - r["simple_payback"]) < 1e-6)
check("net at horizon = 25 x 760 - 6000", abs(r["net_at_horizon"] - (25 * 760 - 6000)) < 0.01)
check("IRR positive for a paying system", r["irr"] and r["irr"] > 0.1)
r = evaluate(H, Q(self_consumption=1.0, size_kw=9))
check("self-used capped at consumption", r["year1_self_used"] == 4000)
check("oversized system flags SP03 and SP04", {"SP03", "SP04"} <= {f["code"] for f in r["findings"]})
r = evaluate(H, Q(price=60000))
check("expensive system never pays back SP01", r["simple_payback"] is None and r["findings"][0]["code"] == "SP01")
r = evaluate(H, Q(price=12000))
check("slow payback flagged SP02", any(f["code"] == "SP02" for f in r["findings"]))
r = evaluate(H, Q(degradation=0.01))
check("degradation lowers year-2 production", r["years"][1]["production_kwh"] == 3960)
r = evaluate(H, Q(inverter_year=12, inverter_cost=1500))
check("inverter cost hits year 12 only", r["years"][11]["costs"] == 1500 and r["years"][10]["costs"] == 0)
check("no SP06 when inverter is planned", not any(f["code"] == "SP06" for f in r["findings"]))
r = evaluate(H, Q(incentives=2000))
check("incentives reduce net cost", r["net_cost"] == 4000)
r = evaluate(H, Q(loan_rate=0.05, loan_years=10, price=9000))
check("financed: no upfront, loan payment in years 1-10 only", r["years"][0]["loan"] > 0 and r["years"][10]["loan"] == 0)
check("loan payment above saving flags SP05", any(f["code"] == "SP05" for f in r["findings"]))
r = evaluate(H, Q(self_consumption=0.9))
check("high self-consumption without battery flags SP08", any(f["code"] == "SP08" for f in r["findings"]))
r = evaluate(H, Q(specific_yield=2500))
check("implausible yield flags SP09", any(f["code"] == "SP09" for f in r["findings"]))
r = evaluate(H, Q(degradation=""))
check("missing degradation defaults and flags SP07", any(f["code"] == "SP07" for f in r["findings"]))
H2 = dict(H, discount_rate=0.05)
r = evaluate(H2, Q())
check("discounting makes discounted payback longer", r["discounted_payback"] > r["simple_payback"])
res = [evaluate(H, Q(name=n, specific_yield=y)) for n, y in (("a", 1000), ("b", 1010), ("c", 1400))]
cross_check([Q(specific_yield=1000), Q(specific_yield=1010), Q(specific_yield=1400)], res)
check("yield far above the other quotes flags SP10", any(f["code"] == "SP10" for f in res[2]["findings"]) and not any(f["code"] == "SP10" for f in res[0]["findings"]))
check("payback None when the position ends negative", payback([-100, -50, 20, -10]) is None)
check("payback 0 when never negative", payback([0, 10, 20]) == 0.0)
for bad, label in ((dict(self_consumption=1.5), "share above 1 rejected"), (dict(loan_rate=6, loan_years=10), "percent loan rate rejected")):
try:
Q(**bad); check(label, False)
except ValueError:
check(label, True)
print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
return 0 if not ok[1] else 1
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("household", nargs="?"); ap.add_argument("quotes", nargs="?")
ap.add_argument("--horizon-years", type=int); ap.add_argument("--json", action="store_true")
ap.add_argument("--table", help="print the year-by-year table for this quote name")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not (a.household and a.quotes):
print("error: give household.json and quotes.csv", file=sys.stderr); return 2
try:
h = load_household(a.household); qs = load_quotes(a.quotes)
res = [evaluate(h, q, a.horizon_years) for q in qs]
cross_check(qs, res)
except (ValueError, OSError, json.JSONDecodeError) as e:
print("error:", e, file=sys.stderr); return 2
if a.json:
print(json.dumps(res, indent=2))
else:
print(render(h, res, a.table))
good = [r for r in res if r["simple_payback"] is not None and not any(f["severity"] == "high" for f in r["findings"])]
return 0 if good else 1
if __name__ == "__main__":
sys.exit(main())
Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---
name: python-import-cycle-detector
description: Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---
# Python Import Cycle Detector
You help developers find and untangle circular imports in a Python codebase. Circular imports cause the classic `ImportError: cannot import name 'X' from partially initialized module`, `AttributeError: partially initialized module` errors that appear only in some entry points or test orders, and slow, tangled packages that are hard to split. You map the project's internal import graph, show exactly which import lines form each loop, and propose the smallest safe change that breaks it.
You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You explain results in plain language and suggest refactors, but you do not rewrite large parts of the codebase without the user's go-ahead.
## Files in this skill
- `scripts/import_cycles.py` - walks the project (skips venvs, build and cache folders; detects a `src/` layout), resolves absolute and relative imports and `from pkg import submodule`, finds strongly connected components (Tarjan), the shortest cycle in each, and findings IC00-IC06; `--json` for tooling, `--include-type-checking` to count `if TYPE_CHECKING:` imports, `--root` to set the folder that holds the top-level packages, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/how-cycles-break.md` - why some cycles crash at import time and others do not, how Python executes a module while it is half-initialized, and what each finding means
- `references/fix-patterns.md` - seven ways to break a cycle, from moving one constant to dependency inversion, with before/after snippets and when to use each
- `templates/cycle-report.md` - the summary you hand back
- `examples/shop/` - a fictional six-module package with a real import-time cycle (`models` <-> `orders`), a longer loop through a deferred import, a `TYPE_CHECKING` import and an `__init__` re-export; `python3 -c "import shop"` inside `examples/` reproduces the ImportError
## Workflow
### 1. Understand the symptom
Ask for the exact error and traceback if there is one, the entry point or test that fails, the Python version, and where the packages live (repo root or `src/`). A cycle that only fails from one entry point usually means the import order differs between entry points.
### 2. Run the detector
```
python3 scripts/import_cycles.py path/to/project
python3 scripts/import_cycles.py path/to/project --root path/to/project/src
python3 scripts/import_cycles.py path/to/project --json > cycles.json
python3 scripts/import_cycles.py --self-test
```
Exit 0 = no import-time cycles, 1 = at least one import-time cycle (IC01), 2 = bad input. Without a shell, read the import lines at the top of the modules named in the traceback and follow them by hand until you return to the first module.
### 3. Read the report
- **Group**: modules that reach each other through imports. Fix groups one at a time, the import-time ones (IC01) first.
- **Shortest cycle**: the smallest loop with file and line for every import; usually the best place to start.
- **Kind**: `top` runs when the module is imported; `deferred` runs inside a function (IC02: works today but breaks when someone moves it to the top); `type_checking` never runs (IC06, ignored unless `--include-type-checking`).
- **Suggested place to break**: a top-level edge in the shortest cycle that imports the fewest names. It is a starting point, not a verdict: prefer the edge whose direction is "wrong" for the architecture (a low-level module such as `models` importing a high-level one such as `orders`).
- IC03 marks tangles of 5+ modules (plan a layered refactor), IC04 an `__init__.py` re-export that pulls the package into the loop, IC05 a star import inside a cycle, IC00 files that could not be parsed.
### 4. Choose a fix
Use `references/fix-patterns.md`. Default order: move the shared constant or type to a lower module; import the module instead of a name (`from shop import orders` then `orders.ORDER_STATUSES`) only as a stopgap; use a `TYPE_CHECKING` import plus string annotations for type-only use; move logic to the module that owns it; invert the dependency with a parameter, callback or registry. Avoid hiding the cycle with function-level imports unless it is a deliberate, commented exception.
### 5. Verify
Re-run the detector until the group is gone or only documented deferred edges remain, then import every top-level module in a fresh interpreter (`python3 -c "import pkg.module"`) and run the test suite. Suggest adding the detector to CI with exit code 1 failing the build.
### 6. Report
Fill `templates/cycle-report.md`: groups found, the fix for each, the changed files, and what was verified.
## Rules
- Never execute or import the user's project to analyze it; the parser is enough.
- Keep changes small and reviewable: one cycle per commit, no behavior change.
- Dynamic imports (`importlib.import_module`, plugins, `__import__`) are invisible to static analysis; say so when the project uses them.
FILE:references/how-cycles-break.md
# How circular imports break (and when they don't)
## What Python does on `import a`
1. Looks in `sys.modules`. If `a` is there, even half-finished, it returns it immediately.
2. Otherwise it creates an empty module object, puts it in `sys.modules["a"]`, and runs `a.py` from top to bottom.
3. Names exist in `a` only after the line that defines them has run.
So in a cycle `a -> b -> a`:
- `import a` starts running `a.py`, which reaches `import b`.
- `b.py` runs and reaches `import a`; `a` is already in `sys.modules` (half-initialized), so it is returned at once.
- If `b` then does `from a import X` (or uses `a.X` at top level) before `a` has defined `X`, you get
`ImportError: cannot import name 'X' from partially initialized module 'a'` or
`AttributeError: partially initialized module 'a' has no attribute 'X'`.
Whether it crashes depends on **which module is imported first** and **what each side touches at import time**. That is why a cycle can pass the test suite and crash in production from a different entry point.
## Kinds of edges the script reports
| kind | where the import is | runs when | risk |
|---|---|---|---|
| `top` | module level (also inside `if`, `try`, `class` bodies) | the module is imported | can crash at import time |
| `deferred` | inside a function or method | the function is called | works if the other module has finished by then; fragile |
| `type_checking` | inside `if TYPE_CHECKING:` | never at runtime | no runtime effect; ignored by default |
## Findings
| code | severity | meaning | first move |
|---|---|---|---|
| IC00 | low | a file could not be parsed (syntax error, encoding) | fix or exclude the file, re-run |
| IC01 | high | cycle made only of import-time edges somewhere in the group | fix now; see fix-patterns.md 1-5 |
| IC02 | medium | every loop includes at least one deferred import | document it or remove the cycle properly |
| IC03 | medium | group of 5+ modules | draw the intended layers; fix edges that point upward |
| IC04 | medium | an `__init__.py` re-export sits in the shortest cycle | stop re-exporting, or import submodules directly |
| IC05 | medium | `from x import *` inside a cycle | replace with explicit names |
| IC06 | info | TYPE_CHECKING-only imports were ignored | nothing; use `--include-type-checking` to see them |
## How modules are resolved
- File `pkg/sub/mod.py` under the root becomes `pkg.sub.mod`; `pkg/__init__.py` becomes `pkg`.
- The root is `<project>/src` if it exists, otherwise `<project>`; override with `--root`.
- `from pkg import name` maps to `pkg.name` when that is a module, otherwise to `pkg`.
- `from . import x` and `from ..core import y` are resolved against the importing module's package.
- Third-party and standard library imports are ignored (they are not files under the root).
- Limitation: `import a.b` also runs `a/__init__.py`; the script records only the edge to `a.b`. If a package `__init__` imports heavily, check it by hand.
## Worked example (examples/shop)
`shop.orders` line 3 imports `Customer` from `shop.models`; `shop.models` line 3 imports `ORDER_STATUSES` from `shop.orders`. Importing `shop` runs `__init__` -> `orders` -> `models`, and `models` asks for `ORDER_STATUSES` before `orders` has defined it, so `python3 -c "import shop"` fails with the ImportError. The longer loop `orders -> payments -> notifications -> orders` survives only because `notifications` imports `orders` inside `send_receipt()`.
FILE:references/fix-patterns.md
# Fix patterns for circular imports
Pick the smallest change that makes dependencies point one way: from high-level modules (services, views, CLI) down to low-level ones (models, constants, utilities).
## 1. Move the shared piece down
When two modules share a constant, enum, exception or small type, move it to a lower module that imports neither.
```python
# before: models.py -> orders.py for ORDER_STATUSES, orders.py -> models.py for Customer
# after: shop/constants.py
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
# models.py and orders.py both: from shop.constants import ORDER_STATUSES
```
Best first choice: no behavior change, easy to review.
## 2. Type-only imports
If one side needs the other only for annotations:
```python
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from shop.models import Customer
def greet(customer: Customer) -> str: ...
```
The import never runs, so the runtime cycle disappears.
## 3. Move the function to its owner
A helper in `orders.py` that only works on customers belongs in `models.py` (or a `customers.py`). Cycles often show that one function lives in the wrong module.
## 4. Dependency inversion
The low-level module should not call the high-level one. Pass what it needs instead:
```python
# payments.py
def charge(order, on_success=None):
...
if on_success:
on_success(order)
# orders.py
payments.charge(order, on_success=notifications.send_receipt)
```
Alternatives: a small registry or signal (`events.subscribe("order_paid", send_receipt)`), or a protocol/ABC in a lower module.
## 5. Split a module that does two jobs
If `utils.py` imports half the project and half the project imports `utils.py`, split it by topic (`utils/text.py`, `utils/money.py`) so each part depends on less.
## 6. Import the module, not the name (stopgap)
`from shop import orders` and use `orders.ORDER_STATUSES` inside functions. Attribute lookup happens later, so some cycles stop crashing. It hides the design problem; leave a TODO and plan pattern 1-5.
## 7. Deferred import (last resort)
```python
def send_receipt(order):
from shop.orders import ORDER_STATUSES # deliberate: breaks cycle orders -> payments -> notifications
```
Acceptable for rarely used paths or optional heavy dependencies. Always add a comment naming the cycle; the detector keeps reporting it as IC02.
## Package `__init__.py` re-exports (IC04)
`from .orders import Order` in `__init__.py` makes `import shop.models` run `orders.py` first. Options: keep `__init__.py` light, re-export only leaf modules, or use a lazy `__getattr__` (PEP 562) for convenience names.
## After every fix
1. `python3 scripts/import_cycles.py <project>` - the group should be gone or smaller.
2. `python3 -c "import <each top-level module>"` in a fresh interpreter.
3. Run the tests, including any that import modules in a different order.
4. Add the detector to CI: a non-zero exit fails the build.
FILE:templates/cycle-report.md
# Import cycle report - {{project}} ({{date}})
**Scope:** {{modules}} modules under `{{root}}`, {{edges}} internal imports. Command: `python3 scripts/import_cycles.py {{project}}`
**Symptom:** {{error_or_reason}}
## Summary
- Cycle groups: {{group_count}} ({{import_time_count}} break at import time, {{deferred_count}} deferred only)
- Status after fixes: {{status}}
## Groups
| # | modules | shortest cycle | kind | fix chosen | status |
|---|---|---|---|---|---|
| 1 | {{modules_1}} | {{cycle_1}} | {{kind_1}} | {{fix_1}} | {{status_1}} |
## Changes
| file | change | pattern (fix-patterns.md) |
|---|---|---|
| {{file}} | {{change}} | {{pattern}} |
## Verification
- Detector re-run: {{detector_result}}
- Fresh-interpreter imports: {{import_check}}
- Tests: {{tests}}
## Remaining and notes
- Documented deferred imports (IC02): {{deferred_notes}}
- Dynamic imports not covered by static analysis: {{dynamic_imports}}
- Suggested CI step: `python3 scripts/import_cycles.py . || exit 1`
FILE:examples/shop/__init__.py
"""Fictional demo package for the import cycle detector (not a real shop)."""
from .orders import Order, place_order
__all__ = ["Order", "place_order"]
FILE:examples/shop/models.py
from dataclasses import dataclass
from shop.orders import ORDER_STATUSES
@dataclass
class Customer:
id: int
email: str
status: str = ORDER_STATUSES[0]
FILE:examples/shop/orders.py
from dataclasses import dataclass, field
from shop.models import Customer
from shop import payments
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
@dataclass
class Order:
id: int
customer: Customer
total_cents: int
status: str = "new"
lines: list = field(default_factory=list)
def place_order(order):
payments.charge(order)
order.status = "paid"
return order
FILE:examples/shop/payments.py
from shop.notifications import send_receipt
def charge(order):
# pretend to call a payment provider here
send_receipt(order)
return True
FILE:examples/shop/notifications.py
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from shop.models import Customer
def send_receipt(order):
from shop.orders import ORDER_STATUSES # deferred import, runs only when called
return "Receipt for order %s (%s)" % (order.id, ORDER_STATUSES[1])
def greet(customer: "Customer"):
return "Hello " + customer.email
FILE:examples/shop/utils.py
def cents_to_text(cents):
return "%d.%02d" % divmod(cents, 100)
FILE:scripts/import_cycles.py
#!/usr/bin/env python3
"""import_cycles.py - find circular imports in a Python project (stdlib only, Python 3.8+).
Usage:
python3 scripts/import_cycles.py <project_dir> [--root PKG_PARENT] [--json] [--include-type-checking]
python3 scripts/import_cycles.py --self-test
Reads every .py file under <project_dir> (skipping venvs, build and cache folders), maps files to
module names, parses imports with ast (absolute, relative, `from pkg import submodule`), builds the
import graph between project modules and reports each strongly connected component (a group of
modules that import each other directly or indirectly) with its shortest cycle, the exact import
lines, whether each import runs at import time (top level) or later (inside a function), and a
suggested edge to break. Findings IC01-IC06. Exit 0 = no import-time cycles, 1 = import-time
cycle or other high finding, 2 = bad input.
"""
import argparse, ast, json, os, sys
from collections import deque
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "build", "dist", "node_modules",
".tox", ".nox", ".mypy_cache", ".pytest_cache", "site-packages", ".eggs"}
def module_name(path, root):
rel = os.path.relpath(path, root)[:-3].replace(os.sep, ".")
if rel.endswith(".__init__"):
rel = rel[: -len(".__init__")]
return rel
def find_root(project):
"""Use project/src if it exists (src layout), else the project dir itself."""
src = os.path.join(project, "src")
return src if os.path.isdir(src) else project
def collect_files(root):
out = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.endswith(".egg-info"))
for f in sorted(filenames):
if f.endswith(".py"):
out.append(os.path.join(dirpath, f))
return out
class ImportVisitor(ast.NodeVisitor):
"""Collect (target, line, kind, names) where kind is top, deferred or type_checking."""
def __init__(self, modname, is_pkg):
self.mod, self.is_pkg, self.depth, self.tc = modname, is_pkg, 0, 0
self.found = []
def _kind(self):
if self.tc:
return "type_checking"
return "deferred" if self.depth else "top"
def visit_FunctionDef(self, node):
self.depth += 1; self.generic_visit(node); self.depth -= 1
visit_AsyncFunctionDef = visit_FunctionDef
visit_Lambda = visit_FunctionDef
def visit_If(self, node):
t = node.test
is_tc = (isinstance(t, ast.Name) and t.id == "TYPE_CHECKING") or \
(isinstance(t, ast.Attribute) and t.attr == "TYPE_CHECKING")
if is_tc:
self.tc += 1
for n in node.body:
self.visit(n)
self.tc -= 1
for n in node.orelse:
self.visit(n)
else:
self.generic_visit(node)
def visit_Import(self, node):
for a in node.names:
self.found.append((a.name, node.lineno, self._kind(), []))
def visit_ImportFrom(self, node):
if node.level:
parts = self.mod.split(".")
base = parts if self.is_pkg else parts[:-1]
up = node.level - 1
if up > len(base):
return
base = base[: len(base) - up] if up else base
target = ".".join(base + ([node.module] if node.module else []))
else:
target = node.module or ""
names = [a.name for a in node.names]
self.found.append((target, node.lineno, self._kind(), names))
def resolve(target, names, modules):
"""Map an import target to project modules: the deepest existing module, plus submodules named in `from x import y`."""
hits = []
if names:
for n in names:
sub = target + "." + n if target else n
if sub in modules:
hits.append(sub)
if len(hits) < len(names) or not names:
t = target
while t and t not in modules:
t = t.rpartition(".")[0]
if t:
hits.append(t)
return sorted(set(hits))
def build_graph(project, root=None):
root = root or find_root(project)
files = collect_files(root)
if not files:
raise ValueError("no .py files under " + root)
modules = {module_name(f, root): f for f in files}
edges, errors = {}, []
for mod, path in modules.items():
try:
tree = ast.parse(open(path, encoding="utf-8").read(), filename=path)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append((mod, str(e).splitlines()[0])); continue
v = ImportVisitor(mod, path.endswith("__init__.py")); v.visit(tree)
for target, line, kind, names in v.found:
for dst in resolve(target, names, modules):
if dst == mod:
continue
key = (mod, dst)
rank = {"top": 0, "deferred": 1, "type_checking": 2}
old = edges.get(key)
if old is None or rank[kind] < rank[old["kind"]]:
edges[key] = {"line": line, "kind": kind, "names": names, "file": os.path.relpath(path, project)}
return root, modules, edges, errors
def sccs(nodes, adj):
"""Tarjan's algorithm, iterative."""
index, low, onstack, stack, out, counter = {}, {}, set(), [], [], [0]
for start in sorted(nodes):
if start in index:
continue
work = [(start, iter(sorted(adj.get(start, ()))))]
index[start] = low[start] = counter[0]; counter[0] += 1; stack.append(start); onstack.add(start)
while work:
v, it = work[-1]
for w in it:
if w not in index:
index[w] = low[w] = counter[0]; counter[0] += 1; stack.append(w); onstack.add(w)
work.append((w, iter(sorted(adj.get(w, ())))))
break
if w in onstack:
low[v] = min(low[v], index[w])
else:
work.pop()
if work:
low[work[-1][0]] = min(low[work[-1][0]], low[v])
if low[v] == index[v]:
comp = []
while True:
w = stack.pop(); onstack.discard(w); comp.append(w)
if w == v:
break
if len(comp) > 1:
out.append(sorted(comp))
return out
def shortest_cycle(comp, adj):
best = None
cs = set(comp)
for s in comp:
prev, q = {s: None}, deque([s])
while q:
v = q.popleft()
for w in sorted(adj.get(v, ())):
if w not in cs:
continue
if w == s:
path = [v]
while prev[path[-1]] is not None:
path.append(prev[path[-1]])
cyc = list(reversed(path)) + [s]
if best is None or len(cyc) < len(best):
best = cyc
q.clear(); break
if w not in prev:
prev[w] = v; q.append(w)
return best
def analyze(project, root=None, include_tc=False):
root, modules, edges, errors = build_graph(project, root)
use = {k: v for k, v in edges.items() if include_tc or v["kind"] != "type_checking"}
top = {k: v for k, v in use.items() if v["kind"] == "top"}
def adj_of(es):
a = {}
for (s, d) in es:
a.setdefault(s, set()).add(d)
return a
adj_all, adj_top = adj_of(use), adj_of(top)
groups, findings = [], []
top_sccs = [set(c) for c in sccs(modules, adj_top)]
for comp in sccs(modules, adj_all):
cyc = shortest_cycle(comp, adj_all)
cyc_edges = [dict(src=a, dst=b, **use[(a, b)]) for a, b in zip(cyc, cyc[1:])]
import_time = any(set(comp) & t for t in top_sccs)
inner = [dict(src=s, dst=d, **e) for (s, d), e in use.items() if s in comp and d in comp]
# break candidate: top-level edge in the shortest cycle importing the fewest names, prefer non-__init__ sources
cands = [e for e in cyc_edges if e["kind"] == "top"] or cyc_edges
brk = min(cands, key=lambda e: (len(e["names"]) or 1, e["file"].endswith("__init__.py"), e["src"]))
g = dict(modules=comp, size=len(comp), shortest_cycle=cyc, cycle_edges=cyc_edges,
import_time=import_time, edges_inside=len(inner), other_edges=[e for e in sorted(inner, key=lambda e: (e["src"], e["dst"])) if (e["src"], e["dst"]) not in set(zip(cyc, cyc[1:]))], break_candidate=brk)
groups.append(g)
label = " -> ".join(cyc)
if import_time:
findings.append(("high", "IC01", "import-time cycle: " + label))
else:
findings.append(("medium", "IC02", "cycle only through imports inside functions (works, but fragile): " + label))
if len(comp) >= 5:
findings.append(("medium", "IC03", "large tangle of %d modules: %s" % (len(comp), ", ".join(comp))))
for e in cyc_edges:
if e["file"].endswith("__init__.py") and e["kind"] == "top":
findings.append(("medium", "IC04", "package __init__ re-exports into the cycle: %s line %d" % (e["file"], e["line"])))
if e["kind"] == "top" and e["names"] == ["*"]:
findings.append(("medium", "IC05", "star import inside a cycle: %s line %d" % (e["file"], e["line"])))
tc_only = [k for k, v in edges.items() if v["kind"] == "type_checking"]
if tc_only and not include_tc:
findings.append(("info", "IC06", "%d TYPE_CHECKING-only import(s) ignored (they never run)" % len(tc_only)))
for mod, err in errors:
findings.append(("low", "IC00", "could not parse %s: %s" % (mod, err)))
return dict(project=project, root=root, modules=len(modules), edges=len(use), groups=groups,
findings=[dict(severity=s, code=c, message=m) for s, c, m in findings])
def render(res):
L = ["# Import cycle report", "",
"Project: %s (modules from %s): %d modules, %d internal imports, %d cycle group(s)" %
(res["project"], res["root"], res["modules"], res["edges"], len(res["groups"])), ""]
for i, g in enumerate(res["groups"], 1):
L.append("## Group %d: %d modules (%s)" % (i, g["size"], "breaks at import time" if g["import_time"] else "deferred imports only"))
L.append("Modules: " + ", ".join(g["modules"]))
L.append("Shortest cycle: " + " -> ".join(g["shortest_cycle"]))
for e in g["cycle_edges"]:
L.append(" - %s line %d: %s imports %s%s [%s]" % (e["file"], e["line"], e["src"], e["dst"],
(" (" + ", ".join(e["names"]) + ")") if e["names"] else "", e["kind"]))
if g["other_edges"]:
L.append("Other imports inside this group:")
for e in g["other_edges"]:
L.append(" - %s line %d: %s imports %s [%s]" % (e["file"], e["line"], e["src"], e["dst"], e["kind"]))
b = g["break_candidate"]
L.append("Suggested place to break: %s line %d (%s -> %s)" % (b["file"], b["line"], b["src"], b["dst"]))
L.append("")
if not res["groups"]:
L += ["No import cycles between project modules.", ""]
L.append("## Findings")
order = {"high": 0, "medium": 1, "low": 2, "info": 3}
for f in sorted(res["findings"], key=lambda f: (order[f["severity"]], f["code"])):
L.append("- [%s] %s %s" % (f["severity"], f["code"], f["message"]))
if not res["findings"]:
L.append("- none")
return "\n".join(L)
def self_test():
import tempfile
ok = [0, 0]
def check(name, cond):
ok[0 if cond else 1] += 1
print(("PASS " if cond else "FAIL ") + name)
def proj(files):
d = tempfile.mkdtemp()
for rel, txt in files.items():
p = os.path.join(d, rel); os.makedirs(os.path.dirname(p), exist_ok=True)
open(p, "w").write(txt)
return d
r = analyze(proj({"a.py": "import b\n", "b.py": "x = 1\n"}))
check("no cycle in a -> b", not r["groups"])
r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
check("direct cycle a <-> b found", len(r["groups"]) == 1 and r["groups"][0]["size"] == 2)
check("direct cycle is import-time IC01", any(f["code"] == "IC01" for f in r["findings"]))
r = analyze(proj({"a.py": "import b\n", "b.py": "import c\n", "c.py": "import a\n"}))
check("three-module cycle shortest path length 4", r["groups"][0]["shortest_cycle"] == ["a", "b", "c", "a"])
r = analyze(proj({"a.py": "import b\n", "b.py": "def f():\n import a\n"}))
check("function-level import gives IC02 not IC01", [f["code"] for f in r["findings"]] == ["IC02"])
r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import a\n"}))
check("TYPE_CHECKING import ignored by default", not r["groups"] and r["findings"][0]["code"] == "IC06")
r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import a\n"}), include_tc=True)
check("TYPE_CHECKING import counted with flag", len(r["groups"]) == 1)
r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from . import y\n", "pkg/y.py": "from .x import thing\n"}))
check("relative imports resolved", r["groups"] and r["groups"][0]["modules"] == ["pkg.x", "pkg.y"])
r = analyze(proj({"pkg/__init__.py": "from .x import X\n", "pkg/x.py": "from pkg import helpers\nX = 1\n", "pkg/helpers.py": "import pkg\n"}))
check("__init__ re-export flagged IC04", any(f["code"] == "IC04" for f in r["findings"]))
r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from pkg import y\n", "pkg/y.py": "x = 1\n"}))
check("from pkg import submodule maps to the submodule", not r["groups"])
r = analyze(proj({"src/app/__init__.py": "", "src/app/a.py": "from app import b\n", "src/app/b.py": "from app.a import f\n"}))
check("src layout root detected", r["root"].endswith("src") and len(r["groups"]) == 1)
r = analyze(proj({"a.py": "from b import *\n", "b.py": "import a\n"}))
check("star import in cycle flagged IC05", any(f["code"] == "IC05" for f in r["findings"]))
files = {"m%d.py" % i: "import m%d\n" % ((i + 1) % 5) for i in range(5)}
r = analyze(proj(files))
check("five-module ring flagged IC03", any(f["code"] == "IC03" for f in r["findings"]))
r = analyze(proj({"a.py": "import os, json\nimport b\n", "b.py": "import sys\n"}))
check("stdlib imports ignored", r["edges"] == 1)
r = analyze(proj({"a.py": "import b\n", "b.py": "def (:\n"}))
check("syntax error reported IC00", any(f["code"] == "IC00" for f in r["findings"]))
r = analyze(proj({"venv/lib/x.py": "import y\n", "venv/lib/y.py": "import x\n", "a.py": "x=1\n"}))
check("venv folder skipped", r["modules"] == 1)
r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
b = r["groups"][0]["break_candidate"]
check("break candidate is an edge of the cycle", (b["src"], b["dst"]) in [("a", "b"), ("b", "a")])
try:
analyze(proj({"README.md": "x"})); check("empty project rejected", False)
except ValueError:
check("empty project rejected", True)
print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
return 0 if not ok[1] else 1
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("project", nargs="?")
ap.add_argument("--root", help="folder that contains the top-level packages (default: <project>/src if present, else <project>)")
ap.add_argument("--json", action="store_true")
ap.add_argument("--include-type-checking", action="store_true")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.project or not os.path.isdir(a.project):
print("error: give a project directory", file=sys.stderr); return 2
try:
res = analyze(a.project, a.root, a.include_type_checking)
except ValueError as e:
print("error:", e, file=sys.stderr); return 2
print(json.dumps(res, indent=2) if a.json else render(res))
return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0
if __name__ == "__main__":
sys.exit(main())
Finds knowledge concentration risk in a Git repo from its history: per-module bus factor, who holds the knowledge, modules nobody active still knows, single-knower hot spots, the repo truck factor and duplicate identities, with a handover plan template. Offline stdlib Python.
---
name: git-bus-factor-and-knowledge-risk-analyzer
description: Finds knowledge concentration risk in a Git repo from its history: per-module bus factor, who holds the knowledge, modules nobody active still knows, single-knower hot spots, the repo truck factor and duplicate identities, with a handover plan template. Offline stdlib Python.
---
# Git Bus Factor and Knowledge Risk Analyzer
You help engineering managers, tech leads, CTOs of small companies and open-source maintainers see where knowledge of their codebase sits with just one or two people, and where nobody who still works on the project knows the code at all. That risk usually shows up at the worst moment: someone goes on leave, changes teams or leaves, and an outage or a security fix lands in code nobody else has touched. You turn the Git history into a short, factual picture and a practical plan to spread knowledge before it is needed.
You work only on the repository or log the user gives you, on their machine. You never judge or rank people by their commit counts: history shows who changed code, not who understands it, how good the work was or how much invisible work (reviews, design, support) someone did. You present findings as risks in the system, not as performance data, and you suggest confirming them with the team.
## Files in this skill
- `scripts/bus_factor.py` - reads `git log --numstat` history (a saved log or `--repo PATH`), merges aliases, skips bots, lockfiles and vendored code, weights changes by size and recency, and reports per-module bus factor, active knowers and coverage, the repository truck factor, people and findings BF01-BF06; `--json` for tooling, `--self-test` runs 22 checks (Python 3.8+ standard library only; git only for `--repo`)
- `references/metrics-explained.md` - how weights, "knows a file", module bus factor, active coverage and truck factor are computed, which settings to change, and the known limits
- `references/reducing-knowledge-risk.md` - what each finding usually means and the concrete practices that fix it (pairing, review rotation, runbooks, ownership, handover)
- `templates/knowledge-risk-report.md` - the report and 90-day plan you hand back
- `examples/git-history.log`, `examples/aliases.csv` - history of a fictional shop API with five people and a bot: a payments module written by someone who left, a frontend only one person changes, an author with two emails
## Workflow
### 1. Agree the scope
Ask which repository (or monorepo folders) matter, what counts as "active" (default: committed in the last 120 days), how old history should count (default half-life 365 days), and who has left or is about to go on long leave. Ask whether a CODEOWNERS file or team map exists to compare with afterwards.
### 2. Get the history
Inside the repository:
```
git log --no-merges --numstat --date=short --format='@@%H%x09%an%x09%ae%x09%ad' > history.log
```
or let the script run git with `--repo PATH`. Build `aliases.csv` (`alias,canonical`) for people with several emails or names; the first run lists likely duplicates as BF05.
### 3. Run the analysis
```
python3 scripts/bus_factor.py examples/git-history.log --aliases examples/aliases.csv
python3 scripts/bus_factor.py --repo . --aliases aliases.csv --depth 2 --since 2024-01-01
python3 scripts/bus_factor.py history.log --aliases aliases.csv --json > knowledge.json
python3 scripts/bus_factor.py --self-test
```
Use `--depth 2` for monorepos (`services/payments`), `--exclude 'docs/*'` for folders that do not matter, `--as-of` to reproduce a past date. Exit 0 = no high findings, 1 = high findings, 2 = bad input.
### 4. Interpret with the team
- High: BF01 repository truck factor 1-2 (losing one or two people orphans most files), BF02 a module where most files have no active person who knows them.
- Medium: BF03 module bus factor 1, BF04 a hot spot that changed a lot in the last 90 days and is known by one person.
- Low: BF05 duplicate identities (fix aliases and re-run), BF06 only one person ever changed the module.
Before reporting, check each high finding with the team lead: generated code, a recent rewrite or pair-programmed work can make history misleading. Map modules to business impact (payments, auth and data pipelines first).
### 5. Report and plan
Fill `templates/knowledge-risk-report.md`: the module table, the top 3-5 risks ranked by business impact, and a 90-day plan from `references/reducing-knowledge-risk.md` with an owner and a check for each action. Re-run the script monthly or quarterly and compare coverage.
## Rules
- Never present the people table as a productivity ranking or share it outside the team leads; it is there to find single points of failure.
- Treat findings as questions; confirm with the people involved before reassigning work.
- Work locally; do not upload the repository or its history anywhere.
FILE:references/metrics-explained.md
# How bus_factor.py measures knowledge
## Inputs and filters
- History comes from `git log --no-merges --numstat`. Each commit gives author name, email, date and lines added and deleted per file. Binary files (`-`) are skipped; renames keep the new path.
- Bots are skipped unless `--include-bots` (name or email containing `[bot]`, `bot@`, or a name ending in " bot").
- Default excludes: lockfiles (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `poetry.lock`, `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`), `vendor/`, `node_modules/`, `dist/`, `build/`, minified files and images. Add more with `--exclude GLOB`.
- Aliases: `aliases.csv` maps an email or a name to one canonical person. Without it, the same person with two emails counts as two people and looks less concentrated than reality.
## Weight of a change
weight = ln(1 + lines added + lines deleted) * 0.5 ^ (age_days / half_life_days)
- The logarithm stops one huge generated diff from outweighing years of small careful changes.
- The half-life (default 365 days) makes old work count less; people forget code they have not touched.
## Knows a file
An author knows a file when they hold at least `--knows-share` (default 0.25) of the file's total weight. A file can have several knowers.
## Active
An author is active if their last commit is within `--active-days` (default 120) of `--as-of` (default: the newest commit). Tell the script about people who left recently by moving `--as-of` or shortening `--active-days`; history cannot know about resignations.
## Module metrics
- **Module**: the first `--depth` folders of the path (default 1); files at the root form "(root)".
- **Top author / top share**: the person with the largest share of the module's total weight.
- **Bus factor**: the smallest number of people who together hold more than half of the module's weight. 1 means one person holds most of it.
- **Active knowers**: active people who know at least one file in the module.
- **Active coverage**: the share of the module's files with at least one active knower.
## Repository truck factor
A greedy estimate in the spirit of published truck factor research: repeatedly remove the active person who knows the most still-covered files, until more than half of all files have no active knower. The number of people removed is the truck factor. 0 means more than half of the files already have no active knower.
## Findings
| code | severity | rule |
|---|---|---|
| BF01 | high | truck factor is 0, 1 or 2 |
| BF02 | high | active coverage of a module is under 50% |
| BF03 | medium | module bus factor 1 and the module has 3 or more files |
| BF04 | medium | bus factor 1 and the module's line changes in the last 90 days are in the top quarter of modules (needs 4+ modules) |
| BF05 | low | one name appears with several emails and no alias |
| BF06 | low | only one person ever changed the module |
## Limits
- Commits show authorship, not understanding: reviewers, pair partners and people who designed or operate the code are invisible.
- Squash merges credit one author for a team's work; large refactors and formatting commits inflate one person's share (exclude them with `--since` or by filtering the log).
- Co-authored-by trailers are not counted.
- Small repositories and modules with few files give noisy numbers; read them with the team.
FILE:references/reducing-knowledge-risk.md
# Reducing knowledge risk
## By finding
| finding | usual meaning | first actions |
|---|---|---|
| BF01 truck factor 1-2 | most of the codebase depends on one or two people | pick the 2-3 most business-critical modules and start the actions below there; make it a quarterly goal, not extra work on top |
| BF02 orphaned module | the people who wrote it left or moved on | name an owner now; schedule a code walkthrough with anyone who remembers it; write a short runbook; add tests around the risky paths before the next change |
| BF03 bus factor 1 | one person does almost all changes | rotate reviews so a second person reviews every change; pair on the next feature; the main author writes a one-page architecture note |
| BF04 single-knower hot spot | the busiest code is known by one person | highest priority after orphaned modules: pair every second change, add a second reviewer as required, keep a changelog of decisions |
| BF05 duplicate identity | one person with several emails | add alias lines and re-run; ask people to set `user.email` per repository |
| BF06 one person ever | nobody else has touched it at all | give a small, real task in that module to a second person with the author as reviewer |
## Practices that work
- **Review rotation**: the second reviewer for a module comes from outside its usual authors; track it for a month.
- **Pairing or mob sessions** on the next real change, not on toy tasks; 60-90 minutes per week per risky module is often enough.
- **Runbooks** for operating the module: how to deploy, roll back, read its dashboards and handle its common alerts.
- **Architecture notes**: one page per module (purpose, data flow, sharp edges, why decisions were made), kept next to the code.
- **Ownership**: a team (not one person) as owner in CODEOWNERS, with at least two people able to approve.
- **On-call shadowing** for modules that page people.
- **Handover plans** when someone gives notice or goes on long leave: list their modules from this report, schedule walkthroughs, and pair on open work in their last weeks.
## Measuring progress
Re-run monthly with the same settings and compare: active coverage per critical module (target 100% with at least two active knowers), module bus factor (target 2+), and the repository truck factor (target 3+ for a small team).
FILE:templates/knowledge-risk-report.md
# Knowledge risk report: {{repository}} - {{date}}
Settings: active = committed in the last {{active_days}} days; half-life {{half_life_days}} days; knows-share {{knows_share}}; module depth {{depth}}. History since {{since}}.
## Summary
- Repository truck factor: {{truck_factor}} ({{people}})
- Modules with low active coverage: {{bf02_modules}}
- Single-knower modules: {{bf03_modules}}
- Hot spots known by one person: {{bf04_modules}}
## Module table
(paste the module table from bus_factor.py)
## Top risks (ranked by business impact)
| # | module | why it matters | finding | confirmed with |
|---|---|---|---|---|
| 1 | {{module}} | {{impact, e.g. checkout payments}} | {{code}} | {{lead}} |
## 90-day plan
| action | module | owner | by | done when |
|---|---|---|---|---|
| {{e.g. pair on next two changes}} | {{module}} | {{name}} | {{date}} | {{second person merged a change alone}} |
## Caveats
- History shows who changed code, not who understands it; reviewers, pair partners and operators are not counted.
- {{anything specific: squash merges, a big refactor, generated code}}
## Next check
{{date}} with the same settings.
FILE:examples/git-history.log
@@58f5d4cce18a5ce4e3f9aa12d9767dcfd74b25ee Ben Okafor ben@shop.example 2026-11-14
5 0 web/src/api.ts
32 0 web/src/checkout.tsx
@@4cbab3078c9e5e9fac0a6d3627c6e022739f96e1 Eli Novak eli@shop.example 2026-11-12
12 0 core/config.py
40 0 core/db.py
@@a0d3945429639f6c562a88444476839744d9453e Ana Silva ana.silva@shop.example 2026-11-10
10 0 core/db.py
29 0 orders/api.py
@@faa0aacf2cd46c8e74c9bd98cf5921fb50dd6c6b Ana Silva ana.silva@shop.example 2026-10-20
15 0 payments/webhooks.py
@@b579089fdf73b4d2bc6598a4ee680b3839743088 Ben Okafor ben@shop.example 2026-10-11
9 0 web/src/cart.tsx
6 0 web/src/checkout.tsx
@@50b03245d12d83ddb1e9ae1c66a2d45178051021 Eli Novak eli@shop.example 2026-10-10
15 0 core/config.py
11 0 search/query.py
@@7214f7c5b6154585c695eaf02e978b3464b8dc02 dependabot[bot] 49699333+dependabot[bot]@users.noreply.github.com 2026-10-01
150 0 web/package-lock.json
150 0 web/package.json
@@16652d4b388444019ca413263b86cbfd87baed7a Ana Silva ana.silva@shop.example 2026-09-24
37 0 orders/api.py
7 0 orders/service.py
@@8290901896c8e9f9611cff8466cf7966b25eb76d Ben Okafor ben@shop.example 2026-09-15
5 0 README.md
@@fffb9688a48be4a6e95b08b16cba70e17e9f4b9b Eli Novak eli@shop.example 2026-09-07
15 0 orders/api.py
31 0 search/query.py
@@e841c7d0bbed56f4725d681b6587a1808123c893 Ben Okafor ben@shop.example 2026-09-07
24 0 web/src/api.ts
25 0 web/src/cart.tsx
@@88ccae50a361536da22fe6b5e96cc008385ccccb Ana Silva ana.silva@shop.example 2026-08-09
25 0 orders/models.py
14 0 orders/service.py
@@000ed52a381b54ba901092d2050c6165b8441de8 Eli Novak eli@shop.example 2026-08-06
37 0 core/db.py
27 0 orders/api.py
@@c548efcb90ebc04644b4f9d761bb0a96bc9be56d Ben Okafor ben@shop.example 2026-08-04
4 0 web/src/api.ts
13 0 web/src/checkout.tsx
@@b9a4d1e4e28cda2113d8ac51cdff3389910dc14e Eli Novak eli@shop.example 2026-07-04
32 0 core/config.py
15 0 core/db.py
@@a003bffd397e386e00c745b4393ca3c509859e35 Ben O. ben.okafor@gmail.example 2026-07-01
3 0 web/src/cart.tsx
9 0 web/src/checkout.tsx
@@10e0e7b09f2d37b0c7055c4a7a17af09dc945e91 Ana Silva ana.silva@shop.example 2026-06-24
18 0 core/db.py
28 0 orders/models.py
@@d0076f938d1899cc368d2cc627220682762e6516 Eli Novak eli@shop.example 2026-06-02
35 0 core/config.py
15 0 search/query.py
@@b70911cb2b187c324a78b2af770bff9c354ed222 Ben Okafor ben@shop.example 2026-05-29
28 0 web/src/api.ts
6 0 web/src/cart.tsx
@@c77843f7c87f8d6ad35d107e4ad625e4559cf306 Chen Wei chen@shop.example 2026-05-15
30 0 core/config.py
9 0 search/query.py
@@faeb60ed9f9ec1faaf33e8393463027d45666e4a Ana Silva ana.silva@shop.example 2026-05-09
25 0 core/db.py
31 0 orders/api.py
@@09c4044f954ffd84dc15713518cc1532a6c5cc6f Ben Okafor ben@shop.example 2026-04-25
8 0 web/src/api.ts
8 0 web/src/checkout.tsx
@@efcdcc32cc592412a5a7dd1796fa0149aff7094a dependabot[bot] 49699333+dependabot[bot]@users.noreply.github.com 2026-04-01
150 0 web/package-lock.json
150 0 web/package.json
@@ae3fc07a50e237c4a8b98c1df55da1f5e8155aa6 Ana Silva ana.silva@shop.example 2026-03-24
30 0 orders/api.py
36 0 orders/service.py
@@eb7130d2a61f5f297762462e5ea807f5c601b827 Ben Okafor ben@shop.example 2026-03-22
36 0 web/src/cart.tsx
30 0 web/src/checkout.tsx
@@bdadf66c0528166414b20facd6e0bc6490dc50c4 Chen Wei chen@shop.example 2026-03-14
38 0 search/index.py
37 0 search/query.py
@@9dd045964286f69e2630aa8d2492d9cb8b126f45 Ben Okafor ben@shop.example 2026-02-16
22 0 web/src/api.ts
39 0 web/src/cart.tsx
@@e5b16b9f4a0600bb1303545da56d8ec5b775a71d Ana Silva ana.silva@shop.example 2026-02-06
40 0 orders/models.py
4 0 orders/service.py
@@9f3ce69e27b7d9c169f07879450c79faffb917e9 Ben Okafor ben@shop.example 2026-01-14
28 0 web/src/api.ts
26 0 web/src/checkout.tsx
@@87c36c4896129acc5b4dacb88498e10394a0dfaf Chen Wei chen@shop.example 2026-01-11
22 0 core/config.py
39 0 search/index.py
@@8ef82e501b1097d202e79c324d4a6118e855f852 Ana Silva ana.silva@shop.example 2025-12-22
28 0 core/db.py
14 0 orders/models.py
@@3433f75f61d9493c5cb9d48d7a5fb86ef241bea0 Ben Okafor ben@shop.example 2025-12-11
36 0 web/src/cart.tsx
29 0 web/src/checkout.tsx
@@304e9fd851a7b0cdd05780fe452310a5d3d86abc Chen Wei chen@shop.example 2025-11-11
21 0 core/config.py
35 0 search/query.py
@@98d8c4bbb5f3b6604cfd38bc5dda9f08736c64ed Ben Okafor ben@shop.example 2025-11-07
29 0 web/src/api.ts
19 0 web/src/cart.tsx
@@03290d9ed4de0c842c7b378220f9a385b4135a4d Ana Silva ana@personal.example 2025-11-06
5 0 core/db.py
37 0 orders/api.py
@@f1e157a039fbe041730b8f1137c684027f0e7c32 Ben Okafor ben@shop.example 2025-10-04
24 0 web/src/api.ts
6 0 web/src/checkout.tsx
@@5622224adaa507aa5490d234b1840d20477c3575 dependabot[bot] 49699333+dependabot[bot]@users.noreply.github.com 2025-09-30
150 0 web/package-lock.json
150 0 web/package.json
@@f658dbaddfcc5963b8e27a6f36a1903d4b3db6e6 Ana Silva ana.silva@shop.example 2025-09-21
30 0 orders/api.py
14 0 orders/service.py
@@bac00f633bef75ed05866ccc8d6d31fb9e071e3e Chen Wei chen@shop.example 2025-09-10
20 0 search/index.py
20 0 search/query.py
@@c460c69d03be963f77b2524616dfde637254e72f Ben Okafor ben@shop.example 2025-09-01
35 0 web/src/cart.tsx
12 0 web/src/checkout.tsx
@@65153a48d22bf9b981f3680e6f9917b64a43ec35 Ana Silva ana.silva@shop.example 2025-08-06
28 0 orders/models.py
22 0 orders/service.py
@@bc8cbd6bf9daee0d05449afbbaccb64f56bfb29a Chen Wei chen@shop.example 2025-07-11
19 0 core/config.py
14 0 search/index.py
@@6a34d862b912eb393cf7f8ca55c028b9010173be Ana Silva ana.silva@shop.example 2025-06-21
23 0 core/db.py
24 0 orders/models.py
@@6059e786b3ab3482031920657fecf929a4a58bd4 Dana Kim dana@shop.example 2025-05-20
6 0 payments/stripe_client.py
39 0 payments/webhooks.py
@@e7cb62d4ed5198d9ce0a3fe0b1c938113a67ad97 Chen Wei chen@shop.example 2025-05-10
36 0 core/config.py
40 0 search/query.py
@@9fd0749dd73e35beb76f65b7e3657463d44c7e54 Ana Silva ana.silva@shop.example 2025-05-06
10 0 core/db.py
14 0 orders/api.py
@@a0c736ff9075a594896ca5bf024440a12c35c115 Dana Kim dana@shop.example 2025-05-03
29 0 payments/refunds.py
15 0 payments/webhooks.py
@@1e40d5f4b152a88dbd317ede961bf06ae2a0a742 Dana Kim dana@shop.example 2025-04-17
22 0 payments/refunds.py
19 0 payments/stripe_client.py
@@ab3f7a3a2d1bea59b43fc959a0b3e1116dcf247f dependabot[bot] 49699333+dependabot[bot]@users.noreply.github.com 2025-04-01
150 0 web/package-lock.json
150 0 web/package.json
@@fb0a311f7267f495367425518ef25dbf365f5ae1 Dana Kim dana@shop.example 2025-03-31
40 0 payments/stripe_client.py
4 0 payments/webhooks.py
@@cd493d2263836828dcb0be8e4c4140125c965850 Ana Silva ana.silva@shop.example 2025-03-21
39 0 orders/api.py
6 0 orders/service.py
@@3c743484d0dd4bca3905f9686bba1f48b22de580 Dana Kim dana@shop.example 2025-03-15
38 0 payments/refunds.py
30 0 payments/webhooks.py
@@981e4f06309729c1da359503aed2ba7acd1a8e8b Chen Wei chen@shop.example 2025-03-10
23 0 search/index.py
14 0 search/query.py
@@c9168c14828d2c382e334aa604064471d5d0cd63 Dana Kim dana@shop.example 2025-02-26
6 0 payments/refunds.py
20 0 payments/stripe_client.py
@@4e20074f7f1b7bddfda1949cc23b0852c36ec61a Dana Kim dana@shop.example 2025-02-10
17 0 payments/stripe_client.py
8 0 payments/webhooks.py
@@d53da3ddd6680b9335a63352e7b365c79f62c028 Ana Silva ana.silva@shop.example 2025-02-03
10 0 orders/models.py
25 0 orders/service.py
@@3e657197ddd176ccb02ab859abd3f8416459b665 Dana Kim dana@shop.example 2025-01-24
31 0 payments/refunds.py
14 0 payments/webhooks.py
@@8590bef42bccc66937a1dcbc79275ed93099cef7 Dana Kim dana@shop.example 2025-01-08
4 0 payments/refunds.py
18 0 payments/stripe_client.py
@@f67141a910fd0594c02e23adbc41e740d373506c Ana Silva ana.silva@shop.example 2025-01-06
11 0 README.md
FILE:examples/aliases.csv
alias,canonical
ben.okafor@gmail.example,Ben Okafor
Ben O.,Ben Okafor
FILE:scripts/bus_factor.py
#!/usr/bin/env python3
"""bus_factor.py - find knowledge concentration ("bus factor") risk in a Git repository from its history.
Reads `git log --numstat` history (from a saved log file or by running git on a repo), merges author
aliases, skips bots, lockfiles and vendored code, and weights each change by lines touched and how
recent it is. Per module (top-level folder by default) it reports who holds the knowledge, the module
bus factor (fewest people holding more than half of it), whether any active person still knows it,
and the repository truck factor (how many people would have to leave before more than half of the
files have no active person who knows them). Standard library only.
Usage:
python3 bus_factor.py LOGFILE [options]
python3 bus_factor.py --repo PATH [options] (runs git log for you)
python3 bus_factor.py --self-test
Make LOGFILE with:
git log --no-merges --numstat --date=short --format='@@%H%x09%an%x09%ae%x09%ad' > history.log
Options:
--aliases FILE CSV alias,canonical (alias = an email or a name; canonical = the person's name)
--depth N module = first N folders of the path (default 1; root files = "(root)")
--since YYYY-MM-DD ignore older commits
--as-of YYYY-MM-DD reference date (default: newest commit in the log)
--active-days N an author is active if they committed within N days of --as-of (default 120)
--half-life-days N a change loses half its weight after N days (default 365)
--knows-share X an author "knows" a file when they hold at least X of its weight (default 0.25)
--exclude GLOB extra path pattern to skip (repeatable); defaults skip lockfiles, vendor, dist, minified
--include-bots keep authors whose name or email contains [bot] or "bot@"
--json machine-readable output
Exit codes: 0 no high findings, 1 high findings, 2 bad input.
"""
import csv, datetime as dt, fnmatch, json, math, os, subprocess, sys
from collections import defaultdict
DEFAULT_EXCLUDES = ["*package-lock.json", "*yarn.lock", "*pnpm-lock.yaml", "*poetry.lock", "*Cargo.lock", "*go.sum",
"*composer.lock", "*Gemfile.lock", "vendor/*", "*/vendor/*", "node_modules/*", "dist/*",
"build/*", "*.min.js", "*.min.css", "*.svg", "*.png", "*.jpg", "*.pdf"]
SEV = {"BF01": "high", "BF02": "high", "BF03": "medium", "BF04": "medium", "BF05": "low", "BF06": "low"}
NAMES = {"BF01": "repository truck factor is 1 or 2",
"BF02": "orphaned module: most files have no active person who knows them",
"BF03": "module bus factor 1: one person holds most of the knowledge",
"BF04": "hot spot with a single knower (busy recently, one person)",
"BF05": "possible duplicate identity (same name, different emails)",
"BF06": "only one person has ever changed this module"}
class InputError(Exception):
pass
def parse_date(s, what):
try:
return dt.date.fromisoformat(s.strip()[:10])
except (ValueError, AttributeError):
raise InputError("bad %s date: %r" % (what, s))
def parse_log(lines):
"""Return list of commits: dict(sha, name, email, date, files=[(path, added, deleted)])."""
commits, cur = [], None
for n, raw in enumerate(lines, 1):
line = raw.rstrip("\n")
if line.startswith("@@"):
parts = line[2:].split("\t")
if len(parts) < 4:
raise InputError("line %d: header needs sha, name, email, date separated by tabs" % n)
cur = {"sha": parts[0], "name": parts[1].strip(), "email": parts[2].strip().lower(),
"date": parse_date(parts[3], "commit"), "files": []}
commits.append(cur)
elif line.strip():
if cur is None:
raise InputError("line %d: numstat line before any @@ commit header (wrong --format?)" % n)
parts = line.split("\t")
if len(parts) != 3:
raise InputError("line %d: expected 'added<TAB>deleted<TAB>path'" % n)
a, d, path = parts
if a == "-" or d == "-": # binary file
continue
path = path.strip()
if " => " in path: # rename: keep the new path
if "{" in path:
pre, rest = path.split("{", 1)
mid, post = rest.split("}", 1)
path = (pre + mid.split(" => ")[1] + post).replace("//", "/")
else:
path = path.split(" => ")[1]
try:
cur["files"].append((path, int(a), int(d)))
except ValueError:
raise InputError("line %d: added/deleted must be numbers" % n)
if not commits:
raise InputError("no commits found (expected lines starting with @@)")
return commits
def git_log(repo, since=None):
cmd = ["git", "-C", repo, "log", "--no-merges", "--numstat", "--date=short", "--format=@@%H%x09%an%x09%ae%x09%ad"]
if since:
cmd.append("--since=" + since)
try:
out = subprocess.run(cmd, capture_output=True, text=True, check=True).stdout
except (OSError, subprocess.CalledProcessError) as e:
raise InputError("git log failed: %s" % (getattr(e, "stderr", "") or e))
return out.splitlines()
def load_aliases(path):
m = {}
if not path:
return m
try:
for row in csv.DictReader(open(path, encoding="utf-8", newline="")):
a, c = (row.get("alias") or "").strip(), (row.get("canonical") or "").strip()
if a and c:
m[a.lower()] = c
except OSError as e:
raise InputError("cannot read aliases: %s" % e)
return m
def module_of(path, depth):
parts = path.split("/")
if len(parts) == 1:
return "(root)"
return "/".join(parts[:min(depth, len(parts) - 1)])
def analyse(commits, aliases=None, depth=1, since=None, as_of=None, active_days=120, half_life=365,
knows_share=0.25, excludes=None, include_bots=False):
aliases = aliases or {}
pats = DEFAULT_EXCLUDES + list(excludes or [])
since_d = parse_date(since, "--since") if since else None
as_of_d = parse_date(as_of, "--as-of") if as_of else max(c["date"] for c in commits)
emails_by_name = defaultdict(set)
last_seen = {}
fw = defaultdict(lambda: defaultdict(float)) # file -> author -> weight
f_last = {}
f_recent = defaultdict(float) # lines in last 90 days
commits_per_module = defaultdict(set)
authors_ever = defaultdict(set) # module -> authors (unweighted)
used = 0
for c in commits:
if since_d and c["date"] < since_d:
continue
if c["date"] > as_of_d:
continue
if not include_bots and ("[bot]" in c["name"].lower() or "bot@" in c["email"] or c["name"].lower().endswith(" bot")):
continue
who = aliases.get(c["email"]) or aliases.get(c["name"].lower()) or c["name"]
if who == c["name"] and not aliases.get(c["email"]):
emails_by_name[c["name"]].add(c["email"])
last_seen[who] = max(last_seen.get(who, c["date"]), c["date"])
age = (as_of_d - c["date"]).days
w = 0.5 ** (age / float(half_life)) if half_life > 0 else 1.0
touched = False
for path, a, d in c["files"]:
if any(fnmatch.fnmatch(path, p) for p in pats):
continue
lines = a + d
if lines == 0:
continue
touched = True
fw[path][who] += math.log1p(lines) * w # log damps huge generated diffs
f_last[path] = max(f_last.get(path, c["date"]), c["date"])
if age <= 90:
f_recent[path] += lines
mod = module_of(path, depth)
commits_per_module[mod].add(c["sha"])
authors_ever[mod].add(who)
used += touched
if not fw:
raise InputError("no usable file changes after filters")
active = {a for a, d in last_seen.items() if (as_of_d - d).days <= active_days}
def knowers(path):
tot = sum(fw[path].values())
return {a for a, v in fw[path].items() if v / tot >= knows_share}
files = sorted(fw)
mods = defaultdict(list)
for p in files:
mods[module_of(p, depth)].append(p)
recent_by_mod = {m: sum(f_recent[p] for p in ps) for m, ps in mods.items()}
hot_cut = sorted(recent_by_mod.values())[int(len(recent_by_mod) * 0.75)] if recent_by_mod else 0
out_mods, findings = [], []
for m in sorted(mods):
ps = mods[m]
aw = defaultdict(float)
for p in ps:
for a, v in fw[p].items():
aw[a] += v
tot = sum(aw.values())
ranked = sorted(aw.items(), key=lambda x: -x[1])
acc, bf = 0.0, 0
for a, v in ranked:
acc += v; bf += 1
if acc > tot / 2:
break
kn = set().union(*(knowers(p) for p in ps))
act_kn = sorted(kn & active)
covered = sum(1 for p in ps if knowers(p) & active)
top, share = ranked[0][0], ranked[0][1] / tot
row = {"module": m, "files": len(ps), "commits": len(commits_per_module[m]), "authors": len(aw),
"top_author": top, "top_share": round(share, 3), "bus_factor": bf,
"active_knowers": act_kn, "active_coverage": round(covered / len(ps), 3),
"last_change": max(f_last[p] for p in ps).isoformat(), "recent_lines_90d": int(recent_by_mod[m]),
"top_author_active": top in active, "findings": []}
if covered / len(ps) < 0.5:
row["findings"].append("BF02")
if bf == 1 and len(ps) >= 3:
row["findings"].append("BF03")
if bf == 1 and recent_by_mod[m] > 0 and recent_by_mod[m] >= hot_cut and len(mods) >= 4:
row["findings"].append("BF04")
if len(authors_ever[m]) == 1:
row["findings"].append("BF06")
out_mods.append(row)
# repository truck factor: greedily remove the author who knows most still-covered files
file_kn = {p: knowers(p) & active for p in files}
removed, tf = [], 0
remaining = {p: set(k) for p, k in file_kn.items()}
def orphaned():
return sum(1 for k in remaining.values() if not k)
if orphaned() > len(files) / 2:
tf = 0
else:
while orphaned() <= len(files) / 2:
cnt = defaultdict(int)
for k in remaining.values():
for a in k:
cnt[a] += 1
if not cnt:
break
a = sorted(cnt.items(), key=lambda x: (-x[1], x[0]))[0][0]
removed.append(a); tf += 1
for k in remaining.values():
k.discard(a)
if tf <= 2:
findings.append({"code": "BF01", "detail": "truck factor %d (%s)" % (tf, ", ".join(removed) or "already orphaned")})
for name, em in sorted(emails_by_name.items()):
if len(em) > 1:
findings.append({"code": "BF05", "detail": "%s uses %s; add an alias line" % (name, ", ".join(sorted(em)))})
for r in out_mods:
for code in r["findings"]:
findings.append({"code": code, "module": r["module"], "detail": "top %s %.0f%%, active knowers: %s" % (
r["top_author"], r["top_share"] * 100, ", ".join(r["active_knowers"]) or "none")})
people = sorted(({"author": a, "last_commit": d.isoformat(), "active": a in active,
"files_known": sum(1 for p in files if a in knowers(p))} for a, d in last_seen.items()),
key=lambda x: -x["files_known"])
return {"as_of": as_of_d.isoformat(), "commits_used": used, "files": len(files), "modules": out_mods,
"truck_factor": tf, "truck_factor_people": removed, "people": people,
"settings": {"depth": depth, "active_days": active_days, "half_life_days": half_life, "knows_share": knows_share},
"findings": findings}
def render(a):
L = ["# Knowledge risk report (as of %s)" % a["as_of"], "",
"Commits used: %d | files: %d | repository truck factor: %d (%s)" % (
a["commits_used"], a["files"], a["truck_factor"], ", ".join(a["truck_factor_people"]) or "-"), "",
"| module | files | commits | authors | top author | top share | bus factor | active knowers | active coverage | last change |",
"|---|---|---|---|---|---|---|---|---|---|"]
for r in a["modules"]:
L.append("| %s | %d | %d | %d | %s%s | %.0f%% | %d | %s | %.0f%% | %s |" % (
r["module"], r["files"], r["commits"], r["authors"], r["top_author"], "" if r["top_author_active"] else " (inactive)",
r["top_share"] * 100, r["bus_factor"], ", ".join(r["active_knowers"]) or "none", r["active_coverage"] * 100,
r["last_change"]))
L += ["", "## People", "", "| author | last commit | active | files known |", "|---|---|---|---|"]
for p in a["people"]:
L.append("| %s | %s | %s | %d |" % (p["author"], p["last_commit"], "yes" if p["active"] else "no", p["files_known"]))
L += ["", "## Findings"]
order = {"high": 0, "medium": 1, "low": 2}
for f in sorted(a["findings"], key=lambda f: (order[SEV[f["code"]]], f["code"], f.get("module", ""))):
L.append("- [%s] %s %s%s: %s" % (SEV[f["code"]], f["code"], NAMES[f["code"]],
(" - " + f["module"]) if f.get("module") else "", f["detail"]))
if not a["findings"]:
L.append("- none")
L += ["", "History shows who changed code, not who understands it; confirm with the team before acting."]
return "\n".join(L)
def self_test():
T = []
def check(name, cond):
T.append((name, bool(cond)))
log = """@@a1\tAna\tana@x.io\t2026-01-10
10\t2\tapi/orders.py
5\t0\tapi/users.py
@@a2\tBen\tben@x.io\t2026-03-01
20\t5\tweb/app.js
3\t1\tapi/orders.py
@@a3\tAna\tana@home.io\t2026-06-01
4\t4\tapi/users.py
-\t-\tweb/logo.png
@@a4\tdependabot[bot]\t49699333+dependabot[bot]@users.noreply.github.com\t2026-06-02
200\t180\tpackage-lock.json
1\t1\tweb/package.json
@@a5\tCara\tcara@x.io\t2025-01-05
50\t0\tbilling/{old => new}/invoice.py
@@a6\tBen\tben@x.io\t2026-06-10
2\t2\tREADME.md
""".splitlines()
c = parse_log(log)
check("parses 6 commits", len(c) == 6)
check("binary numstat rows skipped", all(f[0] != "web/logo.png" for x in c for f in x["files"]))
check("brace rename resolved to new path", c[4]["files"][0][0] == "billing/new/invoice.py")
check("module of root file is (root)", module_of("README.md", 1) == "(root)")
check("module depth 2", module_of("src/api/x/y.py", 2) == "src/api")
a = analyse(c, as_of="2026-06-10")
mods = {m["module"]: m for m in a["modules"]}
check("bot commits skipped", "web" in mods and mods["web"]["authors"] == 1)
check("lockfile excluded", all(m["module"] != "(root)" or m["files"] == 1 for m in a["modules"]))
check("duplicate identity flagged BF05", any(f["code"] == "BF05" and "Ana" in f["detail"] for f in a["findings"]))
a2 = analyse(c, aliases={"ana@home.io": "Ana"}, as_of="2026-06-10")
check("alias removes BF05", not any(f["code"] == "BF05" for f in a2["findings"]))
check("inactive author makes billing orphaned BF02", "BF02" in mods["billing"]["findings"])
check("single-author module flagged BF06", "BF06" in mods["web"]["findings"])
check("api bus factor is 1 (Ana holds most)", mods["api"]["bus_factor"] == 1 and mods["api"]["top_author"] == "Ana")
check("truck factor small -> BF01", any(f["code"] == "BF01" for f in a["findings"]))
a3 = analyse(c, as_of="2026-06-10", since="2026-02-01")
check("--since drops older commits", a3["commits_used"] == 3)
a4 = analyse(c, as_of="2026-06-10", active_days=600)
check("long active window: billing has an active knower", "BF02" not in {m["module"]: m for m in a4["modules"]}["billing"]["findings"])
check("BF02 uses active coverage under 50%", all(("BF02" in m["findings"]) == (m["active_coverage"] < 0.5) for m in a["modules"]))
check("recency weight halves after half-life", abs(0.5 ** (365 / 365.0) - 0.5) < 1e-9)
for bad, label in [(["10\t2\tx.py"], "numstat before header rejected"), (["@@x\tA\ta@b\tnot-a-date"], "bad date rejected"),
(["@@x\tA\ta@b\t2026-01-01", "ten\t2\tx.py"], "non-numeric counts rejected"), ([], "empty log rejected")]:
try:
parse_log(bad); check(label, False)
except InputError:
check(label, True)
try:
analyse(parse_log(["@@x\tA\ta@b\t2026-01-01", "3\t1\tyarn.lock"])); check("only excluded files rejected", False)
except InputError:
check("only excluded files rejected", True)
for name, ok in T:
print(("PASS " if ok else "FAIL ") + name)
good = all(ok for _, ok in T)
print("ALL PASS" if good else "SOME FAILED", "(%d/%d)" % (sum(ok for _, ok in T), len(T)))
return 0 if good else 1
def main(argv):
if "--self-test" in argv:
return self_test()
opts = {"aliases": None, "depth": "1", "since": None, "as-of": None, "active-days": "120", "half-life-days": "365",
"knows-share": "0.25", "repo": None}
excludes, pos, i = [], [], 0
while i < len(argv):
x = argv[i]
if x in ("--json", "--include-bots"):
i += 1; continue
if x.startswith("--"):
k = x[2:]
if i + 1 >= len(argv) or (k not in opts and k != "exclude"):
print("error: unknown or incomplete option %s" % x, file=sys.stderr); return 2
if k == "exclude":
excludes.append(argv[i + 1])
else:
opts[k] = argv[i + 1]
i += 2; continue
pos.append(x); i += 1
try:
if opts["repo"]:
lines = git_log(opts["repo"], opts["since"])
elif len(pos) == 1:
try:
lines = open(pos[0], encoding="utf-8", errors="replace").read().splitlines()
except OSError as e:
raise InputError("cannot read %s: %s" % (pos[0], e))
else:
print(__doc__, file=sys.stderr); return 2
try:
depth, ad, hl, ks = int(opts["depth"]), int(opts["active-days"]), int(opts["half-life-days"]), float(opts["knows-share"])
except ValueError:
raise InputError("--depth, --active-days and --half-life-days need whole numbers, --knows-share a decimal")
if depth < 1 or not 0 < ks <= 1:
raise InputError("--depth must be >= 1 and --knows-share between 0 and 1")
a = analyse(parse_log(lines), load_aliases(opts["aliases"]), depth, opts["since"], opts["as-of"], ad, hl, ks,
excludes, "--include-bots" in argv)
except InputError as e:
print("error: %s" % e, file=sys.stderr); return 2
print(json.dumps(a, indent=2) if "--json" in argv else render(a))
return 1 if any(SEV[f["code"]] == "high" for f in a["findings"]) else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Compares mortgage refinance offers with your current loan: new payment, monthly saving, simple and true break-even month, net benefit over the years you expect to stay, interest to payoff, points payback, and traps like term resets, rolled-in costs and cash-out. Offline stdlib Python.
---
name: mortgage-refinance-break-even-calculator
description: Compares mortgage refinance offers with your current loan: new payment, monthly saving, simple and true break-even month, net benefit over the years you expect to stay, interest to payoff, points payback, and traps like term resets, rolled-in costs and cash-out. Offline stdlib Python.
---
# Mortgage Refinance Break-Even Calculator
You help homeowners decide whether a mortgage refinance is worth it, and which offer is best for how long they expect to keep the loan. Lenders and brokers usually quote the lower monthly payment; that number alone hides the closing costs, the points, a 30-year term that starts again from zero, and costs rolled into the new balance. You turn the current loan and a few offers into one honest comparison and a short list of things to ask the lender.
You work only with the numbers the user gives you, on their machine. You are not a financial adviser or a lender: you never recommend a specific lender, you never guess rates or fees, and you say clearly that results are estimates of principal and interest that must be checked against the lender's official loan estimate. Taxes, insurance, escrow, mortgage insurance, adjustable-rate resets and local fees are outside the script; you mention them when they matter.
## Files in this skill
- `scripts/refi_breakeven.py` - reads the current loan (JSON) and offers (CSV), computes payments, simple and true break-even, net benefit at the horizon, total interest, points payback and findings RF01-RF09; `--horizon-months N` to try other stay lengths, `--json` for tooling, `--self-test` runs 23 checks (Python 3.8+ standard library only)
- `references/refinance-math.md` - the formulas, what "true break-even" means and why it differs from costs divided by savings, and a worked example you can check by hand
- `references/decision-checklist.md` - questions to answer before choosing, what each finding means, and what to ask the lender
- `templates/refinance-summary.md` - the one-page summary you hand back
- `examples/current_loan.json`, `examples/offers.csv` - a fictional 312,000 loan at 7.25% with seven offers (30-year with and without points, a matching-term offer, a no-cost offer, a 15-year, rolled costs and a cash-out)
## Workflow
### 1. Collect the facts
Ask for, from the latest mortgage statement and each lender's loan estimate:
- current balance, interest rate, months left and the principal-and-interest payment (not the total with escrow); any prepayment penalty;
- for each offer: rate, term in months, total closing costs (lender, title, appraisal, recording fees), points as a share of the loan, any cash-out, and whether costs are paid at closing or rolled into the loan;
- how long they expect to keep the home or the loan (the horizon). If unsure, run 3, 5, 7 and 10 years.
Never fill in a rate or fee yourself; if a number is missing, ask or leave that offer out.
### 2. Prepare the files
- `current_loan.json`: `balance`, `annual_rate` (decimal, 0.0725), `remaining_months`, optional `monthly_payment`, `prepayment_penalty`, `currency`, `horizon_months`.
- `offers.csv`: `name,annual_rate,term_months,closing_costs,points_pct,cash_out,roll_costs` with rates and points as decimals (`0.01` = 1 point) and `roll_costs` yes/no.
### 3. Run the comparison
```
python3 scripts/refi_breakeven.py examples/current_loan.json examples/offers.csv
python3 scripts/refi_breakeven.py current_loan.json offers.csv --horizon-months 60
python3 scripts/refi_breakeven.py current_loan.json offers.csv --json > refi.json
python3 scripts/refi_breakeven.py --self-test
```
Exit 0 = at least one offer pays off within the horizon and no high findings, 1 = none pays off or a high finding is present, 2 = bad input. Without a shell, follow `references/refinance-math.md` by hand for the two most promising offers.
### 4. Read the results
- **Net at horizon** is the main number: what the offer saves (or costs) by the end of the horizon, counting payments, the remaining balance and the cash paid at closing.
- **True break-even** is the first month the refinance is ahead. It can be earlier than the simple break-even (shorter terms pay the balance down faster) or later (rolled-in costs, longer terms).
- **Interest to payoff** shows the long-run cost if they keep the loan to the end.
- Findings: RF01 high (does not pay off within the horizon) and RF05 high (higher payment without a shorter term); RF02 term reset, RF03 more lifetime interest, RF04 rolled-in costs and RF07 points that do not pay back are medium; RF06 cash-out, RF08 small rate drop and RF09 higher payment on a shorter term are low.
Run at least two horizons; if the best offer changes, say so plainly.
### 5. Report
Fill `templates/refinance-summary.md`: the current loan, the comparison table, the best offer at each horizon, findings in plain language, the questions for the lender (`references/decision-checklist.md`) and what the numbers do not include.
## Rules
- Compare like for like: a cash-out offer adds new debt, so compare it with other ways to borrow that cash, not only with the current mortgage.
- A lower payment on a new 30-year term is not automatically a saving; always show the payoff date and the interest to payoff next to it.
- Keep personal financial documents private; work from the numbers, never upload statements.
FILE:references/refinance-math.md
# Refinance math used by refi_breakeven.py
## Monthly payment (principal and interest)
For a loan amount `P`, monthly rate `r = annual_rate / 12` and `n` months:
payment = P * r / (1 - (1 + r)^-n) (payment = P / n when r = 0)
Example: 200,000 at 6% for 360 months -> 1,199.10 per month.
## Upfront costs
upfront = closing_costs + points_pct * new_loan + prepayment_penalty
- Points are a share of the new loan: 1 point = 1% of the loan.
- When `roll_costs` is yes, upfront costs are added to the new loan (you pay no cash at closing but pay interest on the costs for the life of the loan). The script solves this iteratively because points depend on the loan amount.
- Cash-out is added to the new loan; the cash you receive counts in your favor in the net position.
## Simple break-even
simple_break_even = ceil(upfront / (old_payment - new_payment))
Shown as "never" when the payment does not go down or the result is longer than the new term. This is the number most calculators show, and it ignores how fast each loan pays down its balance.
## True break-even (the one to use)
Month by month, the script runs both amortization schedules side by side and tracks:
net(m) = sum of (old payment - new payment) up to month m
+ (old balance at m - new balance at m)
- cash paid at closing
+ cash received (cash-out)
The true break-even is the first month where `net(m) >= 0`. `net(horizon)` is the "net at horizon" column: the money you are ahead (or behind) if you sell or refinance again at that point, before taxes and selling costs.
Why they differ:
- A shorter or matching term pays principal down faster, so the true break-even comes before the simple one, even when the payment rises (a 15-year offer can break even in about 16 months while the "saving" is negative).
- A new 30-year term on a loan that had 27 years left lowers the payment partly by stretching it; the slower balance paydown pushes the true break-even later.
- Rolled-in costs show up as a higher new balance, not as cash.
## Points payback
The script assumes the common rule of thumb that 1 point buys about 0.25 percentage points. Points payback = points cost / (payment at rate + 0.25 pp per point - payment at the quoted rate). If the lender quotes the same loan with and without points, compare those two rows directly instead; that is more accurate than the rule of thumb.
## Worked check (from the examples)
Current: 312,000 at 7.25% with 324 months left -> payment 2,197.09.
"Bank A 30y no points": 6.25% for 360 months -> payment 1,921.04, saving 276.05 per month, upfront 5,800, simple break-even ceil(5,800 / 276.05) = 22 months. The true break-even is month 23, slightly later, because the new 30-year schedule pays down principal more slowly than the old one with 27 years left.
## Not modeled
Property tax, insurance and escrow; mortgage insurance; adjustable-rate resets; tax deductibility of interest; inflation and the return you could earn on the closing cost cash; selling costs. Mention them when they could change the decision.
FILE:references/decision-checklist.md
# Refinance decision checklist
## Before choosing
1. How long will you keep the home or this loan? Run the script for at least two horizons (for example 3 and 7 years).
2. Is the new payment comfortable even if income drops? A shorter term saves the most interest but raises the payment (RF09).
3. Are you resetting the clock? A new 30-year loan after paying for years moves the payoff date later (RF02); you can keep the old payoff date by paying extra each month.
4. Are closing costs paid in cash or rolled into the loan (RF04)? Rolling them in feels free but costs interest for years.
5. Are you taking cash out (RF06)? Compare that new debt with other options and with not borrowing it at all.
6. Do the points pay back before you expect to move (RF07)?
7. Is the rate drop large enough (RF08)? Under about 0.5 percentage points, costs often eat the savings unless the offer is genuinely no-cost.
## What each finding means
| code | severity | meaning | what to do |
|---|---|---|---|
| RF01 | high | the offer is still behind at the horizon | skip it, or negotiate costs down and re-run |
| RF02 | medium | payoff date moves later | compare interest to payoff; consider paying extra monthly |
| RF03 | medium | more interest to payoff than the current loan | fine only if you will move or refinance well before payoff |
| RF04 | medium | costs rolled into the balance | ask the price to pay them in cash; compare both |
| RF05 | high | payment rises without a shorter term | usually a bad deal; check for cash-out or fees |
| RF06 | low | cash-out adds debt | compare with a home equity loan or saving up |
| RF07 | medium | points do not pay back within the horizon | ask for the same loan without points |
| RF08 | low | small rate drop | refinance only if costs are very low |
| RF09 | low | shorter term with a higher payment | check the budget and emergency savings |
## Questions for the lender
- Please send the official loan estimate for each option, including the same loan with zero points.
- Which fees are lender fees, and which are third-party (title, appraisal, recording)? Which can be waived or shopped?
- Is the rate locked, until when, and what does extending the lock cost?
- Is there a prepayment penalty on the new loan?
- If costs are rolled in, what is the exact new loan amount?
## Red flags
- Pressure to sign before you receive the loan estimate.
- A "no-cost" offer whose rate is much higher than others (you pay through the rate instead).
- Fees that appear for the first time at closing.
FILE:templates/refinance-summary.md
# Refinance check: {{property_or_household}} - {{date}}
Numbers from: {{statement_date}} statement and loan estimates from {{lenders}}. Estimates of principal and interest only.
## Current loan
- Balance {{balance}} at {{rate}}, {{months_left}} months left, payment {{payment}} (P&I)
- Interest to payoff if nothing changes: {{interest_to_payoff}}
## Comparison (horizon {{horizon_years}} years)
(paste the table from refi_breakeven.py)
## Best option
- At {{horizon_1}} years: {{best_1}} (net {{net_1}})
- At {{horizon_2}} years: {{best_2}} (net {{net_2}})
- Why: {{one or two plain sentences}}
## Watch out
- {{finding code, offer, plain-language meaning}}
## Ask the lender
- {{question}}
## Not included
- Taxes, insurance, escrow, mortgage insurance, rate resets, selling costs, the return on cash you keep.
## Next step
- {{for example: request the zero-point version of offer B and re-run; lock the rate by date}}
FILE:examples/current_loan.json
{
"balance": 312000,
"annual_rate": 0.0725,
"remaining_months": 324,
"prepayment_penalty": 0,
"currency": "USD",
"horizon_months": 84,
"note": "fictional example: 30-year loan taken 3 years ago, owners expect to stay about 7 more years"
}
FILE:examples/offers.csv
name,annual_rate,term_months,closing_costs,points_pct,cash_out,roll_costs
Bank A 30y no points,0.0625,360,5800,0,0,no
Bank A 30y 1 point,0.0600,360,5800,0.01,0,no
Credit union 27y match,0.0630,324,4200,0,0,no
Online lender no-cost,0.0675,360,0,0,0,no
Broker 15y,0.0575,180,6500,0,0,no
Bank B rolled costs,0.0625,360,6200,0,0,yes
Bank B cash-out 30y,0.0650,360,6200,0,35000,no
FILE:scripts/refi_breakeven.py
#!/usr/bin/env python3
"""refi_breakeven.py - compare refinance offers against your current mortgage and find the real break-even month.
For each offer it works out the new monthly payment (principal and interest), the monthly saving,
the simple break-even (upfront costs / monthly saving) and the true break-even month, where the
cumulative payment savings plus the difference in remaining balance first cover what you paid up
front. It also compares total cost over the time you expect to keep the loan, total interest to
payoff, and flags common traps (term reset, costs rolled into the balance, cash-out, points that
never pay back, a prepayment penalty). Standard library only.
Usage:
python3 refi_breakeven.py CURRENT.json OFFERS.csv [--horizon-months N] [--json]
python3 refi_breakeven.py --self-test
CURRENT.json keys: balance, annual_rate (decimal, 0.065 = 6.5%), remaining_months,
optional: monthly_payment (P&I; computed if missing), prepayment_penalty (amount), currency,
horizon_months (how long you expect to keep the loan; default 84).
OFFERS.csv columns: name,annual_rate,term_months,closing_costs,points_pct[,cash_out][,roll_costs]
annual_rate decimal; points_pct as a decimal share of the new loan (0.01 = 1 point);
cash_out extra cash taken (default 0); roll_costs yes/no (costs added to the new loan, default no).
Exit codes: 0 at least one offer breaks even within the horizon and no high findings,
1 no offer pays off within the horizon or high findings present, 2 bad input.
Estimates only: taxes, insurance, escrow, adjustable-rate resets and fees not listed are ignored.
"""
import csv, json, math, sys
SEV = {"RF01": "high", "RF02": "medium", "RF03": "medium", "RF04": "medium", "RF05": "high",
"RF06": "low", "RF07": "medium", "RF08": "low", "RF09": "low"}
NAMES = {"RF01": "does not break even within the horizon",
"RF02": "term reset: payoff date moves later",
"RF03": "more total interest to payoff than keeping the current loan",
"RF04": "costs rolled into the loan (you pay interest on them)",
"RF05": "monthly payment goes up with no shorter term",
"RF06": "cash-out increases the debt (compare like for like)",
"RF07": "points take longer to pay back than the horizon",
"RF08": "rate drop under 0.5 percentage points",
"RF09": "shorter term with a higher payment: check it fits your budget"}
POINT_RATE_CUT = 0.0025 # rule of thumb: 1 point (1% of the loan) buys about 0.25 percentage points
class InputError(Exception):
pass
def payment(principal, annual_rate, months):
if months <= 0:
raise InputError("months must be positive")
r = annual_rate / 12.0
if r == 0:
return principal / months
return principal * r / (1 - (1 + r) ** -months)
def schedule(principal, annual_rate, months, pay):
"""Yield (month, interest, principal_paid, balance) until paid off or months reached."""
r = annual_rate / 12.0
bal = principal
for m in range(1, months + 1):
interest = bal * r
princ = min(pay - interest, bal)
bal = bal - princ
if bal < 0.005:
bal = 0.0
yield m, interest, princ, bal
if bal == 0.0:
break
def balance_after(principal, annual_rate, pay, m):
b = principal
for mm, _, _, bal in schedule(principal, annual_rate, 10 ** 6, pay):
b = bal
if mm >= m or bal == 0:
break
return b if m > 0 else principal
def total_interest(principal, annual_rate, months, pay):
return sum(i for _, i, _, _ in schedule(principal, annual_rate, months, pay))
def to_float(row, key, default=None, lo=None, hi=None):
v = row.get(key)
if v is None or str(v).strip() == "":
if default is None:
raise InputError("missing %s" % key)
return default
try:
f = float(str(v).replace(",", "").strip())
except ValueError:
raise InputError("%s is not a number: %r" % (key, v))
if lo is not None and f < lo or hi is not None and f > hi:
raise InputError("%s out of range: %r" % (key, v))
return f
def load_current(path):
try:
d = json.load(open(path, encoding="utf-8"))
except (OSError, ValueError) as e:
raise InputError("cannot read %s: %s" % (path, e))
cur = {"balance": to_float(d, "balance", lo=1),
"annual_rate": to_float(d, "annual_rate", lo=0, hi=0.5),
"remaining_months": int(to_float(d, "remaining_months", lo=1, hi=600)),
"prepayment_penalty": to_float(d, "prepayment_penalty", 0.0, lo=0),
"currency": d.get("currency", ""),
"horizon_months": int(to_float(d, "horizon_months", 84, lo=1, hi=600))}
if cur["annual_rate"] > 0.3:
raise InputError("annual_rate looks like a percent; use a decimal such as 0.065")
calc = payment(cur["balance"], cur["annual_rate"], cur["remaining_months"])
cur["monthly_payment"] = to_float(d, "monthly_payment", calc, lo=0.01)
if cur["monthly_payment"] <= cur["balance"] * cur["annual_rate"] / 12:
raise InputError("monthly_payment does not cover the interest")
return cur
def load_offers(path):
try:
rows = list(csv.DictReader(open(path, encoding="utf-8", newline="")))
except OSError as e:
raise InputError("cannot read %s: %s" % (path, e))
if not rows:
raise InputError("no offers in %s" % path)
out = []
for n, r in enumerate(rows, 2):
try:
rate = to_float(r, "annual_rate", lo=0, hi=0.5)
if rate > 0.3:
raise InputError("annual_rate looks like a percent; use a decimal")
pts = to_float(r, "points_pct", 0.0, lo=0, hi=0.1)
out.append({"name": (r.get("name") or "offer %d" % (n - 1)).strip(), "annual_rate": rate,
"term_months": int(to_float(r, "term_months", lo=12, hi=600)),
"closing_costs": to_float(r, "closing_costs", 0.0, lo=0), "points_pct": pts,
"cash_out": to_float(r, "cash_out", 0.0, lo=0),
"roll_costs": (r.get("roll_costs") or "no").strip().lower() in ("yes", "y", "true", "1")})
except InputError as e:
raise InputError("offers line %d: %s" % (n, e))
return out
def analyse(cur, offers, horizon=None):
H = horizon or cur["horizon_months"]
bal, rate, rem, pay = cur["balance"], cur["annual_rate"], cur["remaining_months"], cur["monthly_payment"]
cur_interest = total_interest(bal, rate, 10 ** 6, pay)
cur_months = sum(1 for _ in schedule(bal, rate, 10 ** 6, pay))
cur_cost_h = pay * min(H, cur_months) + balance_after(bal, rate, pay, H)
results = []
for o in offers:
base = bal + o["cash_out"]
# points are charged on the new loan amount; solve iteratively when costs are rolled in
loan = base
for _ in range(20):
upfront = o["closing_costs"] + o["points_pct"] * loan + cur["prepayment_penalty"]
new_loan = base + (upfront if o["roll_costs"] else 0.0)
if abs(new_loan - loan) < 0.01:
break
loan = new_loan
loan = new_loan
cash_paid = 0.0 if o["roll_costs"] else upfront
npay = payment(loan, o["annual_rate"], o["term_months"])
saving = pay - npay
simple = math.ceil(upfront / saving) if saving > 0 else None
if simple is not None and simple > o["term_months"]:
simple = None
# true break-even: cumulative (old - new payments) + (old balance - new balance) - cash paid - cash_out adj >= 0
true_be = None
horizon_net = None
cum = 0.0
ob, nb = bal, loan
oi = schedule(bal, rate, 10 ** 6, pay)
ni = schedule(loan, o["annual_rate"], o["term_months"], npay)
for m in range(1, max(cur_months, o["term_months"]) + 1):
op = np_ = 0.0
try:
_, i1, p1, ob = next(oi); op = i1 + p1
except StopIteration:
pass
try:
_, i2, p2, nb = next(ni); np_ = i2 + p2
except StopIteration:
pass
cum += op - np_
net = cum + (ob - nb) - cash_paid + o["cash_out"]
if m == H:
horizon_net = net
if true_be is None and net >= 0 and m >= 1:
true_be = m
if horizon_net is None:
horizon_net = net
new_interest = total_interest(loan, o["annual_rate"], o["term_months"], npay)
r = {"name": o["name"], "new_loan": round(loan, 2), "annual_rate": o["annual_rate"], "term_months": o["term_months"],
"upfront_costs": round(upfront, 2), "cash_paid_at_closing": round(cash_paid, 2), "new_payment": round(npay, 2),
"monthly_saving": round(saving, 2), "simple_break_even_months": simple, "true_break_even_month": true_be,
"net_benefit_at_horizon": round(horizon_net, 2), "total_interest_new": round(new_interest, 2),
"total_interest_current": round(cur_interest, 2), "payoff_shift_months": o["term_months"] - cur_months,
"findings": []}
f = r["findings"]
if true_be is None or true_be > H:
f.append("RF01")
if o["term_months"] > cur_months + 6:
f.append("RF02")
if new_interest > cur_interest:
f.append("RF03")
if o["roll_costs"] and upfront > 0:
f.append("RF04")
if saving < 0 and o["term_months"] >= cur_months:
f.append("RF05")
if o["cash_out"] > 0:
f.append("RF06")
pts_payback = None
if o["points_pct"] > 0:
pts_cost = o["points_pct"] * loan
no_pts_rate = o["annual_rate"] + o["points_pct"] / 0.01 * POINT_RATE_CUT
pts_saving = payment(loan, no_pts_rate, o["term_months"]) - npay
pts_payback = math.ceil(pts_cost / pts_saving) if pts_saving > 0 else None
if pts_payback is None or pts_payback > H:
f.append("RF07")
r["points_payback_months"] = pts_payback
if saving < 0 and o["term_months"] < cur_months:
f.append("RF09")
if 0 <= rate - o["annual_rate"] < 0.005:
f.append("RF08")
results.append(r)
best = max(results, key=lambda x: x["net_benefit_at_horizon"])
return {"current": {"balance": bal, "annual_rate": rate, "remaining_months": rem, "monthly_payment": round(pay, 2),
"months_to_payoff": cur_months, "total_interest_to_payoff": round(cur_interest, 2),
"cost_over_horizon_incl_balance": round(cur_cost_h, 2)},
"horizon_months": H, "currency": cur["currency"], "offers": results,
"best_at_horizon": best["name"] if best["net_benefit_at_horizon"] > 0 else None}
def money(x, cur=""):
return ("%s%s" % (cur + " " if cur else "", "{:,.2f}".format(x)))
def render(a):
c, cur = a["current"], a["currency"]
L = ["# Refinance check (horizon %d months = %.1f years)" % (a["horizon_months"], a["horizon_months"] / 12), "",
"Current loan: balance %s at %.3f%%, %d months left, payment %s (P&I), interest to payoff %s" % (
money(c["balance"], cur), c["annual_rate"] * 100, c["months_to_payoff"], money(c["monthly_payment"], cur),
money(c["total_interest_to_payoff"], cur)), "",
"| offer | rate | term | new loan | upfront | new payment | saving/mo | simple BE | true BE | net at horizon | interest to payoff |",
"|---|---|---|---|---|---|---|---|---|---|---|"]
for r in a["offers"]:
L.append("| %s | %.3f%% | %d | %s | %s | %s | %s | %s | %s | %s | %s |" % (
r["name"], r["annual_rate"] * 100, r["term_months"], money(r["new_loan"]), money(r["upfront_costs"]),
money(r["new_payment"]), money(r["monthly_saving"]),
("%d mo" % r["simple_break_even_months"]) if r["simple_break_even_months"] is not None else "never",
("%d mo" % r["true_break_even_month"]) if r["true_break_even_month"] is not None else "never",
money(r["net_benefit_at_horizon"]), money(r["total_interest_new"])))
L += ["", "Best at the horizon: %s" % (a["best_at_horizon"] or "none - keeping the current loan costs least"), "", "## Findings"]
n = 0
for r in a["offers"]:
for code in r["findings"]:
n += 1
L.append("- [%s] %s %s: %s" % (SEV[code], code, r["name"], NAMES[code]))
if not n:
L.append("- none")
L += ["", "Estimates of principal and interest only; confirm with the lender's official loan estimate."]
return "\n".join(L)
def exit_code(a):
high = any(SEV[c] == "high" for r in a["offers"] for c in r["findings"])
ok = any(r["true_break_even_month"] is not None and r["true_break_even_month"] <= a["horizon_months"] for r in a["offers"])
return 0 if ok and not high else 1
def self_test():
T = []
def check(name, cond):
T.append((name, bool(cond)))
check("payment 200k 6% 360m = 1199.10", abs(payment(200000, 0.06, 360) - 1199.10) < 0.01)
check("zero-rate payment = principal / months", payment(12000, 0, 120) == 100)
check("schedule pays off to zero", list(schedule(10000, 0.05, 60, payment(10000, 0.05, 60)))[-1][3] == 0)
check("balance after 0 months = principal", balance_after(1000, 0.05, 100, 0) == 1000)
cur = {"balance": 300000, "annual_rate": 0.07, "remaining_months": 300, "prepayment_penalty": 0, "currency": "",
"horizon_months": 84}
cur["monthly_payment"] = payment(300000, 0.07, 300)
same = analyse(cur, [{"name": "same", "annual_rate": 0.07, "term_months": 300, "closing_costs": 0, "points_pct": 0,
"cash_out": 0, "roll_costs": False}])["offers"][0]
check("identical free offer saves nothing", abs(same["monthly_saving"]) < 0.01 and abs(same["net_benefit_at_horizon"]) < 0.5)
o = {"name": "cut", "annual_rate": 0.055, "term_months": 300, "closing_costs": 6000, "points_pct": 0, "cash_out": 0,
"roll_costs": False}
r = analyse(cur, [o])["offers"][0]
check("lower rate same term saves money each month", r["monthly_saving"] > 0)
check("simple break-even = ceil(costs / saving)", r["simple_break_even_months"] == math.ceil(6000 / r["monthly_saving"]))
check("true break-even exists and <= simple", r["true_break_even_month"] and r["true_break_even_month"] <= r["simple_break_even_months"])
check("no term reset finding at same term", "RF02" not in r["findings"])
o2 = dict(o, name="reset", term_months=360)
r2 = analyse(cur, [o2])["offers"][0]
check("30-year reset flagged RF02", "RF02" in r2["findings"])
o3 = dict(o, name="tiny", annual_rate=0.068, closing_costs=8000)
r3 = analyse(cur, [o3])["offers"][0]
check("tiny rate drop flagged RF08", "RF08" in r3["findings"])
check("tiny drop with big costs flagged RF01", "RF01" in r3["findings"])
o4 = dict(o, name="rolled", roll_costs=True)
r4 = analyse(cur, [o4])["offers"][0]
check("rolled costs raise the loan by the costs", abs(r4["new_loan"] - 306000) < 0.01)
check("rolled costs flagged RF04 and no cash at closing", "RF04" in r4["findings"] and r4["cash_paid_at_closing"] == 0)
o5 = dict(o, name="points", points_pct=0.01)
r5 = analyse(cur, [o5])["offers"][0]
check("1 point adds 1% of the loan to upfront", abs(r5["upfront_costs"] - 9000) < 0.01)
o6 = dict(o, name="cash", cash_out=40000)
r6 = analyse(cur, [o6])["offers"][0]
check("cash-out flagged RF06 and loan includes it", "RF06" in r6["findings"] and abs(r6["new_loan"] - 340000) < 0.01)
o7 = dict(o, name="higher", annual_rate=0.08)
check("higher payment, same term flagged RF05", "RF05" in analyse(cur, [o7])["offers"][0]["findings"])
o8 = dict(o, name="15y", annual_rate=0.052, term_months=180, closing_costs=5000)
r8 = analyse(cur, [o8])["offers"][0]
check("15-year offer cuts total interest", r8["total_interest_new"] < r8["total_interest_current"])
check("15-year higher payment flagged RF09, not RF05", "RF09" in r8["findings"] and "RF05" not in r8["findings"])
check("points payback uses 0.25 pp per point", r5["points_payback_months"] and r5["points_payback_months"] > 0)
o9 = dict(o, name="free", closing_costs=0)
r9 = analyse(cur, [o9])["offers"][0]
check("no-cost offer: simple break-even 0 months", r9["simple_break_even_months"] == 0 and r9["true_break_even_month"] == 1)
for bad, label in [({"balance": 0, "annual_rate": 0.05, "remaining_months": 100}, "zero balance rejected"),
({"balance": 1000, "annual_rate": 6.5, "remaining_months": 100}, "percent rate rejected")]:
try:
to_float(bad, "balance", lo=1); r_ = to_float(bad, "annual_rate", lo=0, hi=0.5)
check(label, False)
except InputError:
check(label, True)
for name, ok in T:
print(("PASS " if ok else "FAIL ") + name)
good = all(ok for _, ok in T)
print("ALL PASS" if good else "SOME FAILED", "(%d/%d)" % (sum(ok for _, ok in T), len(T)))
return 0 if good else 1
def main(argv):
if "--self-test" in argv:
return self_test()
args = [a for a in argv if not a.startswith("--")]
horizon = None
if "--horizon-months" in argv:
try:
horizon = int(argv[argv.index("--horizon-months") + 1])
args.remove(str(horizon))
except (IndexError, ValueError):
print("error: --horizon-months needs a whole number", file=sys.stderr); return 2
if len(args) != 2:
print(__doc__, file=sys.stderr); return 2
try:
a = analyse(load_current(args[0]), load_offers(args[1]), horizon)
except InputError as e:
print("error: %s" % e, file=sys.stderr); return 2
print(json.dumps(a, indent=2) if "--json" in argv else render(a))
return exit_code(a)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
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
Checks a small team's timesheets pre-payroll: splits each week into regular, overtime and double-time hours under your daily and weekly rules, estimates pay, and flags missing punches, overlaps, duplicates, short breaks, short rest, over-max weeks and too many days in a row. Offline stdlib Python.
---
name: employee-timesheet-and-overtime-checker
description: Checks a small team's timesheets pre-payroll: splits each week into regular, overtime and double-time hours under your daily and weekly rules, estimates pay, and flags missing punches, overlaps, duplicates, short breaks, short rest, over-max weeks and too many days in a row. Offline stdlib Python.
---
# Employee Timesheet and Overtime Checker
You help small business owners, shop and restaurant managers, office managers and payroll admins check a week or two of timesheets before they run payroll. Timesheet mistakes are expensive in both directions: a missing clock-out or a duplicate row pays the wrong amount, overtime that is not paid becomes a wage claim, and short breaks or short rest between a closing and an opening shift can break working-time rules. You turn the raw export into a clear hours-and-pay table and a short list of things to fix or confirm.
You work only on the files the user gives you, on their machine. You never decide what the law is where they are: you apply the rules they confirm, say clearly that the bundled defaults are only an example, and suggest checking local labour rules, the employment contracts or a payroll provider for anything unclear. You do not judge employees; findings are data questions to check with the person and their manager.
## Files in this skill
- `scripts/timesheet_check.py` - reads a timesheet CSV (and optional employees and rules files), splits hours per employee and week into regular, overtime and double time with daily and weekly thresholds, estimates gross pay, and reports findings TS01-TS11 by severity; `--json` for tooling, `--self-test` runs 20 checks (Python 3.8+ standard library only)
- `references/overtime-and-working-time-rules.md` - how the hours are split, what each rule key means, examples of rule sets people commonly configure, and what the script does not handle
- `references/fixing-timesheet-problems.md` - what each finding usually means, how to confirm and correct it, and how to prevent it next time
- `templates/payroll-check-report.md` - the summary you hand back before payroll
- `examples/timesheet.csv`, `examples/employees.csv`, `examples/rules.json` - a fictional shop week with five people and planted problems (missing clock-out, duplicate row, overlap, short break, closing-then-opening, a 49-hour week)
## Workflow
### 1. Confirm the rules first
Before running anything, ask which rules apply and fill `rules.json`:
- week start day and pay period;
- overtime thresholds (daily and/or weekly hours), multipliers and any double-time threshold;
- break rules (break required after how many hours, minimum minutes, paid or unpaid);
- minimum rest between shifts, maximum weekly hours and maximum days in a row;
- which employees are not eligible for overtime (salaried or exempt) and their hourly rates.
If the user does not know, run with the defaults but label every result "example rules" and list the questions in the report.
### 2. Prepare the files
- `timesheet.csv`: `employee,date,start,end,break_minutes[,note]`, date `YYYY-MM-DD`, times `HH:MM` 24 h. An end time earlier than the start means an overnight shift counted on the start date. Most clock systems can export this; rename columns if needed.
- `employees.csv` (optional): `employee,hourly_rate[,overtime_eligible]`.
- Names must match exactly between files.
### 3. Run the check
```
python3 scripts/timesheet_check.py examples/timesheet.csv --rules examples/rules.json --employees examples/employees.csv
python3 scripts/timesheet_check.py timesheet.csv --rules rules.json --employees employees.csv --json > check.json
python3 scripts/timesheet_check.py --self-test
```
Exit 0 = no high findings, 1 = high findings to fix before payroll, 2 = bad input. Without a shell, follow `references/overtime-and-working-time-rules.md` by hand for each employee and week.
### 4. Triage the findings
- High (fix before payroll): TS01 missing or unreadable time (the row was skipped, so pay is too low), TS02 overlapping shifts (double counting or a wrong date), TS08 over the weekly maximum.
- Medium (confirm with the manager): TS04 duplicate row (counted once), TS05 very long shift, TS06 missing or short break, TS07 short rest between shifts, TS09 too many days in a row.
- Low (information): TS10 no pay rate, TS11 overnight shift.
Use `references/fixing-timesheet-problems.md` for the likely cause and the fix. Never "correct" a time yourself: list the question for the employee or manager, then re-run after they confirm.
### 5. Report
Fill `templates/payroll-check-report.md`: rules used, hours and pay table, overtime total and cost, findings with the exact question to ask, and anything the script does not cover (shift premiums, holiday pay, tips, on-call, travel time, local rounding rules).
## Rules
- Overtime is never counted twice: hours already paid as daily overtime or double time do not count toward the weekly regular threshold.
- Pay estimates are gross base pay only, before taxes, premiums, allowances and deductions.
- Keep personal data private: do not upload timesheets, and share only the report with people who need it.
FILE:references/overtime-and-working-time-rules.md
# How timesheet_check.py splits hours and applies rules
## Worked time
worked hours = (end - start) - break. An end at or before the start is an overnight shift (end + 24 h), counted on the start date. Rows with a missing or unreadable time are skipped and reported as TS01, so the employee's total is too low until fixed.
## Splitting a week (no double counting)
For each employee and week (week_start in rules), day by day in date order:
1. Double time = hours above daily_dt_after (if set).
2. Daily overtime = remaining hours above daily_ot_after (if set).
3. The rest is regular, until the week's regular hours reach weekly_ot_after; regular hours beyond that move to overtime.
Employees with overtime_eligible = no get all hours as regular.
Pay estimate = rate x (regular + overtime x ot_multiplier + double time x dt_multiplier).
Example (daily 8 / weekly 40): Mon 8, Tue 8, Wed 10, Thu 8, Fri 9, Sat 5 = 48 h. Daily overtime 2 + 1 = 3 h; regular would be 45, so 5 more hours move to overtime: 40 regular, 8 overtime.
## Rule keys
| key | meaning | default |
|---|---|---|
| week_start | first day of the work week | monday |
| daily_ot_after | overtime after this many hours in a day (null = no daily overtime) | null |
| daily_dt_after | double time after this many hours in a day (null = none) | null |
| weekly_ot_after | overtime after this many regular hours in a week (null = none) | 40 |
| ot_multiplier / dt_multiplier | pay multipliers | 1.5 / 2.0 |
| break_required_after_hours / min_break_minutes | a break of at least N minutes for shifts longer than H hours | 6 / 30 |
| min_rest_hours | minimum rest between two shifts on different days | 11 |
| max_weekly_hours | flag weeks above this total | 48 |
| max_shift_hours | flag a start-to-end span above this (often a typo) | 14 |
| max_days_in_a_row | flag runs of consecutive working days above this | 6 |
## Rule sets people commonly configure (check your own law and contracts)
- Weekly-only overtime: weekly_ot_after 40, daily keys null (a common US federal-style setup).
- Daily and weekly overtime with double time: daily_ot_after 8, daily_dt_after 12, weekly_ot_after 40 (used in some US states).
- Working-time limits without statutory overtime pay: weekly_ot_after null or per contract, min_rest_hours 11, max_weekly_hours 48 (European working-time style; the 48 h is often an average over several months, which this weekly check does not average).
These are examples to start a conversation, not legal advice.
## Not handled
Averaging periods, seventh-day rules, shift or night premiums, holiday and sick pay, on-call and travel time, split-shift premiums, tips, minimum wage checks, time rounding policies, and multi-rate employees. Mention any that apply and handle them separately.
FILE:references/fixing-timesheet-problems.md
# Findings: likely causes and fixes
| code | finding | likely cause | how to confirm and fix | prevent next time |
|---|---|---|---|---|
| TS01 | missing or unreadable time | forgot to clock out, app crash, manual edit | ask the employee and manager for the real time; add it and re-run | clock-out reminders; manager reviews open punches daily |
| TS02 | overlapping shifts | wrong date on an overnight shift, double entry, two locations | compare with the rota and the till/door logs; fix the date or delete the duplicate | one clock-in at a time per person |
| TS03 | break longer than the shift | break entered in hours or the wrong column | confirm the real break and correct it | validate break fields in the export |
| TS04 | duplicate row | double import or edit | the script counts it once; delete it at the source | import each period once |
| TS05 | very long shift | typo in the end time or a missing clock-out the next day | confirm with the employee; if real, check rest and maximum rules | alert on shifts over the limit |
| TS06 | break missing or short | busy shift, break not recorded | ask whether a break was taken; some places owe a penalty for missed breaks | schedule breaks on the rota |
| TS07 | short rest between shifts | closing then opening ("clopening") | confirm; adjust the rota; check whether local rules require a premium | rota checks before publishing |
| TS08 | over the weekly maximum | extra cover, missing staff | confirm the hours are real and any opt-out or averaging agreement | plan cover earlier |
| TS09 | too many days in a row | cover for absence | confirm a day off is scheduled | rota checks |
| TS10 | no pay rate | new hire, name spelled differently | add the employee or fix the name | one employee list as the source of names |
| TS11 | overnight shift | night work | confirm the start date is right | none needed |
When you report a finding, give the exact question to ask, for example: "Priya, on Wed 18 Nov you clocked in at 09:00 but there is no clock-out. What time did you finish?"
FILE:templates/payroll-check-report.md
# Payroll check: {{business}} - pay period {{period}}
Prepared {{date}}. Rules used: {{rules_summary}} ({{confirmed_or_example}} rules).
## Summary
- Employees: {{employee_count}} | shifts: {{shift_count}}
- Overtime and double-time hours: {{ot_hours}} (estimated cost {{ot_cost}})
- Estimated gross base pay: {{gross_pay}}
- Fix before payroll: {{high_count}} high findings | confirm: {{medium_count}} medium
## Hours and pay
(paste the table from timesheet_check.py)
## Fix before payroll
| employee | date | finding | question to ask | owner |
|---|---|---|---|---|
| {{employee}} | {{date}} | {{code and issue}} | {{exact question}} | {{manager}} |
## Confirm with managers
- {{finding and question}}
## Not covered by this check
- {{premiums, holiday pay, tips, averaging periods, local rounding rules}}
## Rota suggestions
- {{for example: avoid closing-then-opening shifts; schedule breaks on 8 h shifts}}
FILE:examples/timesheet.csv
employee,date,start,end,break_minutes,note
Maya Torres,2026-11-16,07:00,15:30,30,
Maya Torres,2026-11-17,07:00,15:30,30,
Maya Torres,2026-11-18,07:00,17:30,30,stock delivery
Maya Torres,2026-11-19,07:00,15:30,30,
Maya Torres,2026-11-20,07:00,16:30,30,
Maya Torres,2026-11-21,08:00,13:00,0,Saturday cover
Jonah Reed,2026-11-16,12:00,20:30,30,
Jonah Reed,2026-11-17,12:00,23:00,30,closing
Jonah Reed,2026-11-18,07:00,15:00,30,opening after closing
Jonah Reed,2026-11-19,12:00,20:30,15,
Jonah Reed,2026-11-20,12:00,20:30,30,
Jonah Reed,2026-11-20,12:00,20:30,30,
Priya Nair,2026-11-16,09:00,17:00,45,
Priya Nair,2026-11-17,09:00,17:00,45,
Priya Nair,2026-11-18,09:00,,45,forgot to clock out
Priya Nair,2026-11-19,09:00,19:00,45,
Priya Nair,2026-11-20,09:00,17:00,45,
Sam Okafor,2026-11-17,22:00,06:30,30,night stock count
Sam Okafor,2026-11-18,06:00,10:00,0,
Sam Okafor,2026-11-19,18:00,23:00,0,
Lena Fischer,2026-11-16,08:00,16:00,30,
Lena Fischer,2026-11-17,08:00,18:00,60,
Lena Fischer,2026-11-18,08:00,18:00,60,
Lena Fischer,2026-11-19,08:00,18:00,60,
Lena Fischer,2026-11-20,08:00,18:00,60,
Lena Fischer,2026-11-21,08:00,14:00,30,
FILE:examples/employees.csv
employee,hourly_rate,overtime_eligible
Maya Torres,19.50,yes
Jonah Reed,17.00,yes
Priya Nair,24.00,yes
Sam Okafor,18.25,yes
Lena Fischer,32.00,no
FILE:examples/rules.json
{
"name": "Example shop rules (illustrative only, set yours from local law and contracts)",
"week_start": "monday",
"daily_ot_after": 8,
"daily_dt_after": 12,
"weekly_ot_after": 40,
"ot_multiplier": 1.5,
"dt_multiplier": 2.0,
"break_required_after_hours": 6,
"min_break_minutes": 30,
"min_rest_hours": 11,
"max_weekly_hours": 48,
"max_shift_hours": 14,
"max_days_in_a_row": 6
}
FILE:scripts/timesheet_check.py
#!/usr/bin/env python3
"""timesheet_check.py - check a team's timesheets and work out regular, overtime and double-time hours.
Reads shift rows, applies your overtime and working-time rules (daily and weekly
thresholds, multipliers, breaks, rest between shifts, weekly maximum, days in a
row), estimates pay per employee and week, and flags data errors and rule
breaches before payroll. Standard library only.
Usage:
python3 timesheet_check.py TIMESHEET.csv [--rules RULES.json] [--employees EMPLOYEES.csv] [--json]
python3 timesheet_check.py --self-test
TIMESHEET.csv columns: employee,date,start,end,break_minutes[,note]
date YYYY-MM-DD, start/end HH:MM (24 h). An end earlier than the start is an overnight shift
(counted on the start date).
EMPLOYEES.csv columns: employee,hourly_rate[,overtime_eligible] (overtime_eligible: yes/no, default yes)
RULES.json keys (all optional, defaults in DEFAULT_RULES): week_start (monday..sunday),
daily_ot_after, daily_dt_after, weekly_ot_after (hours or null), ot_multiplier, dt_multiplier,
break_required_after_hours, min_break_minutes, min_rest_hours, max_weekly_hours,
max_shift_hours, max_days_in_a_row.
Exit codes: 0 no high findings, 1 high findings, 2 bad input.
The default rules are an example, not the law where you are: set them from your local labour rules and contracts.
"""
import csv, datetime as dt, json, sys
from collections import defaultdict
DEFAULT_RULES = {
"week_start": "monday",
"daily_ot_after": None, # e.g. 8 where daily overtime applies
"daily_dt_after": None, # e.g. 12 where daily double time applies
"weekly_ot_after": 40,
"ot_multiplier": 1.5,
"dt_multiplier": 2.0,
"break_required_after_hours": 6,
"min_break_minutes": 30,
"min_rest_hours": 11,
"max_weekly_hours": 48,
"max_shift_hours": 14,
"max_days_in_a_row": 6,
}
DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
SEV = {"TS01": "high", "TS02": "high", "TS03": "high", "TS04": "medium", "TS05": "medium", "TS06": "medium",
"TS07": "medium", "TS08": "high", "TS09": "medium", "TS10": "low", "TS11": "low"}
NAMES = {"TS01": "missing or unreadable time", "TS02": "overlapping shifts", "TS03": "break longer than the shift",
"TS04": "duplicate row", "TS05": "very long shift (typo?)", "TS06": "required break missing or short",
"TS07": "short rest between shifts", "TS08": "over the weekly maximum", "TS09": "too many days in a row",
"TS10": "no pay rate", "TS11": "overnight shift (check the date)"}
class InputError(Exception):
pass
def parse_time(s):
try:
h, m = s.strip().split(":")
h, m = int(h), int(m)
if not (0 <= h <= 24 and 0 <= m < 60) or (h == 24 and m):
raise ValueError
return h * 60 + m
except (ValueError, AttributeError):
return None
def load_rules(path):
rules = dict(DEFAULT_RULES)
if path:
with open(path, encoding="utf-8") as f:
user = json.load(f)
unknown = set(user) - set(DEFAULT_RULES) - {"name", "notes"}
if unknown:
raise InputError("unknown rule keys: " + ", ".join(sorted(unknown)))
rules.update({k: v for k, v in user.items() if k in DEFAULT_RULES})
if str(rules["week_start"]).lower() not in DAYS:
raise InputError("week_start must be a weekday name")
for k in ("ot_multiplier", "dt_multiplier"):
if not isinstance(rules[k], (int, float)) or rules[k] < 1:
raise InputError(k + " must be a number >= 1")
return rules
def load_employees(path):
emp = {}
if not path:
return emp
with open(path, newline="", encoding="utf-8") as f:
for i, row in enumerate(csv.DictReader(f), start=2):
row = {k.strip(): (v or "").strip() for k, v in row.items()}
try:
rate = float(row.get("hourly_rate", ""))
except ValueError:
raise InputError("employees line %d: hourly_rate must be a number" % i)
emp[row["employee"]] = {"rate": rate, "ot": row.get("overtime_eligible", "yes").lower() not in ("no", "n", "false", "0")}
return emp
def load_shifts(path):
shifts, findings = [], []
with open(path, newline="", encoding="utf-8") as f:
r = csv.DictReader(f)
need = {"employee", "date", "start", "end", "break_minutes"}
if not r.fieldnames or not need.issubset({h.strip() for h in r.fieldnames}):
raise InputError("timesheet needs columns employee,date,start,end,break_minutes")
seen = set()
for i, row in enumerate(r, start=2):
row = {k.strip(): (v or "").strip() for k, v in row.items() if k}
if not any(row.values()):
continue
e = row["employee"]
key = (e, row["date"], row["start"], row["end"])
if key in seen:
findings.append(("TS04", e, row["date"], "line %d repeats an earlier row; counted once" % i))
continue
seen.add(key)
try:
day = dt.date.fromisoformat(row["date"])
except ValueError:
findings.append(("TS01", e, row["date"], "line %d: date is not YYYY-MM-DD; row skipped" % i)); continue
s, en = parse_time(row["start"]), parse_time(row["end"])
if s is None or en is None:
findings.append(("TS01", e, row["date"], "line %d: start or end missing/unreadable (%r-%r); row skipped" % (i, row["start"], row["end"]))); continue
try:
brk = int(row["break_minutes"] or 0)
except ValueError:
findings.append(("TS01", e, row["date"], "line %d: break_minutes is not a whole number; treated as 0" % i)); brk = 0
overnight = en <= s
if overnight:
en += 24 * 60
findings.append(("TS11", e, row["date"], "line %d: %s-%s crosses midnight; counted on %s" % (i, row["start"], row["end"], row["date"])))
start = dt.datetime.combine(day, dt.time()) + dt.timedelta(minutes=s)
end = dt.datetime.combine(day, dt.time()) + dt.timedelta(minutes=en)
span = (en - s)
if brk > span:
findings.append(("TS03", e, row["date"], "line %d: break %d min is longer than the %d-min shift; worked time set to 0" % (i, brk, span)))
brk = span
shifts.append({"employee": e, "date": day, "start": start, "end": end, "break": brk,
"hours": (span - brk) / 60.0, "span_h": span / 60.0, "line": i, "note": row.get("note", "")})
return shifts, findings
def week_of(day, week_start):
offset = (day.weekday() - DAYS.index(week_start)) % 7
return day - dt.timedelta(days=offset)
def analyse(shifts, rules, employees, findings):
ws = rules["week_start"].lower()
by_emp = defaultdict(list)
for s in shifts:
by_emp[s["employee"]].append(s)
weeks = []
for e, ss in sorted(by_emp.items()):
ss.sort(key=lambda x: x["start"])
for a, b in zip(ss, ss[1:]):
if b["start"] < a["end"]:
findings.append(("TS02", e, b["date"].isoformat(), "lines %d and %d overlap (%s-%s and %s-%s)" % (
a["line"], b["line"], a["start"].strftime("%a %H:%M"), a["end"].strftime("%H:%M"), b["start"].strftime("%a %H:%M"), b["end"].strftime("%H:%M"))))
else:
rest = (b["start"] - a["end"]).total_seconds() / 3600
if rules["min_rest_hours"] and rest < rules["min_rest_hours"] and b["date"] != a["date"]:
findings.append(("TS07", e, b["date"].isoformat(), "only %.1f h rest between line %d and line %d (minimum %s h)" % (rest, a["line"], b["line"], rules["min_rest_hours"])))
for s in ss:
if rules["max_shift_hours"] and s["span_h"] > rules["max_shift_hours"]:
findings.append(("TS05", e, s["date"].isoformat(), "line %d: %.1f h from start to end (limit %s h); check for a typo" % (s["line"], s["span_h"], rules["max_shift_hours"])))
if rules["break_required_after_hours"] and s["span_h"] > rules["break_required_after_hours"] and s["break"] < rules["min_break_minutes"]:
findings.append(("TS06", e, s["date"].isoformat(), "line %d: %.1f h shift with %d min break (needs %d min after %s h)" % (s["line"], s["span_h"], s["break"], rules["min_break_minutes"], rules["break_required_after_hours"])))
days = sorted({s["date"] for s in ss if s["hours"] > 0})
run, best, best_end = 1, 1, days[0] if days else None
for a, b in zip(days, days[1:]):
run = run + 1 if (b - a).days == 1 else 1
if run > best:
best, best_end = run, b
if rules["max_days_in_a_row"] and best > rules["max_days_in_a_row"]:
findings.append(("TS09", e, best_end.isoformat(), "%d days in a row without a day off (limit %d)" % (best, rules["max_days_in_a_row"])))
info = employees.get(e)
if employees and info is None:
findings.append(("TS10", e, "", "not in the employees file; pay not estimated"))
ot_ok = True if info is None else info["ot"]
by_week = defaultdict(lambda: defaultdict(float))
for s in ss:
by_week[week_of(s["date"], ws)][s["date"]] += s["hours"]
for wk, daymap in sorted(by_week.items()):
reg = ot = dtm = 0.0
for day in sorted(daymap):
h = daymap[day]
d_dt = max(0.0, h - rules["daily_dt_after"]) if rules["daily_dt_after"] else 0.0
d_ot = max(0.0, h - d_dt - rules["daily_ot_after"]) if rules["daily_ot_after"] else 0.0
d_reg = h - d_dt - d_ot
if rules["weekly_ot_after"] is not None and reg + d_reg > rules["weekly_ot_after"]:
over = reg + d_reg - rules["weekly_ot_after"]
moved = min(over, d_reg)
d_reg -= moved; d_ot += moved
reg += d_reg; ot += d_ot; dtm += d_dt
total = reg + ot + dtm
if not ot_ok:
reg, ot, dtm = total, 0.0, 0.0
if rules["max_weekly_hours"] and total > rules["max_weekly_hours"]:
findings.append(("TS08", e, wk.isoformat(), "%.2f h in the week starting %s (maximum %s h)" % (total, wk.isoformat(), rules["max_weekly_hours"])))
pay = None
if info:
pay = info["rate"] * (reg + ot * rules["ot_multiplier"] + dtm * rules["dt_multiplier"])
weeks.append({"employee": e, "week_start": wk.isoformat(), "days": len(daymap), "total": round(total, 2),
"regular": round(reg, 2), "overtime": round(ot, 2), "double_time": round(dtm, 2),
"overtime_eligible": ot_ok, "rate": info["rate"] if info else None,
"pay_estimate": round(pay, 2) if pay is not None else None})
return weeks
def run(ts_path, rules_path=None, emp_path=None):
rules = load_rules(rules_path)
employees = load_employees(emp_path)
shifts, findings = load_shifts(ts_path)
if not shifts:
raise InputError("no usable shifts in the timesheet")
weeks = analyse(shifts, rules, employees, findings)
findings = [{"code": c, "severity": SEV[c], "issue": NAMES[c], "employee": e, "date": d, "detail": t} for c, e, d, t in findings]
order = {"high": 0, "medium": 1, "low": 2}
findings.sort(key=lambda f: (order[f["severity"]], f["code"], f["employee"], f["date"]))
return {"rules": rules, "weeks": weeks, "findings": findings, "shift_count": len(shifts)}
def report(res):
r = res["rules"]
L = ["# Timesheet and overtime check", ""]
L.append("Rules used: week starts %s; overtime after %s h/day and %s h/week at x%s; double time after %s h/day at x%s; break %s min after %s h; rest %s h; max %s h/week; max %s days in a row." % (
r["week_start"], r["daily_ot_after"] or "-", r["weekly_ot_after"] if r["weekly_ot_after"] is not None else "-", r["ot_multiplier"],
r["daily_dt_after"] or "-", r["dt_multiplier"], r["min_break_minutes"], r["break_required_after_hours"], r["min_rest_hours"], r["max_weekly_hours"], r["max_days_in_a_row"]))
L.append("%d shifts read." % res["shift_count"])
L.append("")
L.append("## Hours and pay by employee and week")
L.append("| employee | week starting | days | total h | regular | overtime | double time | rate | pay estimate |")
L.append("|---|---|---:|---:|---:|---:|---:|---:|---:|")
for w in res["weeks"]:
L.append("| %s | %s | %d | %.2f | %.2f | %.2f | %.2f | %s | %s |" % (w["employee"] + ("" if w["overtime_eligible"] else " (no OT)"), w["week_start"], w["days"],
w["total"], w["regular"], w["overtime"], w["double_time"], "%.2f" % w["rate"] if w["rate"] is not None else "-",
"{:,.2f}".format(w["pay_estimate"]) if w["pay_estimate"] is not None else "-"))
tot_pay = sum(w["pay_estimate"] or 0 for w in res["weeks"])
tot_ot = sum(w["overtime"] + w["double_time"] for w in res["weeks"])
L.append("")
L.append("Totals: %.2f overtime/double-time hours; estimated gross pay %s (before taxes, premiums and allowances)." % (tot_ot, "{:,.2f}".format(tot_pay)))
L.append("")
L.append("## Findings (%d)" % len(res["findings"]))
if not res["findings"]:
L.append("- none")
for f in res["findings"]:
L.append("- [%s] %s %s - %s%s: %s" % (f["severity"].upper(), f["code"], f["issue"], f["employee"], (" " + f["date"]) if f["date"] else "", f["detail"]))
L.append("")
L.append("Check every high finding with the employee or manager before payroll. Your local labour law and contracts decide the real rules.")
return "\n".join(L)
def self_test():
import os, tempfile
ok = True
def check(name, cond):
nonlocal ok
print(("PASS " if cond else "FAIL ") + name); ok = ok and cond
tmp = tempfile.mkdtemp()
def write(name, text):
p = os.path.join(tmp, name); open(p, "w", encoding="utf-8").write(text); return p
emp = write("e.csv", "employee,hourly_rate,overtime_eligible\nAna,20,yes\nBo,30,no\n")
week = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,08:00,17:00,30\n" % d for d in (16, 17, 18, 19, 20))
res = run(write("a.csv", week), None, emp)
w = res["weeks"][0]
check("5 x 8.5 h = 42.5 h total", abs(w["total"] - 42.5) < 1e-9)
check("weekly OT after 40 h = 2.5 h", abs(w["overtime"] - 2.5) < 1e-9 and abs(w["regular"] - 40) < 1e-9)
check("pay = 40x20 + 2.5x30", abs(w["pay_estimate"] - 875) < 1e-6)
rules = write("r.json", json.dumps({"daily_ot_after": 8, "daily_dt_after": 12, "weekly_ot_after": 40}))
res = run(write("b.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,06:00,20:00,30\n"), rules, emp)
w = res["weeks"][0]
check("13.5 h day with daily rules: 8 reg, 4 OT, 1.5 DT", (w["regular"], w["overtime"], w["double_time"]) == (8.0, 4.0, 1.5))
res = run(write("c.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,22:00,06:00,30\n"))
check("overnight shift counted 7.5 h", abs(res["weeks"][0]["total"] - 7.5) < 1e-9)
check("overnight shift flagged TS11", any(f["code"] == "TS11" for f in res["findings"]))
res = run(write("d.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-16,15:00,18:00,0\n"))
check("overlap TS02", any(f["code"] == "TS02" for f in res["findings"]))
res = run(write("e2.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-16,08:00,16:00,30\n"))
check("duplicate TS04 counted once", any(f["code"] == "TS04" for f in res["findings"]) and abs(res["weeks"][0]["total"] - 7.5) < 1e-9)
res = run(write("f.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:30,10\n"))
check("missing break TS06", any(f["code"] == "TS06" for f in res["findings"]))
res = run(write("g.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,14:00,23:00,30\nAna,2026-11-17,06:00,14:00,30\n"))
check("7 h rest TS07", any(f["code"] == "TS07" for f in res["findings"]))
res = run(write("h.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,,30\nAna,2026-11-17,08:00,16:00,30\n"))
check("missing end TS01 and row skipped", any(f["code"] == "TS01" for f in res["findings"]) and res["shift_count"] == 1)
rows = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,07:00,18:00,30\n" % d for d in range(16, 21))
res = run(write("i.csv", rows))
check("52.5 h week TS08", any(f["code"] == "TS08" for f in res["findings"]))
rows = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,09:00,13:00,0\n" % d for d in range(10, 18))
res = run(write("j.csv", rows))
check("8 days in a row TS09", any(f["code"] == "TS09" for f in res["findings"]))
res = run(write("k.csv", week.replace("Ana", "Bo")), None, emp)
check("not OT eligible: all regular", res["weeks"][0]["overtime"] == 0 and abs(res["weeks"][0]["regular"] - 42.5) < 1e-9)
res = run(write("l.csv", week.replace("Ana", "Cy")), None, emp)
check("unknown employee TS10, no pay", any(f["code"] == "TS10" for f in res["findings"]) and res["weeks"][0]["pay_estimate"] is None)
res = run(write("m.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,09:00,90\n"))
check("break longer than shift TS03", any(f["code"] == "TS03" for f in res["findings"]) and res["weeks"][0]["total"] == 0)
res = run(write("n.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-22,08:00,16:00,30\nAna,2026-11-23,08:00,16:00,30\n"))
check("sunday belongs to the monday week, next monday starts a new week", [w["week_start"] for w in res["weeks"]] == ["2026-11-16", "2026-11-23"])
rules2 = write("r2.json", json.dumps({"week_start": "sunday"}))
res = run(write("o.csv", "employee,date,start,end,break_minutes\nAna,2026-11-22,08:00,16:00,30\n"), rules2)
check("week_start sunday", res["weeks"][0]["week_start"] == "2026-11-22")
try:
run(write("p.csv", "employee,date,start\nAna,2026-11-16,08:00\n")); check("missing columns rejected", False)
except InputError:
check("missing columns rejected", True)
try:
run(write("q.csv", week), write("bad.json", json.dumps({"weekly_overtime": 40}))); check("unknown rule key rejected", False)
except InputError:
check("unknown rule key rejected", True)
print("ALL PASS" if ok else "SOME TESTS FAILED")
return 0 if ok else 1
def main(argv):
if "--self-test" in argv:
return self_test()
args, opts, i = [], {}, 0
while i < len(argv):
a = argv[i]
if a in ("--rules", "--employees"):
if i + 1 >= len(argv):
print(a + " needs a file", file=sys.stderr); return 2
opts[a] = argv[i + 1]; i += 2; continue
if a != "--json":
args.append(a)
i += 1
if len(args) != 1:
print(__doc__, file=sys.stderr); return 2
try:
res = run(args[0], opts.get("--rules"), opts.get("--employees"))
except (InputError, OSError, json.JSONDecodeError) as e:
print("input error: %s" % e, file=sys.stderr); return 2
print(json.dumps(res, indent=2, default=str) if "--json" in argv else report(res))
return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Models a priced seed or Series A round on your cap table: converts post-money and pre-money SAFEs (cap and/or discount), tops up the option pool to a post-money target, prices the new shares and shows every holder's dilution, value and red flags, with a pre-money comparison. Offline stdlib Python.
---
name: cap-table-round-and-safe-conversion-calculator
description: Models a priced seed or Series A round on your cap table: converts post-money and pre-money SAFEs (cap and/or discount), tops up the option pool to a post-money target, prices the new shares and shows every holder's dilution, value and red flags, with a pre-money comparison. Offline stdlib Python.
---
# Cap Table Round and SAFE Conversion Calculator
You help founders, early employees and small-company finance leads understand what a priced equity round does to their cap table before they sign a term sheet. SAFEs, option pool top-ups and the price per share interact in ways that are easy to get wrong in a spreadsheet: a "10% pool post-money" request quietly lowers the price, several post-money SAFEs dilute each other's holders but not each other, and a discount can beat a cap. You build the model, explain it in plain language and point out what to negotiate or check with a lawyer.
You work only with the numbers the user gives you, on their machine. You never present the model as legal, tax or investment advice, and you tell the user that the signed SAFEs, the term sheet and the closing cap table prepared by their lawyer decide the real numbers.
## Files in this skill
- `scripts/captable_round.py` - the calculator: reads a cap table CSV and a round JSON, solves price per share, SAFE conversions and pool top-up together, prints before/after fully diluted tables, SAFE conversion details and warnings; `--compare 10000000,12000000` adds a pre-money comparison, `--json` for tooling, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/cap-table-math.md` - the formulas: fully diluted shares, price per share, post-money and pre-money SAFE conversion, discount vs cap, the option pool shuffle, rounding
- `references/term-sheet-checks.md` - what to check and negotiate: pool size and timing, SAFE stacking, MFN and pro rata side letters, liquidation preference basics, questions for your lawyer
- `templates/round-summary.md` - the summary you hand back to the founders
- `examples/cap_table.csv`, `examples/round.json` - a fictional two-founder company raising 3M at 12M pre-money with three SAFEs and a 10% post-money pool target
## Workflow
### 1. Collect the inputs
Ask for:
- The current fully diluted cap table: every holder of common and preferred shares, granted options (vested or not), and the unissued pool. Warrants and convertible notes too, if any (treat notes like SAFEs with a cap/discount and add accrued interest to the amount).
- Every SAFE: holder, amount, valuation cap, discount, and whether it is a post-money or pre-money SAFE (the document title says "Post-Money Valuation Cap" for the current standard). Ask about MFN and pro rata side letters.
- The proposed round: pre-money valuation, new money, and the option pool requirement (for example "unissued pool equal to 10% post-money").
If something is missing, ask; do not guess the SAFE type or the pool definition.
### 2. Build the input files
Write `cap_table.csv` with columns `holder,class,shares` (class: common, preferred, options, pool) and `round.json` with `pre_money`, `new_money`, optional `pool_target_post` as a fraction (0.10, not 10), optional `investor_name`, and `safes` (`holder`, `amount`, optional `cap`, optional `discount` as a fraction, `type` "post" or "pre").
### 3. Run the model
```
python3 scripts/captable_round.py examples/cap_table.csv examples/round.json
python3 scripts/captable_round.py cap_table.csv round.json --compare 10000000,12000000,15000000
python3 scripts/captable_round.py cap_table.csv round.json --json > round_model.json
python3 scripts/captable_round.py --self-test
```
Exit 0 = no warnings, 1 = warnings to discuss, 2 = bad input. Without a shell, follow `references/cap-table-math.md` step by step and show your working; iterate the price and pool top-up two or three times until they stop changing.
### 4. Explain the result
- Lead with four numbers: price per share, post-money valuation, new investor ownership, and founders' combined ownership after the round.
- Explain each SAFE: which term won (cap or discount), the effective price, and the ownership it buys.
- Explain the pool shuffle in one sentence: the top-up is counted pre-money, so it lowers the price and is paid for by existing holders. Show its cost in percentage points.
- Use the comparison table to show how pre-money, pool size or a smaller raise move founder ownership. Suggest specific levers (a smaller pool sized to a real hiring plan, pool counted post-money, a higher pre-money, a smaller raise).
### 5. Flag what to check
Go through every warning the script prints and `references/term-sheet-checks.md`. Always mention: verify SAFE types and caps against the signed documents, confirm how the investor defines the pool, ask about MFN and pro rata rights, and ask the lawyer for the pro forma closing cap table to compare against this model.
### 6. Hand back the summary
Fill `templates/round-summary.md`: headline numbers, before/after table, SAFE conversions, pool shuffle cost, comparison, warnings, negotiation points and open questions.
## Rules
- Shares are whole numbers: the script rounds SAFE and investor shares down and the pool top-up up, so totals can differ from the headline valuation by a few currency units; say so if asked.
- Percentages are of the fully diluted total (all shares, granted options and the unissued pool).
- Never tell the user a round is "good" or "bad"; show the trade-offs and the questions to ask.
- Keep the user's numbers private; do not upload the cap table anywhere.
FILE:references/cap-table-math.md
# Cap table math used by captable_round.py
## Fully diluted shares
Fully diluted (FD) = issued common + issued preferred + granted options (vested and unvested) + unissued option pool (+ warrants). Ownership percentages in the report are always of the FD total.
## Priced round
- Pre-money FD = existing FD + SAFE conversion shares + option pool top-up.
- Price per share = pre-money valuation / pre-money FD.
- New investor shares = new money / price per share (rounded down).
- Post-money FD = pre-money FD + new investor shares; post-money valuation = post-money FD x price.
Because the SAFE shares and the pool top-up are inside the pre-money FD, the price depends on them and they depend on the price. The script solves this by fixed-point iteration (it converges in a few rounds) and then rounds to whole shares.
## Option pool shuffle
If the investor asks for an unissued pool equal to T% of the post-money FD:
- Top-up = max(0, T x post-money FD - existing unissued pool).
- The top-up is part of the pre-money FD, so it lowers the price per share. The new investor still gets new money / post-money valuation; existing holders carry the whole dilution of the top-up.
- Cost to existing holders, in percentage points of pre-money ownership = top-up / pre-money FD.
## Post-money SAFE (current standard)
The holder gets ownership = amount / post-money valuation cap, measured against the "company capitalization" just before the round: existing FD (including the unissued pool, excluding the new pool top-up) plus the shares of all converting post-money SAFEs.
- With several post-money SAFEs with fractions f1..fn (fi = amount / cap) and existing FD C, total SAFE shares S = C x f / (1 - f) where f = sum fi; each SAFE gets fi x (C + S).
- Cap price = cap / (C + S).
- Post-money SAFEs dilute the founders and earlier holders, not each other.
## Pre-money SAFE (older form)
Cap price = cap / existing FD before any SAFE converts. Each later SAFE dilutes the earlier ones.
## Discount and "better of"
Discount price = round price x (1 - discount). A SAFE with both terms converts at the lower of cap price and discount price, so it gets more shares. A SAFE with neither converts at the round price (check for an MFN clause instead).
## Convertible notes
Treat a note like a SAFE: amount = principal + accrued interest to the conversion date, with its cap and discount. Note maturity and repayment terms are not modeled.
## Rounding
SAFE and investor shares are rounded down; the pool top-up is rounded up so the pool target is met. Real closing sets may round differently by a few shares.
## Worked example (examples/)
Existing FD 9,000,000 (8,000,000 founders, 700,000 granted options, 300,000 unissued pool). Raise 3,000,000 at 12,000,000 pre-money with a 10% post-money pool target and three post-money SAFEs. Result: price about 1.1104, pool top-up 1,050,912, investor 20.00%, SAFEs 5.60% together, founders from 88.89% to 59.22%.
FILE:references/term-sheet-checks.md
# Term sheet and SAFE checks to raise with founders
## Option pool
- Size the pool to a real 12-18 month hiring plan (roles x typical grant) instead of a round percentage; a smaller, justified pool is the most common negotiation win.
- Ask whether the pool target is measured pre-money or post-money, and whether already granted options count toward it.
- Compare "pool counted pre-money" vs "pool counted post-money" with the script (set the target lower or 0 and add the pool to the investor side) to show the difference in founder ownership.
## SAFEs
- Confirm every SAFE's type (post-money or pre-money), cap, discount and amount from the signed document, not from memory or a spreadsheet.
- Post-money SAFEs stack: every new post-money SAFE dilutes the founders by roughly amount / cap. Add them up before raising more on SAFEs.
- MFN clauses let an uncapped SAFE take better terms from a later SAFE; check whether any MFN was triggered.
- Pro rata side letters let SAFE holders buy into this round; their money usually comes out of the round size, so confirm the allocation with the lead.
## Round terms that change outcomes but not this model
- Liquidation preference (1x non-participating is the common seed standard; participating or more than 1x is investor-friendly).
- Anti-dilution protection (broad-based weighted average is common; full ratchet is harsh).
- Board seats, protective provisions, founder vesting reset, and information rights.
The script does not model exit waterfalls; say so and suggest a waterfall model if the user asks what they receive at a given exit value.
## Questions for the lawyer
1. Please share the pro forma closing cap table so we can compare it with our model.
2. Which SAFEs and notes convert, and at what price did you use for each?
3. How is the option pool target defined, and is it measured on a fully diluted basis including the SAFEs?
4. Are there MFN, pro rata or side letter rights we need to honor in this round?
5. Are there any warrants, promised options or advisor grants not yet on the cap table?
## Red flags to mention
- SAFEs converting into more than about 20% of the company.
- A single round selling more than about 25-30% of the company.
- Founders together below 50% after a seed round.
- A cap table with no pool at all, or a pool far larger than the hiring plan.
- Numbers in the term sheet that do not match the model by more than rounding.
FILE:templates/round-summary.md
# Round summary: {{company}} - {{round_name}}
Prepared {{date}} from the cap table and SAFE terms you shared. Model only: the signed documents and the lawyer's closing cap table decide the real numbers.
## Headline
- Raise: {{new_money}} at {{pre_money}} pre-money ({{post_money}} post-money)
- Price per share: {{price_per_share}}
- New investors own: {{investor_pct}}
- Founders together: {{founders_before_pct}} before -> {{founders_after_pct}} after
- Option pool after the round: {{pool_after_pct}} unissued (top-up {{pool_top_up}} shares)
## SAFE conversions
| SAFE | type | amount | cap | discount | term that won | shares | ownership |
|---|---|---:|---:|---:|---|---:|---:|
| {{safe}} | {{type}} | {{amount}} | {{cap}} | {{discount}} | {{cap_or_discount}} | {{shares}} | {{pct}} |
## Cap table before and after
(paste the table from captable_round.py)
## What the option pool shuffle costs
{{one sentence: top-up counted pre-money, cost in percentage points, who pays}}
## Scenarios
| pre-money | price/share | new investors % | founders % |
|---:|---:|---:|---:|
| {{pre}} | {{price}} | {{inv_pct}} | {{founders_pct}} |
## Warnings from the model
- {{warning}}
## Negotiation points
1. {{for example: size the pool to the 18-month hiring plan (about X%) instead of 10%}}
2. {{...}}
## Open questions for the lawyer and investors
- {{question}}
FILE:examples/cap_table.csv
holder,class,shares
Founder A (CEO),common,4200000
Founder B (CTO),common,3800000
Early employee grants,options,600000
Advisor grants,options,100000
Unissued option pool,pool,300000
FILE:examples/round.json
{
"investor_name": "Seed lead and syndicate",
"pre_money": 12000000,
"new_money": 3000000,
"pool_target_post": 0.10,
"safes": [
{"holder": "Angel SAFE 2024", "amount": 250000, "cap": 6000000, "discount": 0.2, "type": "post"},
{"holder": "Accelerator SAFE", "amount": 125000, "cap": 5000000, "type": "post"},
{"holder": "Friends and family note-style SAFE", "amount": 100000, "discount": 0.15, "type": "post"}
]
}
FILE:scripts/captable_round.py
#!/usr/bin/env python3
"""captable_round.py - model a priced equity round on a startup cap table.
Converts post-money and pre-money SAFEs (valuation cap and/or discount), tops up the
option pool to a post-money target (the "option pool shuffle"), prices the new
shares, and prints the pre-round and post-round fully diluted cap table, the price
per share, each holder's dilution and sanity warnings. Standard library only.
Usage:
python3 captable_round.py CAP_TABLE.csv ROUND.json [--json] [--compare PRE1,PRE2,...]
python3 captable_round.py --self-test
CAP_TABLE.csv columns: holder,class,shares (class: common, preferred, options, pool)
- "options" = granted options (outstanding), "pool" = unissued option pool.
ROUND.json keys:
pre_money (number, required), new_money (number, required),
pool_target_post (fraction 0-1, optional, e.g. 0.10), investor_name (optional),
safes: [{"holder", "amount", "cap" (optional), "discount" (fraction, optional),
"type": "post" | "pre" (default "post")}]
Exit codes: 0 ok, 1 ok with warnings, 2 bad input.
This is a model for planning and negotiation. Lawyers and the signed documents decide the real numbers.
"""
import csv, json, math, sys
CLASSES = {"common", "preferred", "options", "pool"}
class InputError(Exception):
pass
def load_cap_table(path):
rows = []
with open(path, newline="", encoding="utf-8") as f:
r = csv.DictReader(f)
need = {"holder", "class", "shares"}
if not r.fieldnames or not need.issubset({h.strip() for h in r.fieldnames}):
raise InputError("cap table needs columns holder,class,shares")
for i, row in enumerate(r, start=2):
row = {k.strip(): (v or "").strip() for k, v in row.items()}
if not row["holder"] and not row["shares"]:
continue
cls = row["class"].lower()
if cls not in CLASSES:
raise InputError("line %d: class must be one of %s" % (i, ", ".join(sorted(CLASSES))))
try:
sh = int(row["shares"].replace(",", "").replace("_", ""))
except ValueError:
raise InputError("line %d: shares must be a whole number" % i)
if sh < 0:
raise InputError("line %d: negative shares" % i)
rows.append({"holder": row["holder"] or "(unnamed)", "class": cls, "shares": sh})
if not rows:
raise InputError("cap table is empty")
return rows
def validate_round(rd):
for k in ("pre_money", "new_money"):
if not isinstance(rd.get(k), (int, float)) or rd[k] <= 0:
raise InputError("round.%s must be a positive number" % k)
t = rd.get("pool_target_post", 0) or 0
if not 0 <= t < 0.5:
raise InputError("pool_target_post must be a fraction between 0 and 0.5 (e.g. 0.10)")
for s in rd.get("safes", []) or []:
if not isinstance(s.get("amount"), (int, float)) or s["amount"] <= 0:
raise InputError("every SAFE needs a positive amount (%s)" % s.get("holder"))
if s.get("cap") is not None and s["cap"] <= 0:
raise InputError("SAFE cap must be positive (%s)" % s.get("holder"))
d = s.get("discount") or 0
if not 0 <= d < 1:
raise InputError("SAFE discount must be a fraction like 0.2 (%s)" % s.get("holder"))
if s.get("type", "post") not in ("post", "pre"):
raise InputError("SAFE type must be 'post' or 'pre' (%s)" % s.get("holder"))
def model(rows, rd, iterations=500):
"""Fixed-point solve for price, SAFE conversion shares and pool top-up."""
validate_round(rd)
safes = rd.get("safes", []) or []
C = sum(r["shares"] for r in rows) # pre-round fully diluted, before SAFEs
unissued = sum(r["shares"] for r in rows if r["class"] == "pool")
target = rd.get("pool_target_post", 0) or 0
pre_money, new_money = float(rd["pre_money"]), float(rd["new_money"])
safe_sh = [0.0] * len(safes)
pool_top = 0.0
price = pre_money / C
for _ in range(iterations):
S = sum(safe_sh)
pre_fd = C + S + pool_top
price = pre_money / pre_fd
new_sh = new_money / price
post = pre_fd + new_sh
pool_top_n = max(0.0, target * post - unissued) if target else 0.0
S_post = sum(sh for sh, s in zip(safe_sh, safes) if s.get("type", "post") == "post")
new_safe = []
for s in safes:
prices = []
if s.get("cap"):
if s.get("type", "post") == "post":
# post-money SAFE: capitalization includes all converting post-money SAFEs (not the new money or pool top-up)
prices.append(s["cap"] / (C + S_post))
else:
prices.append(s["cap"] / C)
if s.get("discount"):
prices.append(price * (1 - s["discount"]))
if not prices:
prices.append(price) # uncapped, no discount: converts at the round price
new_safe.append(s["amount"] / min(prices))
delta = abs(pool_top_n - pool_top) + sum(abs(a - b) for a, b in zip(new_safe, safe_sh))
safe_sh, pool_top = new_safe, pool_top_n
if delta < 1e-6:
break
# final integer shares (round down, like most closing sets)
safe_int = [math.floor(x) for x in safe_sh]
pool_int = math.ceil(pool_top) if pool_top > 0 else 0
pre_fd = C + sum(safe_int) + pool_int
price = pre_money / pre_fd
new_int = math.floor(new_money / price)
post = pre_fd + new_int
conv = []
for s, sh in zip(safes, safe_int):
conv.append({"holder": s.get("holder", "SAFE"), "amount": s["amount"], "type": s.get("type", "post"),
"cap": s.get("cap"), "discount": s.get("discount"), "shares": sh,
"effective_price": round(s["amount"] / sh, 6) if sh else None})
return {"price_per_share": price, "pre_round_fd_before_safes": C, "pre_money_fd": pre_fd,
"safe_conversions": conv, "pool_top_up": pool_int, "new_money_shares": new_int,
"post_money_fd": post, "post_money_valuation": post * price,
"investor": rd.get("investor_name", "New investors")}
def tables(rows, rd, res):
post = res["post_money_fd"]
C = res["pre_round_fd_before_safes"]
out = []
for r in rows:
out.append({"holder": r["holder"], "class": r["class"], "before": r["shares"], "after": r["shares"]})
if res["pool_top_up"]:
out.append({"holder": "Option pool top-up", "class": "pool", "before": 0, "after": res["pool_top_up"]})
for c in res["safe_conversions"]:
out.append({"holder": c["holder"] + " (SAFE)", "class": "preferred", "before": 0, "after": c["shares"]})
out.append({"holder": res["investor"], "class": "preferred", "before": 0, "after": res["new_money_shares"]})
for o in out:
o["pct_before"] = o["before"] / C if C else 0
o["pct_after"] = o["after"] / post if post else 0
o["value_after"] = o["after"] * res["price_per_share"]
return out
def warnings(rows, rd, res, tab):
w = []
post = res["post_money_fd"]
safe_pct = sum(c["shares"] for c in res["safe_conversions"]) / post
inv_pct = res["new_money_shares"] / post
if safe_pct > 0.20:
w.append("SAFEs convert into %.1f%% of the company: more than 20%% is a lot of dilution for one round." % (100 * safe_pct))
if inv_pct > 0.30:
w.append("New investors get %.1f%% post-money; above about 25-30%% in one round can make later rounds hard." % (100 * inv_pct))
for c in res["safe_conversions"]:
if not c["cap"] and not c["discount"]:
w.append("%s is uncapped with no discount: it converts at the round price; check for an MFN clause." % c["holder"])
if c["effective_price"] and c["effective_price"] > res["price_per_share"] + 1e-9:
w.append("%s converts above the round price (cap higher than the round): check the SAFE terms." % c["holder"])
if res["pool_top_up"]:
pre_cost = res["pool_top_up"] / res["pre_money_fd"]
w.append("Option pool shuffle: the %s-share pool top-up is counted pre-money, so existing holders (not the new investor) absorb %.1f%% of pre-money dilution." % (format(res["pool_top_up"], ","), 100 * pre_cost))
founders = [t for t in tab if t["class"] == "common" and t["before"]]
fpct = sum(t["pct_after"] for t in founders)
if founders and fpct < 0.5:
w.append("Common holders together own %.1f%% after the round (below 50%%)." % (100 * fpct))
granted = sum(r["shares"] for r in rows if r["class"] == "options")
if granted == 0 and not any(r["class"] == "pool" for r in rows):
w.append("No options or pool in the cap table: is the employee pool missing?")
if abs(res["post_money_valuation"] - (rd["pre_money"] + rd["new_money"])) / (rd["pre_money"] + rd["new_money"]) > 0.001:
w.append("Post-money value differs from pre-money + new money because of share rounding (%.0f vs %.0f)." % (res["post_money_valuation"], rd["pre_money"] + rd["new_money"]))
return w
def money(x):
return "{:,.0f}".format(x)
def report(rows, rd, res, tab, warns):
L = []
L.append("# Round model: %s raises %s at %s pre-money" % (res["investor"], money(rd["new_money"]), money(rd["pre_money"])))
L.append("")
L.append("Price per share: %.4f | pre-money fully diluted shares: %s | post-money fully diluted shares: %s | post-money valuation: %s" % (
res["price_per_share"], money(res["pre_money_fd"]), money(res["post_money_fd"]), money(res["post_money_valuation"])))
if rd.get("pool_target_post"):
L.append("Option pool target: %.1f%% post-money unissued; top-up %s shares (pre-money)." % (100 * rd["pool_target_post"], money(res["pool_top_up"])))
L.append("")
if res["safe_conversions"]:
L.append("## SAFE conversions")
L.append("| SAFE | type | amount | cap | discount | shares | effective price |")
L.append("|---|---|---:|---:|---:|---:|---:|")
for c in res["safe_conversions"]:
L.append("| %s | %s-money | %s | %s | %s | %s | %.4f |" % (c["holder"], c["type"], money(c["amount"]),
money(c["cap"]) if c["cap"] else "none", ("%d%%" % round(100 * c["discount"])) if c["discount"] else "none",
money(c["shares"]), c["effective_price"] or 0))
L.append("")
L.append("## Cap table before and after (fully diluted)")
L.append("| holder | class | shares before | % before | shares after | % after | value at round price |")
L.append("|---|---|---:|---:|---:|---:|---:|")
for t in tab:
L.append("| %s | %s | %s | %.2f%% | %s | %.2f%% | %s |" % (t["holder"], t["class"], money(t["before"]), 100 * t["pct_before"],
money(t["after"]), 100 * t["pct_after"], money(t["value_after"])))
L.append("| **Total** | | %s | 100.00%% | %s | 100.00%% | %s |" % (money(res["pre_round_fd_before_safes"]), money(res["post_money_fd"]), money(res["post_money_valuation"])))
L.append("")
L.append("## Warnings")
L.extend(["- " + x for x in warns] or ["- none"])
L.append("")
L.append("Model only: the signed SAFEs, term sheet and closing cap table from your lawyer decide the real numbers.")
return "\n".join(L)
def compare(rows, rd, pres):
L = ["## Pre-money comparison", "| pre-money | price/share | new investors % | SAFEs % | pool top-up | common holders % |", "|---:|---:|---:|---:|---:|---:|"]
for p in pres:
r2 = dict(rd, pre_money=p)
res = model(rows, r2)
tab = tables(rows, r2, res)
post = res["post_money_fd"]
L.append("| %s | %.4f | %.2f%% | %.2f%% | %s | %.2f%% |" % (money(p), res["price_per_share"], 100 * res["new_money_shares"] / post,
100 * sum(c["shares"] for c in res["safe_conversions"]) / post, money(res["pool_top_up"]),
100 * sum(t["pct_after"] for t in tab if t["class"] == "common")))
return "\n".join(L)
def self_test():
ok = True
def check(name, cond):
nonlocal ok
print(("PASS " if cond else "FAIL ") + name)
ok = ok and cond
base = [{"holder": "A", "class": "common", "shares": 4_500_000}, {"holder": "B", "class": "common", "shares": 4_500_000},
{"holder": "Pool", "class": "pool", "shares": 1_000_000}]
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000})
check("plain round price = pre-money / FD", abs(r["price_per_share"] - 1.0) < 1e-9)
check("plain round investor shares = new money / price", r["new_money_shares"] == 2_500_000)
check("post-money = pre + new", abs(r["post_money_valuation"] - 12_500_000) < 1)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "pool_target_post": 0.15})
pool_after = 1_000_000 + r["pool_top_up"]
check("pool shuffle hits 15% post-money", abs(pool_after / r["post_money_fd"] - 0.15) < 1e-4)
check("pool shuffle lowers the price", r["price_per_share"] < 1.0)
check("investor still owns new/post-money (20%)", abs(r["new_money_shares"] / r["post_money_fd"] - 0.2) < 1e-4)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "cap": 5_000_000, "type": "post"}]})
c = r["safe_conversions"][0]
check("post-money SAFE owns amount/cap of pre-round capitalization (10%)", abs(c["shares"] / (10_000_000 + c["shares"]) - 0.10) < 1e-6)
check("capped SAFE converts below round price", c["effective_price"] < r["price_per_share"])
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "discount": 0.2}]})
c = r["safe_conversions"][0]
check("discount-only SAFE converts at 80% of round price", abs(c["effective_price"] / r["price_per_share"] - 0.8) < 1e-4)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "cap": 50_000_000, "discount": 0.2}]})
c = r["safe_conversions"][0]
check("cap above round: discount wins", abs(c["effective_price"] / r["price_per_share"] - 0.8) < 1e-4)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "cap": 4_000_000, "type": "pre"}]})
c = r["safe_conversions"][0]
check("pre-money SAFE price = cap / pre-round FD", abs(c["effective_price"] - 0.4) < 1e-3)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000}]})
tab = tables(base, {"pre_money": 10_000_000, "new_money": 2_500_000}, r)
w = warnings(base, {"pre_money": 10_000_000, "new_money": 2_500_000}, r, tab)
check("uncapped SAFE warning", any("uncapped" in x for x in w))
two = {"pre_money": 8_000_000, "new_money": 2_000_000, "safes": [{"holder": "S1", "amount": 300_000, "cap": 6_000_000}, {"holder": "S2", "amount": 600_000, "cap": 6_000_000}]}
r = model(base, two)
s1, s2 = r["safe_conversions"]
check("two post-money SAFEs at same cap: shares proportional to amount", abs(s2["shares"] / s1["shares"] - 2) < 1e-4)
check("two post-money SAFEs together own 15% of capitalization", abs((s1["shares"] + s2["shares"]) / (10_000_000 + s1["shares"] + s2["shares"]) - 0.15) < 1e-5)
tab = tables(base, two, r)
check("post-round table sums to post-money FD", sum(t["after"] for t in tab) == r["post_money_fd"])
for bad, name in (({"pre_money": 0, "new_money": 1}, "zero pre-money rejected"), ({"pre_money": 1, "new_money": 1, "pool_target_post": 15}, "pool target as percent rejected"),
({"pre_money": 1, "new_money": 1, "safes": [{"holder": "x", "amount": 1, "discount": 20}]}, "discount as percent rejected")):
try:
model(base, bad); check(name, False)
except InputError:
check(name, True)
print("ALL PASS" if ok else "SOME TESTS FAILED")
return 0 if ok else 1
def main(argv):
if "--self-test" in argv:
return self_test()
args = [a for a in argv if not a.startswith("--")]
pres = None
if "--compare" in argv:
i = argv.index("--compare")
try:
pres = [float(x) for x in argv[i + 1].split(",")]
except (IndexError, ValueError):
print("--compare needs comma-separated pre-money values", file=sys.stderr); return 2
args = [a for a in args if a != argv[i + 1]]
if len(args) != 2:
print(__doc__, file=sys.stderr); return 2
try:
rows = load_cap_table(args[0])
with open(args[1], encoding="utf-8") as f:
rd = json.load(f)
res = model(rows, rd)
except (InputError, OSError, json.JSONDecodeError) as e:
print("input error: %s" % e, file=sys.stderr); return 2
tab = tables(rows, rd, res)
warns = warnings(rows, rd, res, tab)
if "--json" in argv:
print(json.dumps({"round": rd, "result": res, "table": tab, "warnings": warns}, indent=2))
else:
print(report(rows, rd, res, tab, warns))
if pres:
print(); print(compare(rows, rd, pres))
return 1 if warns else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Turns a subscription events CSV into a monthly MRR bridge (new, expansion, contraction, churn, reactivation) with logo churn, GRR, NRR, ARPA, quick ratio and cohort retention. Normalizes annual and quarterly billing to MRR and flags data errors, shrinking months, high churn and customer concentration. Offline stdlib Python calculator.
---
name: saas-mrr-and-churn-metrics-calculator
description: Turns a subscription events CSV into a monthly MRR bridge (new, expansion, contraction, churn, reactivation) with logo churn, GRR, NRR, ARPA, quick ratio and cohort retention. Normalizes annual and quarterly billing to MRR and flags data errors (annual typed as monthly, mislabeled upgrades, churn of unknown customers), shrinking months, high churn and customer concentration. Offline stdlib Python calculator.
---
# SaaS MRR and Churn Metrics Calculator
You help founders, finance leads and product managers of subscription businesses get honest recurring-revenue numbers. Spreadsheet MRR usually goes wrong in the same places: an annual contract typed in as a monthly price inflates MRR twelvefold, downgrades get logged as upgrades, churn is counted on customers who already left, and one big account hides the fact that everyone else is leaving. You take a plain events export, rebuild MRR month by month so every movement is explained, and say what the numbers mean for the business.
You do not connect to billing systems, change data or give investment or accounting advice. Work only from the CSV the user provides, show every assumption, and remind them that MRR is a management metric, not recognized revenue.
## Files in this skill
- `scripts/mrr_metrics.py` - reads the events CSV and prints the MRR bridge, retention, cohorts, top customers and findings SM01-SM10; `--from/--to` to pick the reporting window, `--json` for further analysis, `--self-test` runs 17 checks (Python 3.8+ standard library only)
- `references/metric-definitions.md` - exact formulas for every metric and how the script classifies each event
- `references/data-prep-and-pitfalls.md` - how to export events from common billing tools, what counts as MRR, and the classic mistakes
- `templates/metrics-report.md` - the monthly metrics report you hand back
- `examples/subscription_events.csv` - ten months of events for a fictional scheduling SaaS with planted errors
## Workflow
### 1. Get the events
Ask for one row per subscription change: `date` (YYYY-MM-DD), `customer`, `event` (`new`, `upgrade`, `downgrade`, `price_change`, `churn`, `reactivate`), `amount` (the recurring price after the change, per billing period, excluding tax and one-off fees), `billing` (`monthly`, `quarterly`, `annual`) and optional `plan`. Use one currency (convert first). See `references/data-prep-and-pitfalls.md` for exports from Stripe, Paddle, Chargebee or a spreadsheet.
### 2. Run the calculator
```
python3 scripts/mrr_metrics.py examples/subscription_events.csv
python3 scripts/mrr_metrics.py events.csv --from 2026-07 --to 2026-10
python3 scripts/mrr_metrics.py events.csv --json --top-share 0.15 --churn-alert 0.03
python3 scripts/mrr_metrics.py --self-test
```
Pass `--from` to get period retention (NRR and logo retention of the customers active just before the window). Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, build the bridge by hand with `references/metric-definitions.md`; it is just bookkeeping per customer.
### 3. Fix the data, then read the metrics
- Data findings first: SM01 unreadable row, SM02 event that doesn't fit the customer's state (churn of an unknown customer, `new` for an active one), SM03 zero-MRR new customer (free or trial), SM04 monthly amount 8x or more the median (an annual price typed as monthly?), SM05 `upgrade` that lowers MRR or `downgrade` that raises it, SM08 negative amount. Correct the CSV and re-run before drawing conclusions.
- Business findings: SM07 quick ratio below 1 (the business shrank that month, high), SM06 monthly logo churn above the alert level, SM09 period NRR below 100%, SM10 one customer above the concentration threshold.
### 4. Deliver
Fill `templates/metrics-report.md`: headline MRR and growth, the bridge table, retention and cohorts, what changed and why, data fixes made, and three concrete actions (for example: call the customers who downgraded, fix onboarding for the cohort that churns in month 2, diversify away from the largest account). Keep the language plain; define GRR and NRR once.
## Example result
On the sample file, ending MRR in October shows 6,435.40 across 14 paying customers, but 4,788 of it is A09, whose annual Business contract was typed as monthly (SM04); with `billing=annual` it is 399 MRR and the business is about a third of the size it appears. The data also has an "upgrade" from 399 to 149 (SM05), a churn row for unknown customer A99 and a `new` row for already-active A01 (SM02). Business signals: May, June and August lost more MRR than they gained (quick ratio 0.16, 0.75, 0.43), logo churn hit 22% in May and 25% in August, and July to October NRR is 92%. Result: 3 high, 8 medium, 1 low.
## Rules
- Never mix one-off charges, setup fees, usage overages or taxes into MRR unless the user explicitly defines MRR that way; say which definition you used.
- Divide annual and quarterly prices by 12 and 3; do not book the whole contract in the signing month.
- Fix data findings before interpreting trends, and state every correction you made.
- Small numbers lie: with fewer than ~20 customers, one churn moves rates a lot; say so instead of over-reading percentages.
- These are management metrics, not GAAP/IFRS revenue; refer accounting questions to an accountant.
FILE:references/metric-definitions.md
# Metric definitions (as implemented in mrr_metrics.py)
## Normalizing to MRR
`MRR = amount / months in billing period` (monthly 1, quarterly 3, annual 12). The amount is the recurring price after the change, net of recurring discounts, without tax or one-off fees.
## Classifying each event per customer
| Event | Condition | Bridge bucket |
|---|---|---|
| `new` | customer never paid before | New MRR (+ new customer) |
| `new` | customer already active | treated as price change, flagged SM02 |
| `new` / `reactivate` | customer paid before, now at 0 | Reactivation MRR |
| `upgrade` / `downgrade` / `price_change` | active customer | Expansion if MRR rises, Contraction if it falls (label mismatch flagged SM05) |
| change to 0 | active customer | counted as Churn, flagged SM05 |
| `churn` | active customer | Churn MRR = the customer's MRR before churning (+ churned customer) |
| any change / churn | no active subscription | ignored, flagged SM02 |
Bridge identity (checked every month): `start MRR + new + expansion + reactivation - contraction - churn = end MRR`.
## Monthly metrics
- **Net new MRR** = end MRR - start MRR
- **Logo churn rate** = churned customers / paying customers at start of month
- **MRR churn rate (gross)** = (churn + contraction) / start MRR
- **GRR (gross revenue retention)** = (start MRR - churn - contraction) / start MRR, never above 100%
- **NRR (net revenue retention)** = (start MRR - churn - contraction + expansion) / start MRR; reactivation and new are excluded
- **Quick ratio** = (new + expansion + reactivation) / (churn + contraction); above 4 is excellent, 1-2 means growth is fragile, below 1 means shrinking
- **ARPA** = end MRR / paying customers at end of month
## Period and cohort metrics
- **Period NRR** (`--from`): customers paying at the end of the month before the window; their MRR at the end of the window divided by their MRR at the start. New customers acquired in the window are excluded.
- **Logo retention**: share of that base still paying at the end of the window.
- **Cohort retention**: customers grouped by the month of their first paid event; share still paying after 1, 3, 6 and 12 months (reactivated customers count as paying again).
- **Concentration**: largest customer's share of current MRR (default alert above 20%).
## Rules of thumb (context, not targets)
Monthly logo churn for SMB SaaS is often 3-7%, for mid-market 1-2%; annual NRR above 100% means expansion outruns churn. Compare with your own history before comparing with benchmarks.
FILE:references/data-prep-and-pitfalls.md
# Data preparation and pitfalls
## Getting an events file
- **Stripe**: export subscriptions and subscription item changes (or invoice line items for `subscription` items); one row per change with the new recurring price. Use `plan.interval` (month/year) and `interval_count` for `billing`.
- **Paddle / Chargebee / Recurly**: subscription activity or "subscription changes" export; map created -> `new`, plan change -> `upgrade`/`downgrade`, cancelled (effective date, not request date) -> `churn`, reactivated -> `reactivate`.
- **Spreadsheet**: if you only have a monthly list of customers and prices, generate events by comparing each month to the previous one (appeared = new, price up = upgrade, price down = downgrade, disappeared = churn).
## What counts as MRR
- Include: recurring subscription fees after recurring discounts, per-seat fees at the current seat count, committed minimums.
- Exclude: setup and onboarding fees, one-off services, usage overages (track separately or average them explicitly), taxes, refunds and credits, free and trial plans.
- Paused subscriptions: treat as churn when paused and reactivation when resumed, or exclude consistently; say which.
- Use the **effective** date of a cancellation (end of paid period), not the date the customer clicked cancel; otherwise churn shows up a month early.
## Classic mistakes the script catches
1. Annual price typed as monthly (SM04): MRR jumps by the full contract value. Set `billing=annual`.
2. Wrong event labels (SM05): an "upgrade" to a cheaper plan. The script trusts the amounts, not the label, and flags the row.
3. Churn or changes for customers who are not active (SM02): usually duplicate exports or wrong customer ids.
4. Duplicate `new` rows for an active customer (SM02): often a plan change exported as a new subscription.
5. Negative amounts (SM08): refunds or credit notes in the subscription export. Remove them.
## Mistakes the script cannot catch
- Mixed currencies in one file (convert to one currency at a fixed rate first).
- Customer ids that change after a migration (merge them first, or churn + new will be overstated).
- Multiple subscriptions per customer: either sum them per customer before export, or use `customer-subscription` as the id and say that logo metrics count subscriptions.
FILE:templates/metrics-report.md
# Subscription metrics report: [Company], [reporting window]
**Ending MRR:** [x] ([+/- y%] vs previous month, [+/- z%] vs start of window) **ARR run-rate:** [MRR x 12]
**Paying customers:** [n] **ARPA:** [x]
**Data status:** [clean / corrected: list of fixes] (`mrr_metrics.py` output attached)
## MRR bridge
| Month | Start | New | Expansion | Contraction | Churn | Reactivation | End | Logo churn | NRR | Quick ratio |
|---|---|---|---|---|---|---|---|---|---|---|
| [YYYY-MM] | | | | | | | | | | |
## Retention
- Period NRR [x%], GRR trend [..], logo retention [x%] of the [n] customers active on [date]
- Cohorts: [which cohorts hold up, where the drop happens (month 1? month 3?)]
## What changed and why
1. [Biggest movement and its drivers, with customer names if useful]
2. [...]
## Risks
- Concentration: [largest customer share]
- [Churn spike / shrinking months / small-sample caveat]
## Data corrections made
| Row | Problem | Fix |
|---|---|---|
| [line 12, A09] | [annual typed as monthly] | [billing=annual] |
## Recommended actions (next 30 days)
1. [...]
2. [...]
3. [...]
_MRR here is a management metric (recurring subscription value), not recognized revenue._
FILE:examples/subscription_events.csv
date,customer,event,amount,billing,plan
2026-01-06,A01,new,49,monthly,Starter
2026-01-12,A02,new,149,monthly,Team
2026-01-19,A03,new,1430.40,annual,Team
2026-01-27,A04,new,49,monthly,Starter
2026-02-03,A05,new,149,monthly,Team
2026-02-11,A06,new,49,monthly,Starter
2026-02-20,A01,upgrade,149,monthly,Team
2026-03-02,A07,new,399,monthly,Business
2026-03-16,A08,new,49,monthly,Starter
2026-03-30,A04,churn,0,monthly,Starter
2026-04-07,A09,new,4788,monthly,Business
2026-04-15,A10,new,149,monthly,Team
2026-04-22,A06,upgrade,149,monthly,Team
2026-05-05,A11,new,49,monthly,Starter
2026-05-13,A02,downgrade,49,monthly,Starter
2026-05-21,A05,churn,0,monthly,Team
2026-05-28,A08,churn,0,monthly,Starter
2026-06-04,A12,new,149,monthly,Team
2026-06-10,A13,new,470.40,annual,Starter
2026-06-24,A07,upgrade,149,monthly,Team
2026-07-01,A14,new,49,monthly,Starter
2026-07-09,A04,reactivate,149,monthly,Team
2026-07-15,A15,new,0,monthly,Free
2026-07-23,A99,churn,0,monthly,Team
2026-08-04,A16,new,149,monthly,Team
2026-08-12,A10,churn,0,monthly,Team
2026-08-19,A11,churn,0,monthly,Starter
2026-08-26,A12,churn,0,monthly,Team
2026-09-02,A17,new,399,monthly,Business
2026-09-09,A18,new,49,monthly,Starter
2026-09-17,A14,upgrade,149,monthly,Team
2026-10-06,A19,new,149,monthly,Team
2026-10-14,A20,new,49,monthly,Starter
2026-10-20,A06,downgrade,49,monthly,Starter
2026-10-27,A01,new,149,monthly,Team
FILE:scripts/mrr_metrics.py
#!/usr/bin/env python3
"""SaaS MRR and churn metrics calculator (offline, Python 3.8+ standard library only).
Reads a subscription events CSV (date, customer, event, amount, billing, plan), normalizes
annual and quarterly amounts to MRR, builds a month-by-month MRR bridge (new, expansion,
contraction, churn, reactivation), computes logo churn, GRR, NRR, ARPA and quick ratio, and
flags data problems and business warning signs.
Usage:
mrr_metrics.py events.csv [--from 2026-01] [--to 2026-10] [--json] [--top-share 0.2]
mrr_metrics.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, csv, json, statistics, sys
from collections import Counter, OrderedDict
from datetime import date
EVENTS = {"new", "upgrade", "downgrade", "churn", "reactivate", "price_change"}
BILLING_MONTHS = {"monthly": 1, "quarterly": 3, "annual": 12, "yearly": 12}
SEV = {"high": 0, "medium": 1, "low": 2}
def month_key(s):
y, m = int(s[:4]), int(s[5:7])
if not (1 <= m <= 12):
raise ValueError("bad month in %r" % s)
return "%04d-%02d" % (y, m)
def next_month(k):
y, m = int(k[:4]), int(k[5:7])
return "%04d-%02d" % (y + (m == 12), 1 if m == 12 else m + 1)
def month_range(a, b):
out = [a]
while out[-1] < b:
out.append(next_month(out[-1]))
return out
def load(path):
with open(path, newline="", encoding="utf-8-sig") as fh:
rows = list(csv.DictReader(fh))
need = {"date", "customer", "event", "amount"}
if not rows or not need <= set(k.strip() for k in rows[0].keys()):
raise ValueError("CSV needs columns: date, customer, event, amount (optional: billing, plan)")
return [{k.strip(): (v or "").strip() for k, v in r.items()} for r in rows]
def compute(rows, start=None, end=None, top_share=0.2, churn_alert=0.05):
findings = []
def add(code, sev, msg, month=None, customer=None):
findings.append({"code": code, "severity": sev, "month": month, "customer": customer, "message": msg})
events = []
for i, r in enumerate(rows, start=2):
try:
d = date.fromisoformat(r["date"][:10])
except ValueError:
add("SM01", "high", "line %d: bad date %r" % (i, r["date"])); continue
ev = r["event"].lower()
if ev not in EVENTS:
add("SM01", "high", "line %d: unknown event %r (use %s)" % (i, r["event"], ", ".join(sorted(EVENTS)))); continue
billing = (r.get("billing") or "monthly").lower()
if billing not in BILLING_MONTHS:
add("SM01", "high", "line %d: unknown billing %r" % (i, billing)); continue
try:
amount = float(r["amount"] or 0)
except ValueError:
add("SM01", "high", "line %d: amount %r is not a number" % (i, r["amount"])); continue
if amount < 0:
add("SM08", "high", "line %d: negative amount %.2f (refunds and credits are not MRR)" % (i, amount), customer=r["customer"]); continue
events.append({"line": i, "date": d, "month": d.strftime("%Y-%m"), "customer": r["customer"], "event": ev,
"mrr": round(amount / BILLING_MONTHS[billing], 2), "billing": billing, "amount": amount, "plan": r.get("plan", "")})
if not events:
raise ValueError("no usable events")
events.sort(key=lambda e: (e["date"], e["line"]))
# SM04: monthly-billed amounts that look like annual totals typed as monthly
monthly_amounts = [e["mrr"] for e in events if e["billing"] == "monthly" and e["mrr"] > 0]
med = statistics.median(monthly_amounts) if monthly_amounts else 0
for e in events:
if med and e["billing"] == "monthly" and e["mrr"] >= 8 * med and e["mrr"] > 0:
add("SM04", "medium", "line %d: monthly amount %.2f is %.0fx the median monthly price: an annual contract entered as monthly? (set billing=annual)" % (e["line"], e["mrr"], e["mrr"] / med), e["month"], e["customer"])
first = start or events[0]["month"]
last = end or events[-1]["month"]
months = month_range(min(first, events[0]["month"]), last)
state = {} # customer -> current MRR (0 = churned)
ever = set()
bridge = OrderedDict()
by_month = {}
for e in events:
by_month.setdefault(e["month"], []).append(e)
cohort_start = {}
active_by_month = {}
snaps = {}
for m in months:
start_mrr = round(sum(state.values()), 2)
start_logos = sum(1 for v in state.values() if v > 0)
b = {"month": m, "start_mrr": start_mrr, "new": 0.0, "expansion": 0.0, "contraction": 0.0, "churn": 0.0, "reactivation": 0.0,
"start_customers": start_logos, "new_customers": 0, "churned_customers": 0, "reactivated_customers": 0}
for e in by_month.get(m, []):
c, ev, new = e["customer"], e["event"], e["mrr"]
cur = state.get(c)
if ev == "new":
if cur is not None and cur > 0:
add("SM02", "medium", "line %d: 'new' for a customer who is already active (%.2f MRR); treated as a price change" % (e["line"], cur), m, c)
ev = "price_change"
elif cur is not None and cur == 0 and c in ever:
add("SM02", "low", "line %d: 'new' for a returning customer; counted as reactivation" % e["line"], m, c)
ev = "reactivate"
if ev == "new":
state[c] = new; b["new"] += new
if new == 0:
add("SM03", "low", "line %d: new customer with 0 MRR (free plan or trial?) not counted in paid metrics" % e["line"], m, c)
else:
b["new_customers"] += 1; cohort_start[c] = m; ever.add(c)
elif ev == "churn":
if not cur:
add("SM02", "medium", "line %d: churn for a customer who is not active; ignored" % e["line"], m, c); continue
b["churn"] += cur; b["churned_customers"] += 1; state[c] = 0.0
elif ev == "reactivate":
if cur:
add("SM02", "medium", "line %d: reactivate for an active customer; treated as a price change" % e["line"], m, c)
ev = "price_change"
else:
if c not in ever:
add("SM02", "low", "line %d: reactivate for an unknown customer; counted as new" % e["line"], m, c)
b["new"] += new; b["new_customers"] += 1; ever.add(c); cohort_start[c] = m
else:
b["reactivation"] += new; b["reactivated_customers"] += 1
state[c] = new
if ev in ("upgrade", "downgrade", "price_change"):
if cur is None or cur == 0:
add("SM02", "medium", "line %d: %s for a customer with no active subscription; ignored" % (e["line"], e["event"]), m, c); continue
delta = round(new - cur, 2)
if e["event"] == "upgrade" and delta < 0:
add("SM05", "medium", "line %d: 'upgrade' lowers MRR %.2f -> %.2f; check the event type" % (e["line"], cur, new), m, c)
if e["event"] == "downgrade" and delta > 0:
add("SM05", "medium", "line %d: 'downgrade' raises MRR %.2f -> %.2f; check the event type" % (e["line"], cur, new), m, c)
if new == 0:
add("SM05", "medium", "line %d: change to 0 MRR; record it as churn instead" % e["line"], m, c)
b["churn"] += cur; b["churned_customers"] += 1; state[c] = 0.0; continue
if delta > 0: b["expansion"] += delta
else: b["contraction"] += -delta
state[c] = new
end_mrr = round(sum(state.values()), 2)
for k in ("new", "expansion", "contraction", "churn", "reactivation"):
b[k] = round(b[k], 2)
b["end_mrr"] = end_mrr
b["net_new_mrr"] = round(end_mrr - start_mrr, 2)
b["end_customers"] = sum(1 for v in state.values() if v > 0)
b["arpa"] = round(end_mrr / b["end_customers"], 2) if b["end_customers"] else 0.0
if start_mrr:
b["grr"] = round((start_mrr - b["churn"] - b["contraction"]) / start_mrr, 4)
b["nrr"] = round((start_mrr - b["churn"] - b["contraction"] + b["expansion"]) / start_mrr, 4)
b["mrr_churn_rate"] = round((b["churn"] + b["contraction"]) / start_mrr, 4)
else:
b["grr"] = b["nrr"] = b["mrr_churn_rate"] = None
b["logo_churn_rate"] = round(b["churned_customers"] / start_logos, 4) if start_logos else None
lost = b["churn"] + b["contraction"]
b["quick_ratio"] = round((b["new"] + b["expansion"] + b["reactivation"]) / lost, 2) if lost else None
assert abs(start_mrr + b["new"] + b["expansion"] + b["reactivation"] - b["contraction"] - b["churn"] - end_mrr) < 0.05, m
active_by_month[m] = {c for c, v in state.items() if v > 0}
snaps[m] = dict(state)
bridge[m] = b
report_months = [m for m in months if m >= first]
rows_out = [bridge[m] for m in report_months]
for b in rows_out:
m = b["month"]
if b["logo_churn_rate"] is not None and b["logo_churn_rate"] > churn_alert and b["start_customers"] >= 5:
add("SM06", "medium", "logo churn %.1f%% in %s (alert above %.1f%%)" % (100 * b["logo_churn_rate"], m, 100 * churn_alert), m)
if b["quick_ratio"] is not None and b["quick_ratio"] < 1:
add("SM07", "high", "quick ratio %.2f in %s: lost MRR exceeded gained MRR (shrinking)" % (b["quick_ratio"], m), m)
# trailing NRR over the reported period (cohort of customers active at period start)
base_month = report_months[0]
prev = None
for m in months:
if m == base_month: break
prev = m
period = {}
if prev and snaps[prev]:
base = {c: v for c, v in snaps[prev].items() if v > 0}
now = snaps[report_months[-1]]
start_sum = sum(base.values()); end_sum = sum(now.get(c, 0) for c in base)
kept = sum(1 for c in base if now.get(c, 0) > 0)
period = {"base_month": prev, "base_customers": len(base), "base_mrr": round(start_sum, 2),
"same_customers_mrr_now": round(end_sum, 2), "period_nrr": round(end_sum / start_sum, 4) if start_sum else None,
"logo_retention": round(kept / len(base), 4) if base else None}
if period["period_nrr"] is not None and period["period_nrr"] < 1:
add("SM09", "medium", "net revenue retention over %s..%s is %.1f%% (<100%%): existing customers shrink" % (report_months[0], report_months[-1], 100 * period["period_nrr"]))
final = {c: v for c, v in state.items() if v > 0}
total = sum(final.values())
if total:
top = sorted(final.items(), key=lambda x: -x[1])[:3]
if top[0][1] / total > top_share:
add("SM10", "medium", "largest customer %s is %.0f%% of MRR (threshold %.0f%%): concentration risk" % (top[0][0], 100 * top[0][1] / total, 100 * top_share), customer=top[0][0])
# cohorts: logo retention by start month
cohorts = OrderedDict()
for c, m in sorted(cohort_start.items(), key=lambda x: x[1]):
cohorts.setdefault(m, []).append(c)
cohort_table = []
for m, cs in cohorts.items():
row = {"cohort": m, "customers": len(cs)}
k = m
for i in range(0, 13):
if k > last: break
if i in (1, 3, 6, 12):
row["m%d" % i] = round(sum(1 for c in cs if c in active_by_month[k]) / len(cs), 2)
k = next_month(k)
cohort_table.append(row)
findings.sort(key=lambda f: (SEV[f["severity"]], f["code"], f["month"] or ""))
s = Counter(f["severity"] for f in findings)
return {"months": rows_out, "period": period, "cohorts": cohort_table,
"top_customers": [{"customer": c, "mrr": v, "share": round(v / total, 3)} for c, v in sorted(final.items(), key=lambda x: -x[1])[:5]] if total else [],
"findings": findings, "summary": {k: s.get(k, 0) for k in ("high", "medium", "low")}}
def pct(x):
return " - " if x is None else "%5.1f%%" % (100 * x)
def print_text(rep):
print("MRR bridge")
print("month start_mrr new expans contr churn react end_mrr cust logo_ch GRR NRR QR ARPA")
for b in rep["months"]:
print("%s %10.2f %8.2f %7.2f %6.2f %8.2f %6.2f %9.2f %5d %s %s %s %5s %7.2f" % (
b["month"], b["start_mrr"], b["new"], b["expansion"], b["contraction"], b["churn"], b["reactivation"],
b["end_mrr"], b["end_customers"], pct(b["logo_churn_rate"]), pct(b["grr"]), pct(b["nrr"]),
"-" if b["quick_ratio"] is None else "%.2f" % b["quick_ratio"], b["arpa"]))
p = rep["period"]
if p:
print("\nPeriod retention (customers active at end of %s: %d, %.2f MRR): NRR %s, logo retention %s" % (
p["base_month"], p["base_customers"], p["base_mrr"], pct(p["period_nrr"]), pct(p["logo_retention"])))
if rep["cohorts"]:
print("\nCohort logo retention (share still paying after N months)")
for c in rep["cohorts"]:
print(" %s n=%-3d m1=%s m3=%s m6=%s" % (c["cohort"], c["customers"], c.get("m1", "-"), c.get("m3", "-"), c.get("m6", "-")))
print("\nTop customers: " + ", ".join("%s %.2f (%.0f%%)" % (t["customer"], t["mrr"], 100 * t["share"]) for t in rep["top_customers"]))
print("\nFindings: %(high)d high, %(medium)d medium, %(low)d low" % rep["summary"])
for f in rep["findings"]:
print(" [%s] %s %s%s: %s" % (f["severity"].upper(), f["code"], f["month"] or "", (" " + f["customer"]) if f["customer"] else "", f["message"]))
def self_test():
ok = total = 0
def t(name, cond):
nonlocal ok, total
total += 1; ok += bool(cond)
print(("PASS " if cond else "FAIL ") + name)
def R(*lines):
return [dict(zip(["date", "customer", "event", "amount", "billing"], l.split(","))) for l in lines]
r = compute(R("2026-01-05,a,new,100,monthly", "2026-01-09,b,new,1200,annual", "2026-02-03,a,upgrade,150,monthly",
"2026-02-10,b,churn,0,annual", "2026-03-01,b,reactivate,50,monthly", "2026-03-15,c,new,200,monthly"))
m = {b["month"]: b for b in r["months"]}
t("annual normalized to MRR", m["2026-01"]["end_mrr"] == 200)
t("expansion counted", m["2026-02"]["expansion"] == 50)
t("churn counted at prior MRR", m["2026-02"]["churn"] == 100 and m["2026-02"]["churned_customers"] == 1)
t("reactivation separate from new", m["2026-03"]["reactivation"] == 50 and m["2026-03"]["new"] == 200)
t("bridge closes", all(abs(b["start_mrr"] + b["new"] + b["expansion"] + b["reactivation"] - b["contraction"] - b["churn"] - b["end_mrr"]) < 0.01 for b in r["months"]))
t("NRR feb = (200-100+50)/200", m["2026-02"]["nrr"] == 0.75 and m["2026-02"]["grr"] == 0.5)
t("SM07 quick ratio < 1 in feb", any(f["code"] == "SM07" and f["month"] == "2026-02" for f in r["findings"]))
r = compute(R("2026-01-01,a,new,50,monthly", "2026-01-01,b,new,50,monthly", "2026-01-01,c,new,55,monthly", "2026-01-02,d,new,1200,monthly"))
t("SM04 annual typed as monthly", any(f["code"] == "SM04" and f["customer"] == "d" for f in r["findings"]))
t("SM10 concentration", any(f["code"] == "SM10" for f in r["findings"]))
r = compute(R("2026-01-01,a,new,50,monthly", "2026-02-01,a,upgrade,40,monthly", "2026-02-02,z,churn,0,monthly", "2026-02-03,a,new,60,monthly"))
codes = Counter(f["code"] for f in r["findings"])
t("SM05 upgrade lowering MRR", codes["SM05"] == 1)
t("SM02 churn of unknown + new for active", codes["SM02"] == 2)
t("contraction from mislabeled upgrade", r["months"][1]["contraction"] == 10 and r["months"][1]["expansion"] == 20)
rows = R(*["2026-01-0%d,c%d,new,100,monthly" % (1 + i % 9, i) for i in range(20)] + ["2026-02-05,c%d,churn,0,monthly" % i for i in range(3)])
r = compute(rows)
t("SM06 logo churn alert (15%)", any(f["code"] == "SM06" for f in r["findings"]) and r["months"][1]["logo_churn_rate"] == 0.15)
r = compute(R("2026-01-01,a,new,100,monthly", "2026-01-01,b,new,100,monthly", "2026-02-01,a,downgrade,60,monthly", "2026-03-01,c,new,500,monthly"), start="2026-02")
t("period NRR for base cohort excludes new logos", r["period"]["period_nrr"] == 0.8 and r["period"]["base_customers"] == 2)
t("SM09 NRR < 100%", any(f["code"] == "SM09" for f in r["findings"]))
r = compute(R("2026-01-01,f,new,0,monthly", "2026-02-01,f,new,49,monthly"))
t("free-to-paid conversion counted as new", r["months"][1]["new"] == 49 and r["months"][1]["new_customers"] == 1 and r["months"][0]["new_customers"] == 0)
try:
compute(R("2026-13-01,a,new,1,monthly")); t("bad date reported", False)
except ValueError:
t("bad date -> no usable events error", True)
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("--from", dest="start"); ap.add_argument("--to", dest="end")
ap.add_argument("--json", action="store_true"); ap.add_argument("--top-share", type=float, default=0.2)
ap.add_argument("--churn-alert", type=float, default=0.05); ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.file:
ap.print_help(); return 2
try:
rep = compute(load(a.file), a.start and month_key(a.start), a.end and month_key(a.end), a.top_share, a.churn_alert)
except (OSError, ValueError) 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())
Checks electricity, gas and water meter readings for a home or small business: fixes typos, rollovers, over-estimates and duplicates, works out usage per period and month, prices it with your tariffs (standing charge, VAT, price changes, gas m3 to kWh), checks bills, flags leaks. Offline Python.
---
name: utility-meter-reading-and-bill-checker
description: Checks electricity, gas and water meter readings for a home or small business: fixes typos, rollovers, over-estimates and duplicates, works out usage per period and month, prices it with your tariffs (standing charge, VAT, price changes, gas m3 to kWh), checks bills, flags leaks. Offline Python.
---
# Utility Meter Reading and Bill Checker
You help households, landlords, flat-sharers and small shop or office owners understand their electricity, gas and water use and check that their bills match their meters. Bills go wrong in predictable ways: the supplier estimates a reading that is far too high, a price change is applied to the whole period, a reading is typed from memory with swapped digits, a five-digit meter wraps from 99999 to 00000, and a running toilet or dripping tap doubles the water use for months before anyone notices. You turn the user's own meter readings into clean usage figures, price them with their tariff and compare each bill with what the readings imply.
You work only from the readings, tariffs and bills the user gives you. You do not contact suppliers, log into accounts or give legal or financial advice. Show every assumption (meter digits, gas calorific value, which reading was dropped) and say when a figure is interpolated.
## Files in this skill
- `scripts/meter_check.py` - reads the readings CSV (plus optional tariffs and bills CSVs) and prints per-meter periods, monthly usage and cost, annual estimate, a bill check and findings UM01-UM11; `--digits meter=N` for rollover, `--spike`, `--tolerance`, `--calorific`, `--max-gap`, `--json`, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/reading-meters-and-units.md` - how to read common meters, units, rollover, estimated vs actual readings, gas m3 to kWh conversion
- `references/tariffs-and-bill-checks.md` - how to enter tariffs, how the bill check works, typical billing errors and what to ask the supplier
- `templates/usage-and-bill-report.md` - the report you hand back
- `examples/meter_readings.csv` - ten months of readings for a fictional flat with planted problems
- `examples/tariffs.csv` - electricity (with a July price rise), gas priced per kWh, water
- `examples/bills.csv` - five bills to check, one based on an over-estimate
## Workflow
### 1. Collect the readings
Ask for one row per reading: `date` (YYYY-MM-DD), `meter` (any name, e.g. `electricity`, `gas`, `water`, `ev-charger`), `reading` (the number on the display, without the red decimal digits on gas and water dials unless used consistently), optional `type` (`actual`, `customer`, `estimate`) and `note`. Readings from bills count: mark supplier estimates as `estimate`. Monthly readings on roughly the same day work best; photos of the meter are the best evidence. See `references/reading-meters-and-units.md`.
### 2. Collect tariffs and bills (optional but needed for costs)
- `tariffs.csv`: `meter,from,meter_unit,tariff_unit,unit_price,standing_per_day,vat_pct`, one row per price change. For gas measured in m3 but priced per kWh, set `meter_unit=m3`, `tariff_unit=kWh`.
- `bills.csv`: `meter,start,end,amount[,units]` with inclusive dates and the amount including tax.
- Ask how many digits the meter display has (before the decimal point) so rollovers are detected.
### 3. Run the checker
```
python3 scripts/meter_check.py examples/meter_readings.csv --tariffs examples/tariffs.csv --bills examples/bills.csv --digits electricity=5
python3 scripts/meter_check.py readings.csv --tariffs tariffs.csv --calorific 38.9 --json > usage.json
python3 scripts/meter_check.py readings.csv --spike 1.4 --tolerance 0.03
python3 scripts/meter_check.py --self-test
```
Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, follow the formulas in `references/tariffs-and-bill-checks.md`: usage = later reading - earlier reading, prorate by days, cost = (units x unit price + days x standing charge) x (1 + VAT).
### 4. Fix the data first
- UM01 unreadable row, UM02 reading lower than the previous one (typo or wrong meter, ignored), UM06 two different readings on the same day (actual beats customer beats estimate), UM09 rollover assumed (check the digit count), UM07 long gap between readings (monthly numbers are interpolated).
- UM03 an estimate that was higher than the next actual reading: the estimate is dropped and the bills based on it overcharged.
- Ask the user to confirm each correction, then re-run.
### 5. Read usage and bills
- UM04 a period whose daily use is well above the recent periods; UM05 high use for the last two periods in a row: on water this is the classic leak signal (running toilet, dripping tap, outdoor pipe), on electricity a new appliance, heater or faulty fridge.
- UM10 a bill more than the tolerance above (high) or below (medium, a catch-up bill will follow) what readings and tariff imply; compare billed units with reading units to see whether the price or the reading is wrong.
- UM08 a bill that ends on an estimated reading; UM11 a bill that cannot be checked (outside the readings or no tariff).
- Seasonal patterns are normal for gas heating: compare with the same months last year if the user has them.
### 6. Deliver
Fill `templates/usage-and-bill-report.md`: usage and cost per meter, the bill check table, data corrections, problems found, money at stake, and next steps (submit an actual reading and ask for a re-bill, do a leak test, check the tariff). Use the user's currency and units; round money to 2 decimals.
## Example result
On the example files the checker uses 8 of 10 electricity readings: the 89650 typed from memory is ignored (UM02, high) and the April supplier estimate of 98650 is dropped because the May actual was 98500 (UM03). The 00050 in October is read as a rollover of the 5-digit display (UM09). The March-April electricity bill charged 760 kWh, 237.62, but the readings imply 305 kWh, 103.85: an overcharge of 133.77 (UM10 high, UM08). The June-July bill correctly splits the 1 July price rise. Gas has two different readings on 4 July; the actual 5085.5 is kept (UM06). Water jumped from about 0.35 to 0.66-0.68 m3/day in the last two months (UM04 twice, UM05 high): a probable leak costing about 0.67 per day (0.32 m3 x 2.10). Result: 3 high, 5 medium, 1 low.
## Rules
- Never invent readings; interpolate only between real readings and say so.
- Prefer actual readings over estimates; recommend submitting a reading before every bill date.
- Explain rollover and digit assumptions before correcting usage by a power of ten.
- Gas conversion uses volume correction 1.02264 and the calorific value from the user's bill (default 39.5 MJ/m3); say which value you used.
- Do not tell the user to stop paying a bill; suggest disputing it with the supplier with the evidence.
- Leak suspicion is a prompt to test (meter reading before and after a no-use period), not a diagnosis.
FILE:references/reading-meters-and-units.md
# Reading meters and units
## Reading the display
- **Digital electricity meters**: press the display button until the cumulative import register appears (often labelled `1.8.0`, `IMP` or `kWh`). Ignore instantaneous kW values. Day/night (two-rate) meters have two registers: use two meter names, e.g. `electricity-day` and `electricity-night`.
- **Smart meters**: readings are sent automatically, but bills can still be estimated when the communication fails; check the bill says "actual" or "smart".
- **Gas meters**: read the black digits from left to right; ignore the red digits after the decimal point (or include them every time, consistently). Older imperial meters show hundreds of cubic feet; multiply by 2.83 to get m3.
- **Water meters**: black digits are m3; red dials are litres. A slowly turning star or triangle with every tap closed is a leak indicator.
- **Dial meters**: read each dial; if a pointer is between two numbers, take the lower one.
## Digits and rollover
A meter with 5 digits before the decimal point goes from 99999 to 00000. If a reading is much lower than the previous one and the previous one was close to the maximum, it is a rollover, not a typo. Pass `--digits meter=5`. Without `--digits`, any backwards reading is treated as an error (UM02).
## Reading types
- `actual`: read by the supplier or a smart meter.
- `customer`: read and submitted by you (as good as actual if it comes with a photo).
- `estimate`: calculated by the supplier. Estimates are often based on last winter or on a national average and can be far off. When a later actual reading is lower, the estimate was too high and every bill since overcharged you (UM03).
## Units
| Meter | Display unit | Usually priced in |
|---|---|---|
| Electricity | kWh | kWh |
| Gas | m3 (or 100 ft3) | kWh (UK, EU) or m3 / therms (some countries) |
| Water | m3 | m3 (often water + wastewater charges) |
| Heat / district heating | kWh or MWh | kWh |
## Gas m3 to kWh
kWh = m3 x volume correction (1.02264) x calorific value (MJ/m3, printed on the bill, typically 37.5-43) / 3.6. The script uses `--calorific 39.5` by default. For therms: 1 therm = 29.3071 kWh.
## Good habits
Read all meters on the same day every month, photograph the display, and submit the reading to the supplier a day or two before the bill date.
FILE:references/tariffs-and-bill-checks.md
# Tariffs and bill checks
## Entering tariffs
One row per meter and price period in `tariffs.csv`:
| column | meaning |
|---|---|
| `meter` | same name as in the readings |
| `from` | first day the price applies (YYYY-MM-DD) |
| `meter_unit` / `tariff_unit` | e.g. `kWh`/`kWh`, `m3`/`kWh` for gas, `m3`/`m3` for water |
| `unit_price` | price per tariff unit, before tax |
| `standing_per_day` | fixed daily charge, before tax (0 if none; convert monthly fees: x12/365) |
| `vat_pct` | VAT or sales tax percent on the energy bill (e.g. 5, 20, 0) |
Water bills with separate fresh-water and wastewater prices: add them into one `unit_price`, or use two meter names with the same readings.
## How the bill check works
1. The bill covers `start` to `end` inclusive, so usage is measured from the reading at the start date to the reading at the day after `end`.
2. Readings on those exact days are rarely available, so the script interpolates linearly between the nearest real readings.
3. If a price change falls inside the bill, the period is split at the change date and each part is priced with its own tariff.
4. Expected cost = sum over parts of (units x unit price + days x standing charge) x (1 + VAT).
5. The bill is flagged (UM10) when it differs by more than `--tolerance` (default 5%). Above = possible overcharge (high), below = likely undercharge followed by a catch-up bill (medium).
Small differences (under 2-3%) usually come from interpolation, rounding, or a slightly different calorific value. Large differences almost always come from an estimated reading, a wrong price period, a missed price change, or the wrong meter number on the account.
## Typical billing errors
- Bill based on an estimate that was too high (UM03 + UM08 + UM10).
- New price applied to the whole period instead of from the change date.
- Wrong meter serial number on the account (your usage does not match the bill at all).
- Standing charge for days outside your tenancy (move-in/move-out bills).
- Two-rate meter registers swapped (night units priced as day units).
## What to send the supplier
The meter serial number, dated photos of the readings, the period and the difference you calculated, and a request to re-bill on actual readings. Keep it short and factual; ask for a corrected statement and a refund or credit of the overcharge.
## Leak test (water)
Close every tap and appliance, read the meter, wait 1-2 hours without using water, read again. Any movement means a leak; repeat with the toilet supply valve closed to see whether the toilet is the cause.
FILE:templates/usage-and-bill-report.md
# Utility usage and bill check: [address / business], [period]
**Meters:** [electricity, gas, water] **Readings used:** [n of m] **Currency:** [ ]
**Tool:** `meter_check.py` (output attached) **Assumptions:** [digits, calorific value, tolerance]
## Usage and cost
| Meter | Avg per day | Last month | Last month cost | Annual estimate | Annual cost (latest tariff) |
|---|---|---|---|---|---|
| [electricity] | [10.6 kWh] | | | | |
## Bill check
| Meter | Bill period | Billed | Expected from readings | Difference | Billed units vs readings | Verdict |
|---|---|---|---|---|---|---|
| [electricity] | [2026-03-06..2026-04-04] | [237.62] | [103.85] | [+128.8%] | [760 vs 305] | [overcharge, based on estimate] |
## Data corrections
| Meter | Reading | Problem | What we did |
|---|---|---|---|
| [electricity] | [89650 on 2026-07-04] | [lower than previous] | [ignored; please re-check the photo] |
## Problems found
1. [Overcharge / leak / spike, with the evidence and money at stake]
2. [...]
## Next steps
1. [Submit an actual reading with photo and ask the supplier to re-bill period X]
2. [Run the leak test in the water meter guide]
3. [Read all meters on the same day each month]
_Figures between readings are interpolated. This is a usage check, not legal or financial advice._
FILE:examples/meter_readings.csv
date,meter,reading,type,note
2026-01-05,electricity,97200,actual,moved in reading
2026-02-04,electricity,97560,actual,
2026-03-06,electricity,97890,actual,
2026-04-05,electricity,98650,estimate,supplier estimate
2026-05-05,electricity,98500,actual,photo of meter
2026-06-04,electricity,98800,actual,
2026-07-04,electricity,89650,actual,typed from memory
2026-08-03,electricity,99400,actual,
2026-09-02,electricity,99720,actual,
2026-10-02,electricity,00050,actual,display wrapped to 0
2026-01-05,gas,4520.0,actual,
2026-02-04,gas,4690.5,actual,
2026-03-06,gas,4840.2,actual,
2026-04-05,gas,4950.0,actual,
2026-05-05,gas,5020.3,actual,
2026-06-04,gas,5060.0,actual,
2026-07-04,gas,5085.5,actual,
2026-07-04,gas,5058.5,customer,second photo (digits swapped?)
2026-08-03,gas,5110.0,actual,
2026-09-02,gas,5134.2,actual,
2026-10-02,gas,5165.0,actual,
2026-01-05,water,812.4,actual,
2026-02-04,water,822.1,actual,
2026-03-06,water,831.6,actual,
2026-04-05,water,841.0,actual,
2026-05-05,water,851.2,actual,
2026-06-04,water,861.5,actual,
2026-07-04,water,872.4,actual,
2026-08-03,water,883.0,actual,
2026-09-02,water,902.8,actual,
2026-10-02,water,923.1,actual,toilet keeps running?
FILE:examples/tariffs.csv
meter,from,meter_unit,tariff_unit,unit_price,standing_per_day,vat_pct
electricity,2026-01-01,kWh,kWh,0.28,0.45,5
electricity,2026-07-01,kWh,kWh,0.31,0.45,5
gas,2026-01-01,m3,kWh,0.07,0.30,5
water,2026-01-01,m3,m3,2.10,0.15,0
FILE:examples/bills.csv
meter,start,end,amount,units
electricity,2026-01-05,2026-02-03,120.02,360
electricity,2026-03-06,2026-04-04,237.62,760
electricity,2026-06-04,2026-07-03,103.32,300
gas,2026-01-05,2026-03-05,283.10,
water,2026-07-04,2026-10-01,119.97,50.7
FILE:scripts/meter_check.py
#!/usr/bin/env python3
"""Utility meter reading and bill checker (offline, Python 3.8+ standard library only).
Reads household or small-business meter readings (electricity, gas, water or any cumulative
meter), cleans them (backwards readings, typos, meter rollover, over-estimates, conflicting
duplicates), works out usage per period and per calendar month, prices it with your tariffs
(unit price, daily standing charge, VAT/sales tax, price changes, gas m3 -> kWh) and checks
each bill against what the readings imply. Flags spikes and sustained rises (leaks).
Usage:
meter_check.py readings.csv [--tariffs tariffs.csv] [--bills bills.csv] [--digits electricity=5]
[--spike 1.6] [--tolerance 0.05] [--calorific 39.5] [--max-gap 70] [--json]
meter_check.py --self-test
readings.csv: date,meter,reading[,type][,note] type = actual (default) | estimate | customer
tariffs.csv: meter,from,meter_unit,tariff_unit,unit_price,standing_per_day,vat_pct
bills.csv: meter,start,end,amount[,units] start/end inclusive, amount incl. tax
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, csv, json, statistics, sys
from collections import OrderedDict
from datetime import date, timedelta
SEV = {"high": 0, "medium": 1, "low": 2}
VOLUME_CORRECTION = 1.02264
RANK = {"actual": 0, "customer": 1, "estimate": 2} # preferred reading on the same day
def d(s):
return date.fromisoformat(s.strip())
def num(s):
return float(str(s).replace(",", "").strip())
def read_csv(path):
with open(path, newline="", encoding="utf-8-sig") as f:
return [(i, {(k or "").strip().lower(): (v or "").strip() for k, v in r.items()}) for i, r in enumerate(csv.DictReader(f), 2)]
class Report:
def __init__(self):
self.findings = []
def add(self, code, sev, meter, msg, when=None):
self.findings.append({"code": code, "severity": sev, "meter": meter, "date": str(when) if when else "", "message": msg})
def clean_meter(meter, rows, rep, digits=None):
"""rows: list of (line, date, reading, type). Returns cleaned [(date, cumulative, type, raw)]."""
by_date = OrderedDict()
for line, dt, val, typ in sorted(rows, key=lambda r: (r[1], r[0])):
if dt in by_date:
prev = by_date[dt]
keep = prev if RANK[prev[3]] < RANK[typ] else (line, dt, val, typ)
if abs(prev[2] - val) > 1e-9:
rep.add("UM06", "medium", meter, "lines %d/%d: two readings on %s (%g and %g); kept %g (%s)" % (prev[0], line, dt, prev[2], val, keep[2], keep[3]), dt)
by_date[dt] = keep
continue
by_date[dt] = (line, dt, val, typ)
rows = list(by_date.values())
out, offset = [], 0.0
span = 10 ** digits if digits else None
for line, dt, val, typ in rows:
cum = val + offset
if out and cum < out[-1][1]:
last = out[-1]
if span and last[3] >= 0.9 * span and val <= 0.1 * span:
offset += span
cum = val + offset
rep.add("UM09", "low", meter, "line %d: %g after %g read as a %d-digit meter rollover" % (line, val, last[3], digits), dt)
elif last[2] == "estimate" and typ != "estimate":
rep.add("UM03", "medium", meter, "estimated reading %g on %s was higher than the actual %g on %s: bills based on it overcharged, a credit is due"
% (last[3], last[0], val, dt), last[0])
out.pop()
while out and cum < out[-1][1]:
out.pop()
else:
rep.add("UM02", "high", meter, "line %d: reading %g on %s is lower than %g on %s (typo, swapped digits or wrong meter?); ignored"
% (line, val, dt, last[3], last[0]), dt)
continue
out.append((dt, cum, typ, val))
return out
def at(series, when):
"""Cumulative reading at a date by linear interpolation, or None outside the readings."""
if not series or when < series[0][0] or when > series[-1][0]:
return None
for (d0, c0, *_), (d1, c1, *_) in zip(series, series[1:]):
if d0 <= when <= d1:
span = (d1 - d0).days
return c0 if span == 0 else c0 + (c1 - c0) * (when - d0).days / span
return series[-1][1]
def periods(meter, series, rep, spike=1.6, max_gap=70):
ps = []
for (d0, c0, t0, _), (d1, c1, t1, _) in zip(series, series[1:]):
days = (d1 - d0).days
ps.append({"start": str(d0), "end": str(d1), "days": days, "units": round(c1 - c0, 3),
"per_day": round((c1 - c0) / days, 3) if days else 0.0, "estimate": "estimate" in (t0, t1)})
if days > max_gap:
rep.add("UM07", "low", meter, "%d days between readings %s and %s: monthly figures are interpolated" % (days, d0, d1), d0)
flagged = []
for i, p in enumerate(ps):
hist = [q["per_day"] for q in ps[max(0, i - 3):i]]
if len(hist) >= 2:
base = statistics.median(hist)
if base > 0 and p["per_day"] > spike * base:
flagged.append(i)
rep.add("UM04", "medium", meter, "%s to %s: %.2f/day is %.1fx the recent %.2f/day" % (p["start"], p["end"], p["per_day"], p["per_day"] / base, base), p["start"])
if len(flagged) >= 2 and flagged[-1] == len(ps) - 1 and flagged[-2] == len(ps) - 2:
rep.add("UM05", "high", meter, "usage stayed high for the last two periods (since %s): check for a leak, a faulty appliance or a meter fault" % ps[-2]["start"], ps[-2]["start"])
return ps
def load_tariffs(path):
t = {}
for line, r in read_csv(path):
try:
t.setdefault(r["meter"].lower(), []).append({"from": d(r["from"]), "meter_unit": r.get("meter_unit", "") or "unit",
"tariff_unit": r.get("tariff_unit", "") or r.get("meter_unit", "") or "unit", "unit_price": num(r["unit_price"]),
"standing": num(r.get("standing_per_day") or 0), "vat": num(r.get("vat_pct") or 0) / 100})
except (KeyError, ValueError) as e:
raise ValueError("tariffs line %d: %s" % (line, e))
for v in t.values():
v.sort(key=lambda x: x["from"])
return t
def convert(units, tar, calorific):
if tar["meter_unit"].lower() in ("m3", "m³") and tar["tariff_unit"].lower() == "kwh":
return units * VOLUME_CORRECTION * calorific / 3.6
return units
def cost(series, tariffs, start, end_excl, calorific):
"""Units (in tariff unit) and cost incl. tax for [start, end_excl), split at tariff changes."""
if not tariffs:
return None
cuts = sorted({start, end_excl} | {t["from"] for t in tariffs if start < t["from"] < end_excl})
total_units = total_cost = 0.0
for a, b in zip(cuts, cuts[1:]):
ca, cb = at(series, a), at(series, b)
if ca is None or cb is None:
return None
act = [t for t in tariffs if t["from"] <= a]
if not act:
return None
tar = act[-1]
u = convert(cb - ca, tar, calorific)
total_units += u
total_cost += (u * tar["unit_price"] + (b - a).days * tar["standing"]) * (1 + tar["vat"])
return round(total_units, 2), round(total_cost, 2)
def month_starts(a, b):
m = date(a.year, a.month, 1)
while m <= b:
yield m
m = date(m.year + (m.month == 12), 1 if m.month == 12 else m.month + 1, 1)
def analyse(readings, tariffs=None, bills=None, digits=None, spike=1.6, tolerance=0.05, calorific=39.5, max_gap=70):
rep, digits, tariffs = Report(), digits or {}, tariffs or {}
raw = OrderedDict()
for line, r in readings:
try:
dt, meter, val = d(r["date"]), r["meter"].lower(), num(r["reading"])
typ = (r.get("type") or "actual").lower()
if val < 0 or typ not in ("actual", "estimate", "customer"):
raise ValueError("negative reading or unknown type %r" % typ)
except (KeyError, ValueError) as e:
rep.add("UM01", "medium", r.get("meter", "?"), "readings line %d unreadable: %s" % (line, e))
continue
raw.setdefault(meter, []).append((line, dt, val, typ))
out = OrderedDict()
for meter, rows in raw.items():
series = clean_meter(meter, rows, rep, digits.get(meter))
ps = periods(meter, series, rep, spike, max_gap)
tar = tariffs.get(meter, [])
months = []
if len(series) >= 2:
for m in month_starts(series[0][0], series[-1][0]):
nxt = date(m.year + (m.month == 12), 1 if m.month == 12 else m.month + 1, 1)
a, b = at(series, m), at(series, nxt)
if a is None or b is None:
continue
c = cost(series, tar, m, nxt, calorific)
months.append({"month": m.strftime("%Y-%m"), "units": round(b - a, 2), "billed_units": c[0] if c else None, "cost": c[1] if c else None})
span = (series[-1][0] - series[0][0]).days if len(series) >= 2 else 0
per_day = (series[-1][1] - series[0][1]) / span if span else 0
yr = None
if span and tar:
t = tar[-1]
yu = convert(per_day * 365, t, calorific)
yr = round((yu * t["unit_price"] + 365 * t["standing"]) * (1 + t["vat"]), 2)
out[meter] = {"readings_used": len(series), "periods": ps, "months": months, "avg_per_day": round(per_day, 3),
"annual_units": round(per_day * 365, 1), "annual_cost_at_latest_tariff": yr,
"unit": (tar[-1]["meter_unit"] if tar else "units"), "_series": series}
checks = []
for line, b in bills or []:
try:
meter, s, e, amt = b["meter"].lower(), d(b["start"]), d(b["end"]), num(b["amount"])
except (KeyError, ValueError) as ex:
rep.add("UM01", "medium", b.get("meter", "?"), "bills line %d unreadable: %s" % (line, ex)); continue
series = out.get(meter, {}).get("_series", [])
c = cost(series, tariffs.get(meter, []), s, e + timedelta(days=1), calorific)
row = {"meter": meter, "start": str(s), "end": str(e), "billed": amt, "expected": c[1] if c else None,
"expected_units": c[0] if c else None, "billed_units": num(b["units"]) if b.get("units") else None, "diff_pct": None}
checks.append(row)
if c is None:
rep.add("UM11", "low", meter, "bill %s to %s cannot be checked: outside the readings or no tariff" % (s, e), s); continue
row["diff_pct"] = round((amt - c[1]) / c[1] * 100, 1) if c[1] else None
est = [x for x in series if s <= x[0] <= e + timedelta(days=1) and x[2] == "estimate"]
dropped = [f for f in rep.findings if f["code"] == "UM03" and f["meter"] == meter and s <= d(f["date"]) <= e + timedelta(days=1)]
if est or dropped:
rep.add("UM08", "medium", meter, "bill %s to %s ends on or spans an estimated reading: ask for a bill on an actual reading" % (s, e), s)
if row["diff_pct"] is not None and abs(row["diff_pct"]) > tolerance * 100:
over = row["diff_pct"] > 0
rep.add("UM10", "high" if over else "medium", meter, "bill %s to %s is %.2f, readings and tariff imply %.2f (%+.1f%%)%s"
% (s, e, amt, c[1], row["diff_pct"], "" if over else ": undercharged now, expect a catch-up bill"), s)
for m in out.values():
m.pop("_series")
fs = sorted(rep.findings, key=lambda f: (SEV[f["severity"]], f["code"], f["meter"], f["date"]))
return {"meters": out, "bills": checks, "findings": fs,
"counts": {k: sum(f["severity"] == k for f in fs) for k in SEV}}
def print_text(r):
for meter, m in r["meters"].items():
print("== %s (%s): %d readings used, %.3f %s/day, ~%.0f %s/year%s" % (meter, m["unit"], m["readings_used"], m["avg_per_day"], m["unit"],
m["annual_units"], m["unit"], (", ~%.2f/year at latest tariff" % m["annual_cost_at_latest_tariff"]) if m["annual_cost_at_latest_tariff"] else ""))
print(" period days units per_day")
for p in m["periods"]:
print(" %s .. %s %4d %9.2f %9.3f%s" % (p["start"], p["end"], p["days"], p["units"], p["per_day"], " (estimate)" if p["estimate"] else ""))
if m["months"]:
print(" month units priced_units cost")
for x in m["months"]:
print(" %s %8.2f %14s %9s" % (x["month"], x["units"], "-" if x["billed_units"] is None else "%.2f" % x["billed_units"],
"-" if x["cost"] is None else "%.2f" % x["cost"]))
if r["bills"]:
print("\nBill check")
for b in r["bills"]:
units = ""
if b["billed_units"] is not None and b["expected_units"] is not None:
units = " units billed %g vs readings %g" % (b["billed_units"], b["expected_units"])
print(" %-12s %s..%s billed %8.2f expected %8s %7s%s" % (b["meter"], b["start"], b["end"], b["billed"],
"-" if b["expected"] is None else "%.2f" % b["expected"], "-" if b["diff_pct"] is None else "%+.1f%%" % b["diff_pct"], units))
c = r["counts"]
print("\nFindings: %d high, %d medium, %d low" % (c["high"], c["medium"], c["low"]))
for f in r["findings"]:
print(" [%s] %s %s %s: %s" % (f["severity"].upper(), f["code"], f["meter"], f["date"], f["message"]))
def self_test():
tests = []
def t(name, cond):
tests.append((name, bool(cond)))
def R(*rows):
return [(i + 2, dict(zip(("date", "meter", "reading", "type"), r))) for i, r in enumerate(rows)]
def codes(res):
return [f["code"] for f in res["findings"]]
a = analyse(R(("2026-01-01", "e", "100"), ("2026-01-11", "e", "200"), ("2026-01-21", "e", "300")))
t("per-day usage", a["meters"]["e"]["periods"][0]["per_day"] == 10 and a["meters"]["e"]["avg_per_day"] == 10)
t("interpolation", abs(at([(date(2026, 1, 1), 0, "actual", 0), (date(2026, 1, 11), 100, "actual", 100)], date(2026, 1, 6)) - 50) < 1e-9)
b = analyse(R(("2026-01-01", "e", "99900"), ("2026-01-11", "e", "50")), digits={"e": 5})
t("rollover with --digits", b["meters"]["e"]["periods"][0]["units"] == 150 and "UM09" in codes(b))
c = analyse(R(("2026-01-01", "e", "1000"), ("2026-01-11", "e", "1100"), ("2026-01-21", "e", "110"), ("2026-01-31", "e", "1300")))
t("backwards reading ignored", "UM02" in codes(c) and c["meters"]["e"]["readings_used"] == 3)
e = analyse(R(("2026-01-01", "e", "1000"), ("2026-02-01", "e", "1500", "estimate"), ("2026-03-01", "e", "1400")))
t("over-estimate dropped", "UM03" in codes(e) and e["meters"]["e"]["readings_used"] == 2)
f = analyse(R(("2026-01-01", "w", "10"), ("2026-01-01", "w", "11"), ("2026-01-11", "w", "20")))
t("conflicting duplicate", "UM06" in codes(f))
f2 = analyse(R(("2026-01-01", "w", "10"), ("2026-01-11", "w", "20", "actual"), ("2026-01-11", "w", "02", "customer")))
t("duplicate keeps actual over customer", f2["meters"]["w"]["periods"][0]["units"] == 10)
g = analyse(R(*[("2026-%02d-01" % m, "w", str(v)) for m, v in zip(range(1, 8), (0, 10, 20, 30, 40, 60, 80))]))
t("spike + sustained rise -> leak", codes(g).count("UM04") == 2 and "UM05" in codes(g))
tar = {"e": [{"from": date(2026, 1, 1), "meter_unit": "kWh", "tariff_unit": "kWh", "unit_price": 0.2, "standing": 0.5, "vat": 0.1}]}
s = [(date(2026, 1, 1), 0, "actual", 0), (date(2026, 1, 11), 100, "actual", 100)]
t("cost = (units*price + days*standing)*(1+vat)", cost(s, tar["e"], date(2026, 1, 1), date(2026, 1, 11), 39.5) == (100, 27.5))
tar2 = [{"from": date(2026, 1, 1), "meter_unit": "kWh", "tariff_unit": "kWh", "unit_price": 0.2, "standing": 0, "vat": 0},
{"from": date(2026, 1, 6), "meter_unit": "kWh", "tariff_unit": "kWh", "unit_price": 0.4, "standing": 0, "vat": 0}]
t("price change split by date", cost(s, tar2, date(2026, 1, 1), date(2026, 1, 11), 39.5)[1] == 30.0)
gas = [{"from": date(2026, 1, 1), "meter_unit": "m3", "tariff_unit": "kWh", "unit_price": 1, "standing": 0, "vat": 0}]
t("gas m3 -> kWh", abs(cost(s, gas, date(2026, 1, 1), date(2026, 1, 11), 39.5)[0] - 100 * 1.02264 * 39.5 / 3.6) < 0.01)
bills = [(2, {"meter": "e", "start": "2026-01-01", "end": "2026-01-10", "amount": "27.50"}), (3, {"meter": "e", "start": "2026-01-01", "end": "2026-01-10", "amount": "40"}),
(4, {"meter": "e", "start": "2025-12-01", "end": "2025-12-31", "amount": "9"})]
h = analyse(R(("2026-01-01", "e", "0"), ("2026-01-11", "e", "100")), tariffs=tar, bills=bills)
t("matching bill passes", h["bills"][0]["diff_pct"] == 0.0)
t("overcharge flagged high", any(x["code"] == "UM10" and x["severity"] == "high" for x in h["findings"]))
t("bill outside readings -> UM11", "UM11" in codes(h))
i = analyse(R(("2026-01-01", "e", "0"), ("2026-01-31", "e", "100", "estimate")), tariffs=tar, bills=[(2, {"meter": "e", "start": "2026-01-01", "end": "2026-01-30", "amount": "1"})])
t("bill on estimate -> UM08", "UM08" in codes(i))
j = analyse(R(("2026-01-01", "e", "0"), ("2026-03-01", "e", "590")))
t("monthly split by interpolation", [m["units"] for m in j["meters"]["e"]["months"]] == [310.0, 280.0])
k = analyse(R(("2026-13-01", "e", "1"), ("2026-01-01", "e", "-5")))
t("bad rows -> UM01", codes(k).count("UM01") == 2)
l = analyse(R(("2026-01-01", "e", "0"), ("2026-04-01", "e", "90")))
t("long gap -> UM07", "UM07" in codes(l))
ok = 0
for name, c in tests:
print("%s %s" % ("PASS" if c else "FAIL", name)); ok += c
print("%d/%d passed" % (ok, len(tests)))
return 0 if ok == len(tests) else 1
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("readings", nargs="?"); ap.add_argument("--tariffs"); ap.add_argument("--bills")
ap.add_argument("--digits", action="append", default=[], help="meter=N, e.g. electricity=5")
ap.add_argument("--spike", type=float, default=1.6); ap.add_argument("--tolerance", type=float, default=0.05)
ap.add_argument("--calorific", type=float, default=39.5); ap.add_argument("--max-gap", type=int, default=70)
ap.add_argument("--json", action="store_true"); ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.readings:
ap.print_usage(); return 2
try:
digits = {k.strip().lower(): int(v) for k, v in (x.split("=", 1) for x in a.digits)}
readings = read_csv(a.readings)
tariffs = load_tariffs(a.tariffs) if a.tariffs else {}
bills = read_csv(a.bills) if a.bills else []
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr); return 2
if not readings:
print("error: no readings", file=sys.stderr); return 2
r = analyse(readings, tariffs, bills, digits, a.spike, a.tolerance, a.calorific, a.max_gap)
print(json.dumps(r, indent=2)) if a.json else print_text(r)
return 1 if r["counts"]["high"] else 0
if __name__ == "__main__":
sys.exit(main())
Scans plain or JSON-lines logs for data that must never be logged: Luhn-valid cards, IBANs, SSNs, API keys, JWTs, auth headers, passwords, URL tokens, emails, phones, birth dates and public IPs. Masks every value, ranks the loggers to fix and writes a redacted copy. Offline stdlib Python.
---
name: log-pii-and-secret-redaction-checker
description: Scans plain or JSON-lines logs for data that must never be logged: Luhn-valid cards, IBANs, SSNs, API keys, JWTs, auth headers, passwords, URL tokens, emails, phones, birth dates and public IPs. Masks every value, ranks the loggers to fix and writes a redacted copy. Offline stdlib Python.
---
# Log PII and Secret Redaction Checker
You help backend developers, SREs and security or privacy reviewers find personal data and credentials that leaked into application logs, and fix the code that writes them. Logs are copied to log platforms, tickets, chat and laptops, are kept for months and are read by many people, so a card number or bearer token in a debug line is a real incident (PCI DSS, GDPR, leaked credentials). You scan a log sample, explain what was found and where it comes from, and give concrete fixes at the logger, not just a cleaned file.
You work only on the log text the user provides, on their machine. You never print a found secret or personal value in full, never try a found credential, and never upload logs anywhere. Treat any real secret you find as compromised: tell the user to rotate it.
## Files in this skill
- `scripts/log_redaction_check.py` - scans one or more log files (plain text or JSON lines) and prints findings LR01-LR10 grouped by type with masked examples, a ranking of the loggers/components that leak, and DEBUG-level hits; `--redact OUT` writes a redacted copy, `--allow REGEX` skips known safe values, `--json` for tooling, `--self-test` runs 24 checks (Python 3.8+ standard library only)
- `references/detection-rules.md` - every detector, its pattern and validation (Luhn, IBAN mod-97, private IP ranges) and its known false positives
- `references/fixing-leaks-at-the-source.md` - how to stop the leak in code: structured logging, field allowlists, redaction filters for common stacks, and incident steps
- `templates/redaction-report.md` - the report you hand back
- `examples/app.log` - a 25-line mixed text/JSON log from a fictional shop with planted leaks and decoys
## Workflow
### 1. Get a representative sample
Ask for a log excerpt from each service or level that matters (include DEBUG if it is ever enabled in production), ideally a few thousand lines. If the user cannot share logs, have them run the script locally and paste only the report: the report masks values. Ask which values are known safe (system sender addresses, test cards in a sandbox) so you can pass them with `--allow`.
### 2. Run the checker
```
python3 scripts/log_redaction_check.py examples/app.log
python3 scripts/log_redaction_check.py api.log worker.log --allow '^noreply@example\.com$'
python3 scripts/log_redaction_check.py app.log --redact app.redacted.log --json > findings.json
python3 scripts/log_redaction_check.py --self-test
```
Exit 0 = no high findings, 1 = high findings, 2 = bad input. Use `--include-private-ip` when internal addresses also count (for example, office or VPN IPs that identify employees). Without a shell, apply `references/detection-rules.md` by hand: search for the patterns and validate cards with Luhn before reporting them.
### 3. Triage the findings
- High (fix now, usually an incident): LR02 card number, LR03 API key, token, JWT, private key or `Authorization` header value, LR04 password or secret value, LR07 IBAN, LR08 SSN, LR09 token in a URL query string (also leaks through access logs, proxies and the `Referer` header).
- Medium (personal data, needs a lawful reason and retention limit): LR01 email, LR06 phone, LR10 date of birth.
- Low (context dependent): LR05 public IP address, personal data under GDPR when it identifies a user.
- Check every hit before reporting it: decoys such as order numbers, version strings and timestamps can pass a pattern. Mark false positives and re-run with `--allow`.
- Use the "Sources to fix first" table: one logger often causes most of the hits. DEBUG-level hits mean request or payload dumping.
### 4. Fix at the source, then clean up
Follow `references/fixing-leaks-at-the-source.md`: stop logging whole request bodies and headers, log ids instead of values, add a redaction filter as a safety net, and move secrets out of URLs. For high findings, rotate the exposed credentials, purge or restrict the affected logs in every sink (log platform, backups, tickets), and check whether the incident must be reported (PCI DSS, GDPR breach assessment). `--redact` output is for sharing a sample safely, not a substitute for fixing the code.
### 5. Deliver
Fill `templates/redaction-report.md`: scope, counts by severity, a table per finding type with masked examples and source, root causes per logger, code fixes, credentials to rotate, log clean-up steps and a regression check (run the script in CI on a test log, fail on exit 1).
## Example result
On `examples/app.log` the checker finds 20 hits in 25 lines: 11 high, 7 medium, 2 low.
- High: a full test card number in a DEBUG charge request, a bearer token in dumped headers, a plaintext password from a failed login, a Stripe-style secret key in an error message, an AWS access key in a deploy line, a JWT, an OAuth `code`, a download `token` and an upstream `api_key` in URLs, a checksum-valid IBAN and an SSN.
- Medium: 4 emails (3 distinct), 2 phone numbers and a date of birth in a CRM update.
- Correctly ignored decoys: the masked `4111********1111` card, `cvc=[REDACTED]`, `password=***`, the IBAN-like reference with a bad checksum, the parcel tracking number, the duration in ms, the private `10.0.3.14` and `build 1.2.3.4`.
- With `--allow '^noreply@'` the system sender address drops out (19 hits). `auth` is the leakiest logger (5 hits) and 3 hits sit in DEBUG lines.
## Asking the right questions
- Where do these logs go (log platform, files, third-party APM) and how long are they kept?
- Is DEBUG ever enabled in production, even temporarily?
- Which values are test data (sandbox cards, example.com addresses) and may be allowlisted?
- Who owns each logger in the "Sources to fix first" table?
## Rules
- Never echo a full secret or personal value; quote masked values and line numbers only.
- Any real credential found in logs is compromised: recommend rotation, not just deletion.
- Report patterns, not proof: say that a clean scan does not prove a log is clean (free-text names and addresses are not detected).
- Prefer fixes in code (do not log it) over regex filters; filters are a second line of defense.
- Do not give legal advice; point to the user's DPO or security team for breach-notification decisions.
FILE:references/detection-rules.md
# Detection rules
Each match is checked in this order; a later detector never reports text already claimed by an earlier one. Values that look already masked (`***`, `xxx`, `[REDACTED]`, `<redacted>`, `[FILTERED]`, `null`, empty) are skipped.
| Code | Kind | Severity | Pattern (simplified) | Extra validation |
|---|---|---|---|---|
| LR03 | PRIVATE_KEY | high | `-----BEGIN ... PRIVATE KEY-----` | none |
| LR09 | URL_TOKEN | high | `?` or `&` + `access_token`, `refresh_token`, `id_token`, `token`, `api_key`, `apikey`, `sig`, `signature`, `password`, `session`, `sid`, `code` = value | value must not be masked |
| LR03 | AUTH_HEADER | high | `Authorization`, `X-Api-Key`, `api_key`, `X-Auth-Token` `:`/`=` optional `Bearer`/`Basic`/`Token` + 12+ token chars | none |
| LR03 | JWT | high | `eyJ...` three base64url segments | none |
| LR03 | AWS_KEY | high | `AKIA`/`ASIA` + 16 upper-case letters or digits | none |
| LR03 | API_KEY | high | `sk_`/`rk_`/`pk_` + `live_`/`test_` + 16+ chars, GitHub `ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_`, Slack `xoxa-`/`xoxb-`/`xoxp-`/`xoxr-` | none |
| LR04 | PASSWORD | high | `password`, `passwd`, `pwd`, `secret`, `client_secret`, `passphrase` + `:`/`=` + value (text or JSON) | value must not be masked |
| LR10 | DOB | medium | `dob`, `date_of_birth`, `birthdate`, `birth_date`, `birthday` + a date | none |
| LR07 | IBAN | high | 2 letters, 2 digits, 11-30 more alphanumerics, spaces allowed every 4 | ISO 13616 mod-97 checksum = 1 |
| LR02 | CARD | high | 13-19 digits, optional single spaces or dashes, not part of a decimal, time or longer number | Luhn checksum, not all the same digit |
| LR08 | SSN | high | `NNN-NN-NNNN` | not 000, 666 or 9xx area; group not 00; serial not 0000 |
| LR01 | EMAIL | medium | `local@domain.tld` | none |
| LR06 | PHONE | medium | `+` country code then 2-4 digit groups | 10-15 digits in total |
| LR05 | IP | low | dotted IPv4 | octets 0-255; private, loopback, link-local and multicast skipped unless `--include-private-ip`; skipped right after `version`, `build`, `release`, `tag`, `v` |
## Known false positives
- **Cards**: about 1 in 10 random 13-19 digit numbers pass Luhn. Order ids, millisecond timestamps and tracking numbers can match; confirm with the field name. Separators inside numbers are only single spaces or dashes.
- **Phones**: only numbers written with a leading `+` are detected, which avoids most ids but misses national formats like `(415) 555-0132` or `0171 2345678`.
- **SSN**: any `123-45-6789` shape, for example some part numbers.
- **IPs**: version strings in other forms (`lib 2.10.0.1`), public IPs of your own servers.
- **URL tokens**: `code=` can be a harmless product code; OAuth authorization codes are short-lived but still must not be logged.
## Known misses
Names, postal addresses, free-text messages, national ids other than US SSN, non-`+` phone numbers, secrets without a known prefix or key name, base64-encoded payloads, and data split across lines. Combine the scan with a code review of what each log call writes.
FILE:references/fixing-leaks-at-the-source.md
# Fixing leaks at the source
## Principles
1. **Log ids, not values.** `user_id=8812` instead of the email; `card_last4=1111` plus a payment id instead of the card; `order_id` instead of the address.
2. **Allowlist fields.** Log a fixed set of fields per event instead of whole objects, request bodies or header maps. Dumping `request.headers` is the most common source of LR03 bearer tokens.
3. **Keep secrets out of URLs.** Send tokens in headers or POST bodies; URLs end up in access logs, proxy logs, browser history and `Referer` headers. For signed download links, log the path without the query string.
4. **Redaction filter as a safety net.** Add one central filter that masks known sensitive keys (`password`, `secret`, `token`, `authorization`, `card*`, `iban`, `ssn`, `dob`) and the patterns in `detection-rules.md`, before logs leave the process.
5. **DEBUG is not a free pass.** Debug logs get turned on in production during incidents. Apply the same rules.
## Stack hints
- **Python logging / structlog**: a `logging.Filter` or structlog processor that rewrites `record.msg`/event dict keys; never `logger.debug("req %s", request.__dict__)`.
- **Node (pino / winston)**: pino `redact: ["req.headers.authorization", "*.password", "card.number"]`; winston custom format.
- **Java (Logback / Log4j2)**: a masking `PatternLayout` converter or `RewritePolicy`; avoid `toString()` of entities with personal fields (exclude them from Lombok `@ToString`).
- **Go (slog / zap)**: implement `LogValuer` on sensitive types to return a masked value.
- **Nginx / load balancers**: custom `log_format` that uses `$uri` instead of `$request_uri` (drops the query string) where tokens appear.
- **Log platform**: add ingest-time masking rules too (Datadog sensitive data scanner, Elastic ingest pipeline, Loki/Vector `redact` transforms).
## When a high finding is real (incident steps)
1. Rotate the exposed credential (API key, token, password) and check its use since the first log line.
2. Fix and deploy the logging code.
3. Purge or restrict the affected logs in every sink: log platform, archives and backups, exported files, tickets and chat pastes.
4. Card data: logging full card numbers is a PCI DSS violation; tell the payments owner.
5. Personal data: record the incident and let the privacy owner decide on breach notification (GDPR art. 33 has a 72-hour clock once a reportable breach is known).
## Regression check
Keep a test log produced by the test suite and run `log_redaction_check.py test.log` in CI; fail the build on exit code 1. Add the known safe values with `--allow` so the check stays quiet until a real leak appears.
FILE:templates/redaction-report.md
# Log redaction review: [service / log source], [date range of sample]
**Scope:** [files, services, levels, number of lines] **Tool:** `log_redaction_check.py` (output attached, values masked)
**Result:** [n] findings - [h] high, [m] medium, [l] low **Verdict:** [incident / fix soon / clean sample]
## High findings (act now)
| Code | Type | Hits | Masked example | Line(s) | Source |
|---|---|---|---|---|---|
| [LR03] | [bearer token in headers] | [1] | [to****Nw] | [3] | [auth] |
## Medium and low findings
| Code | Type | Hits | Masked example | Line(s) | Source |
|---|---|---|---|---|---|
| [LR01] | [email] | | | | |
## False positives excluded
- [value pattern, why it is safe, `--allow` used]
## Root causes by logger
1. [logger] - [what it writes, e.g. dumps full request headers at DEBUG]
2. [...]
## Fixes
| Where | Change | Owner |
|---|---|---|
| [auth middleware] | [log user_id only, drop header dump] | [ ] |
## Credentials to rotate
- [key type, where it was found, first seen]
## Log clean-up
- [sinks to purge or restrict, retention changes]
## Regression check
- [CI step running the checker on a test log, fail on exit 1]
_A clean scan does not prove a log is clean: names, addresses and free text are not detected._
FILE:examples/app.log
2026-11-18T09:00:01Z INFO [web] GET /health 200 4ms from 10.0.3.14
2026-11-18T09:00:07Z INFO [auth] login ok user_id=8812 email=ana.lima@example.com ip=203.0.113.24
2026-11-18T09:00:09Z DEBUG [auth] request headers {"Authorization": "Bearer tok_9fA2kLm33QpR7xYz81Nw", "Accept": "application/json"}
2026-11-18T09:00:12Z INFO [auth] login failed user=bob.k@example.org password=Summer2026! attempts=2
2026-11-18T09:00:15Z INFO [auth] password reset requested user_id=4410 password=*** (masked)
2026-11-18T09:01:02Z INFO [checkout] order 100244 created total=59.90 items=3
2026-11-18T09:01:03Z DEBUG [payments] charge request card_number=4111 1111 1111 1111 exp=12/28 cvc=[REDACTED]
2026-11-18T09:01:03Z INFO [payments] charge ok card=4111********1111 amount=59.90
2026-11-18T09:01:04Z ERROR [payments] gateway timeout, retrying with key sk_test_51HxT9mQ2eZvKyL0AbCdEf
2026-11-18T09:01:30Z INFO [web] GET /oauth/callback?code=4/0AY0e-g7Qx2mN8&state=af31 302 from 198.51.100.77
2026-11-18T09:02:11Z INFO [web] GET /download/report.pdf?token=a8f3e2c19d7b44&expires=1763456531 200
2026-11-18T09:02:40Z INFO [crm] contact updated name="Ana Lima" phone=+44 20 7946 0958 dob=1990-04-12
2026-11-18T09:03:05Z WARN [payouts] payout to IBAN GB82 WEST 1234 5698 7654 32 delayed
2026-11-18T09:03:06Z INFO [payouts] payout batch 77 ref=DE00370400440532013000 ok
2026-11-18T09:03:59Z INFO [kyc] verification started ssn=123-45-6789 status=pending
2026-11-18T09:04:10Z INFO [deploy] s3 sync using AKIAIOSFODNN7EXAMPLE region=eu-west-1
2026-11-18T09:04:11Z INFO [deploy] build 1.2.3.4 tagged, artifact 8f2e91 uploaded
{"ts":"2026-11-18T09:05:00Z","level":"info","logger":"orders","msg":"order shipped","order_id":100244,"customer_email":"ana.lima@example.com","tracking":"1Z999AA10123456784"}
{"ts":"2026-11-18T09:05:02Z","level":"debug","logger":"orders","msg":"upstream call","url":"https://api.example.net/v2/rates?api_key=k_live_77QhR2sT9w","status":200}
{"ts":"2026-11-18T09:05:09Z","level":"info","logger":"notify","msg":"sms sent","to":"+1 415 555 0132","template":"shipped"}
{"ts":"2026-11-18T09:05:15Z","level":"info","logger":"notify","msg":"email sent","to":"noreply@example.com","template":"digest"}
{"ts":"2026-11-18T09:06:00Z","level":"error","logger":"session","msg":"token expired","jwt":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4ODEyIiwiZXhwIjoxNzYzNDU2NTMxfQ.Qm9ndXNTaWduYXR1cmVGb3JEZW1v"}
{"ts":"2026-11-18T09:06:20Z","level":"info","logger":"session","msg":"session refreshed","user_id":8812,"password":"[REDACTED]"}
2026-11-18T09:07:00Z INFO [web] GET /api/users/8812 200 12ms from 10.0.3.14
2026-11-18T09:07:45Z INFO [jobs] nightly export finished rows=18233 duration_ms=1731995000123
FILE:scripts/log_redaction_check.py
#!/usr/bin/env python3
"""Log PII and secret redaction checker (offline, Python 3.8+ standard library only).
Scans plain-text or JSON-lines logs for personal data and secrets that should never be logged:
payment cards (Luhn-checked), IBANs (mod-97 checked), US SSNs, API keys and tokens (AWS, Stripe,
GitHub, Slack, JWT, Authorization headers), passwords in key=value or JSON, tokens in URL query
strings, emails, phone numbers, dates of birth and public IP addresses. Values that are already
masked ("***", "[REDACTED]") are ignored. Every value is masked in the report; nothing is sent
anywhere. Optionally writes a redacted copy of the log.
Usage:
log_redaction_check.py app.log [more.log ...] [--json] [--redact OUT] [--allow REGEX ...]
[--include-private-ip] [--max-examples 3]
log_redaction_check.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, json, re, sys
from collections import Counter, OrderedDict, defaultdict
SEV = {"high": 0, "medium": 1, "low": 2}
REDACTED = re.compile(r"^(\*+.*|x{3,}|\[?redacted(:\w+)?\]?|<redacted>|\[filtered\]|null|none|\"\"|-|)$", re.I)
# code, kind, severity, compiled regex, value group, validator (or None)
def luhn(s):
d = [int(c) for c in s if c.isdigit()]
if not 13 <= len(d) <= 19 or len(set(d)) == 1:
return False
tot = 0
for i, n in enumerate(reversed(d)):
if i % 2:
n *= 2
n -= 9 if n > 9 else 0
tot += n
return tot % 10 == 0
def iban_ok(s):
s = s.replace(" ", "")
if not 15 <= len(s) <= 34:
return False
r = s[4:] + s[:4]
num = "".join(str(int(c, 36)) for c in r)
return int(num) % 97 == 1
def phone_ok(s):
return 10 <= sum(c.isdigit() for c in s) <= 15
def public_ip(s, include_private=False):
parts = s.split(".")
if len(parts) != 4 or any(not p.isdigit() or int(p) > 255 or (len(p) > 1 and p[0] == "0") for p in parts):
return False
a, b = int(parts[0]), int(parts[1])
private = a in (10, 127, 0) or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168) or (a == 169 and b == 254) or a >= 224
return include_private or not private
DETECTORS = [
("LR03", "PRIVATE_KEY", "high", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), 0, None),
("LR09", "URL_TOKEN", "high", re.compile(r"(?i)[?&](?:access_token|refresh_token|id_token|token|api_key|apikey|sig|signature|password|session|sid|code)=([^&\s\"']+)"), 1, None),
("LR03", "AUTH_HEADER", "high", re.compile(r"(?i)\b(?:authorization|x-api-key|api[_-]?key|x-auth-token)\b\"?\s*[:=]\s*\"?(?:bearer\s+|basic\s+|token\s+)?([A-Za-z0-9._~+/=-]{12,})"), 1, None),
("LR03", "JWT", "high", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}"), 0, None),
("LR03", "AWS_KEY", "high", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), 0, None),
("LR03", "API_KEY", "high", re.compile(r"\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{16,}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,}"), 0, None),
("LR04", "PASSWORD", "high", re.compile(r"(?i)\b(?:password|passwd|pwd|secret|client_secret|passphrase)\b\"?\s*[:=]\s*\"?([^\s\",&}]*)"), 1, None),
("LR10", "DOB", "medium", re.compile(r"(?i)\b(?:dob|date_of_birth|birth_?date|birthday)\b\"?\s*[:=]\s*\"?(\d{4}-\d{2}-\d{2}|\d{1,2}[/.]\d{1,2}[/.]\d{2,4})"), 1, None),
("LR07", "IBAN", "high", re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b"), 0, iban_ok),
("LR02", "CARD", "high", re.compile(r"(?<![\d.:-])\d(?:[ -]?\d){12,18}(?![\d.:])"), 0, luhn),
("LR08", "SSN", "high", re.compile(r"\b(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b"), 0, None),
("LR01", "EMAIL", "medium", re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"), 0, None),
("LR06", "PHONE", "medium", re.compile(r"(?<![\w+])\+\d{1,3}[ .-]?\(?\d{1,4}\)?(?:[ .-]?\d{2,4}){2,4}\b"), 0, phone_ok),
("LR05", "IP", "low", re.compile(r"(?<![\d.])(?:\d{1,3}\.){3}\d{1,3}(?![\d.])"), 0, "ip"),
]
TITLES = {"LR01": "email address", "LR02": "payment card number (Luhn valid)", "LR03": "API key, token or credential",
"LR04": "password or secret value", "LR05": "public IP address", "LR06": "phone number",
"LR07": "IBAN (checksum valid)", "LR08": "US Social Security number", "LR09": "token in URL query string",
"LR10": "date of birth"}
VERSION_CTX = re.compile(r"(?i)(version|build|release|ver|tag|\bv)[\s:=]*$")
LEVEL_RE = re.compile(r"\b(TRACE|DEBUG|INFO|WARN|WARNING|ERROR|FATAL)\b\s*[:\-]?\s*\[?([A-Za-z][\w.\-]*)\]?")
def mask(kind, v):
if kind == "CARD":
d = re.sub(r"\D", "", v)
return d[:1] + "*" * (len(d) - 5) + d[-4:]
if kind == "EMAIL":
user, _, dom = v.partition("@")
return user[:1] + "***@" + dom
if kind == "PRIVATE_KEY":
return v
if len(v) <= 6:
return "*" * len(v)
return v[:2] + "*" * min(len(v) - 4, 12) + v[-2:]
def source_of(line):
s = line.strip()
if s.startswith("{"):
try:
o = json.loads(s)
for k in ("logger", "service", "component", "module", "name"):
if isinstance(o.get(k), str):
return o[k], str(o.get("level", "")).upper()
except ValueError:
pass
m = LEVEL_RE.search(line)
if m:
return m.group(2), m.group(1).upper()
return "-", ""
def scan_line(line, allow=(), include_private_ip=False):
taken, hits = [], []
for code, kind, sev, rx, grp, val in DETECTORS:
for m in rx.finditer(line):
v = m.group(grp)
a, b = m.span(grp)
if v is None or REDACTED.match(v.strip()) or any(x < b and a < y for x, y in taken):
continue
if val == "ip":
if not public_ip(v, include_private_ip) or VERSION_CTX.search(line[max(0, a - 12):a]):
continue
elif val and not val(v):
continue
if any(r.search(v) for r in allow):
continue
taken.append((a, b))
hits.append({"code": code, "kind": kind, "severity": sev, "start": a, "end": b, "value": v})
return sorted(hits, key=lambda h: h["start"])
def redact_line(line, hits):
out = line
for h in sorted(hits, key=lambda h: -h["start"]):
out = out[:h["start"]] + "[REDACTED:%s]" % h["kind"] + out[h["end"]:]
return out
def scan(named_lines, allow=(), include_private_ip=False, max_examples=3):
findings, by_code, sources, redacted = [], OrderedDict(), defaultdict(Counter), {}
distinct = defaultdict(set)
debug_hits = 0
total_lines = 0
for name, lines in named_lines:
red = []
for i, line in enumerate(lines, 1):
total_lines += 1
hits = scan_line(line, allow, include_private_ip)
red.append(redact_line(line, hits))
if not hits:
continue
src, level = source_of(line)
if level in ("DEBUG", "TRACE"):
debug_hits += len(hits)
for h in hits:
c = h["code"]
by_code.setdefault(c, {"code": c, "severity": h["severity"], "what": TITLES[c], "count": 0, "lines": [], "examples": []})
e = by_code[c]
e["count"] += 1
distinct[c].add(h["value"])
if len(e["lines"]) < 20:
e["lines"].append("%s:%d" % (name, i))
if len(e["examples"]) < max_examples:
e["examples"].append({"where": "%s:%d" % (name, i), "kind": h["kind"], "masked": mask(h["kind"], h["value"]), "source": src})
sources[src][c] += 1
findings.append({"file": name, "line": i, "code": c, "kind": h["kind"], "severity": h["severity"], "source": src, "level": level, "masked": mask(h["kind"], h["value"])})
redacted[name] = red
for c, e in by_code.items():
e["distinct_values"] = len(distinct[c])
summary = sorted(by_code.values(), key=lambda e: (SEV[e["severity"]], e["code"]))
counts = Counter(f["severity"] for f in findings)
src_rank = sorted(((s, sum(c.values()), dict(c)) for s, c in sources.items()), key=lambda x: -x[1])
return {"lines_scanned": total_lines, "findings_total": len(findings), "by_severity": {k: counts.get(k, 0) for k in SEV},
"summary": summary, "sources": [{"source": s, "hits": n, "codes": c} for s, n, c in src_rank],
"debug_level_hits": debug_hits, "findings": findings, "redacted": redacted}
def print_text(rep):
print("Scanned %d lines: %d findings (%d high, %d medium, %d low)" % (rep["lines_scanned"], rep["findings_total"],
rep["by_severity"]["high"], rep["by_severity"]["medium"], rep["by_severity"]["low"]))
if not rep["summary"]:
print("No personal data or secrets found by the detectors (this is not proof the log is clean).")
return
print("\nBy type")
for e in rep["summary"]:
print(" [%s] %s %-34s %3d hits, %2d distinct lines %s" % (e["severity"].upper(), e["code"], e["what"], e["count"],
e["distinct_values"], ", ".join(x.split(":")[-1] for x in e["lines"][:8]) + (" ..." if e["count"] > 8 else "")))
for x in e["examples"]:
print(" %s %-11s %s (source %s)" % (x["where"], x["kind"], x["masked"], x["source"]))
print("\nSources to fix first (logger / component)")
for s in rep["sources"]:
print(" %-22s %3d %s" % (s["source"], s["hits"], " ".join("%s=%d" % kv for kv in sorted(s["codes"].items()))))
if rep["debug_level_hits"]:
print("\nNote: %d hits are in DEBUG/TRACE lines; check that debug logging is off in production." % rep["debug_level_hits"])
def self_test():
ok = 0; tests = []
def t(name, cond):
tests.append((name, bool(cond)))
k = lambda line, **kw: [h["kind"] for h in scan_line(line, **kw)]
t("Luhn-valid card found", k("charge card=4111 1111 1111 1111 ok") == ["CARD"])
t("Luhn-invalid number ignored", k("order 4111111111111112 shipped") == [])
t("epoch ms timestamp not a card", k("ts=1731995000123 done") == [])
t("IBAN mod-97 valid", k("payout to DE89 3704 0044 0532 0130 00") == ["IBAN"])
t("IBAN bad checksum ignored", k("ref DE00370400440532013000") == [])
t("AWS access key id", k("using AKIAIOSFODNN7EXAMPLE for s3") == ["AWS_KEY"])
t("bearer header value", k("Authorization: Bearer abcDEF1234567890xyz") == ["AUTH_HEADER"])
t("JWT", k("token eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.c2lnbmF0dXJlLXZhbHVl") == ["JWT"])
t("password in JSON", k('{"user":"bo","password":"hunter2!"}') == ["PASSWORD"])
t("masked password ignored", k("password=*** user=bo") == [] and k('"password": "[REDACTED]"') == [])
t("token in URL query", k("GET /cb?code=abc123&state=x") == ["URL_TOKEN"])
t("email", k("signup ana.lima@example.com") == ["EMAIL"])
t("phone needs + and 10-15 digits", k("call +44 20 7946 0958") == ["PHONE"] and k("build +1 2") == [])
t("SSN", k("ssn 123-45-6789") == ["SSN"])
t("private IP ignored, public flagged", k("from 10.0.0.5") == [] and k("from 203.0.113.7") == ["IP"])
t("include private IP flag", k("from 10.0.0.5", include_private_ip=True) == ["IP"])
t("version string not an IP", k("lib 1.2.3.4.5 loaded") == [])
t("IP after 'build'/'version' ignored", k("build 1.2.3.4 tagged") == [] and k("version=8.8.8.8") == [])
t("api_key in URL is a URL token", k("GET /r?api_key=abcdef123456789") == ["URL_TOKEN"])
t("allowlist", k("mail noreply@example.com", allow=[re.compile(r"^noreply@")]) == [])
t("date of birth", k("dob=1990-04-12 ok") == ["DOB"])
rep = scan([("t.log", ["INFO [auth] login ana@example.com", "DEBUG [pay] card 5500 0000 0000 0004", "INFO [web] fine"])])
t("report counts + severity", rep["findings_total"] == 2 and rep["by_severity"]["high"] == 1 and rep["debug_level_hits"] == 1)
t("redaction keeps key, hides value", rep["redacted"]["t.log"][1] == "DEBUG [pay] card [REDACTED:CARD]")
t("masked output never shows full card", "5500000000000004" not in json.dumps(rep["findings"]))
for name, c in tests:
print("%s %s" % ("PASS" if c else "FAIL", name)); ok += c
print("%d/%d passed" % (ok, len(tests)))
return 0 if ok == len(tests) else 1
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("files", nargs="*"); ap.add_argument("--json", action="store_true")
ap.add_argument("--redact", metavar="OUT"); ap.add_argument("--allow", action="append", default=[])
ap.add_argument("--include-private-ip", action="store_true"); ap.add_argument("--max-examples", type=int, default=3)
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.files:
ap.print_usage(); return 2
try:
allow = [re.compile(x) for x in a.allow]
named = []
for f in a.files:
fh = sys.stdin if f == "-" else open(f, encoding="utf-8", errors="replace")
named.append((f, fh.read().splitlines()))
except (OSError, re.error) as e:
print("error: %s" % e, file=sys.stderr); return 2
rep = scan(named, allow, a.include_private_ip, a.max_examples)
if a.redact:
with open(a.redact, "w", encoding="utf-8") as out:
for f in a.files:
out.write("\n".join(rep["redacted"][f]) + "\n")
red = rep.pop("redacted")
if a.json:
print(json.dumps(rep, indent=2))
else:
print_text(rep)
if a.redact:
print("\nRedacted copy written to %s (%d lines)" % (a.redact, sum(len(v) for v in red.values())))
return 1 if rep["by_severity"]["high"] else 0
if __name__ == "__main__":
sys.exit(main())
Opinionated rules for writing regular expressions that stay readable, safe and well tested instead of turning into line noise.
# Regular Expressions taste of a developer who wants regexes people can still read - Reach for a real parser for HTML, JSON, CSV, URLs and email headers; a regex is the wrong tool there. Confidence: 0.95 - Prefer plain string methods like `startsWith`, `includes` or `split` when they do the job. Confidence: 0.85 - Anchor patterns with `^` and `$` (or `\A` and `\z`) when validating a whole value. Confidence: 0.90 - Use named capture groups instead of counting numbered groups. Confidence: 0.85 - Use non-capturing groups `(?:...)` when you only need grouping, not the captured value. Confidence: 0.75 - Write long patterns in verbose mode with comments, such as `re.VERBOSE` in Python or the `x` flag where supported. Confidence: 0.80 - Prefer specific character classes like `[^"]*` over a lazy `.*?` to make intent clear and matching faster. Confidence: 0.80 - Avoid nested quantifiers like `(a+)+`; they invite catastrophic backtracking and ReDoS. Confidence: 0.95 - Never run user-supplied patterns without a timeout or a linear-time engine like RE2. Confidence: 0.90 - Put a length limit on input before matching it against any non-trivial pattern. Confidence: 0.85 - Compile patterns once at module level and reuse them instead of rebuilding them in a loop. Confidence: 0.75 - Escape dynamic text with `re.escape` or an equivalent helper before putting it into a pattern. Confidence: 0.95 - Turn on the Unicode flag (`u` or `v` in JavaScript) when the input may contain non-ASCII text. Confidence: 0.80 - Remember that `\d` and `\w` can match non-ASCII digits and letters in some engines; use `[0-9]` when you mean ASCII. Confidence: 0.70 - Keep each regex to one job; two simple patterns beat one clever pattern. Confidence: 0.80 - Give every important pattern a table-driven test with strings that must match and strings that must not. Confidence: 0.90 - Add a comment with a real example input above any pattern longer than about twenty characters. Confidence: 0.80 - Do not validate email addresses with a giant regex; check for one `@` and send a confirmation email. Confidence: 0.85 - Use lookarounds sparingly; if a pattern needs several of them, split the logic into code. Confidence: 0.70 - Try patterns in a tester like regex101 with the right engine selected before shipping them. Confidence: 0.70
Opinionated asyncio conventions for Python services that stay fast, cancel cleanly and never block the event loop.
# Python Asyncio taste of a backend developer who never blocks the event loop - Use asyncio only for I/O-bound work like network calls and databases; CPU-heavy work goes to a process pool. Confidence: 0.90 - Start the program with a single `asyncio.run(main())` and never create or manage event loops by hand. Confidence: 0.90 - Use `asyncio.TaskGroup` for running tasks together so a failure cancels the siblings and nothing leaks. Confidence: 0.85 - Never fire and forget with `create_task` without keeping a reference; lost tasks get garbage collected and errors vanish. Confidence: 0.90 - Put a timeout on every network call with `asyncio.timeout()`; waiting forever is a bug. Confidence: 0.90 - Limit concurrency with a `Semaphore` instead of starting thousands of requests at once. Confidence: 0.85 - Never call blocking libraries like `requests` or `time.sleep` inside a coroutine. Confidence: 0.95 - Wrap unavoidable blocking calls in `asyncio.to_thread` and keep them short. Confidence: 0.80 - Use async-native clients such as `httpx` or `asyncpg`, and share one client per app instead of one per request. Confidence: 0.85 - Treat `CancelledError` as normal: clean up in `finally` and re-raise it, never swallow it. Confidence: 0.90 - Avoid `asyncio.gather` without `return_exceptions` for independent jobs where one failure should not hide the others. Confidence: 0.70 - Use `asyncio.Queue` with a fixed number of worker tasks for producer and consumer pipelines. Confidence: 0.80 - Close clients, sessions and connections with `async with` so shutdown is clean. Confidence: 0.85 - Turn on asyncio debug mode in development to catch slow callbacks and never-awaited coroutines. Confidence: 0.75 - Keep sync and async code paths separate instead of writing clever wrappers that run both. Confidence: 0.75 - Do not mix threads and the event loop unless you use `run_coroutine_threadsafe` on purpose. Confidence: 0.80 - Test async code with `pytest-asyncio` or `anyio` and give tests their own short timeouts. Confidence: 0.80 - Use `contextvars` for request IDs and tracing data instead of globals. Confidence: 0.75 - Consider `uvloop` only after measuring; the default loop is fast enough for most services. Confidence: 0.65 - Handle SIGTERM by cancelling the main task and waiting for workers to finish in-flight jobs. Confidence: 0.80
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())
Plans reorders for a small shop, cafe or online store from an items CSV and a settings JSON. Computes safety stock, reorder points and order-up-to levels, rounds orders to case packs and MOQs, caps perishables to shelf life, flags stockouts before delivery, dead stock, overstock and negative margins, groups orders by supplier and fits them into a cash budget. Offline stdlib Python planner.
---
name: small-shop-inventory-reorder-planner
description: Plans reorders for a small shop, cafe or online store from an items CSV and a settings JSON. Computes safety stock, reorder points and order-up-to levels, rounds orders to case packs and MOQs, caps perishables to shelf life, flags stockouts before delivery, dead stock, overstock and negative margins, groups orders by supplier and fits them into a cash budget. Offline stdlib Python planner.
---
# Small Shop Inventory Reorder Planner
You help owners of small shops, cafes, market stalls and online stores decide what to order this week and how much. Running out of a best seller loses sales and regulars; over-ordering ties up cash and, for food, ends up in the bin. You take a simple items sheet and a few settings and produce a clear order list per supplier with the reasoning behind each number.
You do not place orders, contact suppliers or change the user's POS or accounting data. Numbers are planning estimates based on the sales averages the user provides.
## Files in this skill
- `scripts/plan_reorders.py` - reads `items.csv` and `settings.json`; computes safety stock, reorder point (ROP), order-up-to level and suggested order quantity; flags RP01-RP10 (stockout before delivery, open orders too small, at reorder point, MOQ overstock, perishable cap and waste risk, dead stock, overstock, price not above cost, assumed demand variability, cash budget deferrals); groups by supplier and checks supplier minimums (Python 3.8+ standard library only)
- `references/reorder-math.md` - the formulas in plain words, service levels and how to get the inputs from a POS export
- `references/practical-ordering.md` - perishables, MOQs, case packs, cash budgets, dead stock and supplier minimums
- `templates/order-plan.md` - the weekly order note you hand back
- `examples/items.csv` - eleven items for a fictional cafe and pantry, with several traps
- `examples/settings.json` - service level, review period, cash budget and supplier minimums
## Workflow
### 1. Collect the data
Ask for one row per item: `sku`, `name`, `supplier`, `on_hand`, `on_order`, `avg_daily_sales`, `sd_daily_sales` (optional), `lead_time_days`, `moq`, `case_pack`, `unit_cost`, `unit_price`, `shelf_life_days` (blank if not perishable). Help the user get average daily sales from the last 4-8 weeks of POS data (units sold divided by days open). Ask for the review rhythm (how often they order), a service level (0.90-0.98) and this week's cash budget.
### 2. Run the planner
```
python3 scripts/plan_reorders.py examples/items.csv examples/settings.json
python3 scripts/plan_reorders.py items.csv settings.json --json
python3 scripts/plan_reorders.py --self-test
```
Exit 0 = no high findings, 1 = at least one item will run out before an order can arrive, 2 = bad input. Without a shell, apply the formulas in `references/reorder-math.md` row by row.
### 3. Read the result
- High: RP01 runs out before a new order can arrive (order today, consider a faster supplier or a substitute), RP02 open orders are too small to cover the lead time, RP10 when a stockout-risk item does not fit the budget.
- Medium: RP03 at or below the reorder point (order now), RP04 MOQ forces more than two months of stock, RP05 perishable capped to shelf life or waste risk, RP08 price not above cost, RP10 deferred for budget.
- Low: RP06 dead stock, RP07 overstock beyond `overstock_days`, RP09 demand variability assumed.
### 4. Deliver
Fill `templates/order-plan.md`: orders grouped by supplier with totals, items deferred for cash, perishables with a suggested ordering rhythm, and three actions for slow or dead stock. Keep the language simple; owners often read this on a phone between customers.
## Example result
On the sample cafe (95% service level, weekly review, $420 budget), house coffee beans will run out in about 4 days against a 5-day lead time (high, order 48 now), sourdough and cookies are capped to their 3- and 7-day shelf lives with advice to order more often, orange juice sells below cost and its MOQ still risks waste, the PackRight and Dairy orders fall below supplier minimums, logo mugs are dead stock and paper straws have 150 days of cover. Spend: $387.70 of $420.
## Rules
- Base every number on the CSV and settings; show the formula inputs when asked.
- If sales history is short, seasonal or distorted by a stockout, say so and suggest adjusting the average manually.
- Never invent supplier terms, prices or lead times; mark unknowns and ask.
- This is a planning aid, not accounting or financial advice.
FILE:references/reorder-math.md
# Reorder math in plain words
Symbols: d = average daily sales, sd = day-to-day variation of sales, L = lead time in days (order to shelf), R = review period in days (how often you place orders), z = service-level factor.
| Quantity | Formula | Meaning |
|---|---|---|
| Safety stock (SS) | z x sd x sqrt(L + R) | Buffer for busier-than-average days while you wait |
| Reorder point (ROP) | d x L + SS | When stock on hand plus on order falls to this, order |
| Order-up-to level | d x (L + R) + SS | Enough to last until the next order arrives |
| Inventory position | on hand + on order | What you have or will soon have |
| Order quantity | order-up-to - position, then MOQ, then round up to case pack | What to buy now |
| Days of cover | on hand / d | How long current stock lasts |
## Service level
- 0.90 -> z about 1.28; 0.95 -> 1.64; 0.98 -> 2.05; 0.99 -> 2.33.
- Use higher levels for best sellers and items customers come in for; lower for impulse or easily substituted items.
## Getting the inputs
- d: units sold in the last 28-56 open days divided by the number of open days. Exclude days the item was out of stock.
- sd: standard deviation of daily units in the same window. A spreadsheet STDEV over daily totals works. If unknown, the script assumes 50% of d (RP09).
- L: from the day you place the order to the day it is on the shelf, including delivery days and receiving time. Use the slow end of the usual range.
- R: 7 for weekly ordering, 1 for daily bread or dairy runs.
## Limits
- Averages lag behind trends and seasons (holidays, weather, school terms). Adjust d by hand for the coming period.
- New items have no history: start with a small order and review after a week.
FILE:references/practical-ordering.md
# Practical ordering rules
## Perishables (RP05)
- Never order more than you can sell within the shelf life: the script caps the order at d x shelf life - position and rounds DOWN to the case pack.
- If the cap keeps cutting orders, order more often (shorter review period) rather than accepting waste.
- If an MOQ forces more than you can sell, ask the supplier for a smaller pack, share an order with a neighbour business, or drop the item.
## MOQ and case packs (RP04)
- Case packs round up for non-perishables. A big MOQ on a slow item can lock up months of cash: compare MOQ / d with your overstock limit.
## Cash budget (RP10)
- Items that would run out before delivery are funded first, then the rest by margin x daily sales (what earns most per day).
- Deferred items are listed so you can decide: raise the budget, split the order, or accept a short gap on low-margin items.
## Supplier minimum orders
- If a supplier order is below their minimum, either add slow-moving items you will need soon from that supplier or skip this cycle if stock allows.
## Dead stock and overstock (RP06, RP07)
- Dead stock (no sales, stock on hand): bundle it with best sellers, mark it down, return it if terms allow, or use it as a gift with purchase.
- Overstock (more than 90 days of cover): pause reorders, move it to a better shelf position, or run a small promotion.
## Pricing (RP08)
- An item sold at or below cost needs a price review, a cheaper supplier, or a deliberate decision to keep it as a traffic driver.
## Weekly routine (15 minutes)
1. Export or count on-hand stock for the order list.
2. Update on_order with anything not yet received.
3. Run the planner, read high flags first.
4. Place orders per supplier, note expected delivery dates.
5. Once a month, refresh d and sd from the POS.
FILE:templates/order-plan.md
# Weekly order plan - {{shop}}
Week of: {{date}} | Service level: {{service_level}} | Budget: {{currency}}{{budget}} | Spend now: {{currency}}{{spend}}
## Order today (stockout risk)
| Item | On hand | Days of cover | Lead time | Order | Cost |
|---|---|---|---|---|---|
| {{item}} | {{on_hand}} | {{cover}} | {{lead_time}} d | {{qty}} | {{cost}} |
## Orders by supplier
### {{supplier}} - {{lines}} lines, {{currency}}{{total}} {{(below minimum: note)}}
| Item | Order qty | Case pack | Cost | Why |
|---|---|---|---|---|
| {{item}} | {{qty}} | {{pack}} | {{cost}} | {{at reorder point / perishable cap / MOQ}} |
## Deferred for cash
- {{item}}: {{cost}} - {{decision needed: raise budget, split order, accept a short gap}}
## Perishables
- {{item}}: capped to {{qty}} for a {{shelf_life}}-day shelf life -> order every {{days}} days instead of weekly.
## Slow and dead stock
- {{item}}: {{days of cover or no sales}} -> {{bundle / markdown / return / pause}}
## Price checks
- {{item}}: price {{price}} vs cost {{cost}} -> {{review}}
Numbers come from your items sheet and settings; check unusual weeks (holidays, events) before ordering.
FILE:examples/items.csv
sku,name,supplier,on_hand,on_order,avg_daily_sales,sd_daily_sales,lead_time_days,moq,case_pack,unit_cost,unit_price,shelf_life_days
CB-250,House coffee beans 250g,Roastery North,18,0,4.2,1.8,5,24,6,5.40,12.50
OM-1L,Oat milk 1L,Dairy and Plant Co,30,24,6.5,2.5,3,12,12,1.35,2.90,60
SB-12,Sourdough loaf,Local Bakery,8,0,7.0,2.0,1,,1,2.10,5.00,3
CP-12,Paper cups 12oz (sleeve of 50),PackRight,9,0,0.9,0.4,10,20,10,3.80,0,
JR-HN,Wildflower honey jar 340g,Hill Apiary,26,0,0.6,0.5,14,48,12,4.20,9.90,720
TB-EG,English breakfast tea 50 bags,Leaf Traders,40,0,1.1,0.6,7,,10,2.60,6.50,540
CK-CH,Chocolate chip cookies 6-pack,Local Bakery,12,0,3.0,,2,,6,1.90,4.20,7
GF-BR,Gluten-free brownies 4-pack,Free From Foods,6,12,1.4,0.7,6,24,12,3.10,6.90,21
MG-CE,Ceramic mug with shop logo,PackRight,64,0,0,,21,,6,4.50,14.00,
ST-PA,Paper straws (box of 250),PackRight,30,0,0.2,0.1,10,,1,6.00,0,
OJ-1L,Fresh orange juice 1L,Dairy and Plant Co,10,0,2.5,1.2,2,6,6,2.30,2.20,6
FILE:examples/settings.json
{
"shop": "Corner Mill Cafe and Pantry (fictional)",
"currency": "$",
"service_level": 0.95,
"review_period_days": 7,
"overstock_days": 90,
"cash_budget": 420,
"supplier_min_order": {
"PackRight": 150,
"Dairy and Plant Co": 60
}
}
FILE:scripts/plan_reorders.py
#!/usr/bin/env python3
"""Small shop inventory reorder planner (Python 3.8+ standard library only).
Reads an items CSV and a settings JSON, computes safety stock, reorder point,
order-up-to level and a suggested order per SKU (rounded to case pack and MOQ),
flags RP01-RP10 risks, groups orders by supplier and fits them into a cash budget.
Usage:
python3 scripts/plan_reorders.py examples/items.csv examples/settings.json
python3 scripts/plan_reorders.py items.csv settings.json --json
python3 scripts/plan_reorders.py --self-test
Exit codes: 0 = no high findings, 1 = high findings (stockout risk), 2 = bad input.
"""
import argparse, csv, json, math, sys
from statistics import NormalDist
REQUIRED = ["sku", "name", "on_hand", "avg_daily_sales", "lead_time_days"]
SEV = {"high": 0, "medium": 1, "low": 2}
def num(row, key, default=0.0):
v = (row.get(key) or "").strip()
if v == "":
return default
return float(v)
def load_items(path):
with open(path, newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
if not rows:
raise ValueError("items CSV is empty")
missing = [c for c in REQUIRED if c not in rows[0]]
if missing:
raise ValueError("items CSV missing columns: %s" % ", ".join(missing))
return rows
def plan_item(row, s):
z = NormalDist().inv_cdf(s.get("service_level", 0.95))
R = float(s.get("review_period_days", 7))
it = {"sku": row["sku"].strip(), "name": row["name"].strip(), "supplier": (row.get("supplier") or "unknown").strip() or "unknown"}
d = num(row, "avg_daily_sales")
sd = num(row, "sd_daily_sales", d * 0.5) # assume fairly noisy demand if unknown
L = num(row, "lead_time_days")
on_hand, on_order = num(row, "on_hand"), num(row, "on_order")
moq, pack = num(row, "moq", 0), max(1.0, num(row, "case_pack", 1))
cost, price = num(row, "unit_cost"), num(row, "unit_price")
shelf = num(row, "shelf_life_days", 0)
ss = z * sd * math.sqrt(L + R)
rop = d * L + ss
up_to = d * (L + R) + ss
pos = on_hand + on_order
qty = 0.0
if d > 0 and pos <= rop:
qty = max(up_to - pos, 0)
if moq and qty < moq:
qty = moq
qty = math.ceil(qty / pack) * pack
capped = False
if shelf and d > 0 and qty > 0 and pos + qty > d * shelf:
# perishable: never order more than can sell within shelf life (round DOWN to the case pack)
cap = math.floor(max(d * shelf - pos, 0) / pack) * pack
if moq and cap < moq:
qty = min(qty, math.ceil(moq / pack) * pack) # smallest allowed order; RP05 below warns about waste
else:
capped = qty != cap
qty = cap
it.update({
"avg_daily_sales": d, "lead_time_days": L, "on_hand": on_hand, "on_order": on_order,
"safety_stock": round(ss, 1), "reorder_point": round(rop, 1), "order_up_to": round(up_to, 1),
"inventory_position": pos, "order_qty": int(qty), "order_cost": round(qty * cost, 2),
"days_of_cover": round(on_hand / d, 1) if d > 0 else None,
"margin_per_unit": round(price - cost, 2) if price else None,
"shelf_life_days": shelf, "flags": [],
})
def flag(code, sev, msg):
it["flags"].append({"code": code, "severity": sev, "sku": it["sku"], "message": msg})
if d > 0 and on_hand < d * L and on_order == 0:
flag("RP01", "high", "will run out in about %.0f days, before a new order (lead time %.0f d) can arrive" % (on_hand / d, L))
elif d > 0 and on_hand + on_order < d * L:
flag("RP02", "high", "stock plus open orders cover %.0f days, less than the %.0f-day lead time" % (pos / d, L))
if qty > 0:
flag("RP03", "medium", "at or below reorder point (%.0f <= %.0f): order %d now" % (pos, rop, qty))
if d > 0 and qty > 0 and moq and moq > (up_to - pos) * 2 and moq / d > 60:
flag("RP04", "medium", "MOQ %d forces about %.0f days of stock; negotiate a smaller MOQ or share an order" % (moq, moq / d))
if capped:
flag("RP05", "medium", "perishable: order capped to %d so stock sells within the %.0f-day shelf life; order more often than every %.0f days" % (qty, shelf, R))
elif shelf and d > 0 and (on_hand + on_order + qty) / d > shelf:
flag("RP05", "medium", "stock after this order lasts %.1f days but shelf life is %.0f days: waste risk" % ((on_hand + on_order + qty) / d, shelf))
if d == 0 and on_hand > 0:
flag("RP06", "low", "no sales recorded but %d on hand (dead stock): consider bundle, markdown or return" % on_hand)
elif d > 0 and on_hand / d > s.get("overstock_days", 90):
flag("RP07", "low", "%.0f days of cover: overstocked, pause reorders and free up cash" % (on_hand / d))
if price and cost and price <= cost:
flag("RP08", "medium", "unit price %.2f is not above unit cost %.2f" % (price, cost))
if not (row.get("sd_daily_sales") or "").strip():
flag("RP09", "low", "no demand variability given; assumed sd = 50% of average (check with sales history)")
return it
def plan(rows, s):
items = [plan_item(r, s) for r in rows]
budget = s.get("cash_budget")
# priority: stockout risk first, then reorder-point items by margin per day of cover
def prio(it):
risk = 0 if any(f["code"] in ("RP01", "RP02") for f in it["flags"]) else 1
return (risk, -(it["margin_per_unit"] or 0) * it["avg_daily_sales"])
spend, deferred = 0.0, []
for it in sorted([i for i in items if i["order_qty"] > 0], key=prio):
if budget is not None and spend + it["order_cost"] > budget:
it["deferred"] = True
deferred.append(it["sku"])
it["flags"].append({"code": "RP10", "severity": "medium" if prio(it)[0] else "high", "sku": it["sku"],
"message": "order of %.2f does not fit the remaining cash budget; deferred" % it["order_cost"]})
else:
it["deferred"] = False
spend += it["order_cost"]
suppliers = {}
for it in items:
if it["order_qty"] > 0 and not it.get("deferred"):
sp = suppliers.setdefault(it["supplier"], {"lines": 0, "units": 0, "cost": 0.0})
sp["lines"] += 1; sp["units"] += it["order_qty"]; sp["cost"] = round(sp["cost"] + it["order_cost"], 2)
for name, sp in suppliers.items():
mo = (s.get("supplier_min_order") or {}).get(name)
if mo and sp["cost"] < mo:
sp["note"] = "below supplier minimum order %.2f: add slow-moving items or wait a cycle" % mo
flags = sorted([f for it in items for f in it["flags"]], key=lambda f: (SEV[f["severity"]], f["code"], f["sku"]))
return {"items": items, "suppliers": suppliers, "spend": round(spend, 2), "budget": budget, "deferred": deferred, "flags": flags}
def report(res, s):
cur = s.get("currency", "")
out = ["Reorder plan for %s (service level %.0f%%, review every %s days)" % (s.get("shop", "shop"), s.get("service_level", 0.95) * 100, s.get("review_period_days", 7)), ""]
out.append("%-8s %-24s %6s %6s %6s %6s %6s %6s %9s" % ("SKU", "ITEM", "ONHAND", "COVER", "SS", "ROP", "UPTO", "ORDER", "COST"))
for it in res["items"]:
cover = "-" if it["days_of_cover"] is None else "%.0fd" % it["days_of_cover"]
order = ("%d*" % it["order_qty"]) if it.get("deferred") else str(it["order_qty"])
out.append("%-8s %-24s %6d %6s %6.0f %6.0f %6.0f %6s %9.2f" % (it["sku"][:8], it["name"][:24], it["on_hand"], cover, it["safety_stock"], it["reorder_point"], it["order_up_to"], order, it["order_cost"]))
out += ["", "Orders by supplier:"]
for name, sp in sorted(res["suppliers"].items()):
out.append(" %-20s %d lines, %d units, %s%.2f%s" % (name, sp["lines"], sp["units"], cur, sp["cost"], (" (" + sp["note"] + ")") if sp.get("note") else ""))
b = res["budget"]
out.append("Total to spend now: %s%.2f%s" % (cur, res["spend"], "" if b is None else " of %s%.2f budget" % (cur, b)))
if res["deferred"]:
out.append("Deferred (marked *): " + ", ".join(res["deferred"]))
out += ["", "Flags:"]
for f in res["flags"]:
out.append(" [%s] %s %s: %s" % (f["severity"].upper(), f["code"], f["sku"], f["message"]))
return "\n".join(out)
def self_test():
s = {"service_level": 0.95, "review_period_days": 7}
def row(**kw):
r = {"sku": "A", "name": "a", "on_hand": "100", "on_order": "0", "avg_daily_sales": "5", "sd_daily_sales": "2", "lead_time_days": "7", "moq": "", "case_pack": "1", "unit_cost": "2", "unit_price": "4", "shelf_life_days": ""}
r.update({k: str(v) for k, v in kw.items()}); return r
def codes(r, st=s):
return {f["code"] for f in plan_item(r, st)["flags"]}
it = plan_item(row(), s)
z = NormalDist().inv_cdf(0.95)
cases = [
("safety stock formula", abs(it["safety_stock"] - round(z * 2 * math.sqrt(14), 1)) < 0.05, True),
("no order above ROP", it["order_qty"], 0),
("RP01 stockout", "RP01" in codes(row(on_hand=10)), True),
("RP02 open order too small", "RP02" in codes(row(on_hand=10, on_order=10)), True),
("RP03 reorder", "RP03" in codes(row(on_hand=40)), True),
("case pack rounding", plan_item(row(on_hand=40, case_pack=12), s)["order_qty"] % 12, 0),
("MOQ applied", plan_item(row(on_hand=40, moq=200), s)["order_qty"] >= 200, True),
("RP04 big MOQ", "RP04" in codes(row(on_hand=40, moq=400)), True),
("RP05 shelf life cap", "RP05" in codes(row(on_hand=40, shelf_life_days=10)), True),
("perishable qty capped", plan_item(row(on_hand=40, shelf_life_days=10), s)["order_qty"], 10),
("RP05 MOQ waste", "RP05" in codes(row(on_hand=40, shelf_life_days=10, moq=100)), True),
("RP06 dead stock", "RP06" in codes(row(avg_daily_sales=0, on_hand=30)), True),
("RP07 overstock", "RP07" in codes(row(on_hand=1000)), True),
("RP08 negative margin", "RP08" in codes(row(unit_price=1.5)), True),
("RP09 sd assumed", "RP09" in codes(row(sd_daily_sales="")), True),
]
rows = [row(sku="A", on_hand=10), row(sku="B", on_hand=40, unit_cost=50)]
res = plan(rows, dict(s, cash_budget=200))
cases.append(("RP10 budget defers lower priority", res["deferred"], ["B"]))
ok = 0
for name, got, want in cases:
p = got == want; ok += p
print("%s %s" % ("PASS" if p else "FAIL", name))
print("%d/%d passed" % (ok, len(cases)))
return 0 if ok == len(cases) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("items", nargs="?"); ap.add_argument("settings", nargs="?")
ap.add_argument("--json", action="store_true"); ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.items:
ap.print_usage(); return 2
try:
s = {}
if a.settings:
with open(a.settings, encoding="utf-8") as f:
s = json.load(f)
if not 0.5 <= s.get("service_level", 0.95) < 1:
raise ValueError("service_level must be between 0.5 and 0.999")
res = plan(load_items(a.items), s)
except (OSError, ValueError, KeyError, json.JSONDecodeError) as e:
print("input error: %s" % e, file=sys.stderr); return 2
print(json.dumps(res, indent=2) if a.json else report(res, s))
return 1 if any(f["severity"] == "high" for f in res["flags"]) else 0
if __name__ == "__main__":
sys.exit(main())
Checks a JSON inventory of TLS certificates (plus optional PEM files) for expired and soon-expiring certs, stuck auto-renewals, hosts missing from SANs, weak keys and SHA1 signatures, over-long lifetimes, incomplete chains, self-signed public certs, missing owners or runbooks, shared wildcards and renewal clusters. Ranks fixes. Offline stdlib Python checker.
---
name: tls-certificate-expiry-and-inventory-checker
description: Checks a JSON inventory of TLS certificates (plus optional PEM files) for expired and soon-expiring certs, stuck auto-renewals, hosts missing from SANs, weak keys and SHA1 signatures, over-long lifetimes, incomplete chains, self-signed public certs, missing owners or runbooks, shared wildcards and renewal clusters. Ranks fixes. Offline stdlib Python checker.
---
# TLS Certificate Expiry and Inventory Checker
You help engineers and IT admins stop certificate outages before they happen. An expired cert, a host that silently fell out of the SAN list, or a renewal job that has been failing for weeks takes a service down just as hard as a code bug, usually on a weekend. You take a JSON inventory of certificates (and optionally the PEM files) and produce a ranked list of what to renew, reissue or fix, with an owner for each item.
You do not connect to servers, request certificates or handle private keys. Work only from the inventory and public certificate files the user provides. If someone pastes a private key, tell them to remove it and treat it as compromised.
## Files in this skill
- `scripts/check_certs.py` - reads `inventory.json` and any `pem_path` files; reports TC01-TC15 (expired, expiring within 14 or 30 days, stuck auto-renewal, host not in SANs, weak key, SHA1/MD5 signature, lifetime over 398 days, incomplete chain, self-signed public cert, no owner, manual renewal without runbook, wildcard shared across environments, renewal clusters, future not_before); text or `--json` output (Python 3.8+ standard library only)
- `references/expiry-and-renewal.md` - renewal windows, ACME behaviour, why auto-renew still fails, shrinking lifetimes
- `references/key-and-chain-rules.md` - SAN and wildcard matching, key sizes, signature algorithms, chains, self-signed and internal CAs
- `templates/cert-report.md` - the report you hand back
- `examples/inventory.json` - nine certificates for a fictional shop with several traps
- `examples/certs/internal-api.pem` - a public self-signed test certificate decoded by the script (no private key)
## Workflow
### 1. Collect the inventory
Ask for one entry per certificate: `name`, `hosts` served, `sans`, `issuer`, `not_before`, `not_after`, `key_type`, `key_bits`, `sig_alg`, `auto_renew`, `renew_method`, `chain_complete`, `environment`, `public`, `owner`, `renewal_runbook`. If they only have PEM files, set `pem_path` and the script fills dates, SANs and issuer. Useful one-liners for gathering data (run by the user, not you):
```
openssl x509 -in cert.pem -noout -subject -issuer -dates -ext subjectAltName
openssl s_client -connect host:443 -servername host -showcerts </dev/null
```
### 2. Run the checker
```
python3 scripts/check_certs.py examples/inventory.json --today 2026-11-11
python3 scripts/check_certs.py inventory.json --json --warn-days 45
python3 scripts/check_certs.py --self-test
```
Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, walk each entry with the two reference files and apply the same codes by hand.
### 3. Read the result
- High: TC01 expired, TC02 expires within 14 days, TC05 host not covered by SANs, TC06 weak key, TC07 SHA1/MD5 signature, TC09 incomplete chain, TC10 self-signed on a public endpoint, TC14 not_before in the future, TC00 missing expiry data.
- Medium: TC03 manual renewal within 30 days, TC04 auto-renew on but under 20 days left (renewal is stuck), TC08 lifetime over 398 days on a public cert, TC11 no owner, TC13 wildcard shared between production and other environments.
- Low: TC12 manual renewal without a runbook, TC15 three or more certs expiring in the same week.
### 4. Deliver
Fill `templates/cert-report.md`: verdict, a renewal calendar sorted by days left, findings with owners, and the three changes that remove the most risk (usually: automate renewal, add expiry monitoring at 30/14/7 days, fix SAN coverage). Re-run after fixes and attach the clean output.
## Example result
On the sample inventory (as of 11 Nov 2026), `legacy-vpn` expired 6 days ago and also has a 1024-bit RSA key, SHA1 signature and no owner; `checkout-api` expires in 10 days, misses `pay.example-shop.test` in its SANs and serves an incomplete chain; `wildcard-prod` has auto-renew on but only 19 days left, and its wildcard does not cover the two-level `img.cdn` host; `status-page` is self-signed on a public endpoint; the PEM-based `internal-api` lacks `metrics.corp.example`; and the same wildcard is used in production and staging. Result: 9 high, 5 medium, 3 low.
## Rules
- Base every finding on an inventory field or a decoded PEM value; never guess an expiry date.
- Never ask for, print or store private keys or passwords.
- Treat CA and browser policy numbers (398-day limit, shrinking lifetimes) as current guidance to confirm, not as legal requirements for private PKI.
- Recommend monitoring that alerts a named owner, not a shared inbox nobody reads.
FILE:references/expiry-and-renewal.md
# Expiry and renewal
## Windows the checker uses
- Expired (TC01): `not_after` is before the as-of date. Browsers and most API clients refuse the connection.
- Critical (TC02): 14 days or less left. Renew this week and confirm the new cert is actually being served.
- Warning (TC03): 30 days or less left and renewal is manual. Put a dated task with an owner on the calendar.
- Stuck renewal (TC04): `auto_renew` is true but 20 days or less are left. ACME clients such as certbot and acme.sh normally renew around 30 days before expiry (one third of a 90-day lifetime), so a cert this close usually means the job has been failing.
## Why automatic renewal still fails
- DNS-01 API token expired or lost permissions after a provider change.
- HTTP-01 challenge blocked by a new redirect, WAF rule or CDN in front of the origin.
- The renewal ran but the service was never reloaded, so the old cert is still in memory.
- The cert renewed on one server but not on the load balancer, CDN or other replicas.
- Rate limits after repeated failed attempts.
Always check what is actually served (`openssl s_client -connect host:443 -servername host`), not just the file on disk.
## Lifetimes are getting shorter
- Publicly trusted certificates are limited to 398 days today (TC08), and CA/Browser Forum ballots schedule further reductions over the next few years toward much shorter lifetimes. Confirm the current limits with your CA.
- Shorter lifetimes make manual renewal unsustainable: treat every manual public cert as an automation task.
## Monitoring that works
- Alert at 30, 14 and 7 days, sent to a named owner (TC11) and a team channel.
- Monitor from outside, per hostname, so a missing SAN or a stale replica is caught.
- Keep a renewal runbook link for every manual cert (TC12): CSR command, CA account, deploy targets, reload command, verification step.
- Stagger renewals (TC15) so one broken week cannot take down several services.
FILE:references/key-and-chain-rules.md
# Keys, names and chains
## Hostname coverage (TC05)
- Clients check the subjectAltName (SAN) DNS entries; the Common Name alone is ignored by modern browsers.
- A wildcard covers exactly one label: `*.example.com` matches `a.example.com` but NOT `example.com` and NOT `a.b.example.com`.
- List every name a service answers to (apex, www, regional and legacy hostnames) in `hosts` so gaps show up.
## Keys and signatures (TC06, TC07)
| Key type | Minimum | Good default |
|---|---|---|
| RSA | 2048 bits | 2048 or 3072 |
| ECDSA | P-256 | P-256 or P-384 |
| Ed25519 | n/a | supported mainly for internal use |
- SHA1 and MD5 signatures are rejected by browsers and many libraries; reissue with SHA-256 or stronger.
- If a key may have leaked (shared over chat, committed to git), revoke and reissue; do not just renew with the same key.
## Chains (TC09)
- Servers must send the leaf plus intermediate certificates. Some browsers hide a missing intermediate by fetching it, but API clients, mobile apps and older devices fail.
- Test with `openssl s_client -showcerts` or a fresh client container, not only a desktop browser.
## Self-signed and internal CAs (TC10)
- Self-signed or private-CA certs are fine for internal services if clients are configured to trust that CA. Mark them `public: false`.
- On a public endpoint they produce warnings that teach users to click through security errors.
## Blast radius (TC13)
- A wildcard shared between production and staging means a key leaked from a less protected staging box can impersonate production. Prefer separate certs per environment and per sensitive service.
FILE:templates/cert-report.md
# TLS certificate review - {{organization}}
As of: {{as_of_date}} | Certificates checked: {{count}} | Verdict: {{verdict: ACT NOW / SCHEDULE / HEALTHY}}
## Renewal calendar
| Certificate | Expires | Days left | Auto-renew | Owner |
|---|---|---|---|---|
| {{name}} | {{not_after}} | {{days_left}} | {{yes/no}} | {{owner}} |
## High findings (fix first)
| Code | Certificate | Problem | Fix | Owner | Due |
|---|---|---|---|---|---|
| {{TCxx}} | {{name}} | {{message}} | {{fix}} | {{owner}} | {{date}} |
## Medium and low findings
- {{TCxx}} {{name}}: {{message}} -> {{fix}}
## Three changes that remove the most risk
1. {{e.g. automate renewal for the remaining manual public certs}}
2. {{e.g. external expiry monitoring at 30/14/7 days to a named owner}}
3. {{e.g. reissue with full SAN coverage and separate production/staging certs}}
## Verification
- Re-run: `python3 scripts/check_certs.py inventory.json --today {{date}}` -> exit {{code}}
- Served-cert check per host: `openssl s_client -connect {{host}}:443 -servername {{host}}`
Notes: built from the inventory provided; no servers were contacted and no private keys were handled.
FILE:examples/inventory.json
{
"organization": "Example Shop (fictional)",
"certificates": [
{
"name": "www-shop",
"hosts": ["www.example-shop.test", "example-shop.test"],
"sans": ["www.example-shop.test", "example-shop.test"],
"issuer": "Let's Encrypt",
"not_before": "2026-09-20",
"not_after": "2026-12-19",
"key_type": "ec",
"key_bits": 256,
"sig_alg": "ecdsa-with-SHA384",
"auto_renew": true,
"renew_method": "certbot on web-1, cron twice daily",
"chain_complete": true,
"environment": "production",
"owner": "web-team"
},
{
"name": "checkout-api",
"hosts": ["checkout.example-shop.test", "pay.example-shop.test"],
"sans": ["checkout.example-shop.test"],
"issuer": "Commercial CA",
"not_before": "2026-01-10",
"not_after": "2026-11-21",
"key_type": "rsa",
"key_bits": 2048,
"sig_alg": "sha256WithRSAEncryption",
"auto_renew": false,
"chain_complete": false,
"environment": "production",
"owner": "payments"
},
{
"name": "wildcard-prod",
"hosts": ["blog.example-shop.test", "img.cdn.example-shop.test"],
"sans": ["*.example-shop.test"],
"issuer": "Let's Encrypt",
"not_before": "2026-09-01",
"not_after": "2026-11-30",
"key_type": "rsa",
"key_bits": 3072,
"sig_alg": "sha256WithRSAEncryption",
"auto_renew": true,
"renew_method": "acme.sh DNS-01 via DNS API token",
"chain_complete": true,
"environment": "production",
"owner": "platform"
},
{
"name": "wildcard-staging",
"hosts": ["staging.example-shop.test"],
"sans": ["*.example-shop.test"],
"issuer": "Let's Encrypt",
"not_before": "2026-10-20",
"not_after": "2027-01-18",
"key_type": "rsa",
"key_bits": 3072,
"sig_alg": "sha256WithRSAEncryption",
"auto_renew": true,
"chain_complete": true,
"environment": "staging",
"owner": "platform"
},
{
"name": "legacy-vpn",
"hosts": ["vpn.example-shop.test"],
"sans": ["vpn.example-shop.test"],
"issuer": "Old Commercial CA",
"not_before": "2024-10-01",
"not_after": "2026-11-05",
"key_type": "rsa",
"key_bits": 1024,
"sig_alg": "sha1WithRSAEncryption",
"auto_renew": false,
"chain_complete": true,
"environment": "production",
"owner": ""
},
{
"name": "status-page",
"hosts": ["status.example-shop.test"],
"sans": ["status.example-shop.test"],
"issuer": "status-page.local",
"self_signed": true,
"not_before": "2026-06-01",
"not_after": "2027-06-01",
"key_type": "ec",
"key_bits": 256,
"sig_alg": "ecdsa-with-SHA256",
"auto_renew": false,
"renewal_runbook": "https://wiki.example-shop.test/runbooks/status-cert",
"chain_complete": true,
"environment": "production",
"public": true,
"owner": "sre"
},
{
"name": "internal-api",
"pem_path": "certs/internal-api.pem",
"hosts": ["internal-api.corp.example", "api-admin.corp.example", "metrics.corp.example"],
"key_type": "rsa",
"key_bits": 2048,
"sig_alg": "sha256WithRSAEncryption",
"auto_renew": false,
"renewal_runbook": "https://wiki.example-shop.test/runbooks/internal-ca",
"chain_complete": true,
"environment": "production",
"public": false,
"owner": "platform"
},
{
"name": "mail-relay",
"hosts": ["mail.example-shop.test"],
"sans": ["mail.example-shop.test"],
"issuer": "Let's Encrypt",
"not_before": "2026-10-05",
"not_after": "2027-01-03",
"key_type": "ec",
"key_bits": 256,
"sig_alg": "ecdsa-with-SHA384",
"auto_renew": true,
"chain_complete": true,
"environment": "production",
"owner": "it-ops"
},
{
"name": "partner-sftp",
"hosts": ["sftp.example-shop.test"],
"sans": ["sftp.example-shop.test"],
"issuer": "Commercial CA",
"not_before": "2026-01-05",
"not_after": "2026-12-08",
"key_type": "rsa",
"key_bits": 2048,
"sig_alg": "sha256WithRSAEncryption",
"auto_renew": false,
"chain_complete": true,
"environment": "production",
"owner": "it-ops"
}
]
}
FILE:examples/certs/internal-api.pem
-----BEGIN CERTIFICATE-----
MIIDhTCCAm2gAwIBAgICEJIwDQYJKoZIhvcNAQELBQAwOzEiMCAGA1UEAwwZaW50
ZXJuYWwtYXBpLmNvcnAuZXhhbXBsZTEVMBMGA1UECgwMRXhhbXBsZSBDb3JwMB4X
DTI2MTExMTA3MDc0OFoXDTI3MTIxNjA3MDc0OFowOzEiMCAGA1UEAwwZaW50ZXJu
YWwtYXBpLmNvcnAuZXhhbXBsZTEVMBMGA1UECgwMRXhhbXBsZSBDb3JwMIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4oUJHnqdN4I9apnhjwPs7hVQbTO/
vokjVcg4youOUoOEvGZnaNpEFqXL8msD7Xpfj8tkzhRsfxOAjzataIH/0vhJncPW
YPdcV8bV6AjbT1DXD7NrcWzztnVVU69qctruVT2ir1ZX9kf60uT8LXwrC2xmGELR
MmkIxu9yU2u8qa+5fuj+IPX3K2MaveQGpF8uWlklCRKTFdpLJpw/Gz4OPEVFn8zk
uR6PGg0434aoF9oW9dJugLqfpqNDpbzQIi4Im3CsNSRgXDTiZTiP+zCBMGhpHvJT
OpstU/9JSM9m78jAoA0rfyF/Fhl/Qrcb6gHtmswEuu9NBnIr7tbr5qyZxQIDAQAB
o4GSMIGPMB0GA1UdDgQWBBQLC7n+evl0kJ5lrXrErQKoOEHYpDAfBgNVHSMEGDAW
gBQLC7n+evl0kJ5lrXrErQKoOEHYpDAPBgNVHRMBAf8EBTADAQH/MDwGA1UdEQQ1
MDOCGWludGVybmFsLWFwaS5jb3JwLmV4YW1wbGWCFmFwaS1hZG1pbi5jb3JwLmV4
YW1wbGUwDQYJKoZIhvcNAQELBQADggEBANhJq+F8Ux8tYMJgH+TTZ2SnKr6lamzz
0VmSvCYmRz0xIsDzPczvKoHnngxPObV6XwhkAg+mVUW04R2hpVsaLNxfj6zceTN7
IrP75HT4zrthfWjXy1mXO4frMvKgJnS7GQ79CxVVj5CPTsovKGaXzaqC8mHTe+0C
meOv7kglUD6CO35X9Lq8bnrWA771HpiFddK7+d5Y34uQaUbEmMrM5drjw7gn+hxh
w2+tOOSIhOBqoU/tmtslbr+ZyJ4IuItpUDkeEk/n3K6TVMZ6eZHYqjQly2H4lJxE
TsgyHYYiR286zwyr2sKmF7ZGtD9B5yJR6sorJhCAUJuv7EaU7XqOMcU=
-----END CERTIFICATE-----
FILE:scripts/check_certs.py
#!/usr/bin/env python3
"""TLS certificate expiry and inventory checker (Python 3.8+ standard library only).
Reads a JSON inventory of certificates (and optional PEM files referenced by "pem_path")
and reports TC01-TC14 findings: expiry, stuck renewals, hostname coverage, weak keys,
weak signatures, long lifetimes, broken chains, self-signed public certs, ownership,
shared wildcards and renewal clusters.
Usage:
python3 scripts/check_certs.py examples/inventory.json --today 2026-11-11
python3 scripts/check_certs.py inventory.json --json
python3 scripts/check_certs.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, datetime as dt, json, os, ssl, sys
SEV_ORDER = {"high": 0, "medium": 1, "low": 2}
WEAK_SIG = ("sha1", "md5")
MIN_BITS = {"rsa": 2048, "dsa": 2048, "ec": 256, "ecdsa": 256, "ed25519": 0}
def parse_date(s):
"""Accept YYYY-MM-DD, ISO timestamps, or OpenSSL style 'Nov 11 10:00:00 2026 GMT'."""
if not s:
return None
s = str(s).strip()
for fmt in ("%Y-%m-%d", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S", "%b %d %H:%M:%S %Y %Z"):
try:
return dt.datetime.strptime(s, fmt).date()
except ValueError:
pass
try:
return dt.datetime.utcfromtimestamp(ssl.cert_time_to_seconds(s)).date()
except (ValueError, TypeError):
raise ValueError("unparseable date: %r" % s)
def decode_pem(path):
"""Decode a PEM certificate with the stdlib test decoder; returns a partial cert dict."""
info = ssl._ssl._test_decode_cert(path) # stdlib, no third-party crypto needed
subject = {k: v for rdn in info.get("subject", ()) for k, v in rdn}
issuer = {k: v for rdn in info.get("issuer", ()) for k, v in rdn}
sans = [v for k, v in info.get("subjectAltName", ()) if k == "DNS"]
return {
"subject_cn": subject.get("commonName", ""),
"issuer": issuer.get("organizationName") or issuer.get("commonName", ""),
"issuer_cn": issuer.get("commonName", ""),
"not_before": info.get("notBefore"),
"not_after": info.get("notAfter"),
"sans": sans,
"serial": info.get("serialNumber", ""),
}
def host_covered(host, sans):
host = host.lower().rstrip(".")
for san in sans:
san = san.lower().rstrip(".")
if san == host:
return True
if san.startswith("*."):
base = san[2:]
# a wildcard matches exactly one label: *.example.com covers a.example.com, not a.b.example.com or example.com
if host.endswith("." + base) and host.count(".") == base.count(".") + 1:
return True
return False
def load(path, base_dir):
with open(path, encoding="utf-8") as f:
data = json.load(f)
certs = data["certificates"] if isinstance(data, dict) else data
if not isinstance(certs, list) or not certs:
raise ValueError("inventory must contain a non-empty 'certificates' list")
out = []
for i, c in enumerate(certs):
c = dict(c)
c.setdefault("name", "cert-%d" % (i + 1))
if c.get("pem_path"):
p = c["pem_path"]
if not os.path.isabs(p):
p = os.path.join(base_dir, p)
pem = decode_pem(p)
for k, v in pem.items():
if not c.get(k):
c[k] = v
c["_from_pem"] = True
out.append(c)
return out
def check(certs, today, warn_days=30, crit_days=14):
findings = []
def add(code, sev, cert, msg, fix):
findings.append({"code": code, "severity": sev, "cert": cert["name"], "message": msg, "fix": fix})
expiry_dates = []
wildcard_envs = {}
for c in certs:
na, nb = parse_date(c.get("not_after")), parse_date(c.get("not_before"))
if na is None:
add("TC00", "high", c, "no not_after date", "Add not_after or a pem_path so expiry can be checked.")
continue
left = (na - today).days
c["_days_left"] = left
expiry_dates.append((na, c["name"]))
auto = bool(c.get("auto_renew"))
public = c.get("public", True)
if left < 0:
add("TC01", "high", c, "expired %d days ago (%s)" % (-left, na), "Renew and deploy now; check every host in 'hosts'.")
elif left <= crit_days:
add("TC02", "high", c, "expires in %d days (%s)" % (left, na), "Renew this week; confirm the new cert is actually served.")
elif left <= warn_days and not auto:
add("TC03", "medium", c, "expires in %d days with manual renewal" % left, "Schedule the renewal with an owner and a date.")
if auto and 0 <= left <= 20:
add("TC04", "medium", c, "auto_renew is on but only %d days left - renewal looks stuck" % left,
"Check the renewal job logs (ACME clients renew around 30 days left); fix DNS/HTTP challenge or permissions.")
if nb and nb > today:
add("TC14", "high", c, "not_before %s is in the future" % nb, "Check server clock or wait; clients will reject it now.")
sans = c.get("sans") or []
for h in c.get("hosts") or []:
if not host_covered(h, sans):
add("TC05", "high", c, "host %s is not covered by SANs %s" % (h, sans), "Reissue with the host in subjectAltName (CN alone is ignored by browsers).")
kt = str(c.get("key_type", "")).lower()
bits = c.get("key_bits")
if kt in MIN_BITS and bits is not None and int(bits) < MIN_BITS[kt]:
add("TC06", "high", c, "%s key of %s bits is too small (min %d)" % (kt.upper(), bits, MIN_BITS[kt]), "Reissue with RSA 2048+/3072 or ECDSA P-256.")
sig = str(c.get("sig_alg", "")).lower()
if any(w in sig for w in WEAK_SIG):
add("TC07", "high", c, "weak signature algorithm %s" % c.get("sig_alg"), "Reissue with a SHA-256 based signature.")
if nb and na and public and (na - nb).days > 398:
add("TC08", "medium", c, "lifetime %d days exceeds 398 days for a publicly trusted cert" % (na - nb).days,
"Publicly trusted certs must be <=398 days and are getting shorter; automate renewal.")
if c.get("chain_complete") is False:
add("TC09", "high", c, "served chain is incomplete (missing intermediate)", "Serve the full chain (leaf + intermediates); test with a fresh client.")
self_signed = c.get("self_signed")
if self_signed is None and c.get("subject_cn") and c.get("issuer_cn"):
self_signed = c["subject_cn"] == c["issuer_cn"]
if self_signed and public:
add("TC10", "high", c, "self-signed certificate on a public endpoint", "Use a publicly trusted CA cert, or mark public=false if internal-only.")
if not c.get("owner"):
add("TC11", "medium", c, "no owner recorded", "Name a team or person who gets the expiry alert.")
if any(str(s).startswith("*.") for s in sans):
for s in sans:
if str(s).startswith("*."):
wildcard_envs.setdefault(s, set()).add(str(c.get("environment", "unknown")))
if not auto and not c.get("renewal_runbook"):
add("TC12", "low", c, "manual renewal without a runbook link", "Add a short renewal runbook (CSR, CA, deploy targets, test).")
for wc, envs in wildcard_envs.items():
if "production" in envs and len(envs) > 1:
findings.append({"code": "TC13", "severity": "medium", "cert": wc,
"message": "wildcard %s is used in production and %s" % (wc, ", ".join(sorted(envs - {"production"}))),
"fix": "Use separate certs per environment to shrink the blast radius of a leaked key."})
expiry_dates.sort()
for i in range(len(expiry_dates)):
window = [n for d, n in expiry_dates if 0 <= (d - expiry_dates[i][0]).days <= 7 and d >= today]
if len(window) >= 3:
findings.append({"code": "TC15", "severity": "low", "cert": ", ".join(window),
"message": "%d certs expire within the same 7-day window" % len(window),
"fix": "Stagger renewals so one bad week cannot take down several services."})
break
findings.sort(key=lambda f: (SEV_ORDER[f["severity"]], f["code"], f["cert"]))
return findings
def report(certs, findings, today):
lines = ["TLS certificate check as of %s - %d certificates" % (today, len(certs)), ""]
lines.append("%-24s %-12s %6s %-10s %s" % ("NAME", "EXPIRES", "DAYS", "AUTO", "OWNER"))
for c in sorted(certs, key=lambda c: c.get("_days_left", -10**6)):
na = parse_date(c.get("not_after"))
lines.append("%-24s %-12s %6s %-10s %s" % (c["name"][:24], na or "?", c.get("_days_left", "?"),
"yes" if c.get("auto_renew") else "no", c.get("owner") or "-"))
counts = {s: sum(1 for f in findings if f["severity"] == s) for s in SEV_ORDER}
lines += ["", "Findings: %d high, %d medium, %d low" % (counts["high"], counts["medium"], counts["low"]), ""]
for f in findings:
lines.append("[%s] %s %s: %s" % (f["severity"].upper(), f["code"], f["cert"], f["message"]))
lines.append(" fix: %s" % f["fix"])
if not findings:
lines.append("No findings.")
return "\n".join(lines)
def self_test():
today = dt.date(2026, 11, 11)
base = {"name": "ok", "hosts": ["a.example.com"], "sans": ["a.example.com"], "not_before": "2026-09-01",
"not_after": "2027-01-20", "key_type": "ec", "key_bits": 256, "sig_alg": "ecdsa-with-SHA256",
"auto_renew": True, "owner": "web", "chain_complete": True, "environment": "production"}
def run(**kw):
c = dict(base); c.update(kw)
return {f["code"] for f in check([c], today)}
cases = [
("clean", run(), set()),
("TC01 expired", run(not_after="2026-11-01") >= {"TC01"}, True),
("TC02 critical", run(not_after="2026-11-20") >= {"TC02"}, True),
("TC03 manual 30d", run(not_after="2026-12-05", auto_renew=False, renewal_runbook="x") >= {"TC03"}, True),
("TC04 stuck renewal", "TC04" in run(not_after="2026-11-28"), True),
("TC05 SAN miss", "TC05" in run(hosts=["b.example.com"]), True),
("wildcard one label", host_covered("a.example.com", ["*.example.com"]) and not host_covered("x.a.example.com", ["*.example.com"]) and not host_covered("example.com", ["*.example.com"]), True),
("TC06 weak rsa", "TC06" in run(key_type="rsa", key_bits=1024), True),
("TC07 sha1", "TC07" in run(sig_alg="sha1WithRSAEncryption"), True),
("TC08 long life", "TC08" in run(not_before="2025-01-01", not_after="2027-01-01"), True),
("TC08 private ok", "TC08" in run(not_before="2025-01-01", not_after="2027-01-01", public=False), False),
("TC09 chain", "TC09" in run(chain_complete=False), True),
("TC10 self-signed", "TC10" in run(self_signed=True), True),
("TC11 owner", "TC11" in run(owner=""), True),
("TC14 future", "TC14" in run(not_before="2026-12-01"), True),
]
two = [dict(base, name="w1", sans=["*.example.com"], hosts=["a.example.com"]),
dict(base, name="w2", sans=["*.example.com"], hosts=["a.example.com"], environment="staging")]
cases.append(("TC13 shared wildcard", any(f["code"] == "TC13" for f in check(two, today)), True))
three = [dict(base, name="c%d" % i, not_after="2027-01-0%d" % (i + 1)) for i in range(3)]
cases.append(("TC15 cluster", any(f["code"] == "TC15" for f in check(three, today)), True))
cases.append(("date formats", parse_date("Nov 11 10:00:00 2026 GMT") == dt.date(2026, 11, 11), True))
ok = 0
for name, got, want in cases:
passed = got == want
ok += passed
print("%s %s" % ("PASS" if passed else "FAIL", name))
print("%d/%d passed" % (ok, len(cases)))
return 0 if ok == len(cases) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("inventory", nargs="?")
ap.add_argument("--today", help="as-of date YYYY-MM-DD (default: today)")
ap.add_argument("--warn-days", type=int, default=30)
ap.add_argument("--crit-days", type=int, default=14)
ap.add_argument("--json", action="store_true")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.inventory:
ap.print_usage(); return 2
try:
today = parse_date(a.today) if a.today else dt.date.today()
certs = load(a.inventory, os.path.dirname(os.path.abspath(a.inventory)))
findings = check(certs, today, a.warn_days, a.crit_days)
except (OSError, ValueError, KeyError, json.JSONDecodeError, ssl.SSLError) as e:
print("input error: %s" % e, file=sys.stderr)
return 2
if a.json:
clean = [{k: v for k, v in c.items() if not k.startswith("_") or k == "_days_left"} for c in certs]
print(json.dumps({"today": str(today), "certificates": clean, "findings": findings}, indent=2, default=str))
else:
print(report(certs, findings, today))
return 1 if any(f["severity"] == "high" for f in findings) else 0
if __name__ == "__main__":
sys.exit(main())
Opinionated conventions for clean, reproducible Jupyter notebooks in data science work.
# Jupyter Notebook taste of a data scientist who wants notebooks that rerun cleanly - Make every notebook run top to bottom with "Restart and Run All" before sharing or committing it. Confidence: 0.95 - Put imports, configuration and constants in the first cells, never scattered through the notebook. Confidence: 0.85 - Move reusable logic into a normal Python package in the repo and import it, keeping notebooks for exploration and storytelling. Confidence: 0.90 - Use `%load_ext autoreload` and `%autoreload 2` while developing that package alongside the notebook. Confidence: 0.75 - Pin the environment with a lock file such as `uv.lock`, `poetry.lock` or a conda lock, and name the kernel after the project. Confidence: 0.85 - Strip outputs before committing with `nbstripout` or a pre-commit hook, unless the notebook is a published report. Confidence: 0.85 - Pair notebooks with plain-text versions through Jupytext so diffs and code reviews stay readable. Confidence: 0.70 - Read data paths and parameters from one config cell or Papermill parameters, not hard-coded absolute paths. Confidence: 0.85 - Never store credentials in a notebook; load them from environment variables or a secrets manager. Confidence: 0.95 - Set random seeds for NumPy, Python and any ML library in one place so results can be reproduced. Confidence: 0.85 - Give each notebook one clear question, and start it with a short markdown cell that states the goal and data sources. Confidence: 0.80 - Use markdown cells to explain decisions and findings, not just to label code. Confidence: 0.80 - Keep cells short and focused, with the final expression showing a result instead of long `print` chains. Confidence: 0.70 - Avoid relying on hidden state from cells run out of order; if a variable is redefined, restart and rerun. Confidence: 0.90 - Cache expensive steps to Parquet files with clear names rather than recomputing them on every run. Confidence: 0.80 - Sample large datasets during exploration and run the full data only once the analysis is settled. Confidence: 0.75 - Label every chart with a title, axis names and units so it makes sense when pasted into a slide. Confidence: 0.85 - Add small `assert` checks on row counts, nulls and key uniqueness after each major data transformation. Confidence: 0.80 - Name notebooks with a number and topic like `03-churn-features.ipynb` so the order of work is obvious. Confidence: 0.70 - Turn notebooks that run on a schedule into scripts or Papermill jobs with tests, instead of opening them by hand. Confidence: 0.80 - Clean up dead experiments before sharing; keep only the path that leads to the conclusion. Confidence: 0.75
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 writing well-typed, checker-friendly Python code.
# Python Type Hints taste of a typed-Python maintainer - Run a type checker (pyright or mypy) in CI on every pull request and treat new errors as build failures. Confidence: 0.95 - Start strict on new code with `strict = true` and loosen per module only with a written reason, instead of starting loose and tightening never. Confidence: 0.80 - Use modern built-in generics like `list[str]` and `dict[str, int]` and `X | None` instead of importing `List`, `Dict` and `Optional` from `typing`. Confidence: 0.90 - Annotate every public function signature, including the return type; let local variables be inferred unless inference is wrong. Confidence: 0.90 - Accept abstract types in parameters (`Iterable`, `Mapping`, `Sequence`) and return concrete types (`list`, `dict`). Confidence: 0.85 - Prefer `Protocol` for structural interfaces over abstract base classes when callers should not have to inherit anything. Confidence: 0.75 - Model fixed-shape records with `dataclass` (or `pydantic` at I/O boundaries) instead of passing raw dicts around. Confidence: 0.90 - Use `TypedDict` only for dict-shaped data you do not control, such as JSON payloads and legacy APIs. Confidence: 0.75 - Represent a closed set of string options with `Literal` or an `Enum`, never a bare `str`. Confidence: 0.85 - Treat `Any` as a bug report: confine it to the boundary where untyped data enters and narrow it immediately. Confidence: 0.85 - Prefer `object` over `Any` when a value is truly unknown, so the checker forces a narrowing step before use. Confidence: 0.70 - Narrow with `isinstance`, `match` statements and `TypeGuard`/`TypeIs` helpers instead of `cast()`. Confidence: 0.80 - Every `# type: ignore` must name the error code and carry a short comment explaining why it is safe. Confidence: 0.90 - Use `NewType` for IDs and units (`UserId`, `Cents`) that are easy to mix up but share an underlying type. Confidence: 0.70 - Ship a `py.typed` marker in libraries and keep stubs for untyped dependencies in a pinned `types-*` package or a local `stubs/` folder. Confidence: 0.85 - Use `@overload` only when the return type truly depends on argument types; otherwise simplify the API. Confidence: 0.70 - Prefer PEP 695 syntax (`def first[T](xs: list[T]) -> T`) on Python 3.12+ instead of module-level `TypeVar` declarations. Confidence: 0.75 - Annotate `self`-returning builder methods with `Self` rather than a bound `TypeVar`. Confidence: 0.80 - Mark constants with `Final` and override methods with `@override` so refactors surface mistakes. Confidence: 0.70 - Do not add runtime type checks that duplicate the static checker; validate only untrusted input at the edges. Confidence: 0.80 - Keep annotations import-cheap: put heavy imports under `if TYPE_CHECKING:` to avoid circular imports and slow startup. Confidence: 0.75