prompts.example.vnprompts.example.vnprompts.example.vn
TeamsBotsSkillsPromptsPromptmasters
BookFor KidsDevelopers
Login
CC0 2026 prompts.example.vn
DeepWikiHow to...DocsAPIPrivacyTermsSupportAboutGitHub
All Tags

Python Prompts

138 prompts
Python Unused and Missing Dependency Finder
Skill

Finds unused, missing and misplaced dependencies in a Python project: imports never declared, declared packages never imported, runtime code using dev-only packages, test-only runtime deps and requirements.txt vs pyproject.toml drift, with import-name mapping. Stdlib Python.

---
name: python-unused-and-missing-dependency-finder
description: Finds unused, missing and misplaced dependencies in a Python project: imports never declared, declared packages never imported, runtime code using dev-only packages, test-only runtime deps and requirements.txt vs pyproject.toml drift, with import-name mapping. Stdlib Python.
---

# Python Unused and Missing Dependency Finder

You help Python developers keep the list of dependencies honest. Over time projects collect packages nobody imports anymore (slower installs, a bigger attack surface, more security alerts), and code starts importing packages that were never declared and only work because they happen to be installed on the developer's laptop or come in through another package. Production then breaks with `ModuleNotFoundError` after an unrelated upgrade. You compare what the project declares with what its code really imports, explain every finding, and propose a small, safe cleanup.

An import scan is static: it cannot see plugins loaded by name, packages used only from the command line, database drivers chosen by a connection string, or code generated at runtime. Never delete a dependency only because the scan says "unused"; check it first and say how you checked.

## Files in this skill

- `scripts/dep_check.py` - parses requirements*.txt (with `-r` includes, extras, markers, URLs), pyproject.toml (`[project]` dependencies and optional-dependencies, `[dependency-groups]`, Poetry dependencies and groups) and every .py file with `ast` (never executes code); separates runtime code from tests, detects optional imports (`try/except ImportError`) and typing-only imports (`if TYPE_CHECKING`), skips the standard library and the project's own modules, maps import names to package names, and prints findings D01-D10 + E01; `--map`, `--ignore`, `--exclude`, `--use-installed`, `--format text|md|json|csv`, `--fail-on`, `--self-test` runs 31 checks (Python 3.8+ standard library only)
- `references/import-names-vs-package-names.md` - why `import yaml` means PyYAML, the common mismatches, and how to find the right name
- `references/false-positives-and-safe-removal.md` - when "unused" is not really unused, and a safe step-by-step removal routine
- `templates/dependency-cleanup-pr.md` - a pull request description for the cleanup with the evidence for each change
- `examples/shopapp/` - a small FastAPI shop project with a pyproject.toml, a pinned requirements.txt, two modules and one test file that contain one of each typical problem

## Workflow

### 1. Find the declarations
Ask where the project declares its dependencies and how it is installed in production (Docker image from `requirements.txt`, `pip install .`, Poetry, uv). Usual places:
```
pyproject.toml          [project] dependencies, [project.optional-dependencies], [dependency-groups], [tool.poetry.*]
requirements.txt        runtime (often pinned by pip-compile or uv export)
requirements-dev.txt    tests, linters, type checkers (any requirements file with dev/test/lint/doc/ci in its name)
```
If the project uses a different layout, pass the files explicitly with `--requirements` and `--dev-requirements`.

### 2. Run the check
```
python3 scripts/dep_check.py .                                   # auto-detects requirements*.txt and pyproject.toml
python3 scripts/dep_check.py . --format md > dependency-check.md
python3 scripts/dep_check.py . --requirements requirements/base.txt --dev-requirements requirements/test.txt
python3 scripts/dep_check.py . --exclude "scripts/*" --exclude "docs/*"
python3 scripts/dep_check.py . --map ruamel=ruamel.yaml --ignore psycopg2-binary
python3 scripts/dep_check.py . --use-installed                   # inside the project's virtualenv: map names via installed packages
python3 scripts/dep_check.py . --fail-on high                    # CI gate: fail on missing / dev-only runtime imports
python3 scripts/dep_check.py --self-test
```
Exit code 0 = fine (or `--fail-on none`, the default), 1 = findings at or above `--fail-on`, 2 = unreadable input.

| Code | Severity | Finding | Usual fix |
|---|---|---|---|
| D01 | high | runtime code imports a package that is not declared | declare it (with a sensible lower bound) |
| D02 | medium | tests import a package that is not declared | add it to the dev/test group |
| D03 | high | runtime code imports a package declared only as dev | move it to runtime dependencies |
| D04 | medium | runtime dependency never imported | check (see references), then remove |
| D05 | low | runtime dependency only imported by tests | move it to the dev/test group |
| D06 | info | optional import (try/except ImportError), not declared | declare it as an extra, document it |
| D07 | info | typing-only import, not declared | usually a stub package; add to dev if mypy needs it |
| D08 | info | runtime dependency that is a tool or server (uvicorn, gunicorn) | keep if production starts it from the command line |
| D09 | low | dev dependency never imported and not a known tool | check, then remove |
| D10 | low | requirements file and pyproject.toml lists have drifted | regenerate the pins or align the two lists |
| E01 | info | a file could not be parsed | fix the syntax error or exclude the file |

### 3. Check every finding before changing anything
Use `references/false-positives-and-safe-removal.md`. For each D04/D09 candidate search the repository for the package name outside Python imports (`grep -ri name Dockerfile Procfile *.cfg *.ini *.toml *.yaml .github`), check entry points and plugins (pytest plugins, SQLAlchemy dialects, Django `INSTALLED_APPS`, Celery brokers), and ask whether production runs it as a command. For D01 check if the package arrives only through another dependency today: that is exactly the fragile case to fix.

### 4. Propose the change
Group the changes: add missing (D01/D02/D03), move (D03/D05), remove after checks (D04/D09), document optional extras (D06), align pins (D10). Keep version ranges in pyproject.toml and exact pins only in the lock or requirements file. For every removal say how it was verified (tests pass in a fresh virtualenv, app starts, Docker image builds).

### 5. Verify in a clean environment
```
python3 -m venv /tmp/clean && /tmp/clean/bin/pip install -r requirements.txt && /tmp/clean/bin/python -c "import shopapp.api"
/tmp/clean/bin/pip install -e ".[dev]" && /tmp/clean/bin/python -m pytest -q
```
A fresh environment is the only reliable proof that nothing missing was hiding behind a package installed by hand.

### 6. Report
Fill `templates/dependency-cleanup-pr.md`: the findings table, each change with its evidence, what was deliberately kept and why, and the clean-environment test result.

## Rules
- Never remove a package on the scan result alone; show the check for each removal.
- Never run or import the project's code to find imports; the script only parses files.
- Treat missing runtime dependencies (D01, D03) as bugs: they decide whether a fresh deploy works.
- Do not upgrade versions as part of a cleanup; keep it a separate change.
- Respect the project's tool (pip-tools, Poetry, uv, Hatch); give commands for that tool, not a different one.
- Say clearly that dynamic imports, plugins and command-line tools are invisible to the scan.

FILE:references/import-names-vs-package-names.md
# Import names vs package names

The name you `pip install` (the distribution) and the name you `import` (the top-level module) are often different. A dependency checker has to translate between them, otherwise `PyYAML` looks unused and `yaml` looks undeclared at the same time.

## Common mismatches

| Import | Package on PyPI | Note |
|---|---|---|
| `yaml` | PyYAML | |
| `PIL` | Pillow | the old PIL package is dead |
| `sklearn` | scikit-learn | never install the `sklearn` placeholder package |
| `cv2` | opencv-python | also -headless and -contrib variants |
| `bs4` | beautifulsoup4 | |
| `dateutil` | python-dateutil | |
| `dotenv` | python-dotenv | |
| `jwt` | PyJWT | `jwt` on PyPI is a different library |
| `attr` | attrs | `import attrs` also works on newer versions |
| `Crypto` | pycryptodome | |
| `psycopg2` | psycopg2 or psycopg2-binary | |
| `google.protobuf` | protobuf | many `google.*` namespaces belong to different packages |
| `git` | GitPython | |
| `github` | PyGithub | |
| `fitz` | PyMuPDF | |
| `MySQLdb` | mysqlclient | |

## Name normalization
Package names are compared after PEP 503 normalization: lower case, and runs of `-`, `_` and `.` become one `-`. `Flask_SQLAlchemy`, `flask-sqlalchemy` and `flask.sqlalchemy` are the same package.

## Finding the right name for an unknown import
1. Inside the project's virtualenv: `python3 -c "from importlib.metadata import packages_distributions as p; print(p().get('yaml'))"` prints `['PyYAML']`. The script does this for every import with `--use-installed`.
2. `pip show -f <package>` lists the top-level modules a package installs.
3. On PyPI, check the project's "Homepage" and the import example in its README.
4. Add the answer to the run with `--map import_name=package-name` and, if it is common, to the mapping table in the script.

## Packages that are used without an import
- Servers and commands: uvicorn, gunicorn, celery workers, alembic, honcho.
- Plugins discovered by name: pytest-* plugins, flake8-* plugins, SQLAlchemy and Django database drivers named in a URL or a settings file, Jinja extensions.
- Stub packages for type checkers: types-requests, mypy-boto3-*.
- Packages needed by another import: FastAPI's and Starlette's `TestClient` need httpx; pandas needs openpyxl to read Excel files.

The script knows the common tools and a few implied packages, but every project has its own; treat its "unused" list as candidates, not as decisions.

FILE:references/false-positives-and-safe-removal.md
# False positives and safe removal

## Why a package can look unused but is needed
- **Started from the command line**: `uvicorn shopapp.api:app`, `gunicorn`, `celery -A app worker`, `alembic upgrade head`. Search the Dockerfile, Procfile, Makefile, compose files, systemd units and CI workflows.
- **Loaded by name**: pytest plugins (`pytest-cov`, `pytest-asyncio`), Django apps in `INSTALLED_APPS`, SQLAlchemy dialects in a database URL (`postgresql+psycopg2://`), logging handlers in a config file, Celery brokers (`redis://`), Jinja or Markdown extensions.
- **Imported dynamically**: `importlib.import_module(setting)`, entry points, plugin registries. The script only sees literal `import_module("name")` calls.
- **Needed by another import**: `fastapi.testclient` needs httpx, `pandas.read_excel` needs openpyxl, `requests[socks]` needs PySocks.
- **Pinned on purpose**: a transitive dependency pinned in the requirements file to fix a security issue or a bug (for example `urllib3`, `idna`). Keep it and add a comment with the reason.
- **Used in notebooks, scripts or docs that were excluded** from the scan.

## Why a package can look missing but is fine
- It is the project's own package with an unusual layout (pass `--exclude` or check that it lives in `src/` or the project root).
- It is only imported under `if TYPE_CHECKING:` (D07) or in a `try/except ImportError` block (D06).
- It is vendored inside the repository (then it is a local module; check the folder name).

## Safe removal routine
1. Search the whole repository for the package name and its import name, not only `.py` files: `git grep -n -i -e name -e import_name`.
2. Check the plugin and command-line cases above.
3. Remove it from the declaration (pyproject.toml and the requirements or lock file together).
4. Create a fresh virtualenv, install from the declarations only, then import the app, run the tests and, if there is one, build the Docker image.
5. Remove packages in small batches so a failure points to one change.
6. Write the evidence into the pull request (see the template).

## Missing dependencies are the urgent part
A package that is imported but not declared (D01) or declared only for development (D03) works on a laptop where someone installed it by hand, and fails on the next clean deploy. Fix those first, even if the cleanup of unused packages waits.

FILE:templates/dependency-cleanup-pr.md
# Dependency cleanup: {{project or package name}}

**Checked with:** `dep_check.py` on {{date}}, {{N}} Python files ({{M}} tests)  
**Declarations:** {{pyproject.toml / requirements.txt / requirements-dev.txt}}  
**Installed in production by:** {{Docker image from requirements.txt / pip install . / Poetry / uv}}

## Findings
| Code | Package | Finding | Decision |
|---|---|---|---|
| D01 | {{package}} | {{imported in file:line, not declared}} | {{add to runtime, >=x.y}} |
| D03 | {{package}} | {{runtime import, dev-only}} | {{move to runtime}} |
| D04 | {{package}} | {{never imported}} | {{remove / keep because ...}} |

## Changes
### Added
- `{{package}}>={{version}}` - imported by {{file}}; worked only because {{it came in through another package / was installed by hand}}.

### Moved
- `{{package}}` from {{dev}} to {{runtime}} (or the other way) - {{reason}}.

### Removed (with evidence)
- `{{package}}` - no import, no CLI use (searched Dockerfile, Procfile, CI), no plugin entry; tests pass without it.

### Kept on purpose
- `{{package}}` - {{started from the command line / plugin / pinned for a security fix}}.

## Verification
- Fresh virtualenv from the declarations only: {{pass/fail}}
- `python -c "import {{app}}"`: {{pass/fail}}
- Test suite: {{N passed}}
- Docker image build: {{pass/fail or not applicable}}

## Not covered by this check
- Dynamic imports and plugins loaded by name are invisible to a static scan; listed above what was checked by hand.

FILE:examples/shopapp/pyproject.toml
[project]
name = "shopapp"
version = "0.4.0"
description = "Order API and reports for a small online shop (example project)"
requires-python = ">=3.10"
dependencies = [
    "fastapi>=0.110",
    "pydantic>=2.6",
    "sqlalchemy>=2.0",
    "requests>=2.31",
    "python-dateutil>=2.9",
    "PyYAML>=6.0",
    "pandas>=2.2",
    "uvicorn[standard]>=0.29",
    "faker>=24.0",
]

[project.optional-dependencies]
dev = [
    "pytest>=8.0",
    "pytest-cov>=5.0",
    "ruff>=0.4",
    "httpx>=0.27",
    "freezegun>=1.4",
    "openpyxl>=3.1",
    "rich>=13.7",
]

[tool.ruff]
line-length = 100

FILE:examples/shopapp/requirements.txt
# pinned for the Docker image (generated by pip-compile, trimmed for the example)
fastapi==0.115.0
pydantic==2.9.2
sqlalchemy==2.0.35
requests==2.32.3
python-dateutil==2.9.0.post0
PyYAML==6.0.2
uvicorn[standard]==0.30.6

FILE:examples/shopapp/src/shopapp/__init__.py
"""shopapp - order API and reports for a small online shop (example project)."""
__version__ = "0.4.0"

FILE:examples/shopapp/src/shopapp/api.py
"""HTTP API for orders."""
import os
from datetime import datetime

import requests
import stripe
import yaml
from dateutil import parser as dateparser
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import create_engine, text

from shopapp import reports

app = FastAPI(title="shopapp")
engine = create_engine(os.environ.get("DATABASE_URL", "sqlite:///shop.db"))
stripe.api_key = os.environ.get("STRIPE_KEY", "")
with open(os.environ.get("SHOP_CONFIG", "config.yaml"), encoding="utf-8") as fh:
    CONFIG = yaml.safe_load(fh) or {}


class Order(BaseModel):
    id: int
    email: str
    total_cents: int
    created_at: datetime


@app.get("/orders/{order_id}")
def get_order(order_id: int) -> Order:
    with engine.connect() as conn:
        row = conn.execute(text("select id, email, total_cents, created_at from orders where id = :id"), {"id": order_id}).first()
    if row is None:
        raise HTTPException(status_code=404, detail="order not found")
    return Order(id=row[0], email=row[1], total_cents=row[2], created_at=dateparser.parse(str(row[3])))


@app.post("/orders/{order_id}/refund")
def refund(order_id: int) -> dict:
    order = get_order(order_id)
    stripe.Refund.create(payment_intent=str(order.id))
    requests.post(CONFIG.get("webhook_url", "https://example.com/hook"), json={"refunded": order.id}, timeout=10)
    return {"ok": True}


@app.get("/reports/daily.xlsx")
def daily_report() -> dict:
    return {"path": reports.daily_sales_workbook()}

FILE:examples/shopapp/src/shopapp/reports.py
"""Sales reports: an Excel workbook and an optional upload to S3."""
from __future__ import annotations

import csv
import os
from typing import TYPE_CHECKING

from openpyxl import Workbook

try:
    import boto3
except ImportError:  # uploads are optional
    boto3 = None

if TYPE_CHECKING:
    from mypy_boto3_s3 import S3Client


def daily_sales_workbook(rows=None, path="daily_sales.xlsx"):
    wb = Workbook()
    ws = wb.active
    ws.append(["order_id", "email", "total"])
    for row in rows or []:
        ws.append(row)
    wb.save(path)
    if boto3 is not None and os.environ.get("REPORT_BUCKET"):
        client: S3Client = boto3.client("s3")
        client.upload_file(path, os.environ["REPORT_BUCKET"], os.path.basename(path))
    return path


def to_csv(rows, path="daily_sales.csv"):
    with open(path, "w", newline="", encoding="utf-8") as fh:
        csv.writer(fh).writerows(rows)
    return path

FILE:examples/shopapp/tests/test_api.py
import pytest
import respx
from faker import Faker
from fastapi.testclient import TestClient
from freezegun import freeze_time

from shopapp.api import app

fake = Faker()
client = TestClient(app)


@freeze_time("2026-12-01 10:00:00")
def test_missing_order_returns_404():
    assert client.get("/orders/999999").status_code == 404


@respx.mock
def test_refund_calls_webhook():
    respx.post("https://example.com/hook").respond(200)
    pytest.skip("needs a seeded database")

FILE:scripts/dep_check.py
#!/usr/bin/env python3
"""dep_check.py - find unused, missing and misplaced dependencies in a Python project.

Compares what a project declares (requirements*.txt, pyproject.toml: [project] dependencies,
optional-dependencies, [dependency-groups], Poetry dependencies and groups) with what its code
really imports (parsed with ast, never executed). Knows the usual import-name vs package-name
differences (yaml -> PyYAML, PIL -> Pillow, sklearn -> scikit-learn ...), skips the standard
library and the project's own modules, separates runtime code from tests, and understands
optional imports (try/except ImportError) and typing-only imports (if TYPE_CHECKING).

Usage:
  dep_check.py PROJECT_DIR [--requirements FILE ...] [--dev-requirements FILE ...]
               [--pyproject FILE] [--exclude GLOB ...] [--map IMPORT=PACKAGE ...]
               [--ignore PACKAGE ...] [--use-installed] [--format text|md|json|csv]
               [--fail-on none|info|low|medium|high]
  dep_check.py --self-test
Exit: 0 ok, 1 findings at or above --fail-on, 2 unreadable input. Python 3.8+, standard library only
(tomllib is used on 3.11+, a small built-in reader for the needed tables otherwise).
"""
import argparse, ast, csv, fnmatch, io, json, os, re, sys

SEV = {"info": 0, "low": 1, "medium": 2, "high": 3}

# import name -> distribution name, for the common cases where they differ
IMPORT_TO_DIST = {
    "yaml": "pyyaml", "PIL": "pillow", "sklearn": "scikit-learn", "cv2": "opencv-python",
    "bs4": "beautifulsoup4", "dateutil": "python-dateutil", "dotenv": "python-dotenv",
    "jwt": "pyjwt", "attr": "attrs", "Crypto": "pycryptodome", "serial": "pyserial",
    "usb": "pyusb", "docx": "python-docx", "pptx": "python-pptx", "multipart": "python-multipart",
    "jose": "python-jose", "slugify": "python-slugify", "gi": "pygobject", "OpenSSL": "pyopenssl",
    "zmq": "pyzmq", "magic": "python-magic", "psycopg2": "psycopg2", "MySQLdb": "mysqlclient",
    "google.protobuf": "protobuf", "googleapiclient": "google-api-python-client",
    "telegram": "python-telegram-bot", "discord": "discord-py", "win32api": "pywin32",
    "win32com": "pywin32", "skimage": "scikit-image", "Levenshtein": "levenshtein",
    "fitz": "pymupdf", "lxml": "lxml", "markdown": "markdown", "dns": "dnspython",
    "nacl": "pynacl", "socks": "pysocks", "Xlib": "python-xlib", "pkg_resources": "setuptools",
    "setuptools": "setuptools", "ldap": "python-ldap", "jinja2": "jinja2", "kafka": "kafka-python",
    "sentry_sdk": "sentry-sdk", "dateparser": "dateparser", "tz": "pytz", "pytz": "pytz",
    "rest_framework": "djangorestframework", "flask_sqlalchemy": "flask-sqlalchemy",
    "flask_cors": "flask-cors", "github": "pygithub", "git": "gitpython", "editor": "python-editor",
}
# distributions that provide one of several import names (alternatives count as the same package)
DIST_ALIASES = {"psycopg2-binary": "psycopg2", "opencv-python-headless": "opencv-python",
                "opencv-contrib-python": "opencv-python", "pillow-simd": "pillow",
                "pyjwt": "pyjwt", "tensorflow-cpu": "tensorflow"}
# installed and used as tools, plugins, servers or stubs, never imported by application code
TOOL_PREFIXES = ("types-", "pytest-", "flake8-", "mypy-", "sphinx-", "pre-commit", "mkdocs-")
TOOLS = {"pytest", "black", "ruff", "mypy", "flake8", "isort", "pylint", "coverage", "tox", "nox",
         "pre-commit", "build", "twine", "wheel", "setuptools", "pip", "pip-tools", "hatch",
         "hatchling", "poetry", "poetry-core", "sphinx", "mkdocs", "mkdocs-material", "bandit",
         "safety", "pip-audit", "invoke", "ipython", "jupyter", "notebook", "jupyterlab",
         "gunicorn", "uvicorn", "hypercorn", "daphne", "waitress", "supervisor", "honcho",
         "watchdog", "python-dotenv-cli", "alembic", "celery-flower", "flower", "debugpy",
         "commitizen", "towncrier", "bump-my-version", "bumpversion", "pyright", "codespell"}
# imports that need another package which is never imported by name
IMPLIED = {"fastapi.testclient": ["httpx"], "starlette.testclient": ["httpx"],
           "pandas.io.excel": ["openpyxl"], "uvicorn.workers": ["gunicorn"]}
STD_FALLBACK = set("""__future__ abc argparse array ast asyncio base64 bisect builtins bz2 calendar
cmath collections concurrent configparser contextlib contextvars copy csv ctypes dataclasses datetime
decimal difflib dis email encodings enum errno faulthandler fnmatch fractions ftplib functools gc
getpass gettext glob gzip hashlib heapq hmac html http imaplib importlib inspect io ipaddress
itertools json keyword linecache locale logging lzma mailbox math mimetypes multiprocessing netrc
numbers operator os pathlib pickle pkgutil platform plistlib pprint profile pstats queue random re
sched secrets select selectors shelve shlex shutil signal site smtplib socket socketserver sqlite3
ssl stat statistics string struct subprocess sys sysconfig tarfile tempfile textwrap threading time
timeit tkinter token tokenize tomllib trace traceback types typing unicodedata unittest urllib uuid
venv warnings wave weakref webbrowser wsgiref xml xmlrpc zipfile zipimport zlib zoneinfo""".split())
STDLIB = set(getattr(sys, "stdlib_module_names", ())) or STD_FALLBACK
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", ".env", "node_modules", "__pycache__", ".tox",
             ".nox", "build", "dist", ".mypy_cache", ".pytest_cache", ".ruff_cache", "site-packages"}


def norm(name):
    """PEP 503 normalized distribution name."""
    return re.sub(r"[-_.]+", "-", name.strip()).lower()


# ---------------------------------------------------------------- declared dependencies
REQ_NAME = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)\s*(\[[^\]]*\])?\s*(.*)$")


def parse_req_line(line):
    """'requests[socks]>=2.31 ; python_version>="3.8"' -> ('requests', '>=2.31') or None."""
    line = line.split(" #", 1)[0].strip()
    if not line or line.startswith("#"):
        return None
    if " @ " in line:                       # name @ url
        return norm(line.split(" @ ", 1)[0].split("[", 1)[0]), "@ url"
    m = REQ_NAME.match(line.split(";", 1)[0])
    if not m:
        return None
    return norm(m.group(1)), (m.group(3) or "").strip()


def read_requirements(path, seen=None):
    """Returns (deps {name: spec}, notes [str]). Follows -r / -c includes relative to the file."""
    seen = seen if seen is not None else set()
    path = os.path.abspath(path)
    deps, notes = {}, []
    if path in seen:
        return deps, notes
    seen.add(path)
    with open(path, encoding="utf-8") as fh:
        for raw in fh:
            line = raw.strip()
            if not line or line.startswith("#"):
                continue
            if line.startswith(("-r ", "--requirement ")):
                inc = os.path.join(os.path.dirname(path), line.split(None, 1)[1].strip())
                d, n = read_requirements(inc, seen)
                deps.update(d); notes += n
                continue
            if line.startswith(("-c ", "--constraint ", "--index-url", "--extra-index-url", "-i ", "--find-links", "-f ", "--trusted-host", "--hash")):
                continue
            if line.startswith(("-e ", "--editable ")) or re.match(r"^(git\+|https?://|file:|\.{0,2}/)", line):
                egg = re.search(r"#egg=([A-Za-z0-9._-]+)", line)
                if egg:
                    deps[norm(egg.group(1))] = "editable/url"
                else:
                    notes.append("%s: skipped line without a package name: %s" % (os.path.basename(path), line[:80]))
                continue
            r = parse_req_line(line)
            if r:
                deps[r[0]] = r[1]
            else:
                notes.append("%s: could not parse: %s" % (os.path.basename(path), line[:80]))
    return deps, notes


def load_toml(path):
    try:
        import tomllib  # Python 3.11+
        with open(path, "rb") as fh:
            return tomllib.load(fh)
    except ImportError:
        return mini_toml(open(path, encoding="utf-8").read())


def mini_toml(text):
    """Tiny TOML reader for 3.8-3.10: tables, dotted table names, strings, string arrays and inline
    tables as strings. Enough for dependency tables; not a general TOML parser."""
    data, cur = {}, None
    cur = data
    lines = text.splitlines()
    i = 0
    while i < len(lines):
        line = lines[i].split("#", 1)[0].strip() if not lines[i].strip().startswith("#") else ""
        i += 1
        if not line:
            continue
        m = re.match(r"^\[\[?([^\]]+)\]\]?$", line)
        if m:
            cur = data
            for part in [p.strip().strip('"') for p in m.group(1).split(".")]:
                cur = cur.setdefault(part, {})
            continue
        if "=" not in line:
            continue
        key, val = [x.strip() for x in line.split("=", 1)]
        key = key.strip('"')
        if val.startswith("[") and not val.rstrip().endswith("]"):
            while i < len(lines):
                val += " " + lines[i].split("#", 1)[0].strip(); i += 1
                if val.rstrip().endswith("]"):
                    break
        if val.startswith("["):
            cur[key] = re.findall(r'"([^"]*)"|\'([^\']*)\'', val)
            cur[key] = [a or b for a, b in cur[key]]
        elif val.startswith(("\"", "'")):
            cur[key] = val[1:-1]
        else:
            cur[key] = val
    return data


def read_pyproject(path):
    """Returns (runtime {name: spec}, dev {name: spec}, project_name or None)."""
    try:
        t = load_toml(path)
    except ValueError as e:
        raise ValueError("%s: %s" % (os.path.basename(path), e))
    run, dev = {}, {}
    proj = t.get("project", {}) or {}
    for line in proj.get("dependencies", []) or []:
        r = parse_req_line(line)
        if r: run[r[0]] = r[1]
    for group, lines in (proj.get("optional-dependencies", {}) or {}).items():
        target = dev if re.search(r"dev|test|lint|doc|type|ci", group, re.I) else run
        for line in lines or []:
            r = parse_req_line(line)
            if r: target.setdefault(r[0], r[1] + " [extra:%s]" % group)
    for group, lines in (t.get("dependency-groups", {}) or {}).items():
        for line in lines or []:
            if isinstance(line, str):
                r = parse_req_line(line)
                if r: dev[r[0]] = r[1]
    poetry = (t.get("tool", {}) or {}).get("poetry", {}) or {}
    for name, spec in (poetry.get("dependencies", {}) or {}).items():
        if name.lower() != "python":
            run[norm(name)] = spec if isinstance(spec, str) else "poetry"
    for name, spec in (poetry.get("dev-dependencies", {}) or {}).items():
        dev[norm(name)] = spec if isinstance(spec, str) else "poetry"
    for group in (poetry.get("group", {}) or {}).values():
        for name, spec in ((group or {}).get("dependencies", {}) or {}).items():
            dev[norm(name)] = spec if isinstance(spec, str) else "poetry"
    return run, dev, proj.get("name") or poetry.get("name")


# ---------------------------------------------------------------- imports
class ImportVisitor(ast.NodeVisitor):
    def __init__(self):
        self.found = []          # (module, line, kind) kind: normal | optional | typing
        self.optional = 0
        self.typing = 0

    def _add(self, mod, line):
        kind = "typing" if self.typing else ("optional" if self.optional else "normal")
        self.found.append((mod, line, kind))

    def visit_Import(self, node):
        for a in node.names:
            self._add(a.name, node.lineno)

    def visit_ImportFrom(self, node):
        if node.level == 0 and node.module:
            self._add(node.module, node.lineno)

    def visit_Try(self, node):
        catches = any(self._is_import_error(h.type) for h in node.handlers)
        self.optional += catches
        for n in node.body:
            self.visit(n)
        self.optional -= catches
        for part in node.handlers + node.orelse + node.finalbody:
            self.visit(part)
    visit_TryStar = visit_Try

    @staticmethod
    def _is_import_error(t):
        if t is None:
            return True
        names = [t] if not isinstance(t, ast.Tuple) else list(t.elts)
        return any(isinstance(n, ast.Name) and n.id in ("ImportError", "ModuleNotFoundError", "Exception") for n in names)

    def visit_If(self, node):
        test = node.test
        is_tc = (isinstance(test, ast.Name) and test.id == "TYPE_CHECKING") or \
                (isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING")
        self.typing += is_tc
        for n in node.body:
            self.visit(n)
        self.typing -= is_tc
        for n in node.orelse:
            self.visit(n)

    def visit_Call(self, node):
        # importlib.import_module("x") / __import__("x") with a literal name
        f = node.func
        name = f.attr if isinstance(f, ast.Attribute) else (f.id if isinstance(f, ast.Name) else "")
        if name in ("import_module", "__import__") and node.args and isinstance(node.args[0], ast.Constant) \
                and isinstance(node.args[0].value, str) and not node.args[0].value.startswith("."):
            self._add(node.args[0].value, node.lineno)
        self.generic_visit(node)


def is_test_file(rel):
    parts = rel.replace("\\", "/").split("/")
    base = parts[-1]
    return any(p in ("tests", "test", "testing") for p in parts[:-1]) or base.startswith("test_") \
        or base.endswith("_test.py") or base == "conftest.py"


def walk_py(root, excludes):
    for d, dirs, files in os.walk(root):
        dirs[:] = sorted(x for x in dirs if x not in SKIP_DIRS and not x.endswith(".egg-info"))
        for f in sorted(files):
            if f.endswith(".py"):
                full = os.path.join(d, f)
                rel = os.path.relpath(full, root).replace("\\", "/")
                if any(fnmatch.fnmatch(rel, g) for g in excludes):
                    continue
                yield full, rel


def local_modules(root, files):
    """Top-level names that belong to the project itself (packages, modules, src layout)."""
    names = set()
    for _, rel in files:
        parts = rel.split("/")
        if parts[0] in ("src", "lib") and len(parts) > 1:
            parts = parts[1:]
        names.add(parts[0][:-3] if parts[0].endswith(".py") else parts[0])
        if len(parts) > 1 and parts[0] in ("tests", "test"):
            names.add(parts[1][:-3] if parts[1].endswith(".py") else parts[1])
    return names


def import_to_dist(mod, extra_map, installed):
    top = mod.split(".")[0]
    for key in (mod, ".".join(mod.split(".")[:2]), top):
        if key in extra_map:
            return norm(extra_map[key])
        if key in IMPORT_TO_DIST:
            return norm(IMPORT_TO_DIST[key])
    if installed and top in installed:
        return norm(installed[top][0])
    return norm(top)


def same_pkg(a, b):
    a, b = DIST_ALIASES.get(a, a), DIST_ALIASES.get(b, b)
    return a == b


def is_tool(name):
    return name in TOOLS or name.startswith(TOOL_PREFIXES)


# ---------------------------------------------------------------- analysis
def analyze(root, req_files=None, dev_req_files=None, pyproject=None, excludes=(), extra_map=None,
            ignore=(), use_installed=False):
    root = os.path.abspath(root)
    if not os.path.isdir(root):
        raise FileNotFoundError("project directory not found: %s" % root)
    extra_map = dict(extra_map or {})
    notes, runtime, dev, sources = [], {}, {}, {}
    # discover declaration files
    if req_files is None and dev_req_files is None:
        req_files, dev_req_files = [], []
        for f in sorted(os.listdir(root)):
            if re.match(r"^requirements.*\.(txt|in)$", f):
                (dev_req_files if re.search(r"dev|test|lint|doc|ci", f) else req_files).append(os.path.join(root, f))
    for f in req_files or []:
        d, n = read_requirements(f); notes += n
        for k, v in d.items():
            runtime[k] = v; sources.setdefault(k, []).append(os.path.basename(f))
    for f in dev_req_files or []:
        d, n = read_requirements(f); notes += n
        for k, v in d.items():
            dev[k] = v; sources.setdefault(k, []).append(os.path.basename(f))
    pp = pyproject or os.path.join(root, "pyproject.toml")
    project_name, req_run = None, dict(runtime)
    pp_run = {}
    if os.path.exists(pp):
        r, d, project_name = read_pyproject(pp)
        pp_run = {k: v for k, v in r.items() if "extra:" not in v}
        for k, v in r.items():
            runtime.setdefault(k, v); sources.setdefault(k, []).append("pyproject.toml")
        for k, v in d.items():
            dev.setdefault(k, v); sources.setdefault(k, []).append("pyproject.toml (dev)")
    if not runtime and not dev:
        notes.append("no dependency declarations found (requirements*.txt or pyproject.toml)")
    installed = {}
    if use_installed:
        try:
            from importlib.metadata import packages_distributions
            installed = packages_distributions()
        except Exception as e:  # pragma: no cover
            notes.append("--use-installed not available: %s" % e)
    files = list(walk_py(root, excludes))
    local = local_modules(root, files)
    if project_name:
        local.add(project_name.replace("-", "_"))
    uses = {}      # dist -> list of (rel, line, kind, is_test, module)
    implied = {}   # dist -> uses through another import (e.g. httpx via fastapi.testclient)
    parse_errors = []
    for full, rel in files:
        try:
            tree = ast.parse(open(full, encoding="utf-8").read(), filename=rel)
        except (SyntaxError, UnicodeDecodeError) as e:
            parse_errors.append((rel, str(e).split("\n")[0])); continue
        v = ImportVisitor(); v.visit(tree)
        for mod, line, kind in v.found:
            top = mod.split(".")[0]
            if top in STDLIB or top in local or top.startswith("_"):
                continue
            dist = import_to_dist(mod, extra_map, installed)
            uses.setdefault(dist, []).append((rel, line, kind, is_test_file(rel), mod))
            for key, extra_pkgs in IMPLIED.items():
                if mod == key or mod.startswith(key + "."):
                    for x in extra_pkgs:
                        implied.setdefault(norm(x), []).append((rel, line, kind, is_test_file(rel), mod))
    ignore = {norm(x) for x in ignore}

    def declared_as(dist):
        for k in runtime:
            if same_pkg(k, dist): return "runtime", k
        for k in dev:
            if same_pkg(k, dist): return "dev", k
        return None, None

    findings = []
    def add(code, sev, pkg, msg, where=None):
        if pkg in ignore: return
        findings.append({"code": code, "severity": sev, "package": pkg, "message": msg, "where": where or []})

    for dist in sorted(uses):
        u = uses[dist]
        run_u = [x for x in u if not x[3] and x[2] == "normal"]
        opt_u = [x for x in u if not x[3] and x[2] == "optional"]
        typ_u = [x for x in u if not x[3] and x[2] == "typing"]
        test_u = [x for x in u if x[3]]
        kind, decl = declared_as(dist)
        loc = lambda xs: ["%s:%d" % (x[0], x[1]) for x in xs[:5]]
        mods = sorted({x[4].split(".")[0] for x in u})
        hint = "" if mods == [dist] else " (import %s)" % ", ".join(mods)
        if kind is None:
            if run_u:
                add("D01", "high", dist, "imported by runtime code but not declared%s" % hint, loc(run_u))
            elif opt_u:
                add("D06", "info", dist, "optional import (try/except ImportError) not declared; consider an extra%s" % hint, loc(opt_u))
            elif test_u:
                add("D02", "medium", dist, "imported by tests but not declared as a dev/test dependency%s" % hint, loc(test_u))
            elif typ_u:
                add("D07", "info", dist, "imported only under TYPE_CHECKING and not declared; fine if a stub or dev dependency provides it%s" % hint, loc(typ_u))
        elif kind == "dev" and run_u:
            add("D03", "high", decl, "imported by runtime code but declared only as a dev dependency; it will be missing in production%s" % hint, loc(run_u))
        elif kind == "runtime" and not run_u and not opt_u and test_u and not typ_u:
            add("D05", "low", decl, "declared as a runtime dependency but only imported by tests; move it to dev/test%s" % hint, loc(test_u))
    used_dists = set(uses) | set(implied)
    if req_run and pp_run:
        for name in sorted(set(pp_run) - set(req_run)):
            if any(same_pkg(name, d) for d in used_dists) or not is_tool(name):
                add("D10", "low", name, "declared in pyproject.toml but missing from the requirements file(s); installs from the requirements file (e.g. a Docker image) will not get it")
        for name in sorted(set(req_run) - set(pp_run)):
            add("D10", "low", name, "pinned in the requirements file(s) but not declared in pyproject.toml; the two lists have drifted")
        both = sorted(set(req_run) & set(pp_run))
        if both:
            notes.append("%d packages appear in both the requirements file(s) and pyproject.toml (pins vs ranges is normal; keep them in sync): %s" % (len(both), ", ".join(both)))
    for name in sorted(runtime):
        if not any(same_pkg(name, d) for d in used_dists):
            if is_tool(name):
                add("D08", "info", name, "runtime dependency that is a tool, server or plugin and is never imported; check that production really needs it (e.g. an ASGI or WSGI server started from the command line)")
            else:
                add("D04", "medium", name, "declared as a runtime dependency but never imported (check plugins, entry points, CLI use or dynamic imports before removing)")
    for name in sorted(dev):
        if not any(same_pkg(name, d) for d in used_dists) and not is_tool(name):
            add("D09", "low", name, "declared as a dev dependency but never imported and not a known tool")
    for rel, err in parse_errors:
        add("E01", "info", rel, "could not parse file, imports not checked: %s" % err)
    findings.sort(key=lambda f: (-SEV[f["severity"]], f["code"], f["package"]))
    summary = {"project": root, "python_files": len(files), "test_files": sum(1 for _, r in files if is_test_file(r)),
               "declared_runtime": len(runtime), "declared_dev": len(dev), "imported_packages": len(uses),
               "by_severity": {s: sum(1 for f in findings if f["severity"] == s) for s in ("high", "medium", "low", "info")}}
    return {"summary": summary, "findings": findings, "notes": notes,
            "declared": {"runtime": runtime, "dev": dev, "sources": sources},
            "imports": {d: [{"file": x[0], "line": x[1], "kind": x[2], "test": x[3], "module": x[4]} for x in u] for d, u in sorted(uses.items())}}


# ---------------------------------------------------------------- output
def render(res, fmt):
    s, F = res["summary"], res["findings"]
    if fmt == "json":
        return json.dumps(res, indent=2)
    if fmt == "csv":
        out = io.StringIO(); w = csv.writer(out)
        w.writerow(["code", "severity", "package", "message", "where"])
        for f in F:
            w.writerow([f["code"], f["severity"], f["package"], f["message"], " ".join(f["where"])])
        return out.getvalue().rstrip("\n")
    md = fmt == "md"
    L = []
    L.append("## Dependency check" if md else "Dependency check")
    L.append("%s files scanned (%d tests), %d runtime + %d dev dependencies declared, %d third-party packages imported" % (
        s["python_files"], s["test_files"], s["declared_runtime"], s["declared_dev"], s["imported_packages"]))
    b = s["by_severity"]
    L.append("Findings: %d high, %d medium, %d low, %d info" % (b["high"], b["medium"], b["low"], b["info"]))
    L.append("")
    if md:
        L += ["| Code | Severity | Package | Finding | Where |", "|---|---|---|---|---|"]
        for f in F:
            L.append("| %s | %s | `%s` | %s | %s |" % (f["code"], f["severity"], f["package"], f["message"], ", ".join(f["where"]) or "-"))
    else:
        L.append("Findings")
        for f in F:
            L.append("  %s %-6s %-22s %s" % (f["code"], f["severity"], f["package"], f["message"]))
            if f["where"]:
                L.append("      at " + ", ".join(f["where"]))
        if not F:
            L.append("  none")
    if res["notes"]:
        L += ["", "### Notes" if md else "Notes"] + ["- " + n for n in res["notes"]]
    return "\n".join(L)


# ---------------------------------------------------------------- self-test
def self_test():
    import tempfile, shutil
    checks = []
    def ok(name, cond):
        checks.append((name, bool(cond)))
    ok("norm", norm("Py_YAML.x") == "py-yaml-x")
    ok("req line extras/markers", parse_req_line('requests[socks]>=2.31 ; python_version>="3.8"') == ("requests", ">=2.31"))
    ok("req line url", parse_req_line("mypkg @ https://x/y.whl")[0] == "mypkg")
    ok("req comment", parse_req_line("# hi") is None)
    ok("map yaml", import_to_dist("yaml", {}, {}) == "pyyaml")
    ok("map dotted", import_to_dist("google.protobuf.json_format", {}, {}) == "protobuf")
    ok("map override", import_to_dist("foo.bar", {"foo": "Foo-Lib"}, {}) == "foo-lib")
    ok("alias psycopg2-binary", same_pkg("psycopg2-binary", "psycopg2"))
    ok("tool prefix", is_tool("pytest-cov") and is_tool("types-requests") and not is_tool("requests"))
    ok("test file", is_test_file("tests/test_a.py") and is_test_file("pkg/conftest.py") and not is_test_file("pkg/a.py"))
    t = mini_toml('[project]\nname = "x"\ndependencies = [\n  "a>=1",\n  "b",\n]\n[project.optional-dependencies]\ndev = ["pytest"]\n')
    ok("mini toml", t["project"]["dependencies"] == ["a>=1", "b"] and t["project"]["optional-dependencies"]["dev"] == ["pytest"])
    v = ImportVisitor()
    v.visit(ast.parse("import a\ntry:\n    import b\nexcept ImportError:\n    b = None\nif TYPE_CHECKING:\n    import c\nfrom . import d\nimport importlib\nimportlib.import_module('e')\n"))
    kinds = {m: k for m, _, k in v.found}
    ok("visitor kinds", kinds.get("a") == "normal" and kinds.get("b") == "optional" and kinds.get("c") == "typing" and "d" not in kinds and kinds.get("e") == "normal")
    tmp = tempfile.mkdtemp()
    try:
        os.makedirs(os.path.join(tmp, "src", "app")); os.makedirs(os.path.join(tmp, "tests"))
        open(os.path.join(tmp, "requirements.txt"), "w").write("requests==2.31\nPyYAML>=6\nunusedlib\ngunicorn\n-r requirements-extra.txt\n")
        open(os.path.join(tmp, "requirements-extra.txt"), "w").write("psycopg2-binary\n")
        open(os.path.join(tmp, "requirements-dev.txt"), "w").write("pytest\nruff\nhttpx\nnever-used-dev\n")
        open(os.path.join(tmp, "src", "app", "__init__.py"), "w").write("")
        open(os.path.join(tmp, "src", "app", "main.py"), "w").write("import os, json\nimport requests\nimport yaml\nimport psycopg2\nimport httpx\nimport attr\nfrom app import util\ntry:\n    import ujson\nexcept ImportError:\n    ujson = None\n")
        open(os.path.join(tmp, "src", "app", "util.py"), "w").write("def f(:\n")
        open(os.path.join(tmp, "tests", "test_main.py"), "w").write("import pytest\nimport respx\nfrom app import main\n")
        r = analyze(tmp)
        codes = {(f["code"], f["package"]) for f in r["findings"]}
        ok("D01 missing attrs", ("D01", "attrs") in codes)
        ok("D03 dev-only httpx used at runtime", ("D03", "httpx") in codes)
        ok("D04 unused", ("D04", "unusedlib") in codes)
        ok("D08 server tool", ("D08", "gunicorn") in codes)
        ok("D02 test import undeclared", ("D02", "respx") in codes)
        ok("D06 optional", ("D06", "ujson") in codes)
        ok("D09 unused dev", ("D09", "never-used-dev") in codes and ("D09", "ruff") not in codes)
        ok("include + alias used", not any(f["package"] == "psycopg2-binary" for f in r["findings"]))
        ok("yaml mapped, no false D01", ("D01", "yaml") not in codes and ("D04", "pyyaml") not in codes)
        ok("E01 parse error", ("E01", "src/app/util.py") in codes)
        ok("local + stdlib ignored", not any(f["package"] in ("os", "json", "app") for f in r["findings"]))
        r2 = analyze(tmp, ignore=["attrs"])
        ok("ignore", not any(f["package"] == "attrs" for f in r2["findings"]))
        ok("sorted high first", r["findings"][0]["severity"] == "high")
        t2 = os.path.join(tmp, "p2"); os.makedirs(os.path.join(t2, "tests"))
        open(os.path.join(t2, "pyproject.toml"), "w").write('[project]\nname = "p2"\ndependencies = ["requests>=2", "fastapi"]\n[project.optional-dependencies]\ntest = ["httpx", "pytest"]\n')
        open(os.path.join(t2, "requirements.txt"), "w").write("requests==2.32.3\nidna==3.7\n")
        open(os.path.join(t2, "p2.py"), "w").write("import requests\nimport fastapi\n")
        open(os.path.join(t2, "tests", "test_p2.py"), "w").write("from fastapi.testclient import TestClient\nimport p2\n")
        c2 = {(f["code"], f["package"]) for f in analyze(t2)["findings"]}
        ok("D10 drift both ways", ("D10", "fastapi") in c2 and ("D10", "idna") in c2 and ("D10", "requests") not in c2)
        ok("implied httpx via TestClient", ("D09", "httpx") not in c2)
        ok("project module p2 is local", not any(f["package"] == "p2" for f in analyze(t2)["findings"]))
        ok("csv render", render(r, "csv").splitlines()[0].startswith("code,severity"))
        ok("json render", json.loads(render(r, "json"))["summary"]["python_files"] == 4)
        ok("explicit files override auto-detect", not analyze(tmp, [os.path.join(tmp, "requirements-dev.txt")], [])["declared"]["dev"])
    finally:
        shutil.rmtree(tmp)
    bad = [n for n, c in checks if not c]
    if bad:
        print("self-test FAILED: " + ", ".join(bad)); return 1
    print("self-test OK: %d checks" % len(checks)); return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description="Find unused, missing and misplaced Python dependencies.")
    ap.add_argument("project", nargs="?")
    ap.add_argument("--requirements", action="append", help="runtime requirements file (repeatable); default: auto-detect")
    ap.add_argument("--dev-requirements", action="append", help="dev/test requirements file (repeatable)")
    ap.add_argument("--pyproject", help="path to pyproject.toml (default: PROJECT/pyproject.toml)")
    ap.add_argument("--exclude", action="append", default=[], help="glob of files to skip, relative to the project")
    ap.add_argument("--map", action="append", default=[], help="IMPORT=PACKAGE mapping, e.g. --map ruamel=ruamel.yaml")
    ap.add_argument("--ignore", action="append", default=[], help="package name to leave out of the findings")
    ap.add_argument("--use-installed", action="store_true", help="also map import names with the current environment's installed packages")
    ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
    ap.add_argument("--fail-on", choices=["none", "info", "low", "medium", "high"], default="none")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.project:
        ap.error("PROJECT directory is required")
    extra = {}
    for m in a.map:
        if "=" not in m:
            ap.error("--map needs IMPORT=PACKAGE, got %r" % m)
        k, v = m.split("=", 1); extra[k.strip()] = v.strip()
    req = a.requirements; dev = a.dev_requirements
    if req is not None or dev is not None:
        req, dev = req or [], dev or []
    try:
        res = analyze(a.project, req, dev, a.pyproject, a.exclude, extra, a.ignore, a.use_installed)
    except (OSError, ValueError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    print(render(res, a.format))
    if a.fail_on != "none" and any(SEV[f["severity"]] >= SEV[a.fail_on] for f in res["findings"]):
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
PythonCode ReviewCI/CD+4
F@f
0
Support Ticket SLA Breach Analyzer
Skill

Measures support SLAs from a helpdesk ticket export in business hours: first response and resolution times, attainment by priority, agent, channel and week, open tickets breached or about to breach, reopen rate and data gaps, plus a weekly review for support leads and founders. Stdlib Python.

---
name: support-ticket-sla-breach-analyzer
description: Measures support SLAs from a helpdesk ticket export in business hours: first response and resolution times, attainment by priority, agent, channel and week, open tickets breached or about to breach, reopen rate and data gaps, plus a weekly review for support leads and founders. Stdlib Python.
---

# Support Ticket SLA Breach Analyzer

You help support leads, operations managers and founders of small companies see whether they keep the promises they make to customers about response and resolution times. Helpdesk dashboards often show a single average, count nights and weekends as waiting time, or hide which priority, channel or week is slipping. You take a plain ticket export and the team's SLA policy, measure every ticket in business hours, and turn the result into a short, fair review: where the team is on track, where it misses, which open tickets need attention today, and what to change in staffing, routing or the policy itself.

SLA numbers describe a system, not a person. Slow agents usually have the hardest queue, too many channels or no cover. Always look at workload and routing before drawing conclusions about individuals, and never suggest using the report for discipline without context.

## Files in this skill

- `scripts/sla_report.py` - reads a ticket CSV and an SLA policy JSON, computes business minutes (per-weekday hours, holidays, optional 24/7 "calendar hours" for urgent tickets), first-response and resolution breaches, attainment by priority, agent, channel and ISO week, median and p90 first response, open tickets breached or at risk, and flags T01-T08 + E01; `--now`, `--since/--until`, `--risk-share`, `--format text|md|json|csv`, `--fail-on`, `--self-test` runs 21 checks (Python 3.8+ standard library only)
- `references/sla-metrics.md` - what first response, resolution, attainment, median and p90 mean, and which numbers to show to whom
- `references/business-hours-and-policies.md` - how business-hours clocks work, pausing, time zones, and how to set realistic targets
- `templates/weekly-sla-review.md` - a one-page weekly review for a support lead or founder
- `examples/tickets.csv` - two weeks of fictional tickets for a small SaaS team (4 agents, email, chat and phone), with open tickets, one typo row and one ticket closed by automation
- `examples/sla_policy.json` - Mon-Fri 09:00-18:00, holidays, targets for urgent (24/7), high, normal and low

## Workflow

### 1. Get the export and the policy
Ask for a CSV export of the period (two to four weeks is ideal) with these columns; most helpdesks can export them or a spreadsheet can rename them:
```
ticket_id,priority,channel,customer_tier,agent,created_at,first_response_at,resolved_at,status,reopened
T-1043,normal,email,business,dev,2026-11-16 12:20,2026-11-16 15:16,2026-11-18 09:45,solved,0
```
- Required: `ticket_id`, `priority`, `created_at`. Times as `YYYY-MM-DD HH:MM` in the team's local time (convert UTC exports first).
- `first_response_at` = first public reply by a human (not the auto-acknowledgement); empty if none yet.
- `resolved_at` empty for open tickets; `reopened` = 1 if the customer reopened it.
Then write the policy JSON like `examples/sla_policy.json`: business hours, holidays, an `attainment_goal_pct` and, per priority, `first_response_min` and `resolution_min` in business minutes. Add `"calendar_hours": true` to a priority that is covered 24/7.

### 2. Run the analysis
```
python3 scripts/sla_report.py tickets.csv --policy sla_policy.json --now "2026-11-27 17:00"
python3 scripts/sla_report.py tickets.csv --policy sla_policy.json --format md > sla-review.md
python3 scripts/sla_report.py tickets.csv --policy sla_policy.json --since 2026-11-23 --until 2026-11-27
python3 scripts/sla_report.py tickets.csv --policy sla_policy.json --format csv > tickets-sla.csv   # per ticket
python3 scripts/sla_report.py --self-test
```
`--now` is the moment open tickets are measured against (default: the latest timestamp in the file). Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable file, bad policy or missing columns.

| Code | Severity | Finding |
|---|---|---|
| T01 | medium / high | a priority's first-response or resolution attainment is below the goal (high for urgent/high priority or 20+ points below) |
| T02 | medium / high | an open ticket has already breached its first-response or resolution target |
| T03 | medium | an open ticket has `--risk-share` (default 25%) or less of its target left |
| T04 | low | an agent's first-response attainment is 15+ points below the team (5+ tickets) |
| T05 | low | more than 10% of tickets were reopened |
| T06 | info | a ticket was solved without a recorded first response |
| T07 | medium | tickets with a priority that has no target in the policy |
| T08 | info | fewer than 20 tickets; percentages are rough |
| E01 | medium | rows that could not be read (line number and reason shown) |

### 3. Act on today first
Start with T02 and T03: list the open tickets that need a reply or an update now, highest priority first, with the owner. A short, honest update to a customer whose ticket is late is better than silence.

### 4. Find the pattern
Use `references/sla-metrics.md` to read the tables. Compare priorities, channels, weeks and agents. Typical causes and fixes:
- Misses cluster on Monday mornings or after holidays: backlog from the weekend; stagger shifts or add a Monday triage hour.
- Email misses but chat is fine: agents are pulled into live channels; protect email time blocks or set separate owners.
- One agent's numbers are low (T04): check their queue (priority mix, enterprise customers, hard product areas), hours and cover before anything else.
- Urgent first response is slow outside hours: the 24/7 promise has no on-call; either add an on-call rota or change the policy.
- High reopen rate (T05): tickets are closed too early; add a "confirm it works" step.
- Targets missed by a few minutes everywhere: the targets may be unrealistic for the staffing; see `references/business-hours-and-policies.md`.

### 5. Report
Fill `templates/weekly-sla-review.md`. Lead with the customer impact (how many customers waited too long, which tiers), then the numbers, then two or three concrete changes with an owner and a date. Repeat the analysis next week with the same policy and compare.

## Rules
- Measure with the policy the customer was promised; if contracts differ by tier, run the report per tier or add tier-specific priorities.
- Use business minutes consistently; say clearly when a priority uses calendar hours.
- Median and p90 tell more than the average; one ticket that waited a week should not hide or dominate the picture.
- Do not rank or shame individual agents; discuss T04 privately and with workload context.
- Customer names, emails and ticket text are personal data; work from IDs and keep exports out of shared chats.
- Auto-replies and bot answers are not a first response unless the policy explicitly says so.

FILE:references/sla-metrics.md
# SLA metrics in plain words

## First response time (FRT)
Time from ticket creation to the first public reply by a person, counted in business minutes. It tells customers "someone has seen my problem". Automatic acknowledgements do not count. Internal notes do not count.

## Resolution time
Time from creation to the moment the ticket is solved. Most helpdesks can pause this clock while waiting for the customer ("pending"); this script uses the raw times from the export, so if your team pauses the clock, export the helpdesk's own "business resolution time" or treat the numbers as an upper bound.

## Attainment (SLA met %)
The share of measured tickets that met the target: tickets met / tickets with a measured time. Open tickets without a first response are not in the first-response attainment until they get one; they appear as breached (T02) or at risk (T03) instead. A typical goal is 90-95% per priority.

## Median and p90
- Median: half of tickets got a first response faster than this. A good picture of the normal customer experience.
- p90: 9 out of 10 tickets were faster than this. Shows how bad the slow tail is; most complaints come from the tail.
- Averages are easily pulled up by a few very old tickets; prefer median and p90 in reports.

## Reopen rate
The share of solved tickets that the customer reopened. Above about 10% usually means tickets are closed before the problem is really fixed, or the answer was unclear.

## Backlog and at-risk tickets
Open tickets measured at `--now`. "Breached" means the target is already missed; "at risk" means only `--risk-share` (default 25%) of the target is left. This is the list a support lead uses at the start of a shift.

## Who needs which number
- Customers and contracts: attainment per priority and tier, against the promised targets.
- Support lead: open breached and at-risk tickets today, p90 per channel, Monday and post-holiday patterns.
- Founder or manager: weekly attainment trend, reopen rate, and whether staffing matches demand.
- Individual agents: their own queue and workload, discussed one to one, never a public leaderboard.

FILE:references/business-hours-and-policies.md
# Business hours, clocks and realistic targets

## How the business-hours clock works
Only time inside open hours counts. A ticket created Friday at 17:30 in a 09:00-18:00 Monday-Friday team has used 30 minutes by Friday evening and continues Monday at 09:00. Tickets created before opening start counting at opening time. Holidays listed in the policy count as closed days.

Example from the policy in `examples/`: a normal ticket created Monday 12:20 and solved Wednesday 09:45 used 340 + 540 + 45 = 925 business minutes, well inside the 1,620-minute (3 business days) resolution target.

## Calendar hours (24/7)
For priorities that promise round-the-clock cover (often "urgent" for outages), set `"calendar_hours": true`. Then every minute counts, nights and weekends included. Only promise this if someone is really on call.

## Time zones
Convert all timestamps to the team's local time before running the script (most helpdesks export UTC). Teams in several time zones can either use one "follow the sun" calendar with longer hours or run the report per team with its own policy.

## Pausing
Many helpdesks pause the resolution clock while a ticket waits for the customer. If you need paused times, export the helpdesk's own SLA fields; the script cannot see status history in a flat export.

## Setting realistic targets
1. Measure first: run the report with generous targets and look at the median and p90 per priority and channel.
2. Set first-response targets that the team meets 90-95% of the time with current staffing, then tighten slowly.
3. Keep few priorities (3-4) with clear definitions customers understand: urgent = service down or data at risk, high = a key feature blocked, normal = a question or a problem with a workaround, low = feedback or how-to.
4. Match channels to expectations: chat and phone need minutes, email hours.
5. Write down what happens on breach: who is alerted, when the customer gets an update, and whether service credits apply.
6. Review targets every quarter; when attainment is always 100%, the promise may be too loose to be useful.

## Rough staffing check
Tickets per week x average handling minutes / (agents x focused minutes per week) should stay well below 1. If it is close to 1, no process change will fix breaches; the team needs more people, fewer tickets (better docs, product fixes) or looser targets.

FILE:templates/weekly-sla-review.md
# Weekly support SLA review - {{week, e.g. 2026-W48}}

**Period:** {{from}} to {{to}} | **Policy:** {{policy name}} | **Goal:** {{90}}% per priority

## Customer impact
- {{N}} customers waited longer than promised for a first reply ({{tiers affected}}).
- {{N}} open tickets are breached right now; {{N}} more will breach today.

## Numbers
| Priority | Tickets | First response met | Resolution met | FR median | FR p90 |
|---|---|---|---|---|---|
| urgent | {{}} | {{}} | {{}} | {{}} | {{}} |
| high | {{}} | {{}} | {{}} | {{}} | {{}} |
| normal | {{}} | {{}} | {{}} | {{}} | {{}} |
| low | {{}} | {{}} | {{}} | {{}} | {{}} |

Trend vs last week: {{better / same / worse, one sentence}}. Reopen rate: {{x}}%.

## What we see
1. {{pattern, e.g. email first responses slip on Monday mornings}}
2. {{pattern}}
3. {{data gap, e.g. 1 unreadable row, 1 ticket closed by automation}}

## Today
| Ticket | Priority | State | Owner | Next step |
|---|---|---|---|---|
| {{id}} | {{}} | {{breached / at risk}} | {{}} | {{reply / update customer / escalate}} |

## Changes for next week
| Change | Owner | By |
|---|---|---|
| {{e.g. Monday 09:00-10:00 triage hour for the email backlog}} | {{}} | {{date}} |
| {{e.g. on-call rota for urgent phone tickets after 18:00}} | {{}} | {{date}} |

_Numbers describe the system, not individual people. Agent-level details are discussed one to one._

FILE:examples/tickets.csv
ticket_id,priority,channel,customer_tier,agent,created_at,first_response_at,resolved_at,status,reopened
T-1041,urgent,phone,enterprise,ben,2026-11-16 08:40,2026-11-16 09:27,2026-11-16 11:08,solved,0
T-1042,low,email,pro,dev,2026-11-16 11:00,2026-11-17 10:36,2026-11-24 10:19,solved,0
T-1043,normal,email,business,dev,2026-11-16 12:20,2026-11-16 15:16,2026-11-18 09:45,solved,0
T-1044,low,email,business,dev,2026-11-16 13:12,2026-11-16 16:45,2026-11-18 15:43,solved,0
T-1045,normal,chat,business,ana,2026-11-16 18:05,2026-11-17 10:33,2026-11-18 15:49,solved,0
T-1046,normal,email,enterprise,chloe,2026-11-16 18:12,2026-11-17 11:51,2026-11-19 16:22,solved,0
T-1047,normal,chat,business,dev,2026-11-17 15:48,2026-11-18 10:21,2026-11-20 13:42,solved,0
T-1048,normal,email,enterprise,ben,2026-11-17 19:00,2026-11-18 15:06,2026-11-24 10:19,solved,1
T-1049,low,chat,business,chloe,2026-11-18 08:33,2026-11-19 09:39,2026-11-20 15:14,solved,0
T-1050,low,email,business,dev,2026-11-18 09:05,2026-11-18 17:46,2026-11-24 16:46,solved,0
T-1051,normal,email,pro,chloe,2026-11-18 09:41,2026-11-18 11:15,2026-11-20 09:47,solved,0
T-1052,normal,email,pro,ben,2026-11-18 14:00,2026-11-19 15:00,2026-11-23 15:42,solved,0
T-1053,high,chat,free,ben,2026-11-18 15:41,2026-11-18 16:38,2026-11-19 10:56,solved,0
T-1054,high,chat,pro,dev,2026-11-19 14:33,2026-11-19 14:48,2026-11-20 15:11,solved,0
T-1055,normal,email,free,ben,2026-11-20 07:20,2026-11-20 13:18,2026-11-25 10:22,solved,0
T-1056,low,email,pro,ana,2026-11-20 09:12,2026-11-23 09:58,2026-11-25 13:32,solved,0
T-1057,normal,chat,pro,dev,2026-11-20 13:55,2026-11-23 09:26,2026-11-24 17:21,solved,0
T-1058,low,phone,pro,chloe,2026-11-20 16:20,2026-11-23 13:31,2026-11-24 15:29,solved,0
T-1059,normal,chat,pro,dev,2026-11-23 07:55,2026-11-23 10:26,2026-11-24 12:10,solved,0
T-1060,normal,email,pro,chloe,2026-11-23 09:12,2026-11-23 14:35,,open,0
T-1061,high,email,free,ana,2026-11-23 17:12,2026-11-24 09:06,2026-11-25 09:23,solved,0
T-1062,urgent,phone,enterprise,ana,2026-11-23 21:05,2026-11-23 21:36,2026-11-23 23:22,solved,1
T-1063,normal,chat,business,dev,2026-11-24 07:41,2026-11-24 14:03,2026-11-25 12:31,solved,0
T-1064,normal,phone,free,chloe,2026-11-24 08:48,2026-11-24 11:57,2026-11-27 16:11,solved,0
T-1065,high,email,enterprise,ben,2026-11-24 10:20,2026-11-24 11:03,2026-11-24 14:30,solved,0
T-1066,normal,email,pro,dev,2026-11-24 12:00,2026-11-24 14:08,,open,0
T-1067,low,email,pro,chloe,2026-11-24 18:33,2026-11-25 16:06,,open,0
T-1068,normal,phone,pro,ana,2026-11-24 18:41,2026-11-25 10:04,,open,0
T-1069,urgent,phone,free,ana,2026-11-25 13:05,2026-11-25 13:19,2026-11-25 16:34,solved,0
T-1070,normal,email,business,chloe,2026-11-25 17:48,2026-11-27 13:31,,open,0
T-1071,high,phone,pro,dev,2026-11-26 16:20,2026-11-27 09:46,2026-11-27 14:11,solved,0
T-1072,normal,email,pro,ana,2026-11-27 11:05,2026-11-27 13:47,,open,0
T-1073,normal,email,business,ana,2026-11-27 11:05,2026-11-27 12:17,,open,0
T-1074,normal,email,pro,chloe,2026-11-27 13:55,,,new,0
T-1075,high,phone,enterprise,ana,2026-11-27 15:20,2026-11-27 16:04,,open,0
T-1076,normal,email,business,chloe,2026-11-27 17:00,,,new,0
T-1077,low,chat,enterprise,ana,2026-11-27 17:12,,,new,0
T-1078,high,email,free,ana,2026-11-27 18:20,,,new,0
T-1079,high,chat,enterprise,dev,2026-11-27 16:10,,,new,0
T-1080,normal,email,pro,ben,2026-11-27 09:40,,,new,0
T-1081,normal,email,business,chloe,2026-11-24 10:15,2026-11-24 11:02,,open,0
T-1082,low,email,free,ana,2026-11-27 11:30,,,new,0
T-1083,normal,chat,pro,ana,2026-11-25 14:05,2026-11-25 14:40,,pending,0
T-1084,normal,email,pro,chloe,2026-11-31 10:00,,,new,0
T-1085,low,email,free,(bot),2026-11-20 12:00,,2026-11-20 12:01,solved,0

FILE:examples/sla_policy.json
{
  "name": "Example SaaS support policy",
  "business_hours": {"days": ["mon", "tue", "wed", "thu", "fri"], "start": "09:00", "end": "18:00"},
  "holidays": ["2026-11-26", "2026-12-25", "2026-12-31"],
  "attainment_goal_pct": 90,
  "targets": {
    "urgent": {"first_response_min": 30, "resolution_min": 240, "calendar_hours": true},
    "high": {"first_response_min": 60, "resolution_min": 540},
    "normal": {"first_response_min": 240, "resolution_min": 1620},
    "low": {"first_response_min": 540, "resolution_min": 2700}
  }
}

FILE:scripts/sla_report.py
#!/usr/bin/env python3
"""sla_report.py - measure support SLA attainment from a ticket export, in business hours.

Reads a ticket CSV (Zendesk, Freshdesk, Help Scout, Intercom, Jira Service Management or a
spreadsheet export with the columns below) and an SLA policy JSON (business hours, holidays and
first-response / resolution targets per priority). Computes elapsed business minutes per ticket,
breaches, attainment by priority, agent, channel and week, open tickets already breached or at
risk, and flags T01-T08 + E01.

Required columns: ticket_id, priority, created_at
Optional columns: first_response_at, resolved_at, status, agent, channel, customer_tier, reopened
Datetimes: "YYYY-MM-DD HH:MM" (or with seconds / a T), all in the policy's local time.

Usage:
  sla_report.py TICKETS.csv --policy POLICY.json [--now "YYYY-MM-DD HH:MM"] [--since DATE] [--until DATE]
                [--format text|md|json|csv] [--risk-share 0.25] [--fail-on none|info|low|medium|high]
  sla_report.py --self-test
Exit: 0 ok, 1 flags at or above --fail-on, 2 unreadable input. Python 3.8+, standard library only.
"""
import argparse, csv, io, json, statistics, sys
from datetime import date, datetime, time, timedelta

SEV = {"info": 0, "low": 1, "medium": 2, "high": 3}
FMT = ("%Y-%m-%d %H:%M", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M", "%Y-%m-%dT%H:%M:%S")
DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]


def parse_dt(s):
    s = (s or "").strip()
    if not s:
        return None
    s = s.replace("Z", "")
    for f in FMT:
        try:
            return datetime.strptime(s[:19] if "T" in s or s.count(":") == 2 else s, f)
        except ValueError:
            continue
    raise ValueError("bad datetime %r" % s)


def parse_hm(s):
    h, m = s.split(":")
    return time(int(h), int(m))


class Calendar:
    """Business hours: per-weekday open/close times and a set of holiday dates."""

    def __init__(self, policy):
        bh = policy.get("business_hours", {})
        days = [d.lower()[:3] for d in bh.get("days", ["mon", "tue", "wed", "thu", "fri"])]
        start, end = parse_hm(bh.get("start", "09:00")), parse_hm(bh.get("end", "17:00"))
        if end <= start:
            raise ValueError("business_hours end must be after start")
        self.hours = {DAYS.index(d): (start, end) for d in days}
        self.holidays = {date.fromisoformat(h) for h in policy.get("holidays", [])}

    def open_window(self, d):
        if d in self.holidays or d.weekday() not in self.hours:
            return None
        s, e = self.hours[d.weekday()]
        return datetime.combine(d, s), datetime.combine(d, e)

    def minutes(self, a, b):
        """Business minutes between datetimes a and b (0 if b <= a)."""
        if b <= a:
            return 0
        total, d = 0.0, a.date()
        while d <= b.date():
            w = self.open_window(d)
            if w:
                lo, hi = max(a, w[0]), min(b, w[1])
                if hi > lo:
                    total += (hi - lo).total_seconds() / 60
            d += timedelta(days=1)
        return int(round(total))


def load_policy(path):
    with open(path, encoding="utf-8") as fh:
        p = json.load(fh)
    if "targets" not in p or not isinstance(p["targets"], dict):
        raise ValueError("policy needs a 'targets' object keyed by priority")
    for k, t in p["targets"].items():
        if "first_response_min" not in t or "resolution_min" not in t:
            raise ValueError("target %r needs first_response_min and resolution_min" % k)
    return p


def read_tickets(text):
    rows, errors = [], []
    rd = csv.DictReader(io.StringIO(text))
    cols = {c.strip().lower() for c in (rd.fieldnames or [])}
    missing = {"ticket_id", "priority", "created_at"} - cols
    if missing:
        raise ValueError("missing columns: %s" % ", ".join(sorted(missing)))
    for i, raw in enumerate(rd, start=2):
        r = {k.strip().lower(): (v or "").strip() for k, v in raw.items() if k}
        try:
            created = parse_dt(r["created_at"])
            if created is None:
                raise ValueError("empty created_at")
            fr = parse_dt(r.get("first_response_at"))
            res = parse_dt(r.get("resolved_at"))
            if fr and fr < created:
                raise ValueError("first_response_at before created_at")
            if res and res < created:
                raise ValueError("resolved_at before created_at")
        except ValueError as e:
            errors.append(dict(line=i, ticket=r.get("ticket_id", ""), reason=str(e)))
            continue
        status = (r.get("status") or ("solved" if res else "open")).lower()
        rows.append(dict(id=r["ticket_id"], priority=r["priority"].lower(), created=created, first_response=fr,
                         resolved=res, status=status, agent=r.get("agent") or "(unassigned)",
                         channel=(r.get("channel") or "unknown").lower(), tier=r.get("customer_tier") or "",
                         reopened=(r.get("reopened") or "0").strip().lower() in ("1", "yes", "true", "y")))
    return rows, errors


def evaluate(tickets, policy, now, risk_share=0.25):
    cal = Calendar(policy)
    out = []
    for t in tickets:
        tg = policy["targets"].get(t["priority"])
        if tg is None:
            out.append(dict(t, known_priority=False)); continue
        mins = (lambda a, b: max(0, int(round((b - a).total_seconds() / 60)))) if tg.get("calendar_hours") else cal.minutes
        e = dict(t, known_priority=True, fr_target=tg["first_response_min"], res_target=tg["resolution_min"])
        e["fr_min"] = mins(t["created"], t["first_response"]) if t["first_response"] else None
        e["fr_breach"] = (e["fr_min"] > tg["first_response_min"]) if e["fr_min"] is not None else None
        e["res_min"] = mins(t["created"], t["resolved"]) if t["resolved"] else None
        e["res_breach"] = (e["res_min"] > tg["resolution_min"]) if e["res_min"] is not None else None
        e["open"] = t["resolved"] is None and t["status"] not in ("solved", "closed", "resolved")
        e["open_state"] = None
        if e["open"]:
            elapsed_res = mins(t["created"], now)
            waiting_fr = t["first_response"] is None
            elapsed_fr = mins(t["created"], now) if waiting_fr else None
            e["elapsed_open_min"] = elapsed_res
            if waiting_fr and elapsed_fr > tg["first_response_min"]:
                e["open_state"] = "breached_first_response"
            elif elapsed_res > tg["resolution_min"]:
                e["open_state"] = "breached_resolution"
            elif waiting_fr and tg["first_response_min"] - elapsed_fr <= risk_share * tg["first_response_min"]:
                e["open_state"] = "at_risk_first_response"; e["minutes_left"] = tg["first_response_min"] - elapsed_fr
            elif tg["resolution_min"] - elapsed_res <= risk_share * tg["resolution_min"]:
                e["open_state"] = "at_risk_resolution"; e["minutes_left"] = tg["resolution_min"] - elapsed_res
        out.append(e)
    return out


def rate(items, key):
    vals = [x[key] for x in items if x.get(key) is not None]
    if not vals:
        return None, 0
    return round(100.0 * sum(1 for v in vals if not v) / len(vals), 1), len(vals)


def pctl(vals, p):
    if not vals:
        return None
    v = sorted(vals)
    k = max(0, min(len(v) - 1, int(round(p / 100.0 * (len(v) - 1)))))
    return v[k]


def group(ev, key):
    g = {}
    for e in ev:
        if e.get("known_priority"):
            g.setdefault(e[key], []).append(e)
    rows = []
    for k, items in sorted(g.items()):
        fr, nfr = rate(items, "fr_breach"); rs, nrs = rate(items, "res_breach")
        frs = [x["fr_min"] for x in items if x.get("fr_min") is not None]
        rows.append(dict(key=k, tickets=len(items), fr_met_pct=fr, fr_measured=nfr, res_met_pct=rs, res_measured=nrs,
                         fr_median=statistics.median(frs) if frs else None, fr_p90=pctl(frs, 90),
                         reopened=sum(1 for x in items if x["reopened"])))
    return rows


def week_of(d):
    y, w, _ = d.isocalendar()
    return "%d-W%02d" % (y, w)


def analyze(tickets, errors, policy, now, risk_share=0.25):
    ev = evaluate(tickets, policy, now, risk_share)
    for e in ev:
        e["week"] = week_of(e["created"])
    known = [e for e in ev if e.get("known_priority")]
    goal = float(policy.get("attainment_goal_pct", 90))
    fr, nfr = rate(known, "fr_breach"); rs, nrs = rate(known, "res_breach")
    summary = dict(tickets=len(ev), from_=min((e["created"] for e in ev), default=None), to=max((e["created"] for e in ev), default=None),
                   fr_met_pct=fr, fr_measured=nfr, res_met_pct=rs, res_measured=nrs, goal_pct=goal,
                   open=sum(1 for e in known if e["open"]), reopened=sum(1 for e in known if e["reopened"]))
    by_priority, by_agent = group(ev, "priority"), group(ev, "agent")
    by_channel, by_week = group(ev, "channel"), group(ev, "week")
    flags = []

    def flag(code, sev, msg, ref=None):
        flags.append(dict(code=code, severity=sev, ref=ref, message=msg))

    for r in by_priority:
        for kind, label in (("fr", "first response"), ("res", "resolution")):
            v, n = r[kind + "_met_pct"], r[kind + "_measured"]
            if v is not None and n >= 3 and v < goal:
                sev = "high" if r["key"] in ("urgent", "high") or v < goal - 20 else "medium"
                flag("T01", sev, "%s SLA met %.1f%% of %d tickets (goal %.0f%%)" % (label, v, n, goal), r["key"])
    for e in known:
        if e["open_state"] and e["open_state"].startswith("breached"):
            flag("T02", "high" if e["priority"] in ("urgent", "high") else "medium",
                 "open ticket already breached (%s, %s, %d business min open)" % (e["open_state"].replace("breached_", "").replace("_", " "), e["priority"], e["elapsed_open_min"]), e["id"])
        elif e["open_state"]:
            flag("T03", "medium", "open ticket at risk: %d min left for %s (%s)" % (e["minutes_left"], e["open_state"].replace("at_risk_", "").replace("_", " "), e["priority"]), e["id"])
    team_fr = summary["fr_met_pct"]
    for r in by_agent:
        if r["fr_measured"] >= 5 and team_fr is not None and r["fr_met_pct"] is not None and r["fr_met_pct"] < team_fr - 15:
            flag("T04", "low", "first response met %.1f%% vs team %.1f%%; check workload and queue routing before judging the person" % (r["fr_met_pct"], team_fr), r["key"])
    if known and summary["reopened"] / float(len(known)) > 0.10:
        flag("T05", "low", "%d of %d tickets were reopened (%.0f%%); fast closes may hide unsolved problems" % (summary["reopened"], len(known), 100.0 * summary["reopened"] / len(known)))
    for e in known:
        if e["resolved"] and not e["first_response"]:
            flag("T06", "info", "solved without a recorded first response (data gap or solved by a macro/automation)", e["id"])
    unknown = sorted({e["priority"] for e in ev if not e.get("known_priority")})
    if unknown:
        flag("T07", "medium", "priorities without an SLA target: %s (%d tickets ignored)" % (", ".join(unknown), sum(1 for e in ev if not e.get("known_priority"))))
    if len(known) < 20:
        flag("T08", "info", "only %d tickets with a known priority; percentages are rough" % len(known))
    for er in errors:
        flag("E01", "medium", "line %d (%s): %s" % (er["line"], er["ticket"] or "?", er["reason"]))
    flags.sort(key=lambda f: (-SEV[f["severity"]], f["code"], str(f["ref"] or "")))
    worst = sorted([e for e in known if e.get("fr_min") is not None and e["fr_breach"]], key=lambda e: e["fr_min"] - e["fr_target"], reverse=True)[:5]
    return dict(summary=summary, by_priority=by_priority, by_agent=by_agent, by_channel=by_channel, by_week=by_week,
                open=[e for e in known if e["open_state"]], worst_first_response=worst, tickets=ev, flags=flags, errors=errors)


def hm(m):
    if m is None:
        return "-"
    m = int(round(m))
    return "%dh%02d" % (m // 60, m % 60) if m >= 60 else "%dm" % m


def p(v):
    return "  -  " if v is None else "%5.1f%%" % v


def table(rows, title, width=14):
    out = [title, "  %-*s %7s %9s %9s %9s %9s %8s" % (width, "", "tickets", "FR met", "Res met", "FR med", "FR p90", "reopen")]
    for r in rows:
        out.append("  %-*s %7d %9s %9s %9s %9s %8d" % (width, str(r["key"])[:width], r["tickets"], p(r["fr_met_pct"]), p(r["res_met_pct"]), hm(r["fr_median"]), hm(r["fr_p90"]), r["reopened"]))
    return out


def render_text(res):
    s = res["summary"]; out = ["Support SLA report"]
    out.append("  Tickets              %d (created %s to %s), %d open, %d reopened" % (s["tickets"], s["from_"].strftime("%Y-%m-%d") if s["from_"] else "-", s["to"].strftime("%Y-%m-%d") if s["to"] else "-", s["open"], s["reopened"]))
    out.append("  First response met   %s of %d measured (goal %.0f%%)" % (p(s["fr_met_pct"]).strip(), s["fr_measured"], s["goal_pct"]))
    out.append("  Resolution met       %s of %d measured" % (p(s["res_met_pct"]).strip(), s["res_measured"]))
    out.append("")
    out += table(res["by_priority"], "By priority"); out.append("")
    out += table(res["by_agent"], "By agent"); out.append("")
    out += table(res["by_channel"], "By channel"); out.append("")
    out += table(res["by_week"], "By week")
    out.append("")
    out.append("Open tickets breached or at risk (%d)" % len(res["open"]))
    for e in res["open"]:
        out.append("  %-8s %-7s %-12s %-26s open %s" % (e["id"], e["priority"], e["agent"][:12], e["open_state"], hm(e["elapsed_open_min"])))
    out.append("")
    out.append("Slowest first responses over target")
    for e in res["worst_first_response"]:
        out.append("  %-8s %-7s %-8s %s vs target %s" % (e["id"], e["priority"], e["channel"], hm(e["fr_min"]), hm(e["fr_target"])))
    out.append("")
    out.append("Findings (%d)" % len(res["flags"]))
    for f in res["flags"]:
        out.append("  [%s %s] %s%s" % (f["code"], f["severity"], (str(f["ref"]) + ": ") if f["ref"] else "", f["message"]))
    if not res["flags"]:
        out.append("  none")
    return "\n".join(out)


def render_md(res):
    s = res["summary"]; out = ["# Support SLA report", ""]
    out.append("**%d tickets**, %d open, %d reopened. First response met **%s** (goal %.0f%%), resolution met **%s**." % (s["tickets"], s["open"], s["reopened"], p(s["fr_met_pct"]).strip(), s["goal_pct"], p(s["res_met_pct"]).strip()))
    for title, rows in (("By priority", res["by_priority"]), ("By agent", res["by_agent"]), ("By channel", res["by_channel"]), ("By week", res["by_week"])):
        out += ["", "## " + title, "", "| | Tickets | FR met | Resolution met | FR median | FR p90 | Reopened |", "|---|---|---|---|---|---|---|"]
        out += ["| %s | %d | %s | %s | %s | %s | %d |" % (r["key"], r["tickets"], p(r["fr_met_pct"]).strip(), p(r["res_met_pct"]).strip(), hm(r["fr_median"]), hm(r["fr_p90"]), r["reopened"]) for r in rows]
    out += ["", "## Open tickets breached or at risk", ""]
    out += ["- `%s` %s, %s, %s, open %s" % (e["id"], e["priority"], e["agent"], e["open_state"].replace("_", " "), hm(e["elapsed_open_min"])) for e in res["open"]] or ["- none"]
    out += ["", "## Findings", ""]
    out += ["- **%s** (%s) %s%s" % (f["code"], f["severity"], ("`%s`: " % f["ref"]) if f["ref"] else "", f["message"]) for f in res["flags"]] or ["- none"]
    return "\n".join(out)


def render_csv(res):
    buf = io.StringIO(); w = csv.writer(buf, lineterminator="\n")
    w.writerow(["ticket_id", "priority", "agent", "channel", "week", "fr_business_min", "fr_target_min", "fr_breach", "res_business_min", "res_target_min", "res_breach", "open_state"])
    for e in res["tickets"]:
        if not e.get("known_priority"):
            continue
        b = lambda v: "" if v is None else ("yes" if v else "no")
        w.writerow([e["id"], e["priority"], e["agent"], e["channel"], e["week"], "" if e["fr_min"] is None else e["fr_min"], e["fr_target"], b(e["fr_breach"]),
                    "" if e["res_min"] is None else e["res_min"], e["res_target"], b(e["res_breach"]), e["open_state"] or ""])
    return buf.getvalue().rstrip("\n")


def to_json(res):
    def conv(o):
        if isinstance(o, (datetime, date)):
            return o.isoformat(sep=" ") if isinstance(o, datetime) else o.isoformat()
        raise TypeError(type(o))
    r = {k: v for k, v in res.items() if k != "tickets"}
    r["summary"] = dict(res["summary"]); r["summary"]["from"] = r["summary"].pop("from_")
    return json.dumps(r, indent=2, default=conv)


TEST_POLICY = {"business_hours": {"days": ["mon", "tue", "wed", "thu", "fri"], "start": "09:00", "end": "17:00"},
               "holidays": ["2026-12-25"], "attainment_goal_pct": 90,
               "targets": {"urgent": {"first_response_min": 30, "resolution_min": 240, "calendar_hours": True},
                           "normal": {"first_response_min": 240, "resolution_min": 1440}}}


def self_test():
    checks = []

    def ok(name, cond):
        checks.append((name, bool(cond)))

    cal = Calendar(TEST_POLICY)
    D = lambda s: datetime.strptime(s, "%Y-%m-%d %H:%M")
    ok("same day minutes", cal.minutes(D("2026-11-30 10:00"), D("2026-11-30 11:30")) == 90)
    ok("before opening counts from 09:00", cal.minutes(D("2026-11-30 07:00"), D("2026-11-30 09:45")) == 45)
    ok("overnight skips closed hours", cal.minutes(D("2026-11-30 16:30"), D("2026-12-01 09:30")) == 60)
    ok("weekend skipped", cal.minutes(D("2026-12-04 16:00"), D("2026-12-07 10:00")) == 120)
    ok("holiday skipped", cal.minutes(D("2026-12-24 16:00"), D("2026-12-28 09:30")) == 60 + 30)
    ok("reverse is zero", cal.minutes(D("2026-12-01 10:00"), D("2026-12-01 09:00")) == 0)
    csv_text = ("ticket_id,priority,created_at,first_response_at,resolved_at,status,agent,channel,reopened\n"
                "A,normal,2026-11-30 10:00,2026-11-30 11:00,2026-11-30 15:00,solved,ana,email,0\n"
                "B,normal,2026-11-30 16:00,2026-12-01 13:30,2026-12-03 10:00,solved,ben,email,1\n"
                "C,urgent,2026-12-05 23:00,2026-12-05 23:20,2026-12-06 01:00,solved,ana,phone,0\n"
                "D,normal,2026-12-01 09:00,,,open,ben,chat,0\n"
                "E,low,2026-12-01 09:00,,,open,ben,chat,0\n"
                "F,normal,2026-12-01 10:00,2026-12-01 09:00,,open,ana,chat,0\n"
                "G,normal,2026-12-01 13:30,,,open,ana,chat,0\n")
    rows, errs = read_tickets(csv_text)
    ok("bad row reported", len(errs) == 1 and errs[0]["ticket"] == "F" and errs[0]["line"] == 7)
    res = analyze(rows, errs, TEST_POLICY, D("2026-12-01 17:00"))
    t = {e["id"]: e for e in res["tickets"]}
    ok("A first response 60 min met", t["A"]["fr_min"] == 60 and t["A"]["fr_breach"] is False)
    ok("B overnight first response 330 min breached", t["B"]["fr_min"] == 330 and t["B"]["fr_breach"] is True)
    ok("C urgent uses calendar hours", t["C"]["fr_min"] == 20 and t["C"]["res_min"] == 120)
    ok("D open breached first response", t["D"]["open_state"] == "breached_first_response")
    ok("G open at risk", t["G"]["open_state"] == "at_risk_first_response" and t["G"]["minutes_left"] == 30)
    codes = {f["code"] for f in res["flags"]}
    ok("T07 unknown priority", "T07" in codes)
    ok("T02 and T03 present", {"T02", "T03"} <= codes)
    ok("T05 reopened", "T05" in codes)
    ok("E01 present", "E01" in codes)
    ok("fr met pct", res["summary"]["fr_met_pct"] == round(100 * 2 / 3, 1))
    ok("csv rows", len(render_csv(res).splitlines()) == 1 + 5)
    ok("json loads", json.loads(to_json(res))["summary"]["tickets"] == 6)
    try:
        read_tickets("id,prio\n1,2\n"); ok("missing columns rejected", False)
    except ValueError:
        ok("missing columns rejected", True)
    ok("iso T datetime", parse_dt("2026-12-01T09:05:00") == D("2026-12-01 09:05"))
    bad = [n for n, c in checks if not c]
    if bad:
        print("self-test FAILED: " + ", ".join(bad)); return 1
    print("self-test OK: %d checks" % len(checks)); return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("tickets", nargs="?")
    ap.add_argument("--policy")
    ap.add_argument("--now", help="reference time for open tickets (default: latest timestamp in the file)")
    ap.add_argument("--since"); ap.add_argument("--until")
    ap.add_argument("--risk-share", type=float, default=0.25, help="open ticket is at risk when this share of the target is left")
    ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
    ap.add_argument("--fail-on", choices=["none"] + list(SEV), default="none")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.tickets or not a.policy:
        ap.print_usage(sys.stderr); print("error: TICKETS.csv and --policy are required", file=sys.stderr); return 2
    try:
        policy = load_policy(a.policy)
        Calendar(policy)
        with open(a.tickets, encoding="utf-8-sig") as fh:
            rows, errors = read_tickets(fh.read())
        if a.since:
            rows = [r for r in rows if r["created"].date() >= date.fromisoformat(a.since)]
        if a.until:
            rows = [r for r in rows if r["created"].date() <= date.fromisoformat(a.until)]
        now = parse_dt(a.now) if a.now else max([x for r in rows for x in (r["created"], r["first_response"], r["resolved"]) if x], default=datetime.now())
    except (OSError, ValueError, json.JSONDecodeError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    res = analyze(rows, errors, policy, now, a.risk_share)
    print({"text": render_text, "md": render_md, "json": to_json, "csv": render_csv}[a.format](res))
    if a.fail_on != "none" and any(SEV[f["severity"]] >= SEV[a.fail_on] for f in res["flags"]):
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
MetricsReportData Analysis+4
F@f
0
Code Coverage Gap Finder
Skill

Finds the test coverage gaps that matter in a Cobertura XML or LCOV report: files with the most missed lines, uncovered blocks, weak branch coverage, untested files and diff coverage of the lines changed in a pull request, then suggests the few tests worth writing first. Stdlib Python.

---
name: code-coverage-gap-finder
description: Finds the test coverage gaps that matter in a Cobertura XML or LCOV report: files with the most missed lines, uncovered blocks, weak branch coverage, untested files and diff coverage of the lines changed in a pull request, then suggests the few tests worth writing first. Stdlib Python.
---

# Code Coverage Gap Finder

You help developers and reviewers turn a coverage report into a short, useful list of tests to write. A single "coverage 51%" number tells a team almost nothing; what helps is knowing which files and which changed lines are not exercised by any test, where whole blocks or error paths are never run, and which gaps are risky enough to fix now. You read the report (and the diff of the change under review, if there is one), explain the numbers plainly, and propose a small, ranked set of concrete tests.

Coverage is a map of what tests execute, not proof that the code is correct. A line can be covered by a test that asserts nothing. Always say this when someone treats a high number as a quality guarantee, and never suggest tests that only exist to raise the number.

## Files in this skill

- `scripts/coverage_gaps.py` - reads Cobertura XML (coverage.py `coverage xml`, Jest/Vitest/istanbul `cobertura` reporter, gcovr, PHPUnit, coverlet, JaCoCo converted to Cobertura) or LCOV (`lcov.info`), and optionally a unified diff (`git diff`); prints totals, the files with the most missed lines with uncovered line ranges, diff coverage of changed lines and flags C01-C09; `--format text|md|json|csv`, thresholds, `--exclude`, `--strip-prefix`, `--fail-on`, `--self-test` runs 22 checks (Python 3.8+ standard library only)
- `references/coverage-metrics.md` - line, branch and diff coverage, how tools count them differently, and sensible targets
- `references/what-to-test-first.md` - how to rank gaps by risk and what a good test for each kind of gap looks like
- `templates/coverage-review.md` - a pull request or team review comment with numbers, the top gaps and the proposed tests
- `examples/coverage.xml` - a real coverage.py report (with `--branch`) of a small shop project: well-tested pricing, a partly tested discounts module, untested refunds and a new untested gift card module
- `examples/changes.diff` - the `git diff -U0` of the change under review (new discount helpers, new gift card file, one new test)
- `examples/lcov.info` - a small LCOV report from a JavaScript project

## Workflow

### 1. Get the report and the diff
Ask which language and test runner they use and produce a report in one of the two formats:
```
# Python (coverage.py)
coverage run --branch -m pytest && coverage xml -o coverage.xml
# JavaScript / TypeScript (Jest or Vitest with istanbul)
npx jest --coverage --coverageReporters=cobertura      # or lcov -> coverage/lcov.info
npx vitest run --coverage --coverage.reporter=cobertura
# C / C++
gcovr --xml-pretty -o coverage.xml
# The change under review
git diff --no-color -U0 origin/main...HEAD > changes.diff
```
Branch data only appears when branch measurement is on (`--branch` for coverage.py). Paths in the diff must match the paths in the report; if the report stores `src/app/x.py` and the diff says `app/x.py`, use `--strip-prefix src`.

### 2. Run the analysis
```
python3 scripts/coverage_gaps.py coverage.xml
python3 scripts/coverage_gaps.py coverage.xml --diff changes.diff --min-diff 80 --format md > coverage-review.md
python3 scripts/coverage_gaps.py coverage/lcov.info --exclude "src/generated/*" --min-total 70
python3 scripts/coverage_gaps.py coverage.xml --format csv > coverage-by-file.csv
python3 scripts/coverage_gaps.py coverage.xml --diff changes.diff --fail-on high     # CI gate
python3 scripts/coverage_gaps.py --self-test
```
Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable report or diff.

| Code | Severity | Gap |
|---|---|---|
| C01 | medium | total line coverage below `--min-total` (default 80%) |
| C02 | low | a file with at least `--min-lines` lines is below `--min-file` (default 60%) |
| C03 | medium / high | diff coverage of changed executable lines below `--min-diff` (high when below half of it) |
| C04 | medium | a changed source file is not in the report at all (new file never imported, or excluded) |
| C05 | low | an uncovered block of `--block` (default 15) or more consecutive lines in a partly tested file |
| C06 | low | branch coverage 25+ points below line coverage: lines run, but some if/else paths never do |
| C07 | medium | a file with at least `--min-lines` lines has no covered line at all |
| C08 | high | the report has no measured lines (tests did not run, or wrong paths) |
| C09 | info | the diff has no changed executable lines in the report (docs/config change, or path mismatch) |

### 3. Rank the gaps
Use `references/what-to-test-first.md`. Changed lines come first (C03/C04): they are the cheapest to test now and the most likely to hide new bugs. Then untested files that handle money, permissions, data deletion or external input (C07), then uncovered error paths and branches (C05/C06). Generated code, simple getters, logging and `if __name__ == "__main__"` blocks are low priority; suggest `--exclude` or a coverage config exclusion with a reason instead of tests.

### 4. Propose tests
For the top 3-5 gaps, open the uncovered line ranges and write concrete test ideas: the function, the input, the expected result or exception, and which uncovered lines or branch it will run. Prefer one meaningful assertion per behavior over many lines that only execute code. If the code is hard to test (hidden I/O, globals, time), say so and suggest a small refactor.

### 5. Report
Fill `templates/coverage-review.md` for a PR comment or a team review. Include the numbers, the top gaps, the proposed tests and an honest note on what coverage cannot tell.

## Rules
- Coverage numbers differ between tools (lines vs statements, with or without branches); compare runs only from the same tool and settings. coverage.py's own "Cover" column combines lines and branches, so it can differ from this script's line coverage.
- Never recommend tests without assertions, or excluding code from measurement just to hit a target.
- Do not shame a team for a low number; show the cheapest, highest-value next steps.
- Treat thresholds as team agreements, not universal truths; a 100% target is rarely worth its cost.
- Do not paste proprietary source code outside the conversation; line numbers and file names are enough for the report.

FILE:references/coverage-metrics.md
# Coverage metrics in plain words

## Line coverage
The share of executable lines that ran at least once during the tests. Blank lines, comments and most declarations do not count. Tools disagree on details: coverage.py counts statements, istanbul counts statements and lines separately, gcov counts lines. Always compare numbers from the same tool and settings.

## Branch coverage
The share of possible paths through decisions (`if`/`else`, loops entered or skipped, `&&`/`||` short circuits, `switch` cases, ternaries) that ran. A line with `if x:` is "covered" as soon as it runs once, but its branch is only fully covered when the tests make it both true and false. Branch coverage is usually lower than line coverage. A gap of 25 points or more (flag C06) often means error paths, edge cases or `else` cases are never tested.

In Cobertura XML a branch line looks like `<line number="12" hits="3" branch="true" condition-coverage="50% (1/2)"/>`; in LCOV each branch is a `BRDA:<line>,<block>,<branch>,<taken>` record where `-` means never evaluated.

## Diff coverage (patch coverage)
The share of changed executable lines in a pull request that the tests run. It answers "did this change come with tests?" and is fairer than a total number, because old untested code does not punish a new, well-tested change. Many teams gate PRs on diff coverage (for example 80%) and only watch the total.

Only added or modified lines count. Deleted lines, blank lines, comments and test files are ignored. A new source file that does not appear in the report at all (flag C04) usually means no test imports it, or it is excluded in the coverage configuration.

## Function coverage
The share of functions called at least once (LCOV `FN`/`FNDA`). A quick way to spot dead or untested functions; this script reports lines and branches only.

## Sensible targets
- New and changed code: 80-90% diff coverage with meaningful assertions.
- Whole project: a trend that goes up slowly matters more than a fixed number; 70-85% is common for application code.
- Critical modules (payments, permissions, data deletion, parsing external input): aim higher and test branches, not just lines.
- 100% is rarely worth the cost; the last few percent are often defensive code, generated code or platform-specific paths.

## What coverage cannot tell you
- Whether the assertions are right, or whether there are any assertions at all.
- Whether important combinations of inputs are tested (100% branch coverage can still miss a bug that needs two conditions at once).
- Whether integration with real databases, networks or browsers works.
- Mutation testing (for example mutmut, Stryker, PIT) is the next step when a team wants to know if tests would catch real bugs.

FILE:references/what-to-test-first.md
# What to test first

Rank each gap by **risk x likelihood of change / cost to test**. In practice this order works for most teams:

1. **Changed lines without tests (C03, C04).** The author has the context right now and the change is the most likely place for a new bug. Ask for tests in the same pull request.
2. **Untested code that moves money, controls access or deletes data (C07 in such files).** Refunds, payments, prices, discounts, permissions, account deletion, data export, migrations.
3. **Code that parses external input.** File uploads, CSV and JSON imports, webhooks, URL and form parameters, dates and time zones.
4. **Error paths and branches (C05, C06).** `except`/`catch` blocks, early returns, "not found" and "too small" cases, retries and timeouts. Bugs hide where tests never go.
5. **Large uncovered blocks in otherwise tested files (C05).** Often a forgotten feature flag path or a whole function nobody calls; sometimes dead code to delete instead of test.
6. **Everything else**, only when it is cheap.

## Usually not worth a test
- Generated code (protobuf, ORM migrations, API clients), vendored libraries.
- Trivial getters and setters, `__repr__`, simple data classes.
- `if __name__ == "__main__":` blocks and CLI wiring that is covered by an end-to-end test.
- Logging-only lines and debug helpers.
Exclude them with a reason (`# pragma: no cover` with a comment, `/* istanbul ignore next */`, or `omit`/`exclude` in the coverage config) rather than writing empty tests.

## What a good test for a gap looks like
- Names the behavior, not the line: `test_refund_is_zero_after_30_days`, not `test_line_12`.
- Sets up the smallest realistic input, calls the public function, and asserts the result or the exception.
- Covers both sides of the uncovered branch when the logic is important (`opened=True` and `opened=False`).
- Uses boundaries: 0, 1, the limit, limit + 1, empty, None, negative, very large.
- Avoids sleeping, real network calls and current time; inject a clock or a fake.

## Example from `examples/`
- `shop/gift_cards.py` is new in the change and has 0 covered lines: write tests for `redeem` (partial use, more than the balance, zero or negative amount) and `masked`, and for the invalid card number check in `__init__`.
- `shop/discounts.py` lines 29 and 36-41: `best_code` never sees an invalid code (line 29, the `continue`), and `code_expired` is never called. Two small tests cover both.
- `shop/refunds.py` has no tests at all and handles money: add tests for the 30-day limit, opened items (85%), damaged items and a return date before the order date.

FILE:templates/coverage-review.md
# Test coverage review: {{repository or PR title}}

**Report:** {{coverage tool, date, branch measurement on/off}}  
**Change under review:** {{PR link or "whole project"}}

## Numbers
| Metric | Value | Target |
|---|---|---|
| Diff coverage (changed lines) | {{e.g. 30.0% (9/30)}} | {{80%}} |
| Line coverage (project) | {{e.g. 51.0%}} | {{80%}} |
| Branch coverage (project) | {{e.g. 40.9%}} | {{-}} |

## Gaps that matter most
1. **{{file}}** lines {{ranges}} - {{why it matters: new code / money / external input / error path}}
2. **{{file}}** lines {{ranges}} - {{why}}
3. **{{file}}** - {{why}}

## Tests I suggest
| # | Test | Covers | Effort |
|---|---|---|---|
| 1 | {{test name: input -> expected result}} | {{file:lines / branch}} | {{S/M/L}} |
| 2 | {{...}} | {{...}} | {{...}} |
| 3 | {{...}} | {{...}} | {{...}} |

## Not worth testing (exclude with a reason)
- {{file or block}} - {{generated / CLI wiring / logging}}

## Notes
- Coverage shows which code runs during tests, not whether the assertions are right.
- {{anything about flaky tests, missing branch data or path mismatches}}

FILE:examples/coverage.xml
<?xml version="1.0" ?>
<coverage version="7.18.0" timestamp="1796368012084" lines-valid="100" lines-covered="51" line-rate="0.51" branches-valid="44" branches-covered="18" branch-rate="0.4091" complexity="0">
	<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.18.0 -->
	<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
	<sources>
		<source>/home/dev/shop-api</source>
	</sources>
	<packages>
		<package name="shop" line-rate="0.51" branch-rate="0.4091" complexity="0">
			<classes>
				<class name="__init__.py" filename="shop/__init__.py" complexity="0" line-rate="1" branch-rate="1">
					<methods/>
					<lines/>
				</class>
				<class name="cart.py" filename="shop/cart.py" complexity="0" line-rate="0.8333" branch-rate="0.625">
					<methods/>
					<lines>
						<line number="2" hits="1"/>
						<line number="3" hits="1"/>
						<line number="6" hits="1"/>
						<line number="7" hits="1"/>
						<line number="8" hits="1"/>
						<line number="9" hits="1"/>
						<line number="11" hits="1"/>
						<line number="12" hits="1" branch="true" condition-coverage="100% (2/2)"/>
						<line number="13" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="12"/>
						<line number="14" hits="1"/>
						<line number="15" hits="1"/>
						<line number="16" hits="1"/>
						<line number="18" hits="1"/>
						<line number="19" hits="0"/>
						<line number="20" hits="0"/>
						<line number="21" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="exit,22"/>
						<line number="22" hits="0"/>
						<line number="24" hits="1"/>
						<line number="25" hits="1"/>
						<line number="27" hits="1"/>
						<line number="28" hits="1"/>
						<line number="29" hits="1" branch="true" condition-coverage="100% (2/2)"/>
						<line number="30" hits="1"/>
						<line number="31" hits="1"/>
					</lines>
				</class>
				<class name="discounts.py" filename="shop/discounts.py" complexity="0" line-rate="0.6667" branch-rate="0.5625">
					<methods/>
					<lines>
						<line number="3" hits="1"/>
						<line number="10" hits="1"/>
						<line number="11" hits="1"/>
						<line number="12" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="13"/>
						<line number="13" hits="0"/>
						<line number="14" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="15"/>
						<line number="15" hits="0"/>
						<line number="16" hits="1" branch="true" condition-coverage="100% (2/2)"/>
						<line number="17" hits="1"/>
						<line number="19" hits="1"/>
						<line number="20" hits="1"/>
						<line number="23" hits="1"/>
						<line number="25" hits="1"/>
						<line number="26" hits="1" branch="true" condition-coverage="100% (2/2)"/>
						<line number="27" hits="1"/>
						<line number="28" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="29"/>
						<line number="29" hits="0"/>
						<line number="30" hits="1" branch="true" condition-coverage="100% (2/2)"/>
						<line number="31" hits="1"/>
						<line number="32" hits="1"/>
						<line number="35" hits="1"/>
						<line number="36" hits="0"/>
						<line number="37" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="38,39"/>
						<line number="38" hits="0"/>
						<line number="39" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="40,41"/>
						<line number="40" hits="0"/>
						<line number="41" hits="0"/>
					</lines>
				</class>
				<class name="gift_cards.py" filename="shop/gift_cards.py" complexity="0" line-rate="0" branch-rate="0">
					<methods/>
					<lines>
						<line number="4" hits="0"/>
						<line number="5" hits="0"/>
						<line number="6" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="7,8"/>
						<line number="7" hits="0"/>
						<line number="8" hits="0"/>
						<line number="9" hits="0"/>
						<line number="11" hits="0"/>
						<line number="12" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="13,14"/>
						<line number="13" hits="0"/>
						<line number="14" hits="0"/>
						<line number="15" hits="0"/>
						<line number="16" hits="0"/>
						<line number="18" hits="0"/>
						<line number="19" hits="0"/>
					</lines>
				</class>
				<class name="pricing.py" filename="shop/pricing.py" complexity="0" line-rate="0.8667" branch-rate="0.6667">
					<methods/>
					<lines>
						<line number="3" hits="1"/>
						<line number="6" hits="1"/>
						<line number="7" hits="1" branch="true" condition-coverage="100% (2/2)"/>
						<line number="8" hits="1"/>
						<line number="9" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="10"/>
						<line number="10" hits="0"/>
						<line number="11" hits="1"/>
						<line number="14" hits="1"/>
						<line number="15" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="16"/>
						<line number="16" hits="0"/>
						<line number="17" hits="1"/>
						<line number="20" hits="1"/>
						<line number="21" hits="1"/>
						<line number="22" hits="1"/>
						<line number="23" hits="1"/>
					</lines>
				</class>
				<class name="refunds.py" filename="shop/refunds.py" complexity="0" line-rate="0" branch-rate="0">
					<methods/>
					<lines>
						<line number="2" hits="0"/>
						<line number="5" hits="0"/>
						<line number="6" hits="0"/>
						<line number="7" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="8,9"/>
						<line number="8" hits="0"/>
						<line number="9" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="10,11"/>
						<line number="10" hits="0"/>
						<line number="11" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="12,13"/>
						<line number="12" hits="0"/>
						<line number="13" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="14,15"/>
						<line number="14" hits="0"/>
						<line number="15" hits="0"/>
						<line number="18" hits="0"/>
						<line number="19" hits="0"/>
						<line number="25" hits="0" branch="true" condition-coverage="0% (0/2)" missing-branches="26,27"/>
						<line number="26" hits="0"/>
						<line number="27" hits="0"/>
						<line number="30" hits="0"/>
						<line number="31" hits="0"/>
						<line number="32" hits="0"/>
					</lines>
				</class>
			</classes>
		</package>
	</packages>
</coverage>

FILE:examples/changes.diff
diff --git a/shop/discounts.py b/shop/discounts.py
index 7a2f304..81655b4 100644
--- a/shop/discounts.py
+++ b/shop/discounts.py
@@ -20,0 +21,21 @@ def apply_code(total_cents, code):
+
+
+def best_code(total_cents, codes):
+    """Pick the code that gives the lowest total; ties keep the first code."""
+    best, best_total = None, total_cents
+    for code in codes:
+        new_total, error = apply_code(total_cents, code)
+        if error:
+            continue
+        if new_total < best_total:
+            best, best_total = code, new_total
+    return best, best_total
+
+
+def code_expired(code, today, expiry):
+    end = expiry.get(code.strip().upper())
+    if end is None:
+        return False
+    if today > end:
+        return True
+    return False
diff --git a/shop/gift_cards.py b/shop/gift_cards.py
new file mode 100644
index 0000000..a6a7e76
--- /dev/null
+++ b/shop/gift_cards.py
@@ -0,0 +1,19 @@
+"""Gift card balances (new in this change)."""
+
+
+class GiftCard:
+    def __init__(self, number, balance_cents):
+        if len(number) != 16 or not number.isdigit():
+            raise ValueError("gift card number must be 16 digits")
+        self.number = number
+        self.balance = balance_cents
+
+    def redeem(self, amount_cents):
+        if amount_cents <= 0:
+            raise ValueError("amount must be positive")
+        used = min(amount_cents, self.balance)
+        self.balance -= used
+        return amount_cents - used
+
+    def masked(self):
+        return "**** **** **** " + self.number[-4:]
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/test_discounts.py b/tests/test_discounts.py
new file mode 100644
index 0000000..b62587b
--- /dev/null
+++ b/tests/test_discounts.py
@@ -0,0 +1,7 @@
+import unittest
+from shop.discounts import best_code
+
+
+class DiscountTest(unittest.TestCase):
+    def test_best_code(self):
+        self.assertEqual(best_code(5000, ["WELCOME10", "SAVE5"]), ("WELCOME10", 4500))

FILE:examples/lcov.info
TN:
SF:src/utils/slugify.js
FN:1,slugify
FNDA:6,slugify
DA:2,6
DA:3,6
DA:4,1
DA:5,5
DA:6,5
BRDA:3,0,0,1
BRDA:3,0,1,5
LF:5
LH:5
end_of_record
TN:
SF:src/utils/dates.js
FN:1,formatDate
FN:9,daysBetween
FNDA:3,formatDate
FNDA:0,daysBetween
DA:2,3
DA:3,3
DA:4,0
DA:5,3
DA:10,0
DA:11,0
DA:12,0
BRDA:3,0,0,0
BRDA:3,0,1,3
BRDA:11,1,0,-
BRDA:11,1,1,-
LF:7
LH:3
end_of_record

FILE:scripts/coverage_gaps.py
#!/usr/bin/env python3
"""coverage_gaps.py - find the coverage gaps that matter in a Cobertura XML or LCOV report.

Reads a coverage report (Cobertura XML from coverage.py `coverage xml`, Jest/Vitest/istanbul
`cobertura` reporter, PHPUnit, .NET coverlet, gcovr ...; or LCOV `lcov.info`), and optionally a
unified diff of the change under review. Prints totals, the files with the most missed lines,
uncovered line ranges, diff coverage of changed lines, and flags C01-C09.

Usage:
  coverage_gaps.py REPORT [--diff changes.diff] [--format text|md|json|csv]
                   [--min-total 80] [--min-file 60] [--min-diff 80] [--min-lines 10]
                   [--block 15] [--top 10] [--exclude GLOB ...] [--strip-prefix PREFIX]
                   [--fail-on none|info|low|medium|high]
  coverage_gaps.py --self-test
Exit: 0 ok, 1 flags at or above --fail-on, 2 unreadable input. Python 3.8+, standard library only.
"""
import argparse, csv, fnmatch, io, json, os, re, sys
import xml.etree.ElementTree as ET

SEV = {"info": 0, "low": 1, "medium": 2, "high": 3}


class FileCov:
    def __init__(self, path):
        self.path = path
        self.lines = {}          # line number -> hit count
        self.branches = {}       # line number -> (covered, total)

    def add_line(self, n, hits):
        self.lines[n] = max(self.lines.get(n, 0), hits)

    def add_branch(self, n, covered, total):
        c, t = self.branches.get(n, (0, 0))
        self.branches[n] = (max(c, covered), max(t, total))

    @property
    def total(self): return len(self.lines)
    @property
    def covered(self): return sum(1 for h in self.lines.values() if h > 0)
    @property
    def missed_lines(self): return sorted(n for n, h in self.lines.items() if h == 0)
    @property
    def branch_total(self): return sum(t for _, t in self.branches.values())
    @property
    def branch_covered(self): return sum(c for c, _ in self.branches.values())

    def pct(self):
        return 100.0 * self.covered / self.total if self.total else None

    def branch_pct(self):
        return 100.0 * self.branch_covered / self.branch_total if self.branch_total else None


def norm_path(p, strip=""):
    p = p.replace("\\", "/")
    while p.startswith("./"):
        p = p[2:]
    if strip and p.startswith(strip):
        p = p[len(strip):].lstrip("/")
    return p


def parse_cobertura(text, strip=""):
    root = ET.fromstring(text)
    if root.tag != "coverage":
        raise ValueError("not a Cobertura report (root element is <%s>)" % root.tag)
    sources = [s.text.strip() for s in root.iter("source") if s.text and s.text.strip()]
    files = {}
    for cls in root.iter("class"):
        fn = cls.get("filename")
        if not fn:
            continue
        path = norm_path(fn, strip)
        fc = files.setdefault(path, FileCov(path))
        for ln in cls.iter("line"):
            try:
                n = int(ln.get("number")); hits = int(float(ln.get("hits", "0")))
            except (TypeError, ValueError):
                continue
            fc.add_line(n, hits)
            cond = ln.get("condition-coverage")   # e.g. "50% (1/2)"
            if ln.get("branch") == "true" and cond:
                m = re.search(r"\((\d+)/(\d+)\)", cond)
                if m:
                    fc.add_branch(n, int(m.group(1)), int(m.group(2)))
    return files, sources


def parse_lcov(text, strip=""):
    files, cur = {}, None
    for raw in text.splitlines():
        line = raw.strip()
        if line.startswith("SF:"):
            path = norm_path(line[3:], strip)
            cur = files.setdefault(path, FileCov(path))
        elif line.startswith("DA:") and cur is not None:
            parts = line[3:].split(",")
            try:
                cur.add_line(int(parts[0]), int(float(parts[1])))
            except (IndexError, ValueError):
                continue
        elif line.startswith("BRDA:") and cur is not None:
            parts = line[5:].split(",")
            if len(parts) == 4:
                try:
                    n = int(parts[0])
                except ValueError:
                    continue
                taken = parts[3] not in ("-", "0")
                c, t = cur.branches.get(n, (0, 0))
                cur.branches[n] = (c + (1 if taken else 0), t + 1)
        elif line == "end_of_record":
            cur = None
    if not files:
        raise ValueError("no SF: records found; not an LCOV file?")
    return files, []


def load_report(path, strip=""):
    with open(path, encoding="utf-8", errors="replace") as fh:
        text = fh.read()
    head = text.lstrip()[:200]
    if head.startswith("<"):
        return parse_cobertura(text, strip)
    return parse_lcov(text, strip)


def parse_diff(text, strip=""):
    """Return {path: set(added line numbers in the new file)} from a unified diff (git diff / git diff -U0)."""
    changed, path, n = {}, None, None
    for line in text.splitlines():
        if line.startswith("+++ "):
            p = line[4:].split("\t")[0].strip()
            if p == "/dev/null":
                path = None
                continue
            if p.startswith("b/"):
                p = p[2:]
            path = norm_path(p, strip)
            changed.setdefault(path, set())
        elif line.startswith("@@") and path is not None:
            m = re.match(r"@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line)
            n = int(m.group(1)) if m else None
        elif path is not None and n is not None:
            if line.startswith("+") and not line.startswith("+++"):
                changed[path].add(n); n += 1
            elif line.startswith("-") and not line.startswith("---"):
                pass
            elif line.startswith("\\"):
                pass
            else:
                n += 1
    return {p: s for p, s in changed.items() if s}


def ranges(nums):
    out, start, prev = [], None, None
    for x in sorted(nums):
        if start is None:
            start = prev = x
        elif x == prev + 1:
            prev = x
        else:
            out.append((start, prev)); start = prev = x
    if start is not None:
        out.append((start, prev))
    return out


def fmt_ranges(rs, limit=8):
    parts = ["%d" % a if a == b else "%d-%d" % (a, b) for a, b in rs]
    more = len(parts) - limit
    return ", ".join(parts[:limit]) + (" (+%d more)" % more if more > 0 else "")


def is_code_file(path):
    return not re.search(r"\.(md|txt|json|ya?ml|toml|lock|cfg|ini|csv|svg|png|jpg|gif)$", path, re.I)


def is_test_file(path):
    return bool(re.search(r"(^|/)(tests?|__tests__|spec)/|(^|/)test_[^/]+$|_test\.\w+$|\.(test|spec)\.\w+$", path))


def analyze(files, changed=None, opt=None):
    o = dict(min_total=80.0, min_file=60.0, min_diff=80.0, min_lines=10, block=15, top=10, exclude=[])
    o.update(opt or {})
    files = {p: f for p, f in files.items() if not any(fnmatch.fnmatch(p, g) for g in o["exclude"])}
    tot = sum(f.total for f in files.values()); cov = sum(f.covered for f in files.values())
    btot = sum(f.branch_total for f in files.values()); bcov = sum(f.branch_covered for f in files.values())
    rows = []
    for p, f in sorted(files.items()):
        rs = ranges(f.missed_lines)
        biggest = max([b - a + 1 for a, b in rs], default=0)
        rows.append(dict(file=p, lines=f.total, covered=f.covered, missed=f.total - f.covered,
                         pct=None if f.pct() is None else round(f.pct(), 1),
                         branch_pct=None if f.branch_pct() is None else round(f.branch_pct(), 1),
                         branches=f.branch_total, missed_ranges=rs, biggest_gap=biggest))
    rows.sort(key=lambda r: (-r["missed"], r["file"]))
    summary = dict(files=len(files), lines=tot, covered=cov,
                   line_pct=round(100.0 * cov / tot, 1) if tot else None,
                   branches=btot, branch_pct=round(100.0 * bcov / btot, 1) if btot else None)
    flags = []

    def flag(code, sev, msg, file=None):
        flags.append(dict(code=code, severity=sev, file=file, message=msg))

    if tot == 0:
        flag("C08", "high", "the report contains no measured lines (wrong file, wrong paths, or tests did not run)")
    elif summary["line_pct"] < o["min_total"]:
        flag("C01", "medium", "total line coverage %.1f%% is below the %.0f%% target" % (summary["line_pct"], o["min_total"]))
    for r in rows:
        if r["lines"] >= o["min_lines"] and r["covered"] == 0:
            flag("C07", "medium", "no line is covered (%d lines); the file may never be imported by tests" % r["lines"], r["file"])
        elif r["lines"] >= o["min_lines"] and r["pct"] is not None and r["pct"] < o["min_file"]:
            flag("C02", "low", "line coverage %.1f%% is below the per-file target %.0f%%" % (r["pct"], o["min_file"]), r["file"])
        if r["biggest_gap"] >= o["block"] and r["covered"] > 0:
            a, b = max(r["missed_ranges"], key=lambda x: x[1] - x[0])
            flag("C05", "low", "uncovered block of %d lines (%d-%d)" % (b - a + 1, a, b), r["file"])
        if r["branch_pct"] is not None and r["pct"] is not None and r["branches"] >= 4 and r["pct"] - r["branch_pct"] >= 25:
            flag("C06", "low", "branch coverage %.1f%% is far below line coverage %.1f%%: lines run, but some if/else paths never do" % (r["branch_pct"], r["pct"]), r["file"])
    diff = None
    if changed is not None:
        dfiles, dtot, dcov = [], 0, 0
        for p, lines in sorted(changed.items()):
            if any(fnmatch.fnmatch(p, g) for g in o["exclude"]) or not is_code_file(p):
                continue
            f = files.get(p)
            if f is None:
                if is_test_file(p):
                    continue
                dfiles.append(dict(file=p, changed=len(lines), measurable=0, covered=0, pct=None, uncovered_ranges=[], in_report=False))
                flag("C04", "medium", "changed file is not in the coverage report (new file without tests, or excluded from measurement)", p)
                continue
            meas = [n for n in lines if n in f.lines]
            c = [n for n in meas if f.lines[n] > 0]
            unc = ranges([n for n in meas if f.lines[n] == 0])
            dtot += len(meas); dcov += len(c)
            dfiles.append(dict(file=p, changed=len(lines), measurable=len(meas), covered=len(c),
                               pct=round(100.0 * len(c) / len(meas), 1) if meas else None, uncovered_ranges=unc, in_report=True))
        diff = dict(files=dfiles, measurable=dtot, covered=dcov, pct=round(100.0 * dcov / dtot, 1) if dtot else None)
        if diff["pct"] is not None and diff["pct"] < o["min_diff"]:
            sev = "high" if diff["pct"] < o["min_diff"] / 2 else "medium"
            flag("C03", sev, "diff coverage %.1f%% (%d of %d changed executable lines) is below the %.0f%% target" % (diff["pct"], dcov, dtot, o["min_diff"]))
        if diff["measurable"] == 0 and not any(not d["in_report"] for d in dfiles):
            flag("C09", "info", "no changed executable lines found in the report (docs/config-only change, or diff paths do not match report paths; try --strip-prefix)")
    flags.sort(key=lambda x: (-SEV[x["severity"]], x["code"], x["file"] or ""))
    return dict(summary=summary, files=rows, top=[r for r in rows if r["missed"]][:o["top"]], diff=diff, flags=flags, options=o)


def pct_s(v):
    return "  n/a" if v is None else "%5.1f%%" % v


def render_text(res):
    s = res["summary"]; out = []
    out.append("Coverage summary")
    out.append("  Files %d, lines %d, covered %d -> line coverage %s" % (s["files"], s["lines"], s["covered"], pct_s(s["line_pct"]).strip()))
    out.append("  Branches %d -> branch coverage %s" % (s["branches"], pct_s(s["branch_pct"]).strip()))
    if res["diff"] is not None:
        d = res["diff"]
        out.append("  Diff coverage %s (%d of %d changed executable lines covered, %d files changed)" % (pct_s(d["pct"]).strip(), d["covered"], d["measurable"], len(d["files"])))
    out.append("")
    out.append("Files with the most missed lines (top %d)" % len(res["top"]))
    for r in res["top"]:
        out.append("  %-34s %s  missed %3d/%-3d branch %s  gaps %s" % (r["file"][:34], pct_s(r["pct"]), r["missed"], r["lines"], pct_s(r["branch_pct"]), fmt_ranges(r["missed_ranges"], 5)))
    if res["diff"] is not None:
        out.append("")
        out.append("Changed lines")
        for d in res["diff"]["files"]:
            if not d["in_report"]:
                out.append("  %-34s NOT IN REPORT (%d changed lines)" % (d["file"][:34], d["changed"]))
            else:
                out.append("  %-34s %s  %d/%d covered  uncovered %s" % (d["file"][:34], pct_s(d["pct"]), d["covered"], d["measurable"], fmt_ranges(d["uncovered_ranges"]) or "-"))
    out.append("")
    out.append("Findings (%d)" % len(res["flags"]))
    for f in res["flags"]:
        out.append("  [%s %s] %s%s" % (f["code"], f["severity"], (f["file"] + ": ") if f["file"] else "", f["message"]))
    if not res["flags"]:
        out.append("  none")
    return "\n".join(out)


def render_md(res):
    s = res["summary"]; out = ["# Coverage gaps", ""]
    out.append("| Metric | Value |"); out.append("|---|---|")
    out.append("| Line coverage | %s (%d/%d lines, %d files) |" % (pct_s(s["line_pct"]).strip(), s["covered"], s["lines"], s["files"]))
    out.append("| Branch coverage | %s (%d branches) |" % (pct_s(s["branch_pct"]).strip(), s["branches"]))
    if res["diff"] is not None:
        d = res["diff"]
        out.append("| Diff coverage | %s (%d/%d changed lines) |" % (pct_s(d["pct"]).strip(), d["covered"], d["measurable"]))
    out += ["", "## Biggest gaps", "", "| File | Lines | Branches | Missed | Uncovered lines |", "|---|---|---|---|---|"]
    for r in res["top"]:
        if r["missed"]:
            out.append("| `%s` | %s | %s | %d | %s |" % (r["file"], pct_s(r["pct"]).strip(), pct_s(r["branch_pct"]).strip(), r["missed"], fmt_ranges(r["missed_ranges"], 6)))
    if res["diff"] is not None:
        out += ["", "## Changed lines", "", "| File | Covered | Uncovered changed lines |", "|---|---|---|"]
        for d in res["diff"]["files"]:
            out.append("| `%s` | %s | %s |" % (d["file"], "not in report" if not d["in_report"] else "%d/%d" % (d["covered"], d["measurable"]), fmt_ranges(d["uncovered_ranges"]) or "-"))
    out += ["", "## Findings", ""]
    out += ["- **%s** (%s) %s%s" % (f["code"], f["severity"], ("`%s`: " % f["file"]) if f["file"] else "", f["message"]) for f in res["flags"]] or ["- none"]
    return "\n".join(out)


def render_csv(res):
    buf = io.StringIO(); w = csv.writer(buf, lineterminator="\n")
    w.writerow(["file", "lines", "covered", "missed", "line_pct", "branch_pct", "biggest_gap", "uncovered_ranges"])
    for r in sorted(res["files"], key=lambda r: r["file"]):
        w.writerow([r["file"], r["lines"], r["covered"], r["missed"], "" if r["pct"] is None else r["pct"],
                    "" if r["branch_pct"] is None else r["branch_pct"], r["biggest_gap"], fmt_ranges(r["missed_ranges"], 1000)])
    return buf.getvalue().rstrip("\n")


def to_json(res):
    r = dict(res)
    r["files"] = [dict(x, missed_ranges=[list(t) for t in x["missed_ranges"]]) for x in res["files"]]
    r["top"] = [x["file"] for x in res["top"]]
    if res["diff"] is not None:
        r["diff"] = dict(res["diff"], files=[dict(x, uncovered_ranges=[list(t) for t in x["uncovered_ranges"]]) for x in res["diff"]["files"]])
    return json.dumps(r, indent=2)


SAMPLE_XML = """<?xml version="1.0" ?>
<coverage version="7.4" line-rate="0.6" branch-rate="0.5">
 <sources><source>/repo</source></sources>
 <packages><package name="app"><classes>
  <class name="a.py" filename="app/a.py"><lines>
   <line number="1" hits="1"/><line number="2" hits="1"/><line number="3" hits="0"/>
   <line number="4" hits="1" branch="true" condition-coverage="50% (1/2)"/><line number="5" hits="0"/>
  </lines></class>
  <class name="b.py" filename="app/b.py"><lines>
   """ + "".join('<line number="%d" hits="0"/>' % i for i in range(1, 13)) + """
  </lines></class>
 </classes></package></packages>
</coverage>"""

SAMPLE_LCOV = """TN:
SF:src/x.js
DA:1,1
DA:2,0
DA:3,4
BRDA:3,0,0,1
BRDA:3,0,1,-
end_of_record
"""

SAMPLE_DIFF = """diff --git a/app/a.py b/app/a.py
--- a/app/a.py
+++ b/app/a.py
@@ -2,0 +3,3 @@ def f():
+    x = 1
+    if x:
+        return 2
diff --git a/app/new.py b/app/new.py
--- /dev/null
+++ b/app/new.py
@@ -0,0 +1,2 @@
+def g():
+    return 1
diff --git a/tests/test_a.py b/tests/test_a.py
--- a/tests/test_a.py
+++ b/tests/test_a.py
@@ -1,0 +2 @@
+    assert f() == 2
"""


def self_test():
    checks = []

    def ok(name, cond):
        checks.append((name, bool(cond)))

    files, _ = parse_cobertura(SAMPLE_XML)
    ok("cobertura files", sorted(files) == ["app/a.py", "app/b.py"])
    a = files["app/a.py"]
    ok("cobertura line counts", (a.total, a.covered) == (5, 3))
    ok("cobertura missed lines", a.missed_lines == [3, 5])
    ok("cobertura branches", (a.branch_covered, a.branch_total) == (1, 2))
    lf, _ = parse_lcov(SAMPLE_LCOV)
    x = lf["src/x.js"]
    ok("lcov lines", (x.total, x.covered) == (3, 2))
    ok("lcov branches", (x.branch_covered, x.branch_total) == (1, 2))
    ok("ranges", ranges([1, 2, 3, 7, 9, 10]) == [(1, 3), (7, 7), (9, 10)])
    ok("fmt ranges", fmt_ranges([(1, 3), (7, 7)]) == "1-3, 7")
    ch = parse_diff(SAMPLE_DIFF)
    ok("diff added lines", ch.get("app/a.py") == {3, 4, 5})
    ok("diff new file", ch.get("app/new.py") == {1, 2})
    ok("diff strip prefix", parse_diff(SAMPLE_DIFF.replace("b/app/", "b/repo/app/"), "repo").get("app/a.py") == {3, 4, 5})
    res = analyze(files, ch, dict(min_total=80, min_lines=10))
    codes = {f["code"] for f in res["flags"]}
    ok("total line pct", res["summary"]["line_pct"] == round(100 * 3 / 17, 1))
    ok("C01 total below target", "C01" in codes)
    ok("C07 untouched file", any(f["code"] == "C07" and f["file"] == "app/b.py" for f in res["flags"]))
    ok("diff coverage 1 of 3", (res["diff"]["covered"], res["diff"]["measurable"]) == (1, 3))
    ok("C03 diff below target", "C03" in codes)
    ok("C04 new file not in report", any(f["code"] == "C04" and f["file"] == "app/new.py" for f in res["flags"]))
    ok("test files ignored in diff", all(d["file"] != "tests/test_a.py" for d in res["diff"]["files"]))
    ok("exclude glob", analyze(files, None, dict(exclude=["app/b.py"]))["summary"]["files"] == 1)
    ok("empty report C08", any(f["code"] == "C08" for f in analyze({}, None)["flags"]))
    ok("csv header", render_csv(res).splitlines()[0].startswith("file,lines,covered"))
    ok("json roundtrip", json.loads(to_json(res))["summary"]["files"] == 2)
    bad = [n for n, c in checks if not c]
    if bad:
        print("self-test FAILED: " + ", ".join(bad)); return 1
    print("self-test OK: %d checks" % len(checks)); return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("report", nargs="?")
    ap.add_argument("--diff")
    ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
    ap.add_argument("--min-total", type=float, default=80.0)
    ap.add_argument("--min-file", type=float, default=60.0)
    ap.add_argument("--min-diff", type=float, default=80.0)
    ap.add_argument("--min-lines", type=int, default=10, help="ignore smaller files for C02/C07")
    ap.add_argument("--block", type=int, default=15, help="uncovered block size for C05")
    ap.add_argument("--top", type=int, default=10)
    ap.add_argument("--exclude", action="append", default=[])
    ap.add_argument("--strip-prefix", default="")
    ap.add_argument("--fail-on", choices=["none"] + list(SEV), default="none")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.report:
        ap.print_usage(sys.stderr); return 2
    try:
        files, _ = load_report(a.report, a.strip_prefix)
        changed = None
        if a.diff:
            with open(a.diff, encoding="utf-8", errors="replace") as fh:
                changed = parse_diff(fh.read(), a.strip_prefix)
    except (OSError, ValueError, ET.ParseError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    res = analyze(files, changed, dict(min_total=a.min_total, min_file=a.min_file, min_diff=a.min_diff,
                                        min_lines=a.min_lines, block=a.block, top=a.top, exclude=a.exclude))
    print({"text": render_text, "md": render_md, "json": to_json, "csv": render_csv}[a.format](res))
    if a.fail_on != "none" and any(SEV[f["severity"]] >= SEV[a.fail_on] for f in res["flags"]):
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
TestingCoveragePython+4
F@f
0
Sleep Diary Pattern Analyzer
Skill

Turns a nightly sleep diary CSV into clear numbers and patterns: total sleep, time in bed, sleep efficiency, time to fall asleep, regularity, social jet lag between workdays and free days, weekly trends, and flags for late caffeine, long naps, alcohol nights and very short nights. Stdlib Python.

---
name: sleep-diary-pattern-analyzer
description: Turns a nightly sleep diary CSV into clear numbers and patterns: total sleep, time in bed, sleep efficiency, time to fall asleep, regularity, social jet lag between workdays and free days, weekly trends, and flags for late caffeine, long naps, alcohol nights and very short nights. Stdlib Python.
---

# Sleep Diary Pattern Analyzer

You help people who feel they sleep badly look at their own sleep with real numbers instead of impressions. Most people only remember the worst nights. A two- or three-week sleep diary shows what is actually going on: how long they sleep, how much time they lie awake, how much their schedule moves between workdays and weekends, and whether things like late coffee, evening drinks or long naps line up with worse nights. You read the diary, explain the numbers in plain words and suggest a few small, realistic experiments.

You are not a doctor and this is not a diagnosis. A sleep diary is a self-help and conversation tool; sleep clinicians use the same kind of diary, but they combine it with an interview and sometimes tests. Always point people to `references/when-to-get-help.md` when the diary or their description shows warning signs.

## Files in this skill

- `scripts/sleep_diary.py` - reads the diary CSV (times in HH:MM, nights crossing midnight handled automatically), computes per-night time in bed, total sleep, efficiency and sleep midpoint, a summary, a weekly table and flags S01-S10 + E01; `--format text|md|json|csv`, `--since/--until`, `--target-hours`, `--fail-on`, `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/sleep-metrics.md` - what each number means, how it is calculated and typical ranges for adults
- `references/when-to-get-help.md` - warning signs that need a doctor or sleep specialist instead of a spreadsheet, and limits of a diary
- `templates/two-week-sleep-review.md` - a short, friendly review with numbers, patterns and 2-3 experiments
- `examples/sleep_diary.csv` - 3 fictional weeks of an office worker who goes to bed late, drinks coffee in the afternoon on some days and sleeps in on weekends (one row has a typo on purpose)

## Workflow

### 1. Get a diary
If the person has no diary yet, give them the CSV header and ask them to fill one row every morning for at least 14 nights (7 is the minimum for patterns):
```
date,bedtime,sleep_latency_min,awakenings,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type
2026-11-09,23:55,10,2,14,06:50,07:05,0,11:30,0,4,work
```
- `date` = the evening they went to bed (a 00:20 bedtime still belongs to the previous date)
- `bedtime` = when they turned the lights off to sleep; `out_of_bed` = when they actually got up (defaults to `wake_time`)
- `sleep_latency_min` and `awake_min` are guesses, not measurements; rough numbers are fine
- `caffeine_last` = time of the last coffee, tea, cola or energy drink; `quality` = 1 (very bad) to 5 (very good)
- `day_type` = whether the NEXT day is a `work` or `free` day
Data from a sleep tracker or watch works too: export bedtime and wake time and fill the rest by hand.

### 2. Run the analysis
```
python3 scripts/sleep_diary.py sleep_diary.csv
python3 scripts/sleep_diary.py sleep_diary.csv --format md > sleep-review.md
python3 scripts/sleep_diary.py sleep_diary.csv --since 2026-11-16 --target-hours 8
python3 scripts/sleep_diary.py sleep_diary.csv --format csv      # per-night table for a spreadsheet
python3 scripts/sleep_diary.py --self-test
```
Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable file or missing columns.

| Code | Severity | Pattern |
|---|---|---|
| S01 | medium | average sleep efficiency below 85% |
| S02 | medium / high | average total sleep below 7 h / below 6 h |
| S03 | medium | wake-up time varies by more than 60 min (standard deviation) |
| S04 | low / medium | social jet lag of 1 h+ / 2 h+ (free-day sleep midpoint later than on workdays) |
| S05 | medium | average time to fall asleep over 30 min |
| S06 | low | nights with caffeine after 14:00 took 10+ min longer to fall asleep |
| S07 | low | naps over 30 min on 3+ days |
| S08 | low | nights after alcohol had 15+ min more time awake |
| S09 | info | fewer than 7 nights or gaps of 2+ missing nights |
| S10 | medium | 2+ nights with less than 5 h of sleep |
| E01 | medium | rows that could not be read (the line number and reason are shown) |

### 3. Explain and suggest
Use `references/sleep-metrics.md` to explain the numbers in one or two sentences each. Then pick at most three experiments for the next two weeks, linked to the flags, for example:
- S03/S04: the same wake-up time every day, weekends included, within 30-60 minutes; morning daylight soon after waking.
- S06: last caffeine before 14:00 for two weeks, then compare `--since` the start date.
- S07: naps under 30 minutes and before 15:00.
- S01/S05: get up after about 20 minutes awake in bed, do something calm in dim light, return when sleepy.
- S08: compare a few alcohol-free evenings.
The "consistent schedule idea" in the output uses the median workday wake time and `--target-hours`; present it as a starting point, not a rule, and never suggest less than 7 hours in bed on their own.

### 4. Report
Fill `templates/two-week-sleep-review.md`. Keep it kind and concrete; say what went well, too. Repeat the analysis after the experiment period and compare.

## Rules
- Never diagnose (insomnia, sleep apnea, depression, etc.) and never recommend medication, supplements or doses. Refer to a doctor when `when-to-get-help.md` applies.
- Do not recommend strict sleep restriction (shortening time in bed below current sleep) without a clinician; it is a treatment step that needs supervision.
- Diary values are estimates. Talk about patterns over several nights, never about one night.
- Correlation is not cause: "nights with late coffee took longer" is a hint for an experiment, not proof.
- Keep the diary private; it is health data. Do not ask for names or share it outside the conversation.

FILE:references/sleep-metrics.md
# Sleep diary metrics

All values come from the diary, so they are estimates. Look at averages and patterns over at least 7, ideally 14 or more nights.

| Metric | How it is calculated | Typical adult range / meaning |
|---|---|---|
| Time in bed (TIB) | `out_of_bed - bedtime` | Should be close to the sleep you need plus 15-30 min. Much more than that often means lying awake. |
| Time to fall asleep (sleep onset latency) | `sleep_latency_min` | 10-20 min is typical. Regularly over 30 min is a sign of trouble falling asleep (S05). Under 5 min every night can mean sleep debt. |
| Time awake at night (WASO) | `awake_min` | Short awakenings are normal; people rarely remember those under a few minutes. 30+ min per night on average is worth noting. |
| Total sleep time (TST) | `wake_time - (bedtime + latency) - awake_min` | Most adults need 7-9 hours (American Academy of Sleep Medicine, National Sleep Foundation). Below 7 h on average: S02. |
| Sleep efficiency (SE) | `TST / TIB x 100` | 85% or more is usually considered good; below 85% (S01) means a lot of time in bed awake. |
| Sleep midpoint | halfway between falling asleep and waking | A marker of the body clock. Later midpoints = later chronotype or a shifted schedule. |
| Social jet lag | free-day midpoint minus workday midpoint | Like flying one or two time zones every weekend. 1 h+ is common (S04 low), 2 h+ makes Monday mornings much harder (S04 medium). |
| Regularity | standard deviation of bedtime and wake time | Wake time matters most. A spread over 60 min (S03) makes the body clock drift. |
| Quality | the person's 1-5 rating | Subjective, but useful: compare quality with the other numbers. |

## Reading the numbers together
- Short sleep + high efficiency + very short latency: probably not enough time in bed (going to bed too late or getting up very early). Experiment: earlier lights out.
- Normal sleep time + low efficiency + long latency: lots of time awake in bed. Experiments: consistent wake time, get up when awake for long, avoid long naps and late caffeine.
- Good weekday numbers + big social jet lag: the weekend schedule pulls the body clock later; Monday and Tuesday nights then start badly.
- Worse nights after alcohol: alcohol helps people fall asleep but often causes more awakenings in the second half of the night.

## Caffeine and naps
Caffeine has an average half-life of about 5 hours (it varies a lot between people, from about 2 to 10 hours), so an afternoon coffee is still partly active at bedtime. Short naps (10-30 min) before mid-afternoon refresh most people without hurting night sleep; longer or later naps reduce sleep pressure in the evening.

## The "consistent schedule idea"
The script suggests a fixed wake time (the median workday wake time) and a lights-out time that gives `--target-hours` of sleep plus a typical time to fall asleep. It is a starting point for a conversation. Keeping the same wake time every day is the single most useful habit for a regular body clock.

FILE:references/when-to-get-help.md
# When a sleep diary is not enough

A diary helps people notice patterns and try small habit changes. Some situations need a doctor, ideally a general practitioner first, who can refer to a sleep specialist. Recommend getting help, kindly and clearly, when any of these apply:

## See a doctor soon
- Loud snoring with pauses in breathing, gasping or choking at night (noticed by a partner), especially with morning headaches or high blood pressure: possible sleep apnea.
- Strong sleepiness during the day: falling asleep while driving, in meetings or in conversations, even after enough hours in bed.
- Trouble falling or staying asleep at least 3 nights a week for 3 months or more, affecting the day: chronic insomnia has effective treatments, especially cognitive behavioral therapy for insomnia (CBT-I).
- An urge to move the legs in the evening with uncomfortable feelings that get better with movement.
- Acting out dreams, sudden muscle weakness with laughter or strong emotions, or sleep attacks.
- Sleep problems together with low mood, loss of interest, strong anxiety or thoughts of self-harm. If someone mentions thoughts of self-harm, encourage them to contact local emergency services or a crisis line right away.
- Sleep problems that started with a new medication, or that come with pain, breathing problems at night or frequent urination.
- Pregnancy, shift work with accidents or near misses, or a child or teenager with persistent sleep problems: get specific professional advice.

## Never do in this skill
- Diagnose a sleep disorder or rule one out.
- Recommend sleeping pills, melatonin doses, supplements or stopping a prescribed medication.
- Tell someone to drive or work in a safety-critical job when they report strong sleepiness.

## Limits of a diary
- Times are estimates; people often overestimate time awake and underestimate sleep, especially on bad nights.
- Wearable trackers estimate sleep from movement and heart rate; they are fine for bedtime and wake time but not exact for sleep stages.
- A few weeks show habits, not health. Bring the diary and the script's summary to the doctor; clinicians find a filled diary useful.

FILE:templates/two-week-sleep-review.md
# Your sleep review: {{from}} to {{to}} ({{N}} nights)

## The short version
{{2-3 sentences in plain words: how much you sleep, how regular it is, the main pattern, one thing that is already good}}

## Your numbers
| | Your average | Typical range |
|---|---|---|
| Sleep per night | {{6h38}} | 7-9 h |
| Time in bed | {{7h38}} | sleep + 15-30 min |
| Sleep efficiency | {{87%}} | 85% or more |
| Time to fall asleep | {{25 min}} | 10-20 min |
| Wake-up time variation | {{73 min}} | under 60 min |
| Social jet lag | {{1h49}} | under 1 h |

## Patterns we noticed
- {{e.g. On the 7 nights with coffee after 14:00 you needed about 42 minutes to fall asleep, compared with 16 minutes on other nights.}}
- {{...}}

## Experiments for the next two weeks (pick 2-3)
1. {{e.g. Wake up at 06:50 every day, also on weekends (within 30-60 minutes), and get daylight within an hour.}}
2. {{e.g. Last coffee before 14:00.}}
3. {{e.g. Keep naps under 30 minutes and before 15:00.}}

Keep filling the diary, then run the analysis again from {{start date}} and compare.

## Please talk to a doctor if
{{Only if relevant: the warning signs from when-to-get-help.md that apply, written kindly. Otherwise: "Nothing in your diary suggests you need medical help right now, but see a doctor if ..."}}

_This review is based on your own diary estimates and is not medical advice._

FILE:examples/sleep_diary.csv
date,bedtime,sleep_latency_min,awakenings,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type
2026-11-09,23:55,10,2,14,06:50,07:05,0,11:30,0,4,work
2026-11-10,23:10,50,2,14,06:50,07:00,0,16:30,0,2,work
2026-11-11,00:20,15,1,7,06:45,07:00,0,10:00,0,4,work
2026-11-12,23:25,50,1,7,06:50,06:55,40,16:00,0,3,work
2026-11-13,00:55,20,3,50,09:20,09:40,40,08:30,2,3,free
2026-11-14,00:55,10,3,55,09:20,10:00,40,,2,2,free
2026-11-15,00:20,15,2,14,06:45,07:00,0,08:30,0,4,work
2026-11-16,00:20,20,0,0,06:50,07:00,0,,0,4,work
2026-11-17,23:10,40,1,7,06:45,07:00,0,16:30,0,3,work
2026-11-18,23:40,40,1,7,06:45,06:55,0,16:00,0,3,work
2026-11-19,00:20,35,2,14,07:00,07:15,50,16:00,0,2,work
2026-11-20,00:40,10,2,35,09:20,10:00,40,,2,2,free
2026-11-22,23:25,10,2,14,06:45,07:00,0,11:30,0,4,work
2026-11-23,23:40,20,2,14,06:50,07:00,0,08:30,0,4,work
2026-11-24,00:50,40,2,60,06:45,06:55,0,16:30,0,1,work
2026-11-25,01:05,30,1,7,06:45,06:55,0,11:30,0,4,work
2026-11-26,23:25,40,1,7,07:00,07:05,0,16:30,0,2,work
2026-11-27,00:40,20,1,25,10:10,10:30,40,10:00,2,2,free
2026-11-28,01:30,10,3,55,10:10,10:40,50,08:30,2,3,free
2026-11-29,23:40,15,1,7,07:00,07:10,0,10:00,0,4,work
2026-11-30,23:30,15,,10,7:05,,0,,0,,work
2026-12-01,23:15,,1,abc,06:50,07:00,0,09:00,0,4,work

FILE:scripts/sleep_diary.py
#!/usr/bin/env python3
"""sleep_diary.py - turn a simple sleep diary CSV into clear sleep metrics and pattern flags.

One row per night. Required columns: date, bedtime, wake_time. Optional: sleep_latency_min,
awake_min, awakenings, out_of_bed, nap_min, caffeine_last, alcohol_drinks, quality, day_type.
Times are HH:MM (24 h); a night that crosses midnight is handled automatically. date is the
evening you went to bed (YYYY-MM-DD or DD.MM.YYYY). day_type is the NEXT day: work or free.

Per night: time in bed, sleep onset, total sleep time, sleep efficiency, sleep midpoint.
Summary: averages, regularity, workday vs free-day comparison (social jet lag), weekly table,
and flags S01-S10 + E01. Not a medical tool; see references/when-to-get-help.md.

Python 3.8+ standard library only.
Usage:
  sleep_diary.py DIARY.csv [--format text|md|json|csv] [--since YYYY-MM-DD] [--until YYYY-MM-DD]
                 [--target-hours 7.5] [--fail-on high|medium|low|none]
  sleep_diary.py --self-test
Exit codes: 0 = no flags at or above --fail-on (default none), 1 = flags at or above it, 2 = bad input.
"""
import argparse, csv, datetime, io, json, statistics, sys

FLAGS = {
    "S01": "average sleep efficiency below 85% (a lot of time in bed awake)",
    "S02": "average total sleep below the healthy adult range (7 h); below 6 h is high",
    "S03": "wake-up time varies a lot (standard deviation over 60 min)",
    "S04": "social jet lag: sleep midpoint on free days is 1 h or more later than on workdays (2 h+ is medium)",
    "S05": "average time to fall asleep over 30 min",
    "S06": "nights with caffeine after 14:00 took clearly longer to fall asleep (10 min+ on average)",
    "S07": "long daytime naps (over 30 min) on 3 or more days",
    "S08": "nights after alcohol had clearly more time awake (15 min+ on average)",
    "S09": "fewer than 7 nights logged, or gaps of 2+ missing nights; patterns are less reliable",
    "S10": "2 or more very short nights (under 5 h of sleep)",
    "E01": "rows that could not be read",
}
SEV_ORDER = {"high": 3, "medium": 2, "low": 1, "info": 0}


def parse_date(s):
    s = (s or "").strip()
    for fmt in ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y"):
        try:
            return datetime.datetime.strptime(s, fmt).date()
        except ValueError:
            pass
    raise ValueError("bad date %r" % s)


def parse_clock(s):
    s = (s or "").strip().replace(".", ":")
    h, _, m = s.partition(":")
    h, m = int(h), int(m or 0)
    if not (0 <= h <= 23 and 0 <= m <= 59):
        raise ValueError("bad time %r" % s)
    return h * 60 + m


def since_noon(clock_min):
    """Minutes since 12:00 on the diary date: 23:30 -> 690, 00:30 -> 750, 07:00 -> 1140.
    Assumes bedtimes after 12:00 belong to the evening and times before 12:00 to the next morning."""
    return clock_min - 720 if clock_min >= 720 else clock_min + 720


def num(row, key, default=0.0):
    v = (row.get(key) or "").strip().replace(",", ".")
    try:
        return float(v) if v else default
    except ValueError:
        raise ValueError("bad number %r in %s" % (v, key))


def fmt_clock(m_since_noon):
    m = int(round(m_since_noon + 720)) % 1440
    return "%02d:%02d" % (m // 60, m % 60)


def hm(minutes):
    minutes = int(round(minutes))
    sign = "-" if minutes < 0 else ""
    minutes = abs(minutes)
    return "%s%dh%02d" % (sign, minutes // 60, minutes % 60)


def read_nights(text, since=None, until=None):
    nights, errors = [], []
    rdr = csv.DictReader(io.StringIO(text))
    if not rdr.fieldnames:
        raise ValueError("empty file")
    cols = {c.strip().lower() for c in rdr.fieldnames if c}
    missing = {"date", "bedtime", "wake_time"} - cols
    if missing:
        raise ValueError("missing required column(s): " + ", ".join(sorted(missing)))
    for i, raw in enumerate(rdr, 2):
        row = {(k or "").strip().lower(): (v or "").strip() for k, v in raw.items()}
        if not any(row.values()):
            continue
        try:
            d = parse_date(row["date"])
            if (since and d < since) or (until and d > until):
                continue
            bed = since_noon(parse_clock(row["bedtime"]))
            wake = since_noon(parse_clock(row["wake_time"]))
            oob = since_noon(parse_clock(row["out_of_bed"])) if row.get("out_of_bed") else wake
            lat, awake = num(row, "sleep_latency_min"), num(row, "awake_min")
            onset = bed + lat
            if not (bed < wake <= oob) or onset >= wake:
                raise ValueError("times out of order (bed %s, wake %s, out of bed %s)" % (row["bedtime"], row["wake_time"], row.get("out_of_bed") or "-"))
            tib = oob - bed
            tst = wake - onset - awake
            if tst <= 0 or tib > 20 * 60:
                raise ValueError("implausible night (sleep %.0f min, in bed %.0f min)" % (tst, tib))
            caf = row.get("caffeine_last", "")
            q = row.get("quality", "")
            nights.append({
                "date": d.isoformat(), "bedtime": row["bedtime"], "wake_time": row["wake_time"],
                "tib_min": tib, "tst_min": tst, "latency_min": lat, "awake_min": awake,
                "awakenings": num(row, "awakenings", 0), "efficiency": round(100.0 * tst / tib, 1),
                "midpoint": onset + (wake - onset) / 2.0, "wake": wake, "bed": bed,
                "nap_min": num(row, "nap_min"), "late_caffeine": bool(caf) and parse_clock(caf) >= 14 * 60,
                "alcohol": num(row, "alcohol_drinks") > 0, "quality": int(q) if q else None,
                "day_type": (row.get("day_type") or "").lower() or None})
        except (ValueError, KeyError) as e:
            errors.append({"line": i, "error": str(e)})
    nights.sort(key=lambda n: n["date"])
    return nights, errors


def mean(xs):
    xs = [x for x in xs if x is not None]
    return sum(xs) / len(xs) if xs else None


def analyze(nights, errors, target_hours=7.5):
    flags = []

    def add(code, sev, detail):
        flags.append({"code": code, "severity": sev, "detail": detail})
    if errors:
        add("E01", "medium", "%d row(s): %s" % (len(errors), "; ".join("line %d %s" % (e["line"], e["error"]) for e in errors[:3])))
    if not nights:
        return {"summary": {"nights": 0}, "nights": [], "weekly": [], "flags": flags}
    tst = mean(n["tst_min"] for n in nights)
    eff = mean(n["efficiency"] for n in nights)
    lat = mean(n["latency_min"] for n in nights)
    wake_sd = statistics.pstdev([n["wake"] for n in nights]) if len(nights) > 1 else 0.0
    bed_sd = statistics.pstdev([n["bed"] for n in nights]) if len(nights) > 1 else 0.0
    work = [n for n in nights if n["day_type"] == "work"]
    free = [n for n in nights if n["day_type"] == "free"]
    sjl = (mean(n["midpoint"] for n in free) - mean(n["midpoint"] for n in work)) if work and free else None
    if eff < 85:
        add("S01", "medium", "average efficiency %.1f%%" % eff)
    if tst < 360:
        add("S02", "high", "average sleep %s" % hm(tst))
    elif tst < 420:
        add("S02", "medium", "average sleep %s" % hm(tst))
    if wake_sd > 60:
        add("S03", "medium", "wake time SD %d min" % round(wake_sd))
    if sjl is not None and sjl >= 60:
        add("S04", "medium" if sjl >= 120 else "low", "free-day midpoint %s later than workdays" % hm(sjl))
    if lat > 30:
        add("S05", "medium", "average %d min to fall asleep" % round(lat))
    lc = [n["latency_min"] for n in nights if n["late_caffeine"]]
    nc = [n["latency_min"] for n in nights if not n["late_caffeine"]]
    if len(lc) >= 2 and len(nc) >= 2 and mean(lc) - mean(nc) >= 10:
        add("S06", "low", "%d min vs %d min to fall asleep (%d late-caffeine nights)" % (round(mean(lc)), round(mean(nc)), len(lc)))
    longnaps = [n for n in nights if n["nap_min"] > 30]
    if len(longnaps) >= 3:
        add("S07", "low", "%d days with naps over 30 min" % len(longnaps))
    al = [n["awake_min"] for n in nights if n["alcohol"]]
    na = [n["awake_min"] for n in nights if not n["alcohol"]]
    if len(al) >= 2 and len(na) >= 2 and mean(al) - mean(na) >= 15:
        add("S08", "low", "%d min vs %d min awake at night (%d alcohol nights)" % (round(mean(al)), round(mean(na)), len(al)))
    dates = [datetime.date.fromisoformat(n["date"]) for n in nights]
    gaps = [(a, b) for a, b in zip(dates, dates[1:]) if (b - a).days >= 3]
    if len(nights) < 7 or gaps:
        add("S09", "info", "%d nights logged%s" % (len(nights), ("; gaps after " + ", ".join(a.isoformat() for a, _ in gaps)) if gaps else ""))
    short = [n for n in nights if n["tst_min"] < 300]
    if len(short) >= 2:
        add("S10", "medium", "%d nights under 5 h: %s" % (len(short), ", ".join(n["date"] for n in short)))
    flags.sort(key=lambda f: (-SEV_ORDER[f["severity"]], f["code"]))
    weeks = {}
    for n in nights:
        y, w, _ = datetime.date.fromisoformat(n["date"]).isocalendar()
        weeks.setdefault("%d-W%02d" % (y, w), []).append(n)
    weekly = [{"week": k, "nights": len(v), "avg_sleep": hm(mean(x["tst_min"] for x in v)),
               "avg_efficiency": round(mean(x["efficiency"] for x in v), 1),
               "avg_quality": (round(mean(x["quality"] for x in v), 1) if any(x["quality"] for x in v) else None)}
              for k, v in sorted(weeks.items())]
    wake_ref = statistics.median([n["wake"] for n in (work or nights)])
    summary = {
        "nights": len(nights), "from": nights[0]["date"], "to": nights[-1]["date"],
        "avg_sleep": hm(tst), "avg_time_in_bed": hm(mean(n["tib_min"] for n in nights)),
        "avg_efficiency_pct": round(eff, 1), "avg_latency_min": round(lat), "avg_awake_min": round(mean(n["awake_min"] for n in nights)),
        "avg_bedtime": fmt_clock(mean(n["bed"] for n in nights)), "avg_wake_time": fmt_clock(mean(n["wake"] for n in nights)),
        "bedtime_sd_min": round(bed_sd), "wake_sd_min": round(wake_sd),
        "workday_midpoint": fmt_clock(mean(n["midpoint"] for n in work)) if work else None,
        "free_day_midpoint": fmt_clock(mean(n["midpoint"] for n in free)) if free else None,
        "social_jet_lag": hm(sjl) if sjl is not None else None,
        "avg_quality": round(mean(n["quality"] for n in nights), 1) if any(n["quality"] for n in nights) else None,
        "anchor_wake_time": fmt_clock(wake_ref),
        "suggested_lights_out": fmt_clock(wake_ref - target_hours * 60 - max(15, min(lat, 30))),
        "target_hours": target_hours,
    }
    return {"summary": summary, "nights": nights, "weekly": weekly, "flags": flags}


def render(res, fmt):
    s = res["summary"]
    if fmt == "json":
        return json.dumps(res, indent=2, default=str)
    if fmt == "csv":
        b = io.StringIO(); w = csv.writer(b, lineterminator="\n")
        w.writerow(["date", "bedtime", "wake_time", "time_in_bed", "sleep", "efficiency_pct", "latency_min", "awake_min", "midpoint", "day_type", "quality"])
        for n in res["nights"]:
            w.writerow([n["date"], n["bedtime"], n["wake_time"], hm(n["tib_min"]), hm(n["tst_min"]), n["efficiency"], int(n["latency_min"]), int(n["awake_min"]), fmt_clock(n["midpoint"]), n["day_type"] or "", n["quality"] or ""])
        return b.getvalue().rstrip("\n")
    if not s.get("nights"):
        return "No readable nights.\n" + "\n".join("  %s %s" % (f["code"], f["detail"]) for f in res["flags"])
    lines = [
        ("Nights", "%d (%s to %s)" % (s["nights"], s["from"], s["to"])),
        ("Average sleep", "%s of %s in bed (efficiency %.1f%%)" % (s["avg_sleep"], s["avg_time_in_bed"], s["avg_efficiency_pct"])),
        ("Falling asleep", "%d min on average; %d min awake during the night" % (s["avg_latency_min"], s["avg_awake_min"])),
        ("Bedtime / wake time", "%s / %s (variation %d / %d min SD)" % (s["avg_bedtime"], s["avg_wake_time"], s["bedtime_sd_min"], s["wake_sd_min"])),
        ("Sleep midpoint", "workdays %s, free days %s, social jet lag %s" % (s["workday_midpoint"] or "-", s["free_day_midpoint"] or "-", s["social_jet_lag"] or "-")),
        ("Quality (1-5)", str(s["avg_quality"] or "-")),
        ("Consistent schedule idea", "wake at %s every day; lights out around %s for %.1f h of sleep" % (s["anchor_wake_time"], s["suggested_lights_out"], s["target_hours"])),
    ]
    if fmt == "md":
        out = ["## Sleep diary summary", "", "| Metric | Value |", "|---|---|"] + ["| %s | %s |" % l for l in lines]
        out += ["", "### Weekly", "", "| Week | Nights | Avg sleep | Efficiency | Quality |", "|---|---|---|---|---|"]
        out += ["| %s | %d | %s | %.1f%% | %s |" % (w["week"], w["nights"], w["avg_sleep"], w["avg_efficiency"], w["avg_quality"] or "-") for w in res["weekly"]]
        out += ["", "### Patterns", ""] + (["- **%s %s** %s - %s" % (f["severity"], f["code"], FLAGS[f["code"]], f["detail"]) for f in res["flags"]] or ["- none"])
        out += ["", "_Not medical advice. See when-to-get-help before changing sleep on purpose._"]
        return "\n".join(out)
    out = ["Sleep diary summary"] + ["  %-25s %s" % l for l in lines] + ["", "Weekly"]
    out += ["  %-9s %d night%s  sleep %s  efficiency %5.1f%%  quality %s" % (w["week"], w["nights"], "" if w["nights"] == 1 else "s", w["avg_sleep"], w["avg_efficiency"], w["avg_quality"] or "-") for w in res["weekly"]]
    out += ["", "Patterns"] + (["  %-6s %s  %s" % (f["severity"].upper(), f["code"], f["detail"]) for f in res["flags"]] or ["  none"])
    out += ["", "Not medical advice; see references/when-to-get-help.md."]
    return "\n".join(out)


def self_test():
    head = "date,bedtime,sleep_latency_min,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type\n"
    rows = [
        "2026-11-02,23:30,10,10,07:00,07:10,0,09:00,0,4,work",
        "2026-11-03,23:45,40,20,07:00,07:15,0,16:30,0,3,work",
        "2026-11-04,00:15,15,40,07:00,07:20,45,10:00,2,2,work",
        "2026-11-05,23:30,45,15,07:00,07:30,40,17:00,0,3,work",
        "2026-11-06,01:30,10,45,09:30,10:00,0,11:00,3,2,free",
        "2026-11-07,02:00,10,10,10:30,10:45,60,,0,4,free",
        "2026-11-08,23:00,20,10,07:00,07:05,0,08:30,0,4,work",
        "2026-11-09,bad,10,10,07:00,,,,,,work",
    ]
    nights, errs = read_nights(head + "\n".join(rows) + "\n")
    r = analyze(nights, errs, 7.5)
    codes = {f["code"] for f in r["flags"]}
    n0 = nights[0]
    checks = [
        ("7 nights read", len(nights) == 7), ("1 error row", len(errs) == 1 and errs[0]["line"] == 9),
        ("midnight crossing tib", n0["tib_min"] == 460), ("tst", n0["tst_min"] == 430),
        ("efficiency", n0["efficiency"] == round(100 * 430 / 460, 1)),
        ("after-midnight bedtime", nights[2]["bed"] == 735 and nights[2]["tst_min"] == 350),
        ("S04 social jet lag", "S04" in codes), ("S06 late caffeine", "S06" in codes),
        ("S07 naps", "S07" in codes), ("S08 alcohol", "S08" in codes), ("E01", "E01" in codes),
        ("S03 wake variation", "S03" in codes), ("no S10", "S10" not in codes),
        ("clock format", fmt_clock(750) == "00:30" and fmt_clock(1140) == "07:00"),
        ("hm", hm(430) == "7h10" and hm(-75) == "-1h15"),
        ("dd.mm.yyyy", parse_date("03.12.2026") == datetime.date(2026, 12, 3)),
        ("out of order rejected", read_nights(head + "2026-11-02,07:00,10,0,06:00,,,,,,\n")[1] != []),
        ("md render", render(r, "md").startswith("## Sleep diary summary")),
        ("csv render", render(r, "csv").count("\n") == 7),
    ]
    bad = [n for n, ok in checks if not ok]
    if bad:
        print("self-test FAILED:", ", ".join(bad)); print(sorted(codes)); return 1
    print("self-test OK: %d checks" % len(checks)); return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description="Analyze a sleep diary CSV (stdlib only).")
    ap.add_argument("diary", nargs="?")
    ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
    ap.add_argument("--since"); ap.add_argument("--until")
    ap.add_argument("--target-hours", type=float, default=7.5)
    ap.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="none")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.diary:
        ap.error("give a diary CSV (or --self-test)")
    try:
        text = sys.stdin.read() if a.diary == "-" else open(a.diary, encoding="utf-8-sig").read()
        nights, errors = read_nights(text, parse_date(a.since) if a.since else None, parse_date(a.until) if a.until else None)
    except (OSError, ValueError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    if not 4 <= a.target_hours <= 10:
        print("error: --target-hours must be between 4 and 10", file=sys.stderr); return 2
    res = analyze(nights, errors, a.target_hours)
    print(render(res, a.format))
    if a.fail_on == "none":
        return 0
    return 1 if any(SEV_ORDER[f["severity"]] >= SEV_ORDER[a.fail_on] for f in res["flags"]) else 0


if __name__ == "__main__":
    sys.exit(main())
HealthDaily RoutinePython+4
F@f
0
SSH Authorized Keys Auditor
Skill

Audits OpenSSH authorized_keys files offline: SHA256 fingerprints like ssh-keygen -lf, weak DSA and short RSA keys, duplicates, missing comments, unrestricted automation keys, expired or loose options, plus keys of people who left or were never known, using an optional owners CSV. Stdlib Python.

---
name: ssh-authorized-keys-auditor
description: Audits OpenSSH authorized_keys files offline: SHA256 fingerprints like ssh-keygen -lf, weak DSA and short RSA keys, duplicates, missing comments, unrestricted automation keys, expired or loose options, plus keys of people who left or were never known, using an optional owners CSV. Stdlib Python.
---

# SSH Authorized Keys Auditor

You help developers, sysadmins and team leads answer a simple question that is surprisingly hard on real servers: who can log in here with a key, and should they still be able to? `authorized_keys` files grow for years. People change laptops and add a new key without removing the old one, contractors finish their projects, a backup host from 2019 still has a 1024-bit RSA key with full shell access, and nobody remembers what `AAAAC3...` without a comment belongs to. You read the files, list every key with its fingerprint, size and owner, and point at the few lines that need action.

You work offline on copies of the files. You never connect to servers, never ask for private keys and never test a key by logging in with it. A finding means "decide about this line", not "this server is compromised".

## Files in this skill

- `scripts/ssh_keys_audit.py` - parses one or more `authorized_keys` files (options with quoted values, key type, base64 blob, comment), computes the SHA256 fingerprint exactly like `ssh-keygen -lf`, reads the real RSA/DSA key size from the blob, and prints findings K01-K12 + E01 with a severity; `--owners` maps keys to people, `--format text|md|json|csv`, `--fail-on` for CI, `--today` for reproducible checks, `--self-test` runs 21 checks (Python 3.8+ standard library only)
- `references/key-types-and-strength.md` - which key types and sizes to accept in 2026, hardware-backed `sk-` keys, and how to replace weak keys without locking anyone out
- `references/authorized-keys-options.md` - `from=`, `command=`, `restrict`, `expiry-time=`, `permitopen=` and friends, with safe patterns for automation keys
- `templates/access-review-report.md` - a short access review report for one server or a fleet
- `examples/authorized_keys` - a fictional `deploy` user on `web-01` with 16 key lines (public keys only; the matching private keys were deleted after generating them)
- `examples/owners.csv` - the owners list for the example, with one person who left and one ended contract

## Workflow

### 1. Collect the files
Copy the files instead of auditing on the live server:
```
scp web-01:/home/deploy/.ssh/authorized_keys ./web-01.deploy.authorized_keys
sudo find /home /root -name 'authorized_keys*' -path '*/.ssh/*' 2>/dev/null   # on the server, to find all of them
grep -i AuthorizedKeysFile /etc/ssh/sshd_config /etc/ssh/sshd_config.d/* 2>/dev/null   # non-default locations
```
Also check whether `AuthorizedKeysCommand` or SSH certificates (`TrustedUserCAKeys`) are used; keys served that way are not in these files and need a separate review.

### 2. Build or update the owners list (optional, recommended)
`owners.csv` has the columns `match,owner,status,last_review,note`. `match` is either the exact key comment or the `SHA256:` fingerprint (safer, because comments can be edited). `status` is `active`, `left`, `revoked`, `inactive` or `offboarded`. Start with `--format csv` output to get every fingerprint, then fill in owners with the team.

### 3. Run the audit
```
python3 scripts/ssh_keys_audit.py web-01.deploy.authorized_keys
python3 scripts/ssh_keys_audit.py hosts/*.authorized_keys --owners owners.csv --format md > access-review.md
python3 scripts/ssh_keys_audit.py authorized_keys --owners owners.csv --fail-on medium     # CI or cron gate
python3 scripts/ssh_keys_audit.py authorized_keys --format csv > key-inventory.csv
python3 scripts/ssh_keys_audit.py --self-test
```
Exit code 0 = nothing at or above `--fail-on` (default high; info never fails), 1 = findings at or above it, 2 = unreadable input or owners file.

| Code | Severity | Meaning |
|---|---|---|
| K01 | high | DSA (`ssh-dss`) key |
| K02 | high | RSA key shorter than 2048 bits |
| K03 | medium | RSA key shorter than `--min-rsa-bits` (default 3072) |
| K04 | medium | the same public key appears more than once (also across files) |
| K05 | low | key without a comment |
| K06 | medium | automation-looking key (ci, deploy, backup, bot, cron, ansible...) with neither `from=` nor `command=` |
| K07 | high | `expiry-time=` already in the past |
| K08 | medium | `command=` key that still allows forwarding or a PTY |
| K09 | high | owner marked left / revoked in the owners file |
| K10 | medium | key not in the owners file |
| K11 | low | owners file review older than `--review-days` (default 365) |
| K12 | info | port forwarding explicitly allowed (`permitopen`, `permitlisten`, `restrict,port-forwarding`) |
| E01 | medium | line that cannot be parsed (truncated paste, bad base64, type mismatch) |

### 4. Decide per finding
Work from high to low with the two reference files:
- K09 and K07: remove the line now, after checking that no running job depends on it; tell the owner's manager.
- K01 and K02: ask the owner for a new Ed25519 key (or `sk-ssh-ed25519` on a hardware key), add it, confirm the login works, then remove the old line.
- K10 and K05: find the owner with the fingerprint (`ssh-keygen -lf`, git history of config management, the team chat). If nobody claims it within the agreed time, disable it by commenting it out first, then remove it.
- K04: keep one line; duplicates often hide a key that was "removed" but still has a second copy.
- K06 and K08: restrict automation keys with `from=` the runner's network and `restrict` plus a forced `command=` when the job only needs one action.
- E01: a broken line is ignored by sshd but often means someone pasted a key wrongly and is now locked out or has a second copy elsewhere.

### 5. Report
Fill `templates/access-review-report.md`: summary counts, the actions table with owner and due date, what was removed, and what is still unknown. Re-run the script after the changes and attach the clean output.

## Rules
- Never ask for, read or store private keys. Public keys and fingerprints are enough for every check here.
- Never remove keys on a live server without a second session open and a tested way back in; removing the wrong key can lock out the only admin.
- Treat the owners file as the source of truth only if someone reviewed it; say when it is old (K11).
- Report what the file says, not guesses about who uses a key. If the owner is unknown, say so.
- Keys in config management (Ansible, Puppet, cloud-init, NixOS) will come back after manual removal; fix them at the source.

FILE:references/key-types-and-strength.md
# Key types and strength (OpenSSH, 2026)

| Type in `authorized_keys` | Verdict | Notes |
|---|---|---|
| `ssh-ed25519` | recommended | Fast, small, fixed 256-bit strength. Default for new keys. |
| `sk-ssh-ed25519@openssh.com` | recommended for admins | Private key lives on a FIDO2 hardware key (YubiKey, SoloKey); a touch is needed for each login. Needs OpenSSH 8.2+ on both sides. |
| `ecdsa-sha2-nistp256/384/521` | acceptable | Fine in practice; some teams prefer Ed25519 for simpler, safer implementations. |
| `sk-ecdsa-sha2-nistp256@openssh.com` | acceptable | Hardware-backed ECDSA for older FIDO keys without Ed25519 support. |
| `ssh-rsa` 3072+ bits | acceptable | Still widely used. 4096 is common. Keep the key, but new keys should be Ed25519. |
| `ssh-rsa` 2048 bits | replace when convenient (K03) | Not broken today, but below the 3072-bit level many policies (NIST, BSI) ask for beyond 2030. |
| `ssh-rsa` below 2048 bits | replace now (K02) | 1024-bit RSA is considered breakable by well-funded attackers. OpenSSH 9.1+ refuses RSA keys below 1024 bits by default (`RequiredRSASize`), and some distributions raise the minimum further. |
| `ssh-dss` (DSA) | replace now (K01) | Fixed 1024-bit size. Disabled by default since OpenSSH 7.0 and removed completely in OpenSSH 10.0; if it still works, the server runs an old or specially configured sshd. |

## The signature algorithm is not the key type
The `ssh-rsa` key type is fine with modern signatures (`rsa-sha2-256`, `rsa-sha2-512`). What OpenSSH 8.8 disabled by default is the old SHA-1 signature algorithm, also called `ssh-rsa`. If very old clients or devices fail to log in after an upgrade, that is usually the reason, not the key itself.

## Fingerprints
`ssh-keygen -lf <file>` prints the size, the SHA256 fingerprint and the comment of every key in a public key or `authorized_keys` file. The fingerprint is the SHA256 hash of the decoded base64 key blob, base64-encoded without `=` padding. The audit script computes the same value, so you can match keys with server logs (`sshd` logs `Accepted publickey for deploy ... SHA256:...`) and with what people see on their laptops (`ssh-keygen -lf ~/.ssh/id_ed25519.pub`).

Older tools show MD5 fingerprints (`ssh-keygen -E md5 -lf ...`, format `aa:bb:...`). Ask for SHA256 to avoid confusion.

## Replacing a weak or old key without lockouts
1. The owner creates a new key on their machine: `ssh-keygen -t ed25519 -C "name@device-2026"` (or `-t ed25519-sk` with a hardware key).
2. They send only the `.pub` file, or the public line, through a channel you trust.
3. Add the new line, keep the old one, and ask them to log in with the new key (`ssh -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes host`).
4. Check the `sshd` log for the new fingerprint, then remove the old line.
5. Update the owners file with the new fingerprint and today's review date.

For automation keys, generate the new key on the machine that uses it (the CI runner, the backup host), never on a laptop, and store the private key only there or in the CI secret store.

## Good comment conventions
Comments are free text and can be changed by anyone who edits the file, so they are hints, not proof. A useful convention is `person-or-service@device-year`, for example `alice@laptop-2026` or `ci-deploy@build-runner`. Match owners by fingerprint when it matters.

FILE:references/authorized-keys-options.md
# authorized_keys options that matter

An `authorized_keys` line is: `[options] keytype base64-key [comment]`. Options are comma-separated; values with spaces or commas are in double quotes, for example `from="10.0.0.0/8,192.168.1.5"`. A line without options gives a full interactive shell with all forwarding allowed, as far as `sshd_config` permits.

## Options checked by the script

| Option | What it does | Typical use |
|---|---|---|
| `from="pattern-list"` | Only accepts the key from matching client addresses or hostnames (CIDR ranges allowed). | Pin automation keys to the CI runner or backup host network. |
| `command="cmd"` | Runs only this command, whatever the client asks for; the original request is in `SSH_ORIGINAL_COMMAND`. | Backup receivers, git-only access, one-purpose jobs. |
| `restrict` | Turns off port, agent and X11 forwarding, PTY allocation and `~/.ssh/rc` in one word (OpenSSH 7.2+). Future restrictions are included automatically. | Start every non-human key with it. |
| `no-port-forwarding`, `no-agent-forwarding`, `no-X11-forwarding`, `no-pty` | The older one-by-one form of `restrict`. | Servers with OpenSSH older than 7.2. |
| `port-forwarding`, `agent-forwarding`, `pty`, `X11-forwarding` | Turn single features back on after `restrict`. | A tunnel key that needs only port forwarding. |
| `permitopen="host:port"` / `permitlisten="port"` | Limit local / remote forwarding to these destinations. | Database tunnels. |
| `expiry-time="YYYYMMDD[HHMM[SS]]"` | sshd refuses the key after this time (OpenSSH 8.2+). | Contractors, temporary support access, break-glass keys. |
| `principals="..."`, `cert-authority` | Used with SSH certificates instead of plain keys. | Fleets that use a CA; review the CA separately. |

## Safe patterns

Human admin with a hardware key:
```
sk-ssh-ed25519@openssh.com AAAA... erin@yubikey
```

CI deploy key that may only run the deploy script from the runner network:
```
from="10.20.0.0/16",restrict,command="/usr/local/bin/deploy.sh" ssh-ed25519 AAAA... ci-deploy@build-runner
```

Backup receiver (only rsync into one directory):
```
restrict,command="/usr/bin/rrsync /srv/backups/web-01" ssh-ed25519 AAAA... backup@backup-02
```

Temporary vendor access for two weeks:
```
expiry-time="20261215",restrict,pty ssh-ed25519 AAAA... vendor-support@contractor
```

Database tunnel only:
```
restrict,port-forwarding,permitopen="localhost:5432" ssh-ed25519 AAAA... db-tunnel@ops
```

## Things that look safe but are not
- `command=` without `restrict` (or the four `no-*` options) still lets the client open port forwards and use agent forwarding: K08.
- Deleting a key from one `authorized_keys` file does not remove it from other users, other servers, golden images or config management.
- `from=` with a hostname depends on reverse DNS; prefer IP ranges.
- An expired `expiry-time` key no longer works, but it shows that the cleanup process is not running: K07.

## sshd_config settings worth checking at the same time
`PubkeyAuthentication yes`, `PasswordAuthentication no`, `PermitRootLogin prohibit-password` or `no`, `AuthorizedKeysFile` (which files are read), `PubkeyAcceptedAlgorithms` (which key types are allowed), and `LogLevel VERBOSE` so logins are logged with the key fingerprint.

FILE:templates/access-review-report.md
# SSH key access review: {{server or fleet}} ({{date}})

Reviewer: {{name}} | Files reviewed: {{count and paths}} | Owners list: {{file, last updated}}

## Summary
- {{N}} keys in {{N}} files; {{N}} high, {{N}} medium, {{N}} low findings
- Key types: {{e.g. 9 ed25519, 2 rsa-4096, 1 rsa-1024, 1 dsa}}
- Verdict: {{clean / actions needed / urgent removals done today}}

## Actions
| # | Finding | Key (comment, fingerprint) | Owner | Action | Due | Done |
|---|---|---|---|---|---|---|
| 1 | {{K09 owner left}} | {{carol@old-macbook, SHA256:...}} | {{manager}} | Remove line | {{today}} | {{yes/no}} |
| 2 | {{K02 RSA 1024}} | {{legacy-backup, SHA256:...}} | {{ops}} | New ed25519 key on the backup host, restrict + command, then remove old | {{date}} | |
| 3 | {{K10 unknown key}} | {{SHA256:...}} | unknown | Ask in {{channel}}; comment out on {{date}}, remove on {{date}} | | |

## Removed today
- {{comment / fingerprint}} - {{reason}} - {{who confirmed}}

## Still unknown
- {{keys nobody claimed yet, and the deadline}}

## Follow-up
- Fix at the source: {{config management repo / image}}
- Next review: {{date}} (re-run `ssh_keys_audit.py --owners owners.csv --fail-on medium`)

FILE:examples/authorized_keys
# /home/deploy/.ssh/authorized_keys on web-01.example.internal (fictional demo; public keys only)
# people
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHFe7WeKd2Owa2Hh2kJr7nzgVZC8s9Ovp1f121uAPFhX alice@laptop-2026
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCnWx5TWWgt37zJmeY9/bLqaQnO0UnBNUQHVfbs5cQdeJ/f/QFHtN2tiK7p0xNF1FhZPFgRsl9UIKjQe3QSSOmX4TIu0y7wWjdfeO160ZQhlPNAh7IK8wvBvFo7g05jwI7P62B+fmvRHz0EL20n7E3fuw9HiRU77sKtdlGvKr/y8mXkFp70FFKtFmQcj53WzHEFCp6KwuJZD4YrI+rcSjULx4ZRyDNF4QJmg4jn1LcUAl7NfyV44Ow0yvZQ5a5d2gKjDbCC3//VINtJrN1eXgp13oFHzFxY3JedFCG0AjxokzIxr8zC/ATsdBPeEV15OQNxwqPb1dSQ/F8n5QznixiwkIi58h7+Zcu3QNhrZNZpjaj7rt+f2cPzMC3CQ+QYp3CmebfATT/tcq4zpVhT5nKPZHuekrxD8BLB1eqk2NNtVqG9bp12kmTcTExk9goR1dVKmGTmiKN4Y6OY5PbLRrVq/vaxBqPZsRt1nmN+tqqk36ONqhAzcSzcTnzMBI0AfzUOj4mmdWcGaJWbO70vMyjKF5gb3OxCecdhw0xwgb5JFiinPVaDZpysA/dViHouz2cBZ6xub5GEqYaitPb6EJnRZWXGAS3Ht+87lnlMTP1Xf6aa93B3b+69CRh0BtpqjDd11SFGHSxAqoGPtM7yWrA0H/mzuCDA5Sh/I5MLJx4kEw== bob@workstation
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3+BmTPsItN0a8fWMCarZW08Kdcm2YJzCJvSc+T38xNvbJapmg4F5GCsw8jI0vuOcTn1h7WV/d0ou/8H4LNinVQ1ozTbjM3FLgXokB5GH05nXsn/uBeiARO/tqQ5/7ZGuOs0im5ubGwwzp113SgsGHQT7vihcwcDSMwYpHQcKOxSPjpN04346VuwA0hUU/CKD8VAg3/Jv4Tx8hPcXMj0iWVTEcXdhGkk9inXgJnTnGKswWvaodO4xo9zz1Ilpt1/vHSasGoDBY69Ix6YelhmQgoNRTZAGUqFR4HbYVS87jlwe2nmBnrswrqHiMphbV0AqCM0dklwiXzxxq/W4yjF9D carol@old-macbook
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBN7PNxyNXn5mvgmJcQJ5XnbF6ecut86YWirOFbgbU4FNdCM926HTQO+WiB5fVv9q4i1Z2IA8T2IlI6OzUjDR4WE= dave@tablet
sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIG51r2VHz7EbQgckgtxTHCvDkHyWF+teUInkAYa6qKV9AAAABHNzaDo= erin@yubikey
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHFe7WeKd2Owa2Hh2kJr7nzgVZC8s9Ovp1f121uAPFhX alice@laptop-2026-copy
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHunuVy30PtFkG0kzjW2DyAijGaDf4mamV1EeC1IVBe9
# automation
from="10.20.0.0/16",restrict ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPayPOBQUnoa7No6o2EaQvGV1rmdcohl25jOvTU+h3pV ci-deploy@build-runner
command="/usr/local/bin/backup-receive",no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC0yY9ApJXN7gLq07iGKSGC5X3mT5xqBjH5XVe35ZhhZ95IGyyV4LyGuoW8W+yHUPj9XbzafPvcaa4r45fmXOY2Avj2IzMdrG3hYBO9w+urhN736J/A5+wSKFAmSShJDbRckmT1Pooph6HBM8AwG2b4iBiV97bQXjbUJoSlQHj4zQ== legacy-backup
ssh-dss AAAAB3NzaC1kc3MAAACBANGlTcoYJTC7HW0TLN7WI3su2R4/ch/LGXEXRJTWSTydXDRgvjEgHmn+2qDu6LmZf1x8KZn9r+WTJTzWVK9N+tcUJ6Cus/7pIy+K8iEfnuSRxbEL7LVWO/web5NCfsvI/ilV5c2ORtyO1LfCdk0qWk12dwb4XYaQAkrWvaNAG+nIAAAAFQCby8zJNfbNH2EiauFTOK4aNABNMwAAAIC6DSRqwEyBsbryPjv57vX3nytJNK+H9VILablLDZguhbtVtnKocmN6zXRm/LYODo/xhGOw5LK6KXA0dPBkrGj3APWwKz3GZvRb3qosyu3NK1FXQQ5N7krys09DCgc0R95jbA6AbJV7poTWQx+16tdCTQnhXQJMWEjyPR+m9zYdfwAAAIBhjRUy5w4g4qZmjef0foRn5UbVPsjioSV72yVsmz5Pu0mBRu9wMMv5U3JS3M6t12S2oy+7Ca3q4QnEqZcgOXU1K4eLFFyKQtiEz0z9py2OHV3ZJYkILYUqcSKHPugFrdWJQhZ6OFKGGVxnn5xplORbirEJgBIHCWHzfeQ23f3JnQ== nagios-check
expiry-time="20261115",restrict ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBGeb7ZdAKvDKvOOZn8CLoctScwVyQuZm3crT8em/UyR vendor-support@contractor
restrict,port-forwarding,permitopen="localhost:5432" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEoW20cIdSsPFUS4NcDnGQl9+ocB6SMvIfKBJod4aXbr db-tunnel@ops
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPzDJ/WTF2UnS6mCm0QG9h/4iTJv+pSS7e7uPGafK/II cron-sync@reports
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7truncated-paste frank@desktop

FILE:examples/owners.csv
match,owner,status,last_review,note
alice@laptop-2026,Alice Kaya (backend),active,2026-09-14,
bob@workstation,Bob Lindqvist (SRE),active,2026-09-14,
carol@old-macbook,Carol Mendes (frontend),left,2026-03-02,left the company 2026-06-30
dave@tablet,Dave Osei (support lead),active,2025-08-20,
erin@yubikey,Erin Novak (security),active,2026-11-01,hardware key
ci-deploy@build-runner,CI pipeline (platform team),active,2026-10-05,
legacy-backup,Backup server (ops),active,2024-11-11,old backup host scheduled for replacement
vendor-support@contractor,Vendor support contract,revoked,2026-11-15,contract ended 2026-11-15
db-tunnel@ops,Ops on-call tunnel,active,2026-10-05,

FILE:scripts/ssh_keys_audit.py
#!/usr/bin/env python3
"""ssh_keys_audit.py - audit OpenSSH authorized_keys files without connecting anywhere.

Reads one or more authorized_keys files (or '-' for stdin), parses options, key type, key blob
and comment, computes the SHA256 fingerprint exactly like `ssh-keygen -lf`, measures RSA key size,
and prints findings K01-K12 (+ E01). Optional --owners CSV maps fingerprints or comments to people
so keys of people who left, unknown keys and overdue reviews are flagged too.

Python 3.8+ standard library only. Never reads private keys; never opens network connections.

Usage:
  ssh_keys_audit.py FILE [FILE ...] [--owners owners.csv] [--today YYYY-MM-DD]
                    [--format text|md|json|csv] [--fail-on high|medium|low|none]
                    [--min-rsa-bits 3072] [--review-days 365]
  ssh_keys_audit.py --self-test
Exit codes: 0 = nothing at or above --fail-on, 1 = findings at or above it, 2 = unreadable input.
"""
import argparse, base64, csv, datetime, hashlib, io, json, re, struct, sys

SEV_ORDER = {"high": 3, "medium": 2, "low": 1, "info": 0}
FLAGS = {
    "K01": ("high", "DSA (ssh-dss) key: disabled by default since OpenSSH 7.0 and removed in OpenSSH 10.0"),
    "K02": ("high", "RSA key shorter than 2048 bits"),
    "K03": ("medium", "RSA key shorter than --min-rsa-bits (default 3072) but at least 2048 bits"),
    "K04": ("medium", "same public key appears more than once (in one file or across files)"),
    "K05": ("low", "key has no comment, so nobody can tell whose key it is"),
    "K06": ("medium", "automation-looking key (comment mentions ci, deploy, backup, bot, cron, ansible...) without from= or command= restriction"),
    "K07": ("high", "expiry-time option is in the past (OpenSSH already refuses it, but it is clutter and may hide a gap)"),
    "K08": ("medium", "forced command= key still allows forwarding or a PTY (add restrict or no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty)"),
    "K09": ("high", "owners file marks this key's owner as left/revoked"),
    "K10": ("medium", "key not found in the owners file (unknown key)"),
    "K11": ("low", "last review in the owners file is older than --review-days (default 365)"),
    "K12": ("info", "agent forwarding or port forwarding explicitly enabled with permitopen/permitlisten - check that it is intended"),
    "E01": ("medium", "line could not be parsed (bad base64, unknown type, type mismatch inside the blob)"),
}
KEY_TYPES = {"ssh-ed25519", "ssh-rsa", "ssh-dss", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521",
             "sk-ssh-ed25519@openssh.com", "sk-ecdsa-sha2-nistp256@openssh.com"}
CERT_SUFFIX = "-cert-v01@openssh.com"
AUTOMATION = re.compile(r"\b(ci|cd|deploy|deployer|backup|bot|cron|ansible|jenkins|runner|github-actions|gitlab|terraform|svc|service)\b", re.I)
RESTRICT_ALL = {"no-port-forwarding", "no-agent-forwarding", "no-x11-forwarding", "no-pty"}


def split_options(s):
    """Split the leading options field of an authorized_keys line. Returns (options list, rest)."""
    opts, cur, i, inq = [], "", 0, False
    while i < len(s):
        ch = s[i]
        if ch == "\\" and inq and i + 1 < len(s):
            cur += s[i:i + 2]; i += 2; continue
        if ch == '"':
            inq = not inq; cur += ch
        elif ch == "," and not inq:
            opts.append(cur); cur = ""
        elif ch in " \t" and not inq:
            opts.append(cur); return [o for o in opts if o], s[i:].strip()
        else:
            cur += ch
        i += 1
    raise ValueError("options field without a key")


def read_string(blob, off):
    if off + 4 > len(blob):
        raise ValueError("truncated blob")
    (n,) = struct.unpack(">I", blob[off:off + 4])
    if off + 4 + n > len(blob):
        raise ValueError("truncated blob")
    return blob[off + 4:off + 4 + n], off + 4 + n


def mpint_bits(b):
    b = b.lstrip(b"\x00")
    return 0 if not b else (len(b) - 1) * 8 + b[0].bit_length()


def parse_line(line):
    """Return dict(options, type, blob_b64, comment, bits, fingerprint) or raise ValueError."""
    s = line.strip()
    first = s.split(None, 1)[0]
    if first in KEY_TYPES or first.endswith(CERT_SUFFIX):
        options, rest = [], s
    else:
        options, rest = split_options(s)
    parts = rest.split(None, 2)
    if len(parts) < 2:
        raise ValueError("missing key data")
    ktype, b64 = parts[0], parts[1]
    comment = parts[2].strip() if len(parts) > 2 else ""
    if ktype not in KEY_TYPES and not ktype.endswith(CERT_SUFFIX):
        raise ValueError("unknown key type %r" % ktype[:40])
    try:
        blob = base64.b64decode(b64, validate=True)
    except Exception:
        raise ValueError("invalid base64 key data")
    inner, off = read_string(blob, 0)
    if inner.decode("ascii", "replace") != ktype:
        raise ValueError("key type %s does not match blob type %s" % (ktype, inner.decode("ascii", "replace")[:40]))
    bits = None
    if ktype == "ssh-rsa":
        _e, off = read_string(blob, off)
        n, off = read_string(blob, off)
        bits = mpint_bits(n)
    elif ktype == "ssh-dss":
        p, off = read_string(blob, off)
        bits = mpint_bits(p)
    elif "nistp" in ktype:
        bits = int(re.search(r"nistp(\d+)", ktype).group(1))
    elif "ed25519" in ktype:
        bits = 256
    fp = "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=")
    return {"options": options, "type": ktype, "blob_b64": b64, "comment": comment, "bits": bits, "fingerprint": fp}


def opt_map(options):
    m = {}
    for o in options:
        k, _, v = o.partition("=")
        m.setdefault(k.lower(), []).append(v.strip('"') if v else True)
    return m


def load_owners(path):
    rows = []
    with open(path, newline="", encoding="utf-8") as f:
        for r in csv.DictReader(f):
            rows.append({k.strip().lower(): (v or "").strip() for k, v in r.items() if k})
    need = {"match", "owner", "status"}
    if rows and not need <= set(rows[0]):
        raise ValueError("owners CSV needs columns match,owner,status (optional: last_review,note)")
    return rows


def find_owner(key, owners):
    for r in owners:
        m = r["match"]
        if m.startswith("SHA256:") and m == key["fingerprint"]:
            return r
    for r in owners:
        m = r["match"]
        if not m.startswith("SHA256:") and m and m == key["comment"]:
            return r
    return None


def parse_date(s):
    s = s.strip()
    for fmt in ("%Y-%m-%d", "%Y%m%d", "%Y%m%d%H%M", "%Y%m%d%H%M%S"):
        try:
            return datetime.datetime.strptime(s, fmt).date()
        except ValueError:
            pass
    return None


def audit(files, owners=None, today=None, min_rsa=3072, review_days=365):
    today = today or datetime.date.today()
    keys, flags, seen = [], [], {}
    for name, text in files:
        for ln, raw in enumerate(text.splitlines(), 1):
            if not raw.strip() or raw.lstrip().startswith("#"):
                continue
            where = "%s:%d" % (name, ln)
            try:
                k = parse_line(raw)
            except ValueError as e:
                flags.append({"code": "E01", "severity": FLAGS["E01"][0], "where": where, "key": None, "detail": str(e)})
                continue
            k["where"] = where
            keys.append(k)
            om = opt_map(k["options"])
            label = k["comment"] or k["fingerprint"][:20]

            def add(code, detail):
                flags.append({"code": code, "severity": FLAGS[code][0], "where": where, "key": label, "detail": detail})
            if k["type"] == "ssh-dss":
                add("K01", "ssh-dss %s bits" % k["bits"])
            if k["type"] == "ssh-rsa":
                if k["bits"] < 2048:
                    add("K02", "RSA %d bits" % k["bits"])
                elif k["bits"] < min_rsa:
                    add("K03", "RSA %d bits < %d" % (k["bits"], min_rsa))
            if k["blob_b64"] in seen:
                add("K04", "same key as %s" % seen[k["blob_b64"]])
            else:
                seen[k["blob_b64"]] = where
            if not k["comment"]:
                add("K05", k["fingerprint"])
            restricted = "from" in om or "command" in om
            if k["comment"] and AUTOMATION.search(k["comment"]) and not restricted:
                add("K06", "comment %r has no from= or command=" % k["comment"])
            if "expiry-time" in om:
                d = parse_date(str(om["expiry-time"][0]))
                if d and d < today:
                    add("K07", "expired %s" % d.isoformat())
            if "command" in om and "restrict" not in om and not RESTRICT_ALL <= set(om):
                missing = sorted(RESTRICT_ALL - set(om))
                add("K08", "forced command without " + ",".join(missing))
            if {"permitopen", "permitlisten"} & set(om) or ("restrict" in om and {"port-forwarding", "agent-forwarding"} & set(om)):
                add("K12", ",".join(sorted(x for x in om if x in ("permitopen", "permitlisten", "port-forwarding", "agent-forwarding"))))
            if owners is not None:
                o = find_owner(k, owners)
                k["owner"] = o["owner"] if o else None
                if o is None:
                    add("K10", k["fingerprint"])
                else:
                    st = o["status"].lower()
                    if st in ("left", "revoked", "inactive", "offboarded"):
                        add("K09", "%s is %s" % (o["owner"], st))
                    lr = parse_date(o.get("last_review", "")) if o.get("last_review") else None
                    if lr is None or (today - lr).days > review_days:
                        add("K11", "last review %s" % (lr.isoformat() if lr else "never"))
    def _w(w):
        name, _, ln = w.rpartition(":")
        return (name, int(ln) if ln.isdigit() else 0)
    flags.sort(key=lambda f: (-SEV_ORDER[f["severity"]], f["code"], _w(f["where"])))
    count = {s: sum(1 for f in flags if f["severity"] == s) for s in SEV_ORDER}
    types = {}
    for k in keys:
        t = k["type"] + ("-%d" % k["bits"] if k["type"] == "ssh-rsa" else "")
        types[t] = types.get(t, 0) + 1
    summary = {"files": len(files), "keys": len(keys), "unparsed": sum(1 for f in flags if f["code"] == "E01"),
               "by_type": dict(sorted(types.items())), "findings": count, "today": today.isoformat()}
    return {"summary": summary, "keys": keys, "flags": flags}


def render(res, fmt):
    s, out = res["summary"], []
    if fmt == "json":
        keys = [{k: v for k, v in x.items() if k != "blob_b64"} for x in res["keys"]]
        return json.dumps({"summary": s, "keys": keys, "flags": res["flags"]}, indent=2)
    if fmt == "csv":
        b = io.StringIO(); w = csv.writer(b, lineterminator="\n")
        w.writerow(["where", "type", "bits", "fingerprint", "comment", "owner", "options"])
        for k in res["keys"]:
            w.writerow([k["where"], k["type"], k["bits"], k["fingerprint"], k["comment"], k.get("owner") or "", ",".join(k["options"])])
        return b.getvalue().rstrip("\n")
    f = s["findings"]
    head = "%d keys in %d file(s), %d unparsed line(s); findings: %d high, %d medium, %d low, %d info" % (
        s["keys"], s["files"], s["unparsed"], f["high"], f["medium"], f["low"], f["info"])
    types = ", ".join("%s x%d" % kv for kv in s["by_type"].items())
    if fmt == "md":
        out += ["## SSH authorized_keys audit (%s)" % s["today"], "", "- " + head, "- key types: " + types, "",
                "| Sev | Code | Where | Key | Detail |", "|---|---|---|---|---|"]
        out += ["| %s | %s | %s | %s | %s |" % (x["severity"], x["code"], x["where"], x["key"] or "-", x["detail"].replace("|", "/")) for x in res["flags"]]
        out += ["", "### Keys", "", "| Where | Type | Bits | Fingerprint | Comment | Owner |", "|---|---|---|---|---|---|"]
        out += ["| %s | %s | %s | `%s` | %s | %s |" % (k["where"], k["type"], k["bits"], k["fingerprint"], k["comment"] or "-", k.get("owner") or "-") for k in res["keys"]]
        return "\n".join(out)
    out += ["SSH authorized_keys audit (%s)" % s["today"], "- " + head, "- key types: " + types, "", "Keys"]
    for k in res["keys"]:
        out.append("  %-28s %-20s %5s  %s  %s%s" % (k["where"], k["type"][:20], k["bits"], k["fingerprint"][:27] + "...", k["comment"] or "(no comment)",
                                                  ("  [" + (k.get("owner") or "unknown") + "]") if "owner" in k else ""))
    out += ["", "Findings"]
    if not res["flags"]:
        out.append("  none")
    for x in res["flags"]:
        out.append("  %-6s %s  %-28s %-24s %s" % (x["severity"].upper(), x["code"], x["where"], (x["key"] or "-")[:24], x["detail"]))
    return "\n".join(out)


def self_test():
    import os, tempfile
    def blob(*parts):
        return base64.b64encode(b"".join(struct.pack(">I", len(p)) + p for p in parts)).decode()
    ed = blob(b"ssh-ed25519", bytes(range(32)))
    ed2 = blob(b"ssh-ed25519", bytes(range(1, 33)))
    rsa1k = blob(b"ssh-rsa", b"\x01\x00\x01", b"\x00" + b"\xc3" + b"\x11" * 127)
    rsa2k = blob(b"ssh-rsa", b"\x01\x00\x01", b"\x00" + b"\xc3" + b"\x22" * 255)
    dss = blob(b"ssh-dss", b"\x00" + b"\x99" * 128, b"\x88" * 20, b"\x77" * 128, b"\x66" * 128)
    text = "\n".join([
        "# comment line", "",
        "ssh-ed25519 %s alice@laptop" % ed,
        'from="10.0.0.0/8",no-agent-forwarding ssh-ed25519 %s ci-deploy@runner' % ed2,
        "ssh-rsa %s old" % rsa1k,
        "ssh-rsa %s mid@host" % rsa2k,
        "ssh-dss %s legacy" % dss,
        "ssh-ed25519 %s" % ed,
        'command="/usr/bin/backup.sh",no-pty ssh-ed25519 %s backup-bot' % blob(b"ssh-ed25519", b"\x05" * 32),
        'expiry-time="20250101",restrict ssh-ed25519 %s temp@contractor' % blob(b"ssh-ed25519", b"\x06" * 32),
        "ssh-ed25519 !!!notbase64 bad",
        "ssh-rsa %s mismatch" % ed,
        'restrict,port-forwarding,permitopen="db:5432" ssh-ed25519 %s tunnel@ops' % blob(b"ssh-ed25519", b"\x07" * 32),
        "ssh-ed25519 %s deploy@ci" % blob(b"ssh-ed25519", b"\x08" * 32)])
    owners = [{"match": "alice@laptop", "owner": "Alice", "status": "active", "last_review": "2026-10-01"},
              {"match": "old", "owner": "Olga", "status": "left", "last_review": "2024-01-01"}]
    r = audit([("t", text)], owners=owners, today=datetime.date(2026, 12, 3))
    codes = [f["code"] for f in r["flags"]]
    checks = [
        ("10 keys parsed", r["summary"]["keys"] == 10),
        ("2 unparsed", codes.count("E01") == 2),
        ("rsa 1024 bits", any(k["bits"] == 1024 for k in r["keys"])),
        ("rsa 2048 bits", any(k["bits"] == 2048 for k in r["keys"])),
        ("K01 dss", "K01" in codes), ("K02 short rsa", codes.count("K02") == 1), ("K03 2048", codes.count("K03") == 1),
        ("K04 duplicate", codes.count("K04") == 1), ("K05 no comment", codes.count("K05") == 1),
        ("K06 unrestricted automation only deploy@ci", [f["key"] for f in r["flags"] if f["code"] == "K06"] == ["deploy@ci"]),
        ("K07 expired", codes.count("K07") == 1), ("K08 forced command partial", codes.count("K08") == 1),
        ("K09 left", codes.count("K09") == 1), ("K10 unknown", codes.count("K10") == 8),
        ("K11 stale review", codes.count("K11") == 1), ("K12 permitopen", codes.count("K12") == 1),
        ("options with quoted comma", split_options('from="a,b",no-pty ssh-ed25519 X')[0] == ['from="a,b"', "no-pty"]),
        ("fingerprint format", r["keys"][0]["fingerprint"].startswith("SHA256:") and "=" not in r["keys"][0]["fingerprint"]),
        ("sorted by severity", [SEV_ORDER[f["severity"]] for f in r["flags"]] == sorted([SEV_ORDER[f["severity"]] for f in r["flags"]], reverse=True)),
        ("md render", render(r, "md").startswith("## SSH authorized_keys audit")),
        ("csv render", render(r, "csv").splitlines()[0].startswith("where,type,bits")),
    ]
    bad = [n for n, ok in checks if not ok]
    if bad:
        print("self-test FAILED:", ", ".join(bad)); print(codes); return 1
    print("self-test OK: %d checks" % len(checks)); return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description="Audit OpenSSH authorized_keys files (offline, stdlib only).")
    ap.add_argument("files", nargs="*", help="authorized_keys files, or - for stdin")
    ap.add_argument("--owners", help="CSV with columns match,owner,status[,last_review,note]; match = SHA256 fingerprint or exact comment")
    ap.add_argument("--today", help="date for expiry/review checks (YYYY-MM-DD), default today")
    ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
    ap.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="high")
    ap.add_argument("--min-rsa-bits", type=int, default=3072)
    ap.add_argument("--review-days", type=int, default=365)
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.files:
        ap.error("give at least one authorized_keys file (or --self-test)")
    files = []
    try:
        for p in a.files:
            files.append(("stdin", sys.stdin.read()) if p == "-" else (p, open(p, encoding="utf-8", errors="replace").read()))
        owners = load_owners(a.owners) if a.owners else None
    except (OSError, ValueError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    today = parse_date(a.today) if a.today else None
    if a.today and today is None:
        print("error: --today must be YYYY-MM-DD", file=sys.stderr); return 2
    res = audit(files, owners, today, a.min_rsa_bits, a.review_days)
    print(render(res, a.format))
    if a.fail_on == "none":
        return 0
    lim = SEV_ORDER[a.fail_on]
    return 1 if any(SEV_ORDER[f["severity"]] >= lim and f["severity"] != "info" for f in res["flags"]) else 0


if __name__ == "__main__":
    sys.exit(main())
SecurityLinuxPython+4
F@f
0
Python Web Scraping taste
Taste

Opinionated Python web scraping preferences: APIs before HTML, polite rate limits, httpx and selectolax, Playwright only when needed, resilient parsing, validation and storing raw pages.

# Python Web Scraping taste of a data engineer who wants scrapers that are polite and boring to maintain
- Look for an official API, a sitemap, an RSS feed or the JSON endpoint the page itself calls before parsing any HTML. Confidence: 0.90
- Read the site's terms and robots.txt first, and skip sources that clearly forbid automated access. Confidence: 0.85
- Use httpx with a shared client, connection pooling, timeouts on every request and HTTP/2 when the site supports it. Confidence: 0.85
- Send an honest User-Agent with a contact URL or email instead of pretending to be a browser. Confidence: 0.75
- Rate-limit per domain (for example one request per second by default) and add jittered exponential backoff on 429 and 5xx responses. Confidence: 0.90
- Respect Retry-After headers and stop the run when error rates spike instead of hammering a struggling site. Confidence: 0.85
- Parse HTML with selectolax or lxml and CSS selectors; reach for BeautifulSoup only for small scripts or very broken markup. Confidence: 0.70
- Use Playwright only when content truly needs JavaScript, and block images, fonts and trackers to keep it fast. Confidence: 0.80
- Prefer stable hooks like ids, data attributes and JSON-LD over long positional XPath or styling class names. Confidence: 0.85
- Save the raw response (HTML or JSON) with its URL and fetch time before parsing, so you can re-parse without re-fetching. Confidence: 0.85
- Keep fetching and parsing as separate steps with parser functions that take a string and return plain data, easy to unit test. Confidence: 0.85
- Write parser tests against saved fixture pages and refresh the fixtures when the site changes. Confidence: 0.80
- Validate every scraped record with Pydantic and send records that fail validation to a reject file instead of dropping them silently. Confidence: 0.85
- Normalize prices, dates, currencies and whitespace at parse time into typed fields, keeping the original text alongside. Confidence: 0.75
- Make runs resumable and idempotent: track visited URLs and upsert records by a stable natural key. Confidence: 0.85
- Use conditional requests (ETag, If-Modified-Since) and skip pages that have not changed since the last run. Confidence: 0.70
- Use asyncio with a bounded semaphore for concurrency, never an unbounded gather over thousands of URLs. Confidence: 0.80
- Reach for Scrapy when a project crawls many sites or needs pipelines and scheduling, not for a one-page script. Confidence: 0.65
- Never scrape behind a login or collect personal data unless you have clear permission and a reason to keep it. Confidence: 0.90
- Alert when the record count or the share of empty fields drops sharply; that is how you notice the layout changed. Confidence: 0.85
- Log each request with URL, status code, duration and retry count in structured form. Confidence: 0.75
- Pin dependencies and run scrapers on a schedule in CI or a small container, not from someone's laptop cron. Confidence: 0.75
PythonAutomationBest Practices+2
F@f
0
Strength Training Log Progress Analyzer
Skill

Turns a strength training CSV log into clear progress feedback: estimated one-rep max per lift and week, top sets, hard sets and tonnage, plus flags for plateaus, load spikes, RPE creep, missing deload weeks, push/pull imbalance and sudden strength drops. Stdlib Python.

---
name: strength-training-log-progress-analyzer
description: Turns a strength training CSV log into clear progress feedback: estimated one-rep max per lift and week, top sets, hard sets and tonnage, plus flags for plateaus, load spikes, RPE creep, missing deload weeks, push/pull imbalance and sudden strength drops. Stdlib Python.
---

# Strength Training Log Progress Analyzer

You help people who lift weights two to five times a week see whether their training is working: which lifts are still going up, which have stalled, whether the workload jumped too fast, and whether it is time for a lighter week. You work from a simple workout log (one row per set), estimate one-rep maxes from normal working sets so nobody has to test a true maximum, and turn the numbers into two or three concrete changes for the next training block.

This is training feedback, not medical advice. If the person mentions pain, an injury, dizziness, chest symptoms or a health condition, tell them to stop the painful movement and see a doctor or physiotherapist before changing the plan. Do not prescribe diets or supplements.

## Files in this skill

- `scripts/training_log.py` - reads the CSV log (comma or semicolon, decimal commas, kg or lb, optional RPE and sets columns), computes estimated 1RM (Epley or Brzycki), top set, hard sets, tonnage and average RPE per exercise and ISO week, and prints flags S01-S06 + E01; `--format text|md|json|csv`; `--self-test` runs 15 checks (Python 3.8+ standard library only)
- `references/progress-metrics.md` - what e1RM, hard sets, tonnage and RPE mean, the formulas and their limits
- `references/plateau-and-load-guide.md` - what to change for each flag: small load steps, rep ranges, deload weeks, exercise variations, sleep and recovery basics
- `templates/training-review.md` - a one-page review of a 6-12 week block with next-block decisions
- `examples/training_log.csv` - 12 fictional weeks of Monday/Wednesday/Friday full-body training with a holiday week, a cold, a volume challenge and a squat plateau

## Workflow

### 1. Collect the log
Ask for an export from the training app or notebook with at least `date, exercise, weight, reps`; `rpe`, `sets` and `notes` are optional. One row per set is best; a row with `sets=3` is expanded to three identical sets. Use the same exercise name every time (`Back Squat`, not sometimes `Squat`). Bodyweight exercises use weight 0 (or the added weight for weighted pull-ups). Also ask about the goal (strength, muscle, general fitness), training days per week and anything unusual (illness, travel, new job, sleep).

### 2. Run the analysis
```
python3 scripts/training_log.py training_log.csv
python3 scripts/training_log.py training_log.csv --unit lb --formula brzycki
python3 scripts/training_log.py training_log.csv --exercise "Back Squat" --exercise "Bench Press" --format csv
python3 scripts/training_log.py training_log.csv --since 2026-10-01 --plateau-weeks 3 --format md > review.md
python3 scripts/training_log.py --self-test
```
Exit code 0 = no flags, 1 = flags present, 2 = unreadable input.

| Code | Meaning |
|---|---|
| S01 | plateau: no new best e1RM in the last `--plateau-weeks` training weeks of that lift (default 4) |
| S02 | load spike: hard sets for a lift in one week above `--spike` x the average of the previous weeks (default 1.5, at least 3 extra sets) |
| S03 | RPE creep: average RPE up by 1 or more over the last 3 weeks while e1RM did not improve |
| S04 | 6 or more training weeks in a row without a lighter week (hard sets at most 70% of recent weeks) |
| S05 | pressing hard sets more than 1.5x pulling hard sets (rows, pull-ups, deadlifts and curls count as pulling) |
| S06 | latest e1RM 10% or more below the best for that lift |
| E01 | rows that could not be parsed (skipped) |

A hard set is a set at RPE 7 or higher, or any set when no RPE is logged.

### 3. Interpret with context
- Read the progress table first: early in training most lifts rise every week; after a few months progress slows and plateaus are normal.
- S01 together with S03 (same weight, harder every week) is the clearest sign that fatigue is building; S01 alone may simply mean the person repeats the same weight and reps.
- S02 after an unusual week (a challenge, a camp) is fine once; repeated spikes are the injury risk.
- S06 right after an illness, poor sleep or travel is expected; ask before calling it a problem. It can also be a logging error (wrong unit).
- e1RM from sets of 10+ reps is less accurate; compare lifts with similar rep ranges over time.

### 4. Decide the next block
Use `references/plateau-and-load-guide.md` and pick at most three changes, for example: a deload week now, smaller load steps for the stalled lift, a new rep range for 4-6 weeks, or two extra rowing sets per week to balance pressing. Write them as concrete numbers for the next weeks, not general advice.

### 5. Report
Fill `templates/training-review.md`: block dates, progress per main lift, weekly hard sets, flags with context, the decisions for the next block and the date of the next review.

## Rules
- Use the person's own numbers; never compare them with other people or "standards" unless asked.
- Keep load increases small (typically 1-2.5 kg or 2.5-5 lb for upper body, 2.5-5 kg or 5-10 lb for lower body per step).
- Always keep pain, injury and medical topics out of scope and refer to a professional.
- Say clearly when the log is too short (under 4 weeks) or too sparse to conclude anything.

FILE:references/progress-metrics.md
# Progress metrics in short

## Estimated one-rep max (e1RM)
An estimate of the heaviest single rep possible today, calculated from a normal working set, so progress can be followed without testing a true maximum.
- **Epley:** e1RM = weight x (1 + reps / 30). Example: 100 kg x 5 = 116.7 kg.
- **Brzycki:** e1RM = weight x 36 / (37 - reps). Example: 100 kg x 5 = 112.5 kg.
- Both are close for 2-10 reps; above 10 reps they drift apart and become unreliable. The script ignores sets above 30 reps and bodyweight sets (weight 0).
- Use the same formula over time. The absolute number matters less than the trend.
- The best e1RM per week is taken from the single best set of that week.

## Hard sets
Sets that are close enough to failure to drive progress: RPE 7 or more (3 or fewer reps left in reserve). When no RPE is logged, every set counts as hard. Hard sets per muscle or lift per week is the most practical workload measure for recreational lifters; many people progress well on roughly 6-15 hard sets per muscle group per week, built up gradually.

## Tonnage
Weight x reps summed over sets. Useful for spotting big jumps in workload within the same lift; not comparable across lifts (a deadlift moves far more weight than a curl).

## RPE (rate of perceived exertion)
A 1-10 score of how hard a set felt: 10 = no rep left, 9 = one rep left, 8 = two reps left, 7 = three left. Rising RPE at the same weight and reps means the set is getting harder: fatigue, poor sleep, stress or illness.

## Weeks
Weeks are ISO weeks (Monday to Sunday, e.g. 2026-W48). Trends are compared between training weeks of each lift, so a missed week does not count as a plateau week.

## Limits
- Logs contain errors (wrong unit, typo in weight); one strange week should be checked before acting on it.
- Technique changes (deeper squat, pause on the chest) can lower e1RM while the lifter actually got better.
- Estimates do not replace a coach's eye on technique.

FILE:references/plateau-and-load-guide.md
# What to change for each flag

Pick at most three changes for the next 4-6 weeks, write them as numbers and re-run the analysis afterwards.

## S01 plateau
- First check: is the person still adding weight or reps at all, or repeating the same session? A plateau needs a plan, not more effort.
- Smaller load steps: use 1-1.25 kg plates for upper-body lifts, 2.5 kg for lower body.
- Add reps before weight: for example 3x5 -> 3x6 -> 3x7 at the same weight, then +2.5 kg and back to 3x5.
- Change the rep range for a block (5s -> 8s, or 8s -> 4-6s), or swap to a close variation (paused squat, close-grip bench) for 4-6 weeks.
- If S03 is also present, start with a deload week.

## S02 load spike
- Bring hard sets back near the recent average next week, then increase by about 1-2 sets per lift per week at most.
- Spikes during an event or challenge are fine once; plan a lighter week after.

## S03 RPE creep
- Fatigue is building faster than fitness. Options: a deload week, fewer hard sets, or one less training day for a week.
- Ask about sleep, stress, illness, calories and step count; these change RPE more than the program does.

## S04 no lighter week
- Plan a deload: about half the hard sets at the usual weights, or the usual sets at about 80-90% of the weights, for one week every 4-8 weeks.
- Holidays and busy weeks can be used as natural deloads.

## S05 push/pull imbalance
- Add 2-4 hard sets per week of rows, pull-ups or face pulls, or replace one pressing exercise with a pulling one.
- Note that the script counts deadlifts as pulling; for upper-back balance, look at rows and pull-ups.

## S06 strength drop
- Ask what happened: illness, injury, travel, poor sleep, a technique change, or a logging mistake (lb vs kg).
- After illness, restart at about 80-90% of the previous working weights and build back over 1-3 weeks.
- If pain is involved, stop the painful movement and refer to a doctor or physiotherapist.

## Recovery basics worth asking about
Sleep of 7-9 hours, regular meals with enough protein, daily walking, and stress. Do not give medical, diet or supplement prescriptions; suggest a professional for specific needs.

FILE:templates/training-review.md
# Training review - {{name}} - {{block start}} to {{block end}}

## Goal and context
- Goal: {{strength / muscle / general fitness}}
- Days per week: {{days}}; unusual weeks: {{holiday, illness, travel, work}}

## Progress of the main lifts (e1RM, {{formula}}, {{unit}})
| Lift | First | Best (week) | Latest | Change |
|---|---:|---:|---:|---:|
| {{lift}} | {{first}} | {{best}} ({{week}}) | {{latest}} | {{change}} |

## Workload
- Hard sets per week: {{list}}
- Lighter weeks in this block: {{weeks or none}}

## Flags and what they mean here
- {{code}} {{lift}}: {{detail}} - context: {{explanation}}

## Next block ({{dates}}, max 3 changes)
1. {{change with numbers, e.g. deload in week 1: 2 sets per lift at usual weights}}
2. {{change}}
3. {{change}}

## Next review
Re-run the analysis on {{date}} with the same options and compare the stalled lift and weekly hard sets.

Training feedback only, not medical advice.

FILE:examples/training_log.csv
date,exercise,weight,reps,rpe,notes
2026-09-07,Back Squat,80,5,7,
2026-09-07,Back Squat,80,5,7,
2026-09-07,Back Squat,80,5,7,
2026-09-07,Bench Press,60,5,7.5,
2026-09-07,Bench Press,60,5,7.5,
2026-09-07,Bench Press,60,5,7.5,
2026-09-11,Bench Press,55,8,7,
2026-09-11,Bench Press,55,8,7,
2026-09-11,Bench Press,55,8,7,
2026-09-09,Deadlift,110,3,8,
2026-09-09,Deadlift,110,3,8,
2026-09-09,Overhead Press,40,5,8,
2026-09-09,Overhead Press,40,5,8,
2026-09-09,Overhead Press,40,5,8,
2026-09-11,Barbell Row,55,8,7,
2026-09-11,Barbell Row,55,8,7,
2026-09-09,Pull-Up,0,6,8,
2026-09-09,Pull-Up,0,6,8,
2026-09-14,Back Squat,82.5,5,7,
2026-09-14,Back Squat,82.5,5,7,
2026-09-14,Back Squat,82.5,5,7,
2026-09-14,Bench Press,61.25,5,7.5,
2026-09-14,Bench Press,61.25,5,7.5,
2026-09-14,Bench Press,61.25,5,7.5,
2026-09-18,Bench Press,56.25,8,7,
2026-09-18,Bench Press,56.25,8,7,
2026-09-18,Bench Press,56.25,8,7,
2026-09-16,Deadlift,112.5,3,8,
2026-09-16,Deadlift,112.5,3,8,
2026-09-16,Overhead Press,40,5,8,
2026-09-16,Overhead Press,40,5,8,
2026-09-16,Overhead Press,40,5,8,
2026-09-18,Barbell Row,55,8,7,
2026-09-18,Barbell Row,55,8,7,
2026-09-16,Pull-Up,0,6,8,
2026-09-16,Pull-Up,0,6,8,
2026-09-21,Back Squat,85,5,7,
2026-09-21,Back Squat,85,5,7,
2026-09-21,Back Squat,85,5,7,
2026-09-21,Bench Press,62.5,5,7.5,
2026-09-21,Bench Press,62.5,5,7.5,
2026-09-21,Bench Press,62.5,5,7.5,
2026-09-25,Bench Press,57.5,8,7,
2026-09-25,Bench Press,57.5,8,7,
2026-09-25,Bench Press,57.5,8,7,
2026-09-23,Deadlift,115,3,8,
2026-09-23,Deadlift,115,3,8,
2026-09-23,Overhead Press,41.25,5,8,
2026-09-23,Overhead Press,41.25,5,8,
2026-09-23,Overhead Press,41.25,5,8,
2026-09-25,Barbell Row,55,8,7,
2026-09-25,Barbell Row,55,8,7,
2026-09-23,Pull-Up,0,6,8,
2026-09-23,Pull-Up,0,6,8,
2026-09-28,Back Squat,87.5,5,7,
2026-09-28,Back Squat,87.5,5,7,
2026-09-28,Back Squat,87.5,5,7,
2026-09-28,Bench Press,63.75,5,7.5,
2026-09-28,Bench Press,63.75,5,7.5,
2026-09-28,Bench Press,63.75,5,7.5,
2026-10-02,Bench Press,58.75,8,7,
2026-10-02,Bench Press,58.75,8,7,
2026-10-02,Bench Press,58.75,8,7,
2026-09-30,Deadlift,117.5,3,8,
2026-09-30,Deadlift,117.5,3,8,
2026-09-30,Overhead Press,41.25,5,8,
2026-09-30,Overhead Press,41.25,5,8,
2026-09-30,Overhead Press,41.25,5,8,
2026-10-02,Barbell Row,57.5,8,7,
2026-10-02,Barbell Row,57.5,8,7,
2026-09-30,Pull-Up,0,6,8,
2026-09-30,Pull-Up,0,6,8,
2026-10-05,Back Squat,90,5,7,
2026-10-05,Back Squat,90,5,7,
2026-10-05,Back Squat,90,5,7,
2026-10-05,Bench Press,65,5,7.5,
2026-10-05,Bench Press,65,5,7.5,
2026-10-05,Bench Press,65,5,7.5,
2026-10-09,Bench Press,60,8,7,
2026-10-09,Bench Press,60,8,7,
2026-10-09,Bench Press,60,8,7,
2026-10-07,Deadlift,120,3,8,
2026-10-07,Deadlift,120,3,8,
2026-10-07,Overhead Press,42.5,5,8,
2026-10-07,Overhead Press,42.5,5,8,
2026-10-07,Overhead Press,42.5,5,8,
2026-10-09,Barbell Row,57.5,8,7,
2026-10-09,Barbell Row,57.5,8,7,
2026-10-07,Pull-Up,0,7,8,
2026-10-07,Pull-Up,0,7,8,
2026-10-12,Back Squat,70,5,6,holiday week
2026-10-12,Back Squat,70,5,6,holiday week
2026-10-12,Bench Press,55,5,6,
2026-10-12,Bench Press,55,5,6,
2026-10-14,Deadlift,100,3,6,
2026-10-14,Overhead Press,35,5,6,
2026-10-14,Overhead Press,35,5,6,
2026-10-16,Barbell Row,50,8,6,
2026-10-19,Back Squat,95,5,7,
2026-10-19,Back Squat,95,5,7,
2026-10-19,Back Squat,95,5,7,
2026-10-19,Bench Press,67.5,5,7.5,
2026-10-19,Bench Press,67.5,5,7.5,
2026-10-19,Bench Press,67.5,5,7.5,
2026-10-23,Bench Press,62.5,8,7,
2026-10-23,Bench Press,62.5,8,7,
2026-10-23,Bench Press,62.5,8,7,
2026-10-21,Deadlift,125,3,8,
2026-10-21,Deadlift,125,3,8,
2026-10-21,Overhead Press,43.75,5,8,
2026-10-21,Overhead Press,43.75,5,8,
2026-10-21,Overhead Press,43.75,5,8,
2026-10-23,Barbell Row,60,8,7,
2026-10-23,Barbell Row,60,8,7,
2026-10-21,Pull-Up,0,7,8,
2026-10-21,Pull-Up,0,7,8,
2026-10-26,Back Squat,97.5,5,7,
2026-10-26,Back Squat,97.5,5,7,
2026-10-26,Back Squat,97.5,5,7,
2026-10-26,Bench Press,68.75,5,7.5,
2026-10-26,Bench Press,68.75,5,7.5,
2026-10-26,Bench Press,68.75,5,7.5,
2026-10-30,Bench Press,63.75,8,7,
2026-10-30,Bench Press,63.75,8,7,
2026-10-30,Bench Press,63.75,8,7,
2026-10-28,Deadlift,127.5,3,8,
2026-10-28,Deadlift,127.5,3,8,
2026-10-28,Overhead Press,43.75,5,8,
2026-10-28,Overhead Press,43.75,5,8,
2026-10-28,Overhead Press,43.75,5,8,
2026-10-30,Barbell Row,60,8,7,
2026-10-30,Barbell Row,60,8,7,
2026-10-28,Pull-Up,0,7,8,
2026-10-28,Pull-Up,0,7,8,
2026-11-02,Back Squat,97.5,5,7.5,
2026-11-02,Back Squat,97.5,5,7.5,
2026-11-02,Back Squat,97.5,5,7.5,
2026-11-02,Bench Press,70,5,7.5,
2026-11-02,Bench Press,70,5,7.5,
2026-11-02,Bench Press,70,5,7.5,
2026-11-06,Bench Press,65,8,7,
2026-11-06,Bench Press,65,8,7,
2026-11-06,Bench Press,65,8,7,
2026-11-04,Deadlift,105,3,8.5,had a cold
2026-11-04,Deadlift,105,3,8.5,had a cold
2026-11-04,Overhead Press,45,5,8,
2026-11-04,Overhead Press,45,5,8,
2026-11-04,Overhead Press,45,5,8,
2026-11-06,Barbell Row,60,8,7,
2026-11-06,Barbell Row,60,8,7,
2026-11-04,Pull-Up,0,8,8,
2026-11-04,Pull-Up,0,8,8,
2026-11-09,Back Squat,97.5,5,8,
2026-11-09,Back Squat,97.5,5,8,
2026-11-09,Back Squat,97.5,5,8,
2026-11-09,Bench Press,71.25,5,7.5,
2026-11-09,Bench Press,71.25,5,7.5,
2026-11-09,Bench Press,71.25,5,7.5,
2026-11-13,Bench Press,66.25,8,7,
2026-11-13,Bench Press,66.25,8,7,
2026-11-13,Bench Press,66.25,8,7,
2026-11-11,Deadlift,132.5,3,8,
2026-11-11,Deadlift,132.5,3,8,
2026-11-11,Overhead Press,45,5,8,
2026-11-11,Overhead Press,45,5,8,
2026-11-11,Overhead Press,45,5,8,
2026-11-13,Barbell Row,62.5,8,7,
2026-11-13,Barbell Row,62.5,8,7,
2026-11-11,Pull-Up,0,8,8,
2026-11-11,Pull-Up,0,8,8,
2026-11-16,Back Squat,97.5,5,8.5,
2026-11-16,Back Squat,97.5,5,8.5,
2026-11-16,Back Squat,97.5,5,8.5,
2026-11-16,Bench Press,72.5,5,7.5,
2026-11-16,Bench Press,72.5,5,7.5,
2026-11-16,Bench Press,72.5,5,7.5,
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-18,Deadlift,135,3,8,
2026-11-18,Deadlift,135,3,8,
2026-11-18,Overhead Press,46.25,5,8,
2026-11-18,Overhead Press,46.25,5,8,
2026-11-18,Overhead Press,46.25,5,8,
2026-11-20,Barbell Row,62.5,8,7,
2026-11-20,Barbell Row,62.5,8,7,
2026-11-18,Pull-Up,0,8,8,
2026-11-18,Pull-Up,0,8,8,
2026-11-23,Back Squat,97.5,5,9.5,
2026-11-23,Back Squat,97.5,5,9.5,
2026-11-23,Back Squat,97.5,5,9.5,
2026-11-23,Bench Press,73.75,5,7.5,
2026-11-23,Bench Press,73.75,5,7.5,
2026-11-23,Bench Press,73.75,5,7.5,
2026-11-27,Bench Press,68.75,8,7,
2026-11-27,Bench Press,68.75,8,7,
2026-11-27,Bench Press,68.75,8,7,
2026-11-25,Deadlift,137.5,3,8,
2026-11-25,Deadlift,137.5,3,8,
2026-11-25,Overhead Press,46.25,5,8,
2026-11-25,Overhead Press,46.25,5,8,
2026-11-25,Overhead Press,46.25,5,8,
2026-11-27,Barbell Row,62.5,8,7,
2026-11-27,Barbell Row,62.5,8,7,
2026-11-25,Pull-Up,0,8,8,
2026-11-25,Pull-Up,0,8,8,

FILE:scripts/training_log.py
#!/usr/bin/env python3
"""training_log.py - strength training log progress analyzer. Python 3.8+ standard library only.

Input: a CSV workout log with one row per set:
  date,exercise,weight,reps[,rpe][,sets][,notes]
  2026-09-01,Back Squat,80,5,7
- date: YYYY-MM-DD (also DD.MM.YYYY or DD/MM/YYYY)
- weight: external load per rep in --unit (kg default, or lb); 0 or empty = bodyweight (no e1RM)
- reps: reps done in the set (1-30 count for e1RM; more reps are counted as volume only)
- rpe: optional rate of perceived exertion 1-10
- sets: optional, repeats the row (for logs that write "3x5 at 80 kg" as one line)
Commas or semicolons as separator; decimal commas are accepted when the separator is a semicolon.

Per exercise and ISO week it computes: best estimated one-rep max (Epley, or Brzycki with --formula),
top set, hard sets (RPE >= 7, or every set when RPE is missing), and tonnage (weight x reps).
Across weeks it reports progress, plateaus, load spikes and recovery signals.

Usage:
  training_log.py log.csv [--unit kg|lb] [--formula epley|brzycki] [--plateau-weeks 4]
                  [--spike 1.5] [--exercise "Back Squat"] [--since 2026-09-01]
                  [--format text|md|json|csv]
  training_log.py --self-test
Exit: 0 no flags, 1 flags present, 2 unreadable input.

Flags:
  S01 plateau: no new best e1RM for an exercise in the last --plateau-weeks weeks it was trained
  S02 load spike: a week's hard sets for an exercise above --spike x the average of the 4 weeks before
  S03 RPE creep: same or lower e1RM over 3+ weeks while average RPE rose by 1 or more
  S04 no lighter week in 6+ consecutive training weeks (consider a deload)
  S05 push/pull imbalance: pressing hard sets more than 1.5x pulling hard sets over the log
  S06 e1RM drop of 10% or more from the best for an exercise (check sleep, illness, technique, logging)
  E01 rows that could not be parsed (skipped)
This is training feedback, not medical advice.
"""
import argparse, csv, io, json, re, statistics, sys
from datetime import date, datetime

PUSH = re.compile(r"bench|(?<!leg )press|push|dip|incline|overhead|ohp|chest fly", re.I)
PULL = re.compile(r"row|pull|chin|lat|face pull|deadlift|rdl|curl", re.I)


def parse_date(s):
    s = s.strip()
    for fmt in ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y"):
        try:
            return datetime.strptime(s, fmt).date()
        except ValueError:
            pass
    raise ValueError("bad date %r" % s)


def num(s, comma_decimal=False):
    s = (s or "").strip()
    if not s:
        return None
    if comma_decimal:
        s = s.replace(".", "").replace(",", ".") if re.match(r"^\d{1,3}(\.\d{3})+(,\d+)?$", s) else s.replace(",", ".")
    return float(s)


def e1rm(weight, reps, formula="epley"):
    """Estimated one-rep max; None for bodyweight sets or reps outside 1..30."""
    if not weight or weight <= 0 or reps is None or reps < 1 or reps > 30:
        return None
    if reps == 1:
        return float(weight)
    if formula == "brzycki":
        return weight * 36.0 / (37.0 - reps)
    return weight * (1 + reps / 30.0)


def week_key(d):
    y, w, _ = d.isocalendar()
    return "%d-W%02d" % (y, w)


def read_log(text):
    sample = text[:2000]
    delim = ";" if sample.count(";") > sample.count(",") else ","
    rows, errors = [], []
    rd = csv.DictReader(io.StringIO(text), delimiter=delim)
    if not rd.fieldnames:
        raise ValueError("empty file")
    fields = {f.strip().lower(): f for f in rd.fieldnames}
    alias = {"weight": ["weight", "load", "kg", "lb", "weight_kg", "weight_lb"], "reps": ["reps", "rep"], "exercise": ["exercise", "lift", "movement"],
             "date": ["date", "day"], "rpe": ["rpe"], "sets": ["sets"], "notes": ["notes", "note", "comment"]}
    col = {}
    for k, names in alias.items():
        for n in names:
            if n in fields:
                col[k] = fields[n]
                break
    missing = [k for k in ("date", "exercise", "weight", "reps") if k not in col]
    if missing:
        raise ValueError("missing column(s): " + ", ".join(missing))
    for i, r in enumerate(rd, start=2):
        try:
            d = parse_date(r[col["date"]])
            ex = " ".join((r[col["exercise"]] or "").split())
            if not ex:
                raise ValueError("no exercise")
            w = num(r.get(col["weight"]), delim == ";") or 0.0
            reps = num(r.get(col["reps"]), delim == ";")
            if reps is None or reps <= 0 or w < 0:
                raise ValueError("bad reps/weight")
            rpe = num(r.get(col.get("rpe", ""), ""), delim == ";") if "rpe" in col else None
            if rpe is not None and not 1 <= rpe <= 10:
                raise ValueError("rpe out of range")
            n = int(num(r.get(col["sets"]), delim == ";") or 1) if "sets" in col else 1
            for _ in range(max(1, n)):
                rows.append(dict(date=d, exercise=ex, weight=w, reps=int(reps), rpe=rpe))
        except (ValueError, TypeError, KeyError) as e:
            errors.append("line %d: %s" % (i, e))
    return rows, errors


def analyze(rows, errors=(), unit="kg", formula="epley", plateau_weeks=4, spike=1.5):
    ex_weeks = {}
    all_weeks = sorted({week_key(r["date"]) for r in rows})
    for r in rows:
        wk = week_key(r["date"])
        s = ex_weeks.setdefault(r["exercise"], {}).setdefault(wk, dict(e1rm=None, top=None, hard=0, sets=0, tonnage=0.0, rpes=[]))
        est = e1rm(r["weight"], r["reps"], formula)
        if est is not None and (s["e1rm"] is None or est > s["e1rm"]):
            s["e1rm"], s["top"] = est, "%g x %d" % (r["weight"], r["reps"])
        s["sets"] += 1
        s["tonnage"] += r["weight"] * r["reps"]
        if r["rpe"] is None or r["rpe"] >= 7:
            s["hard"] += 1
        if r["rpe"] is not None:
            s["rpes"].append(r["rpe"])
    flags, exercises = [], []

    def flag(code, ex, detail):
        flags.append(dict(code=code, exercise=ex, detail=detail))

    for ex in sorted(ex_weeks):
        wk = ex_weeks[ex]
        keys = sorted(wk)
        series = [(k, wk[k]["e1rm"]) for k in keys if wk[k]["e1rm"] is not None]
        info = dict(exercise=ex, weeks=len(keys), sets=sum(wk[k]["sets"] for k in keys), tonnage=round(sum(wk[k]["tonnage"] for k in keys), 1))
        if series:
            first, best = series[0][1], max(v for _, v in series)
            best_week = [k for k, v in series if v == best][0]
            last = series[-1][1]
            info.update(first_e1rm=round(first, 1), best_e1rm=round(best, 1), best_week=best_week, last_e1rm=round(last, 1),
                        change_pct=round(100 * (last - first) / first, 1))
            if len(series) > plateau_weeks:
                recent = [v for _, v in series[-plateau_weeks:]]
                before = max(v for _, v in series[:-plateau_weeks])
                if max(recent) <= before:
                    flag("S01", ex, "no new best e1RM in the last %d training weeks (best %.1f %s in %s)" % (plateau_weeks, best, unit, best_week))
            if last <= best * 0.9 and len(series) >= 3:
                flag("S06", ex, "latest e1RM %.1f %s is %.0f%% below the best %.1f %s" % (last, unit, 100 * (1 - last / best), best, unit))
            if len(series) >= 3:
                tail = series[-3:]
                rp = [statistics.mean(wk[k]["rpes"]) if wk[k]["rpes"] else None for k, _ in tail]
                if None not in rp and rp[-1] - rp[0] >= 1 and tail[-1][1] <= tail[0][1]:
                    flag("S03", ex, "average RPE %.1f -> %.1f over %s..%s while e1RM did not improve" % (rp[0], rp[-1], tail[0][0], tail[-1][0]))
        for i, k in enumerate(keys):
            prev = [wk[p]["hard"] for p in keys[max(0, i - 4):i]]
            if len(prev) >= 3 and statistics.mean(prev) > 0 and wk[k]["hard"] > spike * statistics.mean(prev) and wk[k]["hard"] - statistics.mean(prev) >= 3:
                flag("S02", ex, "%s: %d hard sets vs %.1f average of the previous weeks" % (k, wk[k]["hard"], statistics.mean(prev)))
        info["weekly"] = [dict(week=k, e1rm=round(wk[k]["e1rm"], 1) if wk[k]["e1rm"] else None, top_set=wk[k]["top"], hard_sets=wk[k]["hard"],
                               sets=wk[k]["sets"], tonnage=round(wk[k]["tonnage"], 1),
                               avg_rpe=round(statistics.mean(wk[k]["rpes"]), 1) if wk[k]["rpes"] else None) for k in keys]
        exercises.append(info)
    # deload check on total hard sets per week across all exercises
    totals = []
    for k in all_weeks:
        totals.append(sum(ex_weeks[e][k]["hard"] for e in ex_weeks if k in ex_weeks[e]))
    run = 0
    for i, t in enumerate(totals):
        ref = statistics.mean(totals[max(0, i - 4):i]) if i else t
        run = 0 if (i and t <= 0.7 * ref) else run + 1
    if run >= 6:
        flag("S04", "-", "%d training weeks in a row without a lighter week (hard sets per week: %s)" % (run, ", ".join(str(t) for t in totals[-run:])))
    push = sum(r["rpe"] is None or r["rpe"] >= 7 for r in rows if PUSH.search(r["exercise"]) and not PULL.search(r["exercise"]))
    pull = sum(r["rpe"] is None or r["rpe"] >= 7 for r in rows if PULL.search(r["exercise"]))
    if pull and push > 1.5 * pull or (push >= 10 and not pull):
        flag("S05", "-", "pressing hard sets %d vs pulling hard sets %d" % (push, pull))
    for e in errors:
        flag("E01", "-", e)
    order = ["S06", "S02", "S03", "S01", "S04", "S05", "E01"]
    flags.sort(key=lambda f: (order.index(f["code"]), f["exercise"]))
    summary = dict(rows=len(rows), skipped=len(errors), exercises=len(exercises), weeks=len(all_weeks),
                   first_date=min(r["date"] for r in rows).isoformat() if rows else None,
                   last_date=max(r["date"] for r in rows).isoformat() if rows else None,
                   hard_sets_per_week=totals, unit=unit, formula=formula, push_hard_sets=push, pull_hard_sets=pull)
    return dict(summary=summary, exercises=exercises, flags=flags)


def render_text(r):
    s = r["summary"]
    out = ["Strength training progress (%s, e1RM %s)" % (s["unit"], s["formula"]),
           "- %d sets, %d exercises, %d weeks (%s to %s); hard sets per week: %s" % (s["rows"], s["exercises"], s["weeks"], s["first_date"], s["last_date"], ", ".join(map(str, s["hard_sets_per_week"]))), ""]
    out.append("%-22s %6s %8s %8s %8s %7s %9s" % ("Exercise", "weeks", "first", "best", "latest", "change", "tonnage"))
    for e in r["exercises"]:
        if "best_e1rm" in e:
            out.append("%-22s %6d %8.1f %8.1f %8.1f %6.1f%% %9.0f" % (e["exercise"][:22], e["weeks"], e["first_e1rm"], e["best_e1rm"], e["last_e1rm"], e["change_pct"], e["tonnage"]))
        else:
            out.append("%-22s %6d %8s %8s %8s %7s %9.0f" % (e["exercise"][:22], e["weeks"], "-", "-", "-", "bw", e["tonnage"]))
    out += ["", "Flags" if r["flags"] else "Flags: none"]
    out += ["  %s %-16s %s" % (f["code"], f["exercise"][:16], f["detail"]) for f in r["flags"]]
    out.append("Training feedback only, not medical advice.")
    return "\n".join(out)


def render_md(r):
    s = r["summary"]
    out = ["## Training progress %s to %s" % (s["first_date"], s["last_date"]), "",
           "%d sets over %d weeks, %d exercises. e1RM by %s, unit %s." % (s["rows"], s["weeks"], s["exercises"], s["formula"], s["unit"]), "",
           "| Exercise | Weeks | First e1RM | Best e1RM | Latest | Change |", "|---|---:|---:|---:|---:|---:|"]
    for e in r["exercises"]:
        if "best_e1rm" in e:
            out.append("| %s | %d | %.1f | %.1f (%s) | %.1f | %+.1f%% |" % (e["exercise"], e["weeks"], e["first_e1rm"], e["best_e1rm"], e["best_week"], e["last_e1rm"], e["change_pct"]))
    out += ["", "| Flag | Exercise | Detail |", "|---|---|---|"] + ["| %s | %s | %s |" % (f["code"], f["exercise"], f["detail"]) for f in r["flags"]]
    return "\n".join(out)


def render_csv(r):
    buf = io.StringIO()
    w = csv.writer(buf, lineterminator="\n")
    w.writerow(["exercise", "week", "e1rm", "top_set", "hard_sets", "sets", "tonnage", "avg_rpe"])
    for e in r["exercises"]:
        for k in e["weekly"]:
            w.writerow([e["exercise"], k["week"], k["e1rm"] if k["e1rm"] is not None else "", k["top_set"] or "", k["hard_sets"], k["sets"], k["tonnage"], k["avg_rpe"] if k["avg_rpe"] is not None else ""])
    return buf.getvalue().rstrip("\n")


def run(argv):
    ap = argparse.ArgumentParser(description="Analyze a strength training CSV log.")
    ap.add_argument("log", nargs="?")
    ap.add_argument("--unit", choices=["kg", "lb"], default="kg")
    ap.add_argument("--formula", choices=["epley", "brzycki"], default="epley")
    ap.add_argument("--plateau-weeks", type=int, default=4)
    ap.add_argument("--spike", type=float, default=1.5)
    ap.add_argument("--exercise", action="append", help="only these exercises (repeatable, case-insensitive)")
    ap.add_argument("--since", help="ignore sets before this date (YYYY-MM-DD)")
    ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.log:
        ap.print_usage(sys.stderr)
        return 2
    try:
        with open(a.log, encoding="utf-8-sig") as fh:
            rows, errors = read_log(fh.read())
    except (OSError, ValueError, UnicodeDecodeError) as e:
        print("error: cannot read log: %s" % e, file=sys.stderr)
        return 2
    if a.since:
        cut = parse_date(a.since)
        rows = [r for r in rows if r["date"] >= cut]
    if a.exercise:
        wanted = {x.lower() for x in a.exercise}
        rows = [r for r in rows if r["exercise"].lower() in wanted]
    if not rows:
        print("error: no usable rows (%d skipped)" % len(errors), file=sys.stderr)
        return 2
    r = analyze(rows, errors, a.unit, a.formula, a.plateau_weeks, a.spike)
    if a.format == "json":
        print(json.dumps(r, indent=2, default=str))
    else:
        print({"text": render_text, "md": render_md, "csv": render_csv}[a.format](r))
    return 1 if r["flags"] else 0


def self_test():
    checks = 0
    def ok(cond, msg):
        nonlocal checks
        checks += 1
        if not cond:
            raise AssertionError(msg)
    ok(abs(e1rm(100, 5) - 116.667) < 0.01, "epley 100x5")
    ok(abs(e1rm(100, 5, "brzycki") - 112.5) < 0.01, "brzycki 100x5")
    ok(e1rm(100, 1) == 100 and e1rm(0, 10) is None and e1rm(50, 40) is None, "edge cases")
    ok(week_key(date(2026, 12, 31)) == "2026-W53" and week_key(date(2027, 1, 4)) == "2027-W01", "iso weeks")
    ok(parse_date("05.10.2026") == date(2026, 10, 5), "dotted date")
    rows, err = read_log("date;exercise;weight;reps;rpe\n2026-09-01;Squat;82,5;5;7\n2026-09-01;Squat;x;5;7\n")
    ok(len(rows) == 1 and rows[0]["weight"] == 82.5 and len(err) == 1, "semicolon + decimal comma + bad row")
    rows, _ = read_log("date,exercise,weight,reps,sets\n2026-09-01,Bench Press,60,5,3\n")
    ok(len(rows) == 3, "sets column expands rows")
    def mk(weeks, w0, step, ex="Back Squat", sets=3, rpe=7):
        out = []
        for i in range(weeks):
            d = date.fromordinal(date(2026, 9, 7).toordinal() + 7 * i)
            for _ in range(sets):
                out.append(dict(date=d, exercise=ex, weight=w0 + step(i), reps=5, rpe=rpe))
        return out
    r = analyze(mk(8, 80, lambda i: 2.5 * i))
    ok(not [f for f in r["flags"] if f["code"] == "S01"], "steady progress is no plateau")
    ok(r["exercises"][0]["change_pct"] > 0, "progress positive")
    r = analyze(mk(8, 80, lambda i: min(i, 3) * 2.5))
    ok([f for f in r["flags"] if f["code"] == "S01"], "plateau flagged")
    ok([f for f in r["flags"] if f["code"] == "S04"], "8 weeks without deload flagged")
    rows = mk(4, 80, lambda i: 0, sets=3) + [dict(date=date(2026, 10, 5), exercise="Back Squat", weight=80, reps=5, rpe=8) for _ in range(9)]
    ok([f for f in analyze(rows)["flags"] if f["code"] == "S02"], "load spike flagged")
    drop = mk(4, 100, lambda i: 0) + mk(1, 85, lambda i: 0)
    drop[-1]["date"] = drop[-2]["date"] = drop[-3]["date"] = date(2026, 10, 12)
    ok([f for f in analyze(drop)["flags"] if f["code"] == "S06"], "e1RM drop flagged")
    bench = mk(4, 60, lambda i: 0, ex="Bench Press", sets=4) + mk(4, 50, lambda i: 0, ex="Barbell Row", sets=2)
    ok([f for f in analyze(bench)["flags"] if f["code"] == "S05"], "push/pull imbalance flagged")
    ok(not PUSH.search("Leg Press") and PUSH.search("Overhead Press"), "leg press is not a push")
    print("self-test OK: %d checks" % checks)
    return 0


if __name__ == "__main__":
    sys.exit(run(sys.argv[1:]))
FitnessPythonData Analysis+5
F@f
0
npm Lockfile Change Auditor
Skill

Reviews the changes between two npm package-lock.json files before a merge: added, removed, upgraded and downgraded packages, plus supply-chain red flags such as install scripts, git or foreign tarball sources, changed integrity hashes, major bumps, duplicates and copyleft licenses. Stdlib Python.

---
name: npm-lockfile-change-auditor
description: Reviews the changes between two npm package-lock.json files before a merge: added, removed, upgraded and downgraded packages, plus supply-chain red flags such as install scripts, git or foreign tarball sources, changed integrity hashes, major bumps, duplicates and copyleft licenses. Stdlib Python.
---

# npm Lockfile Change Auditor

You help developers and reviewers understand what a change to `package-lock.json` really installs. Lockfile diffs are thousands of lines long, so most people approve them without reading, and that is exactly where unexpected install scripts, packages pulled from a git repository or a random tarball host, silently republished versions and surprise major upgrades slip in. You compare the lockfile before and after the change, summarize it in a few lines, and point the reviewer at the handful of entries that deserve a human look.

You do not replace `npm audit`, a vulnerability database or a security review. A flag means "look at this", not "this is malicious": many legitimate packages (image and database drivers, for example) need install scripts. Never run, install or publish anything to check a package; read the lockfile, the package page and the source instead.

## Files in this skill

- `scripts/lockfile_diff.py` - compares two lockfiles (lockfileVersion 1, 2 or 3), lists added, removed, upgraded and downgraded packages with semver bump kind and direct/dev markers, and prints flags L01-L09 + E01 with a severity; `--format text|md|json`, `--fail-on` for CI, `--allow-scope` for your own scopes, `--self-test` runs 16 checks (Python 3.8+ standard library only)
- `references/lockfile-format.md` - how npm lockfiles are structured (v1 vs v2/v3), what `resolved`, `integrity`, `hasInstallScript`, `dev` and `link` mean, and how to get the "before" file from git
- `references/supply-chain-red-flags.md` - what each flag can mean, how to check it in a few minutes, and when it is fine
- `templates/lockfile-review-comment.md` - a short pull request comment for the reviewer or author
- `examples/package-lock.before.json`, `examples/package-lock.after.json` - a fictional shop front end before and after a dependency update (hashes are synthetic; `num-guard`, `fast-mirror-cache`, `pdf-forge-lite` and `tiny-color-utils` are made-up packages)

## Workflow

### 1. Get both lockfiles
In the repository, with the pull request branch checked out:
```
git show origin/main:package-lock.json > /tmp/lock.before.json
cp package-lock.json /tmp/lock.after.json
```
For a merge request from a fork, use the merge base: `git show $(git merge-base origin/main HEAD):package-lock.json`. If the project uses `npm-shrinkwrap.json`, compare that file instead. pnpm and Yarn lockfiles have other formats and are not supported.

### 2. Run the audit
```
python3 scripts/lockfile_diff.py /tmp/lock.before.json /tmp/lock.after.json
python3 scripts/lockfile_diff.py before.json after.json --format md > lockfile-review.md
python3 scripts/lockfile_diff.py before.json after.json --allow-scope @acme --registry https://npm.acme.internal/
python3 scripts/lockfile_diff.py before.json after.json --fail-on medium --max-added 40   # CI gate
python3 scripts/lockfile_diff.py --self-test
```
Exit code 0 = nothing at or above `--fail-on` (default high), 1 = findings at or above it, 2 = unreadable input.

| Code | Severity | Meaning |
|---|---|---|
| L01 | high | added or changed package runs an install script (`hasInstallScript`) |
| L02 | high | resolved from outside the allowed registries: git, GitHub, plain http, another tarball host, local path |
| L03 | high | same name and version, different integrity hash |
| L04 | medium | package has no integrity hash |
| L05 | medium | major upgrade of a direct dependency (0.x minor bumps count as major) |
| L06 | medium | any downgrade |
| L07 | low | a package is now installed in more versions than before |
| L08 | low | more than `--max-added` packages added (default 25) |
| L09 | medium | license changed, or a strong copyleft license (GPL, AGPL, SSPL) was added; LGPL is not flagged |
| E01 | low | lockfile entries that could not be parsed |

### 3. Investigate the flags
Work from high to low with `references/supply-chain-red-flags.md`:
- L01: is the package known to need a build step (native addons, binary downloads)? Read its `package.json` scripts on the registry page or in the source before installing. Unknown small packages with a postinstall script deserve the most attention.
- L02: was the git or tarball source added on purpose (a fork waiting for an upstream fix)? Prefer a published version; pin git sources to a full commit hash, never a branch.
- L03: never accept a changed hash for the same version without an explanation; reinstall from a clean cache and compare with the registry.
- L05/L06: check the changelog for breaking changes; ask why a downgrade happened (often a merge conflict resolved the wrong way).
- L07/L08: run `npm ls <name>` and `npm dedupe`; ask whether the new dependency is worth its tree.
- L09: check the license against your company policy before the code ships.

### 4. Report
Fill `templates/lockfile-review-comment.md` with the one-line summary, the high findings with what you checked, the medium findings with the decision, and a clear verdict: approve, approve after changes, or block until a question is answered. Keep the comment short; link to the full `--format md` output if needed.

## Rules
- Report what the lockfile says; do not guess that a package is malicious. Say what you checked and what is still unknown.
- Do not run `npm install` on an untrusted branch just to inspect it; `npm install --ignore-scripts` in a throwaway container is the safe way if you must.
- Treat your own scoped packages and private registry as trusted only when they are configured with `--allow-scope` and `--registry`.
- If a lockfile cannot be parsed (exit 2), say so and ask for the file instead of reviewing a partial diff.

FILE:references/lockfile-format.md
# npm lockfile format in short

## Versions
- **lockfileVersion 1** (npm 5-6): a nested `dependencies` map. Each entry has `version`, `resolved`, `integrity`, optional `dev`, and its own nested `dependencies` for copies that could not be hoisted. Git dependencies keep the git URL in `version`.
- **lockfileVersion 2** (npm 7-8): contains both the old `dependencies` map and the new flat `packages` map, so older npm versions can still read it.
- **lockfileVersion 3** (npm 9+): only the `packages` map. This is what most projects have today.

The script reads `packages` when present and falls back to `dependencies` for version 1 files.

## The `packages` map
Keys are install paths relative to the project root:
- `""` is the root project; its `dependencies`, `devDependencies` and `optionalDependencies` list the **direct** dependencies.
- `node_modules/express` is a hoisted copy at the top level.
- `node_modules/pdf-forge-lite/node_modules/ms` is a nested copy, installed because another version of `ms` already sits at the top.
- Workspace folders appear as `packages/web` with a matching `node_modules/web` entry that has `"link": true`.

## Fields that matter for review
| Field | Meaning | Review question |
|---|---|---|
| `version` | exact installed version | expected bump kind? |
| `resolved` | where the tarball comes from | registry, or git / other host / local path? |
| `integrity` | SRI hash (`sha512-...`) checked on install | present? changed for the same version? |
| `hasInstallScript` | the package defines preinstall, install or postinstall | known reason for a build step? |
| `dev`, `optional`, `peer` | install context | does a production image get it? |
| `license` | license string from the package manifest | allowed by policy? |
| `link` | symlink to a local folder (workspaces) | expected workspace? |

## Getting the "before" file
```
git show origin/main:package-lock.json > /tmp/lock.before.json                    # target branch
git show $(git merge-base origin/main HEAD):package-lock.json > /tmp/lock.base.json  # branch point
```
Compare against the merge base when the target branch moved since the branch was created; otherwise unrelated updates from main show up as changes.

## Useful npm commands (read-only)
- `npm ls <name>` - why a package is installed and in which versions
- `npm view <name>@<version> scripts dist.integrity license repository` - registry metadata
- `npm explain <name>` - the dependency path to a package
- `npm ci --ignore-scripts` - install exactly from the lockfile without running scripts (use in a throwaway container)

FILE:references/supply-chain-red-flags.md
# Lockfile red flags: what they can mean and how to check

Spend a few minutes per high finding. Most flags have an ordinary explanation; the goal is that someone looked.

## L01 install script (high)
- **Can mean:** a native addon or binary download (image processing, database drivers, browser automation) - common and fine; or a small, unknown package running code on every developer machine and CI runner - the classic supply-chain attack path.
- **Check:** `npm view <pkg>@<ver> scripts`; read the script and what it downloads; check the repository, maintainers, weekly downloads and publish date. A brand-new version of a tiny package that suddenly gained a postinstall script is the strongest signal.
- **Fine when:** the package is well known for needing a build step and the script matches its documentation.
- **Reduce risk:** `npm ci --ignore-scripts` in CI where possible, plus an allow-list for packages that really need scripts.

## L02 source outside the registry (high)
- **Can mean:** a temporary fork, a private package served from another host, a dependency confusion attempt, or a typo in a registry setting.
- **Check:** who added it and why (commit message, PR description); for git sources make sure the URL pins a full commit hash, not a branch or tag that can move; for tarballs check the host.
- **Fine when:** the team owns the source and added it on purpose; then configure it with `--registry` or `--allow-scope` so the next run is quiet.

## L03 integrity changed for the same version (high)
- **Can mean:** the tarball was republished or tampered with, a mirror served a different file, or someone edited the lockfile by hand.
- **Check:** `npm view <pkg>@<ver> dist.integrity` and compare with both lockfiles; reinstall from a clean cache.
- **Never** accept this without an explanation.

## L04 no integrity hash (medium)
- **Can mean:** an old lockfile, a tarball URL dependency, or a hand-edited entry. Without a hash npm cannot verify the download.
- **Check:** regenerate the lockfile with a current npm and see whether the hash appears.

## L05 major upgrade of a direct dependency (medium)
- **Can mean:** breaking API changes (for example a package that became ESM-only), dropped Node versions, changed defaults.
- **Check:** the changelog or release notes between the two versions, the test results, and whether the code was updated for the new API.

## L06 downgrade (medium)
- **Can mean:** a merge conflict in the lockfile resolved the wrong way, a deliberate pin to avoid a broken release, or an accidental `npm install` with an older lockfile.
- **Check:** ask the author; deliberate pins deserve a comment in `package.json` or the PR.

## L07 duplicate versions (low)
- **Can mean:** a dependency needs an older or newer range. Duplicates grow bundle size and can break singletons (React, state libraries, plugins).
- **Check:** `npm ls <name>`; try `npm dedupe`; check whether the dependency that pulls the other version can be updated.

## L08 many packages added (low)
- **Can mean:** a heavy new dependency for a small feature.
- **Check:** is there a lighter alternative or a built-in API? How much does it add to install time and bundle size?

## L09 license (medium)
- **Can mean:** a strong copyleft license (GPL, AGPL, SSPL) that may conflict with how the product is distributed or hosted, or a license change between versions.
- **Check:** the company license policy; ask legal when unsure. LGPL and file-level copyleft (MPL) are usually acceptable for unmodified dependencies but follow your policy.

## Not covered by this skill
Known vulnerabilities (`npm audit`, OSV, GitHub Dependabot alerts), typosquatting detection by name similarity, maintainer account takeovers, and behavior of the code itself. Mention these limits in the review when the change is risky.

FILE:templates/lockfile-review-comment.md
### Lockfile review - {{branch or PR number}}

**Summary:** {{before}} -> {{after}} packages (+{{added}} / -{{removed}}, {{upgraded}} upgraded, {{downgraded}} downgraded). Findings: {{high}} high, {{medium}} medium, {{low}} low.

**High findings (checked):**
- `{{package}}` {{code}}: {{what the flag says}} - checked: {{what you looked at}} - result: {{ok / needs change / unknown}}

**Medium findings (decision):**
- `{{package}}` {{code}}: {{detail}} - {{accepted because ... / please ...}}

**Questions for the author:**
- {{question}}

**Verdict:** {{approve / approve after the changes above / blocked until the questions are answered}}

<sub>Generated with `lockfile_diff.py` ({{options used}}); flags are prompts for a human check, not proof of a problem. Known vulnerabilities are covered separately by {{npm audit / Dependabot / OSV}}.</sub>

FILE:examples/package-lock.before.json
{
  "name": "shop-web",
  "version": "1.8.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "shop-web",
      "version": "1.8.0",
      "license": "UNLICENSED",
      "dependencies": {
        "axios": "^1.6.8",
        "chalk": "^4.1.2",
        "dotenv": "^16.4.5",
        "express": "^4.19.2",
        "lodash": "^4.17.21",
        "num-guard": "^7.0.0"
      },
      "devDependencies": {
        "eslint-plugin-shop": "^2.3.0"
      }
    },
    "node_modules/axios": {
      "version": "1.6.8",
      "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
      "integrity": "sha512-h+pJqpknU/puknkW9gNz2SJzAC3yayISzJVs5NMocV9W8TtJgXtgkjSV1dV43UyCg3doAQHr5aHoGDltkR+9Qg==",
      "license": "MIT",
      "dependencies": {
        "follow-redirects": "^1.15.6"
      }
    },
    "node_modules/chalk": {
      "version": "4.1.2",
      "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
      "integrity": "sha512-tuZs5w21yj0mWJSFWzn/P1KbPjKDszFi8jUvyYwvFraLNC9SxaSFLxTd5j3J5sckjw1iQRUAlmZq36Sk8SCPsw==",
      "license": "MIT"
    },
    "node_modules/debug": {
      "version": "2.6.9",
      "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
      "integrity": "sha512-IGyVRcglbQuX9vghGUdjPizKtlC9kF6pKI4iF0VbeM2D4OcU4I7EVNu7jF1NtCnvCg2K4VRgeCD4JBcMVJvekg==",
      "license": "MIT",
      "dependencies": {
        "ms": "2.0.0"
      }
    },
    "node_modules/dotenv": {
      "version": "16.4.5",
      "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz",
      "integrity": "sha512-FozMT1uEvHOVZ5j8YRBmYvqyYFwCw8U2EV3sB9duBP0B9RpzkMR99rEyqFUHj75jrN8yFRZRblpffavyTT3DHQ==",
      "license": "BSD-2-Clause"
    },
    "node_modules/eslint-plugin-shop": {
      "version": "2.3.0",
      "resolved": "https://registry.npmjs.org/eslint-plugin-shop/-/eslint-plugin-shop-2.3.0.tgz",
      "integrity": "sha512-Nxo9SDdVqWsY3GgmyJeZJPHoGgIGS4qk5NvrHhwlKmvalrqVQdTlgYlv+/j9i5i9e0jFGijQP5wwrWRPpCXI3g==",
      "license": "MIT",
      "dev": true
    },
    "node_modules/express": {
      "version": "4.19.2",
      "resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz",
      "integrity": "sha512-pK3Mp/RdynyDYm/vwEbzN3s024WaRmmBKhoHa/1MJYfDX39wcj3GhpP+ePsf50bSqMIu+2B3/bRfxCFnXNCW0g==",
      "license": "MIT",
      "dependencies": {
        "debug": "2.6.9"
      }
    },
    "node_modules/follow-redirects": {
      "version": "1.15.6",
      "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
      "integrity": "sha512-tw23l2yC1J9sF5HNEgkG/stImEWD7XAr/WhWGjkP9/EawlvZDTyqzBjse0gwgoPXIsDpU2aaIs41w1icDCqoWg==",
      "license": "MIT"
    },
    "node_modules/lodash": {
      "version": "4.17.21",
      "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
      "integrity": "sha512-fxzPxCwrTent7KYhmQeq0bJWwlz0JeL/i+kQPiTfMp16m0A2Xb0sMtBqoprlMokIPx1b6Wjvam1PKY+foW2HVQ==",
      "license": "MIT"
    },
    "node_modules/ms": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
      "integrity": "sha512-GzDco1VK+DfxVedli4bMu6XC47vqtBmY8/ezspZotp8r4Hs/5pUXBizBu70MZuxmkTa9Zk713DWfcC47dVLcaA==",
      "license": "MIT"
    },
    "node_modules/num-guard": {
      "version": "7.0.0",
      "resolved": "https://registry.npmjs.org/num-guard/-/num-guard-7.0.0.tgz",
      "integrity": "sha512-SA+dO/f3ji1Qn2qHJDKNw/pddElkUFmZ6xwnx9nA6u5/tn9eVFg4W6iWjpWLYqwuVZpdUIPAeoS+LOgYgjdlyA==",
      "license": "MIT"
    }
  }
}

FILE:examples/package-lock.after.json
{
  "name": "shop-web",
  "version": "1.9.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "shop-web",
      "version": "1.9.0",
      "license": "UNLICENSED",
      "dependencies": {
        "axios": "^1.7.7",
        "chalk": "^5.3.0",
        "dotenv": "^15.0.1",
        "express": "^4.21.1",
        "fast-mirror-cache": "^0.9.2",
        "lodash-es": "^4.17.21",
        "num-guard": "^7.0.0",
        "pdf-forge-lite": "^3.1.0",
        "sharp": "^0.33.5",
        "tiny-color-utils": "github:tinycolor-dev/tiny-color-utils#v1.2.0"
      },
      "devDependencies": {
        "eslint-plugin-shop": "^2.3.0"
      }
    },
    "node_modules/@img/sharp-libvips-linux-x64": {
      "version": "1.0.4",
      "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz",
      "integrity": "sha512-KSKmbu86qbPDX2Fg7mzOJBqPzWFwm/vvgNWxV+OStenJTzTXEG23BY9IXodPqCj1I56IknMT0Yzc7FORZ8WizQ==",
      "license": "LGPL-3.0-or-later",
      "optional": true
    },
    "node_modules/axios": {
      "version": "1.7.7",
      "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz",
      "integrity": "sha512-gEwIsrhOaKnz/2O83q20UHMgotVsn+9mJP/UXM39JJvtKcv6dBDfWp07KyoFzp/L8B+2r2ARQT8NcfQt595rVw==",
      "license": "MIT",
      "dependencies": {
        "follow-redirects": "^1.15.6"
      }
    },
    "node_modules/chalk": {
      "version": "5.3.0",
      "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz",
      "integrity": "sha512-kzbQJkH30MjQcVvUMzvngjj8dZquO6SGW8NZAqAzcdSQjq1lBnslgEv/t3pfD05FRRw+YVLBg1k5r1Xk//0DiA==",
      "license": "MIT"
    },
    "node_modules/color": {
      "version": "4.2.3",
      "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
      "integrity": "sha512-QAM/0AGs6Rbsjyd5RpCAMTvZBcJOlKnqDFo1U28hVQXIArfyMkRd5DgKSF2ACkmj3VDDB2FkuTdQsTohiI7uwg==",
      "license": "MIT"
    },
    "node_modules/debug": {
      "version": "2.6.9",
      "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
      "integrity": "sha512-IGyVRcglbQuX9vghGUdjPizKtlC9kF6pKI4iF0VbeM2D4OcU4I7EVNu7jF1NtCnvCg2K4VRgeCD4JBcMVJvekg==",
      "license": "MIT",
      "dependencies": {
        "ms": "2.0.0"
      }
    },
    "node_modules/detect-libc": {
      "version": "2.0.3",
      "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz",
      "integrity": "sha512-b1oO5S/RaQ1B8eqrd/4rLs373tpfvrn9OJZjzfp6qbf1tWwHWe8flGoA1y61x1Q9Ir4ci6Vggf4dwEcmT31ZLg==",
      "license": "Apache-2.0"
    },
    "node_modules/dotenv": {
      "version": "15.0.1",
      "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-15.0.1.tgz",
      "integrity": "sha512-C2QtPIs33kljlM6z0PAcQLDm0vjzBA0j7eNcyuLZeMqzPvnEHUca+04HvUE+cBqsGP4Np7Aa0yKNLgiOEZVUfA==",
      "license": "BSD-2-Clause"
    },
    "node_modules/eslint-plugin-shop": {
      "version": "2.3.0",
      "resolved": "https://registry.npmjs.org/eslint-plugin-shop/-/eslint-plugin-shop-2.3.0.tgz",
      "integrity": "sha512-Nxo9SDdVqWsY3GgmyJeZJPHoGgIGS4qk5NvrHhwlKmvalrqVQdTlgYlv+/j9i5i9e0jFGijQP5wwrWRPpCXI3g==",
      "license": "MIT",
      "dev": true
    },
    "node_modules/express": {
      "version": "4.21.1",
      "resolved": "https://registry.npmjs.org/express/-/express-4.21.1.tgz",
      "integrity": "sha512-rAzf1CydYap1e4hQCgawnrbmFPhK3m5mqdtgbjAlrXv0/gw8R4LjfbRYlI6ep33Z4WjJBJf5F0iNXTYGtFezqA==",
      "license": "MIT",
      "dependencies": {
        "debug": "2.6.9"
      }
    },
    "node_modules/fast-mirror-cache": {
      "version": "0.9.2",
      "resolved": "https://cdn.fastmirror.example/fast-mirror-cache-0.9.2.tgz",
      "license": "MIT"
    },
    "node_modules/follow-redirects": {
      "version": "1.15.9",
      "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
      "integrity": "sha512-Gup9VODh23XNgK9/olbrZz3eFBvVRw8uDLHmZXgxsibt93VvdzJnQ+Sic8dGACxqghxt8wjgbjkfyj5exQOM3g==",
      "license": "MIT"
    },
    "node_modules/lodash-es": {
      "version": "4.17.21",
      "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",
      "integrity": "sha512-XSr9Mh++0EfIoxa8f08FovgmfZnC9S3Wu5cGGXLKtqurs7eIGuc69n+gTRYYq4fldrustqc/zTJf1Gp9hWSDgw==",
      "license": "MIT"
    },
    "node_modules/ms": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
      "integrity": "sha512-GzDco1VK+DfxVedli4bMu6XC47vqtBmY8/ezspZotp8r4Hs/5pUXBizBu70MZuxmkTa9Zk713DWfcC47dVLcaA==",
      "license": "MIT"
    },
    "node_modules/num-guard": {
      "version": "7.0.0",
      "resolved": "https://registry.npmjs.org/num-guard/-/num-guard-7.0.0.tgz",
      "integrity": "sha512-eCC5PP9eeiIfi59qfoUPSyvnSHliveOayW2MlGMo4vibNcHy+coWksCNDg9kMth0LXSSIFqGtYVAzIES3hGiwg==",
      "license": "MIT"
    },
    "node_modules/pdf-forge-lite": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/pdf-forge-lite/-/pdf-forge-lite-3.1.0.tgz",
      "integrity": "sha512-JR3M9MvN1ddgL4WBYkzdOhylzW8fXBVlgsoyVKr8/81lyNjESpI33qVl7MsG7Dr6gbcg4wR5Edp+IrsrULGUuw==",
      "license": "AGPL-3.0-only",
      "dependencies": {
        "ms": "^2.1.3"
      }
    },
    "node_modules/pdf-forge-lite/node_modules/ms": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
      "integrity": "sha512-SNPMCfwMJciLloOwk1dR7uiNbEGq+2NV3Dxrg760V/KNK+Uq4w5U2vcmL31cswWNU1Fht3QgPY4jDq3ysrp7FQ==",
      "license": "MIT"
    },
    "node_modules/semver": {
      "version": "7.6.3",
      "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz",
      "integrity": "sha512-78L8GUmHBY1B5u6cHP5VdH/RoVks7Oiw8LRc6hpI1qLFY8RrEx8SZaLGZRRHduWjubYvBj9CMOawQM3Y7J1/HQ==",
      "license": "ISC"
    },
    "node_modules/sharp": {
      "version": "0.33.5",
      "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz",
      "integrity": "sha512-QuP41KmtRXiWMfiTQsT7tGQV872pcKpHPvNzOxXuizG9/ecgKUnjW5JV9PzgdaOTUsD6EeUh3wLwVLCfELm4Fg==",
      "license": "Apache-2.0",
      "hasInstallScript": true,
      "dependencies": {
        "color": "^4.2.3",
        "detect-libc": "^2.0.3",
        "semver": "^7.6.3"
      }
    },
    "node_modules/tiny-color-utils": {
      "version": "1.2.0",
      "resolved": "git+ssh://git@github.com/tinycolor-dev/tiny-color-utils.git#3f9c2a1d8e7b6c5a4f3e2d1c0b9a8f7e6d5c4b3a",
      "license": "MIT",
      "hasInstallScript": true
    }
  }
}

FILE:scripts/lockfile_diff.py
#!/usr/bin/env python3
"""lockfile_diff.py - npm lockfile change auditor. Python 3.8+ standard library only.

Compares two npm lockfiles (package-lock.json or npm-shrinkwrap.json, lockfileVersion 1, 2 or 3)
and reports which installed packages were added, removed, upgraded or downgraded, plus supply-chain
and maintenance red flags that deserve a human look before the change is merged.

Typical use in a pull request:
  git show origin/main:package-lock.json > /tmp/lock.before.json
  lockfile_diff.py /tmp/lock.before.json package-lock.json

Usage:
  lockfile_diff.py BEFORE AFTER [--registry https://registry.npmjs.org/] [--allow-scope @acme]
                   [--max-added 25] [--fail-on high|medium|low|none] [--format text|md|json]
  lockfile_diff.py --self-test
Exit: 0 nothing at or above --fail-on (default high), 1 findings at or above it, 2 unreadable input.

Flags (severity):
  L01 high    added or changed package that runs an install script (hasInstallScript)
  L02 high    package resolved from outside the registry (git, GitHub, http(s) tarball, file/link)
  L03 high    same name and version but a different integrity hash (possible tampering or republish)
  L04 medium  package without an integrity hash (cannot be verified on install)
  L05 medium  major version upgrade of a direct dependency
  L06 medium  downgrade of any package
  L07 low     a package now installed in two or more versions (duplicate copies)
  L08 low     more than --max-added packages added in one change
  L09 medium  license changed, or a strong copyleft license (GPL, AGPL, SSPL) appears
  E01         entries that could not be parsed (skipped)
"""
import argparse, json, re, sys
from urllib.parse import urlparse

SEV = {"L01": "high", "L02": "high", "L03": "high", "L04": "medium", "L05": "medium", "L06": "medium",
       "L07": "low", "L08": "low", "L09": "medium", "E01": "low"}
RANK = {"none": 99, "high": 3, "medium": 2, "low": 1}
COPYLEFT = re.compile(r"\b(A?GPL|SSPL)", re.I)


def parse_version(v):
    """'1.2.3-beta.1' -> (1, 2, 3, 'beta.1'); returns None for non-semver strings."""
    m = re.match(r"^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$", str(v or "").strip())
    if not m:
        return None
    return int(m.group(1)), int(m.group(2)), int(m.group(3)), m.group(4) or ""


def cmp_version(a, b):
    pa, pb = parse_version(a), parse_version(b)
    if pa is None or pb is None:
        return 0 if a == b else None
    if pa[:3] != pb[:3]:
        return -1 if pa[:3] < pb[:3] else 1
    if pa[3] == pb[3]:
        return 0
    if not pa[3]:
        return 1   # release > prerelease
    if not pb[3]:
        return -1
    return -1 if pa[3] < pb[3] else 1


def bump_kind(old, new):
    po, pn = parse_version(old), parse_version(new)
    if po is None or pn is None:
        return "other"
    if pn[0] != po[0]:
        return "major"
    if pn[0] == 0 and pn[1] != po[1]:
        return "major"   # 0.x minor bumps are breaking by semver convention
    if pn[1] != po[1]:
        return "minor"
    if pn[2] != po[2]:
        return "patch"
    return "prerelease"


def name_from_path(path):
    """'node_modules/a/node_modules/@s/b' -> '@s/b'."""
    tail = path.split("node_modules/")[-1]
    return tail.rstrip("/")


def load(path):
    """Return (entries, errors, meta). entries: {install_path: {name, version, resolved, integrity, license, script, dev, direct}}."""
    with open(path, encoding="utf-8") as fh:
        data = json.load(fh)
    if not isinstance(data, dict):
        raise ValueError("top level is not a JSON object")
    lv = data.get("lockfileVersion", 1)
    entries, errors = {}, []
    root = {}
    if isinstance(data.get("packages"), dict):
        root = data["packages"].get("", {}) or {}
        direct = set((root.get("dependencies") or {})) | set((root.get("devDependencies") or {})) | set((root.get("optionalDependencies") or {}))
        for p, e in data["packages"].items():
            if p == "":
                continue
            if not isinstance(e, dict) or "node_modules/" not in p:
                if isinstance(e, dict) and e.get("link"):
                    continue   # workspace folder entry; its node_modules link is checked instead
                errors.append(p)
                continue
            name = e.get("name") or name_from_path(p)
            top = p.count("node_modules/") == 1
            entries[p] = dict(name=name, version=str(e.get("version", "")), resolved=e.get("resolved", ""),
                              integrity=e.get("integrity", ""), license=e.get("license", ""),
                              script=bool(e.get("hasInstallScript")), dev=bool(e.get("dev")),
                              link=bool(e.get("link")), direct=top and name in direct)
    elif isinstance(data.get("dependencies"), dict):
        def walk(deps, prefix, top):
            for name, e in deps.items():
                p = prefix + "node_modules/" + name
                if not isinstance(e, dict) or "version" not in e:
                    errors.append(p)
                    continue
                ver = str(e["version"])
                resolved = e.get("resolved", "")
                if not resolved and re.match(r"^(git|github:|file:|https?:)", ver):
                    resolved = ver
                entries[p] = dict(name=name, version=ver, resolved=resolved, integrity=e.get("integrity", ""),
                                  license="", script=False, dev=bool(e.get("dev")), link=False, direct=top)
                if isinstance(e.get("dependencies"), dict):
                    walk(e["dependencies"], p + "/", False)
        walk(data["dependencies"], "", True)
    else:
        raise ValueError("no 'packages' or 'dependencies' map found")
    return entries, errors, dict(lockfileVersion=lv, name=data.get("name", ""), root=root)


def source_problem(resolved, registry, link):
    if link:
        return None
    if not resolved:
        return None
    r = resolved.lower()
    if r.startswith(("git+", "git:", "github:", "git@")) or "codeload.github.com" in r:
        return "git source"
    if r.startswith(("file:", "link:")):
        return "local path"
    if r.startswith("http:"):
        return "plain http tarball"
    if r.startswith("https:"):
        host = urlparse(r).netloc
        if host not in {urlparse(x).netloc for x in registry}:
            return "tarball from " + host
    return None


def audit(before, after, registry=("https://registry.npmjs.org/",), allow_scopes=(), max_added=25):
    b_ent, b_err, b_meta = before
    a_ent, a_err, a_meta = after
    by_name_b, by_name_a = {}, {}
    for p, e in b_ent.items():
        by_name_b.setdefault(e["name"], set()).add(e["version"])
    for p, e in a_ent.items():
        by_name_a.setdefault(e["name"], set()).add(e["version"])
    changes = dict(added=[], removed=[], upgraded=[], downgraded=[], changed_source=[])
    flags = []

    def flag(code, pkg, detail):
        flags.append(dict(code=code, severity=SEV[code], package=pkg, detail=detail))

    for p in sorted(set(a_ent) - set(b_ent)):
        e = a_ent[p]
        changes["added"].append(dict(path=p, name=e["name"], version=e["version"], direct=e["direct"], dev=e["dev"]))
    for p in sorted(set(b_ent) - set(a_ent)):
        e = b_ent[p]
        changes["removed"].append(dict(path=p, name=e["name"], version=e["version"], direct=e["direct"]))
    for p in sorted(set(a_ent) & set(b_ent)):
        o, n = b_ent[p], a_ent[p]
        if o["version"] != n["version"]:
            c = cmp_version(o["version"], n["version"])
            row = dict(path=p, name=n["name"], old=o["version"], new=n["version"], kind=bump_kind(o["version"], n["version"]), direct=n["direct"])
            if c == 1:
                row["kind"] = "downgrade"
                changes["downgraded"].append(row)
                flag("L06", n["name"], "%s -> %s (downgrade)" % (o["version"], n["version"]))
            else:
                changes["upgraded"].append(row)
                if row["kind"] == "major" and n["direct"]:
                    flag("L05", n["name"], "%s -> %s (major, direct dependency)" % (o["version"], n["version"]))
        elif o["integrity"] and n["integrity"] and o["integrity"] != n["integrity"]:
            flag("L03", n["name"], "%s: integrity hash changed without a version change" % n["version"])
        if o["resolved"] != n["resolved"] and o["version"] == n["version"] and source_problem(n["resolved"], registry, n["link"]):
            changes["changed_source"].append(dict(path=p, name=n["name"], old=o["resolved"], new=n["resolved"]))
        if o["license"] and n["license"] and o["license"] != n["license"]:
            flag("L09", n["name"], "license %s -> %s" % (o["license"], n["license"]))

    touched = set(x["path"] for x in changes["added"]) | set(x["path"] for x in changes["upgraded"] + changes["downgraded"] + changes["changed_source"])
    for p in sorted(touched):
        e = a_ent[p]
        scoped_ok = any(e["name"].startswith(s.rstrip("/") + "/") for s in allow_scopes)
        if e["script"] and not scoped_ok:
            flag("L01", e["name"], "%s runs an install script (preinstall/install/postinstall)" % e["version"])
        sp = source_problem(e["resolved"], registry, e["link"])
        if sp and not scoped_ok:
            flag("L02", e["name"], "%s resolved from %s: %s" % (e["version"], sp, e["resolved"]))
        if not e["integrity"] and not e["link"] and not (sp and sp.startswith(("git", "local"))):
            flag("L04", e["name"], "%s has no integrity hash" % e["version"])
        if p in {x["path"] for x in changes["added"]} and e["license"] and COPYLEFT.search(e["license"]):
            flag("L09", e["name"], "%s added with license %s" % (e["version"], e["license"]))
    for name in sorted(by_name_a):
        if len(by_name_a[name]) > 1 and len(by_name_a[name]) > len(by_name_b.get(name, set())):
            flag("L07", name, "now installed in %d versions: %s" % (len(by_name_a[name]), ", ".join(sorted(by_name_a[name], key=lambda v: parse_version(v) or (0, 0, 0, v)))))
    if len(changes["added"]) > max_added:
        flag("L08", "-", "%d packages added (limit %d)" % (len(changes["added"]), max_added))
    for p in a_err:
        flag("E01", p, "entry could not be parsed and was skipped")
    order = {"high": 0, "medium": 1, "low": 2}
    flags.sort(key=lambda f: (order[f["severity"]], f["code"], f["package"]))
    summary = dict(before=len(b_ent), after=len(a_ent), added=len(changes["added"]), removed=len(changes["removed"]),
                   upgraded=len(changes["upgraded"]), downgraded=len(changes["downgraded"]),
                   direct_changes=sum(1 for x in changes["added"] + changes["upgraded"] + changes["downgraded"] if x.get("direct")),
                   high=sum(f["severity"] == "high" for f in flags), medium=sum(f["severity"] == "medium" for f in flags),
                   low=sum(f["severity"] == "low" for f in flags),
                   lockfile_versions=[b_meta["lockfileVersion"], a_meta["lockfileVersion"]])
    return dict(summary=summary, changes=changes, flags=flags)


def render_text(r):
    s = r["summary"]
    out = ["npm lockfile change audit",
           "- packages %d -> %d: +%d added, -%d removed, %d upgraded, %d downgraded (%d direct)" % (
               s["before"], s["after"], s["added"], s["removed"], s["upgraded"], s["downgraded"], s["direct_changes"]),
           "- findings: %d high, %d medium, %d low; lockfileVersion %s -> %s" % (s["high"], s["medium"], s["low"], *s["lockfile_versions"]), ""]
    c = r["changes"]
    if c["upgraded"] or c["downgraded"]:
        out.append("Version changes")
        for x in c["upgraded"] + c["downgraded"]:
            out.append("  %-28s %-10s -> %-10s %-10s%s" % (x["name"], x["old"], x["new"], x["kind"], " direct" if x["direct"] else ""))
        out.append("")
    if c["added"]:
        out.append("Added")
        for x in c["added"]:
            out.append("  %-28s %-10s%s%s" % (x["name"], x["version"], " direct" if x["direct"] else "", " dev" if x["dev"] else ""))
        out.append("")
    if c["removed"]:
        out.append("Removed")
        for x in c["removed"]:
            out.append("  %-28s %s" % (x["name"], x["version"]))
        out.append("")
    out.append("Findings" if r["flags"] else "Findings: none")
    for f in r["flags"]:
        out.append("  %s %-6s %-26s %s" % (f["code"], f["severity"], f["package"], f["detail"]))
    return "\n".join(out)


def render_md(r):
    s = r["summary"]
    out = ["## npm lockfile change audit", "",
           "**%d -> %d packages**: +%d added, -%d removed, %d upgraded, %d downgraded (%d direct). Findings: **%d high**, %d medium, %d low." % (
               s["before"], s["after"], s["added"], s["removed"], s["upgraded"], s["downgraded"], s["direct_changes"], s["high"], s["medium"], s["low"]), ""]
    if r["flags"]:
        out += ["| Code | Severity | Package | Detail |", "|---|---|---|---|"]
        out += ["| %s | %s | `%s` | %s |" % (f["code"], f["severity"], f["package"], f["detail"].replace("|", "\\|")) for f in r["flags"]]
        out.append("")
    ch = r["changes"]["upgraded"] + r["changes"]["downgraded"]
    if ch:
        out += ["| Package | From | To | Kind |", "|---|---|---|---|"]
        out += ["| `%s`%s | %s | %s | %s |" % (x["name"], " (direct)" if x["direct"] else "", x["old"], x["new"], x["kind"]) for x in ch]
    return "\n".join(out)


def run(argv):
    ap = argparse.ArgumentParser(description="Audit the changes between two npm lockfiles.")
    ap.add_argument("before", nargs="?")
    ap.add_argument("after", nargs="?")
    ap.add_argument("--registry", action="append", help="allowed registry URL (repeatable; default registry.npmjs.org)")
    ap.add_argument("--allow-scope", action="append", default=[], help="trusted scope, e.g. @acme (skips L01/L02 for it)")
    ap.add_argument("--max-added", type=int, default=25)
    ap.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="high")
    ap.add_argument("--format", choices=["text", "md", "json"], default="text")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.before or not a.after:
        ap.print_usage(sys.stderr)
        return 2
    try:
        before, after = load(a.before), load(a.after)
    except (OSError, ValueError) as e:
        print("error: cannot read lockfile: %s" % e, file=sys.stderr)
        return 2
    r = audit(before, after, tuple(a.registry or ["https://registry.npmjs.org/"]), tuple(a.allow_scope), a.max_added)
    print(json.dumps(r, indent=2) if a.format == "json" else render_md(r) if a.format == "md" else render_text(r))
    worst = max([RANK[f["severity"]] for f in r["flags"]] or [0])
    return 1 if worst >= RANK[a.fail_on] else 0


def self_test():
    checks = 0
    def ok(cond, msg):
        nonlocal checks
        checks += 1
        if not cond:
            raise AssertionError(msg)
    ok(cmp_version("1.2.3", "1.10.0") == -1, "numeric compare")
    ok(cmp_version("2.0.0-rc.1", "2.0.0") == -1, "prerelease < release")
    ok(bump_kind("4.17.21", "5.0.0") == "major", "major")
    ok(bump_kind("0.3.1", "0.4.0") == "major", "0.x minor is major")
    ok(bump_kind("1.2.3", "1.2.9") == "patch", "patch")
    ok(name_from_path("node_modules/a/node_modules/@s/b") == "@s/b", "nested scoped name")
    reg = ("https://registry.npmjs.org/",)
    ok(source_problem("git+ssh://git@github.com/x/y.git#abc", reg, False) == "git source", "git")
    ok(source_problem("https://registry.npmjs.org/a/-/a-1.0.0.tgz", reg, False) is None, "registry ok")
    ok(source_problem("https://example.com/a.tgz", reg, False) == "tarball from example.com", "foreign host")
    def lock(pk):
        return ({"node_modules/" + k: dict(dict(name=k, resolved="https://registry.npmjs.org/%s/-/x.tgz" % k, integrity="sha512-" + k + v.get("version", ""),
                 license="MIT", script=False, dev=False, link=False, direct=True), **v) for k, v in pk.items()}, [], dict(lockfileVersion=3))
    b = lock({"a": dict(version="1.0.0"), "b": dict(version="2.0.0"), "c": dict(version="1.0.0")})
    n = lock({"a": dict(version="2.0.0"), "b": dict(version="1.9.0"), "d": dict(version="1.0.0", script=True, license="AGPL-3.0")})
    n[0]["node_modules/c"] = dict(b[0]["node_modules/c"], integrity="sha512-other")
    r = audit(b, n, reg)
    codes = sorted(f["code"] for f in r["flags"])
    ok(r["summary"]["added"] == 1 and r["summary"]["removed"] == 0, "added count")
    ok("L05" in codes, "major direct flagged")
    ok("L06" in codes, "downgrade flagged")
    ok("L01" in codes and "L09" in codes, "install script and copyleft flagged")
    ok("L03" in codes, "integrity change flagged")
    r2 = audit(b, b, reg)
    ok(r2["flags"] == [] and r2["summary"]["upgraded"] == 0, "identical lockfiles are clean")
    n2 = lock({"a": dict(version="1.0.0"), "b": dict(version="2.0.0"), "c": dict(version="1.0.0"), "@acme/tool": dict(version="1.0.0", script=True)})
    ok(not [f for f in audit(b, n2, reg, ("@acme",))["flags"] if f["code"] == "L01"], "allowed scope skips L01")
    print("self-test OK: %d checks" % checks)
    return 0


if __name__ == "__main__":
    sys.exit(run(sys.argv[1:]))
Node.jsJavaScriptSecurity+5
F@f
0
Pull Request Review Turnaround Analyzer
Skill

Measures how long pull requests wait for review and merge from a GitHub CLI JSON export: time to first review, approval and merge with medians and p90 by size and author, reviewer load, and flags for slow first reviews, stale or unapproved PRs, oversized PRs and review bottlenecks. Stdlib Python.

---
name: pull-request-review-turnaround-analyzer
description: Measures how long pull requests wait for review and merge from a GitHub CLI JSON export: time to first review, approval and merge with medians and p90 by size and author, reviewer load, and flags for slow first reviews, stale or unapproved PRs, oversized PRs and review bottlenecks. Stdlib Python.
---

# Pull Request Review Turnaround Analyzer

You help developers, tech leads and engineering managers see where code review slows a team down: PRs waiting a day or more for a first look, large PRs that sit for a week, approvals that land on one person, and merges that skipped review. You work from a JSON export of the team's pull requests, report medians and p90 instead of averages, and turn the numbers into a few agreed team habits, not a ranking of people.

Use the numbers to improve the process, never to score individuals. Do not share per-person tables outside the team without the team's agreement, and remember that review time depends on time zones, on-call duty, holidays and PR size.

## Files in this skill

- `scripts/pr_turnaround.py` - reads `gh pr list --json ...` output, ignores self-reviews, measures time to first review, first approval and merge (optionally without weekends), size buckets (XS-XL), per-author and per-size medians and p90, reviewer load, and prints flags R01-R06 + E01; `--format text|md|json`; `--self-test` runs 14 checks (Python 3.8+ standard library only)
- `references/review-metrics.md` - what each metric means, healthy ranges for small teams, how to export data from GitHub (and GitLab via conversion), and the main pitfalls
- `references/improvement-playbook.md` - team habits and settings that fix each flag (review slots, PR size limits, CODEOWNERS rotation, draft PRs, branch protection)
- `templates/review-health-report.md` - a short retro or monthly engineering note
- `examples/prs.json` - 13 fictional PRs from a two-week sprint of a small shop team, with a huge refactor, a bot PR, an unreviewed hotfix, a stale PR and one overloaded reviewer

## Workflow

### 1. Export the data
Agree the window (a sprint, a month) and the repository. Then run, in the repository:
```
gh pr list --state all --limit 300 --search "created:>=2026-11-01" \
  --json number,title,author,createdAt,mergedAt,closedAt,isDraft,additions,deletions,reviews,url > prs.json
```
For several repositories export each one and analyze them separately first (different teams, different norms). Agree the targets with the team: first review within 24 working hours (default), PRs under 400 changed lines, nothing open without review for more than 3 days.

### 2. Run the analysis
```
python3 scripts/pr_turnaround.py prs.json
python3 scripts/pr_turnaround.py prs.json --exclude-weekends --ignore-bots
python3 scripts/pr_turnaround.py prs.json --first-review-hours 8 --stale-days 2 --large-lines 300
python3 scripts/pr_turnaround.py prs.json --since 2026-11-16 --format md > review-health.md
python3 scripts/pr_turnaround.py prs.json --now 2026-11-27T17:00:00Z   # reproducible ages for open PRs
python3 scripts/pr_turnaround.py --self-test
```
Exit code 0 = no flags, 1 = flags present, 2 = unreadable input.

| Code | Meaning |
|---|---|
| R01 | first review took longer than `--first-review-hours` |
| R02 | open, non-draft PR without any review for more than `--stale-days` |
| R03 | merged without an approval from someone other than the author |
| R04 | large PR (at least `--large-lines` changed lines, default 400) |
| R05 | one reviewer wrote at least half of all reviews (10+ reviews in the window) |
| R06 | changes were requested and nothing happened for more than `--stale-days` |
| E01 | PR entries that could not be parsed |

### 3. Interpret
- Look at the size table first: if L and XL PRs take days while XS and S take hours, the fix is smaller PRs, not faster reviewers.
- First review time is the main waiting cost; time to merge also includes the author's rework and CI.
- Use `--exclude-weekends` for teams that do not work weekends, otherwise Friday PRs look slow.
- Bot PRs (Renovate, Dependabot) follow other rules; analyze with and without `--ignore-bots`.
- R03 is not always wrong (an emergency hotfix), but each case should have a follow-up review.
- R05 is a bus-factor and burnout signal: one person approves most changes.

### 4. Act
Pick at most two habits from `references/improvement-playbook.md` that match the biggest flags, agree them in a retro, and re-run on the next sprint with the same options to compare.

### 5. Report
Fill `templates/review-health-report.md`: window, overall medians and p90, size table, reviewer load, flags, the agreed habits and the date of the next check.

FILE:references/review-metrics.md
# Review metrics

## Definitions (as computed by scripts/pr_turnaround.py)
- Time to first review: PR creation to the first submitted review (approve, comment or request changes) by someone other than the author. Self-reviews and pending reviews are ignored. Comments that are not part of a review are not counted.
- Time to first approval: creation to the first APPROVED review by someone else.
- Time to merge: creation to merge. Includes waiting, rework, CI and merge queues.
- Size: additions + deletions. Buckets: XS <50, S 50-199, M 200-399, L 400-999, XL 1000+.
- Median and p90: half of the PRs are faster than the median; 9 out of 10 are faster than p90. Averages hide the slow tail, so they are not used.
- Weekends: with --exclude-weekends, Saturday and Sunday in UTC do not count. Teams far from UTC should keep this in mind.

## Healthy ranges for small product teams (rules of thumb)
- First review median: a few working hours; p90 within one working day.
- Merge median: within one or two working days for S and M PRs.
- Most PRs in XS-M; L and XL should be rare and announced.
- No single reviewer above about 40% of reviews in a team of four or more.
These are starting points to discuss, not targets to enforce.

## Exporting data
GitHub CLI (in the repository folder):

    gh pr list --state all --limit 300 --search "created:>=2026-11-01" \
      --json number,title,author,createdAt,mergedAt,closedAt,isDraft,additions,deletions,reviews,url > prs.json

- --limit must cover the window; raise it for busy repositories.
- Reviews in the export do not include the time a reviewer was requested; the script measures from PR creation.
- PRs opened as drafts and marked ready later look slower than they were; count draft time separately or exclude them with --since.

GitLab: export merge requests with the API and map fields to the same names: iid -> number, author.username -> author.login, created_at -> createdAt, merged_at -> mergedAt, closed_at -> closedAt, draft -> isDraft, approvals -> reviews with state APPROVED and submittedAt. Line counts need the changes endpoint.

## Pitfalls
- Do not compare people: authors who take the hardest work naturally have slower PRs.
- Time zones and on-call duty change first-review times a lot.
- Small samples: with fewer than about 10 PRs per group, treat medians as anecdotes.
- Holidays and code freezes distort a window; note them in the report.

FILE:references/improvement-playbook.md
# Improvement playbook: from flag to habit

Pick at most two changes per retro. Re-run the analysis after one sprint to see if they helped.

## R01 slow first reviews
- Review slots: everyone checks open PRs twice a day (for example after stand-up and after lunch) before starting new work.
- A shared rule: first look within one working day, even if it is only "I will review this afternoon".
- Turn on review request notifications in chat for the team channel, not only email.
- Use CODEOWNERS or auto-assignment with round-robin so a PR always has a named reviewer.

## R02 stale PRs without review
- A daily or weekly "PRs waiting" list in chat (gh pr list --search "review:none draft:false").
- Authors ping a specific person after one day instead of the whole channel.
- If a PR is not needed any more, close it; open PRs cost attention.

## R03 merged without approval
- Branch protection: require at least one approval and passing checks on the main branch.
- Allow an emergency path for hotfixes, but add a follow-up review issue within one working day.
- Check whether admins bypass protection by default.

## R04 large PRs
- Agree a soft limit (for example 400 changed lines) and split by layers or behind feature flags.
- Stacked PRs or a short design note before a big refactor.
- Exclude generated files and lockfiles from the diff with .gitattributes linguist-generated, so size reflects real review work.

## R05 one reviewer does most reviews
- Rotate reviewer duty weekly; pair a newer teammate with the main reviewer to spread knowledge.
- Widen CODEOWNERS to a team instead of one person.
- Protect focus time: the main reviewer should not be the default for every PR.

## R06 changes requested, then silence
- Authors answer review comments within one working day, even if only to say when they will fix them.
- Reviewers mark comments as blocking or optional (for example a "nit:" prefix) so authors know what really must change.
- Close or convert to draft if the work is paused.

FILE:templates/review-health-report.md
# Code review health - {{team or repository}} - {{window}}

## Numbers
- PRs: {{prs}} (merged {{merged}}, open or draft {{open}})
- First review: median {{first_review_median}}, p90 {{first_review_p90}} (target {{target}})
- Merge: median {{merge_median}}, p90 {{merge_p90}}
- Options used: {{for example --exclude-weekends --ignore-bots}}

## By size
| Size | PRs | First review median | Merge median |
|---|---:|---:|---:|
| {{bucket}} | {{n}} | {{first_review}} | {{merge}} |

## Reviewer load
- {{reviewer}}: {{reviews}} reviews ({{share}})

## Flags and context
- {{code}} {{where}}: {{detail}} - context: {{holiday, incident, hotfix, on-call}}

## Habits we agreed (max 2)
1. {{habit}} - owner {{name}}
2. {{habit}} - owner {{name}}

## Next check
Re-run on {{date}} with the same options and compare the first review p90 and the size table.

FILE:examples/prs.json
[
 {
  "number": 412,
  "title": "Add invoice PDF export",
  "author": {
   "login": "maya"
  },
  "createdAt": "2026-11-16T09:10:00Z",
  "mergedAt": "2026-11-17T15:30:00Z",
  "closedAt": "2026-11-17T15:30:00Z",
  "isDraft": false,
  "additions": 180,
  "deletions": 40,
  "reviews": [
   {
    "author": {
     "login": "deniz"
    },
    "submittedAt": "2026-11-16T13:05:00Z",
    "state": "COMMENTED"
   },
   {
    "author": {
     "login": "deniz"
    },
    "submittedAt": "2026-11-17T10:20:00Z",
    "state": "APPROVED"
   }
  ],
  "url": "https://github.com/example-shop/storefront/pull/412"
 },
 {
  "number": 413,
  "title": "Fix timezone in reminder emails",
  "author": {
   "login": "ali"
  },
  "createdAt": "2026-11-16T11:00:00Z",
  "mergedAt": "2026-11-16T16:45:00Z",
  "closedAt": "2026-11-16T16:45:00Z",
  "isDraft": false,
  "additions": 22,
  "deletions": 6,
  "reviews": [
   {
    "author": {
     "login": "maya"
    },
    "submittedAt": "2026-11-16T12:10:00Z",
    "state": "APPROVED"
   }
  ],
  "url": "https://github.com/example-shop/storefront/pull/413"
 },
 {
  "number": 414,
  "title": "Refactor billing service into modules",
  "author": {
   "login": "deniz"
  },
  "createdAt": "2026-11-17T08:30:00Z",
  "mergedAt": "2026-11-21T17:00:00Z",
  "closedAt": "2026-11-21T17:00:00Z",
  "isDraft": false,
  "additions": 1640,
  "deletions": 1210,
  "reviews": [
   {
    "author": {
     "login": "selin"
    },
    "submittedAt": "2026-11-19T16:00:00Z",
    "state": "CHANGES_REQUESTED"
   },
   {
    "author": {
     "login": "selin"
    },
    "submittedAt": "2026-11-21T11:30:00Z",
    "state": "APPROVED"
   }
  ],
  "url": "https://github.com/example-shop/storefront/pull/414"
 },
 {
  "number": 415,
  "title": "Bump eslint to v9",
  "author": {
   "login": "renovate[bot]"
  },
  "createdAt": "2026-11-17T06:00:00Z",
  "mergedAt": "2026-11-18T09:00:00Z",
  "closedAt": "2026-11-18T09:00:00Z",
  "isDraft": false,
  "additions": 35,
  "deletions": 30,
  "reviews": [
   {
    "author": {
     "login": "deniz"
    },
    "submittedAt": "2026-11-18T08:40:00Z",
    "state": "APPROVED"
   }
  ],
  "url": "https://github.com/example-shop/storefront/pull/415"
 },
 {
  "number": 416,
  "title": "Add rate limit to public API",
  "author": {
   "login": "selin"
  },
  "createdAt": "2026-11-18T10:00:00Z",
  "mergedAt": "2026-11-19T12:00:00Z",
  "closedAt": "2026-11-19T12:00:00Z",
  "isDraft": false,
  "additions": 260,
  "deletions": 20,
  "reviews": [
   {
    "author": {
     "login": "deniz"
    },
    "submittedAt": "2026-11-18T14:30:00Z",
    "state": "APPROVED"
   }
  ],
  "url": "https://github.com/example-shop/storefront/pull/416"
 },
 {
  "number": 417,
  "title": "Hotfix: null check in checkout",
  "author": {
   "login": "ali"
  },
  "createdAt": "2026-11-19T18:20:00Z",
  "mergedAt": "2026-11-19T18:35:00Z",
  "closedAt": "2026-11-19T18:35:00Z",
  "isDraft": false,
  "additions": 4,
  "deletions": 1,
  "reviews": [],
  "url": "https://github.com/example-shop/storefront/pull/417"
 },
 {
  "number": 418,
  "title": "Dark mode for settings page",
  "author": {
   "login": "maya"
  },
  "createdAt": "2026-11-20T15:00:00Z",
  "mergedAt": "2026-11-24T10:00:00Z",
  "closedAt": "2026-11-24T10:00:00Z",
  "isDraft": false,
  "additions": 320,
  "deletions": 90,
  "reviews": [
   {
    "author": {
     "login": "deniz"
    },
    "submittedAt": "2026-11-23T09:00:00Z",
    "state": "APPROVED"
   }
  ],
  "url": "https://github.com/example-shop/storefront/pull/418"
 },
 {
  "number": 419,
  "title": "Migrate cron jobs to queue workers",
  "author": {
   "login": "ali"
  },
  "createdAt": "2026-11-21T16:30:00Z",
  "mergedAt": null,
  "closedAt": null,
  "isDraft": false,
  "additions": 540,
  "deletions": 210,
  "reviews": [
   {
    "author": {
     "login": "deniz"
    },
    "submittedAt": "2026-11-24T10:15:00Z",
    "state": "CHANGES_REQUESTED"
   }
  ],
  "url": "https://github.com/example-shop/storefront/pull/419"
 },
 {
  "number": 420,
  "title": "Update onboarding copy",
  "author": {
   "login": "selin"
  },
  "createdAt": "2026-11-24T09:00:00Z",
  "mergedAt": "2026-11-24T11:00:00Z",
  "closedAt": "2026-11-24T11:00:00Z",
  "isDraft": false,
  "additions": 12,
  "deletions": 12,
  "reviews": [
   {
    "author": {
     "login": "deniz"
    },
    "submittedAt": "2026-11-24T10:30:00Z",
    "state": "APPROVED"
   }
  ],
  "url": "https://github.com/example-shop/storefront/pull/420"
 },
 {
  "number": 421,
  "title": "Experiment: new search ranking",
  "author": {
   "login": "deniz"
  },
  "createdAt": "2026-11-24T13:00:00Z",
  "mergedAt": null,
  "closedAt": "2026-11-26T09:00:00Z",
  "isDraft": false,
  "additions": 410,
  "deletions": 60,
  "reviews": [
   {
    "author": {
     "login": "maya"
    },
    "submittedAt": "2026-11-25T09:30:00Z",
    "state": "COMMENTED"
   }
  ],
  "url": "https://github.com/example-shop/storefront/pull/421"
 },
 {
  "number": 422,
  "title": "Add audit log table",
  "author": {
   "login": "maya"
  },
  "createdAt": "2026-11-24T08:00:00Z",
  "mergedAt": null,
  "closedAt": null,
  "isDraft": false,
  "additions": 150,
  "deletions": 10,
  "reviews": [],
  "url": "https://github.com/example-shop/storefront/pull/422"
 },
 {
  "number": 423,
  "title": "WIP: mobile push notifications",
  "author": {
   "login": "ali"
  },
  "createdAt": "2026-11-26T14:00:00Z",
  "mergedAt": null,
  "closedAt": null,
  "isDraft": true,
  "additions": 700,
  "deletions": 40,
  "reviews": [],
  "url": "https://github.com/example-shop/storefront/pull/423"
 },
 {
  "number": 424,
  "title": "Cache product list responses",
  "author": {
   "login": "selin"
  },
  "createdAt": "2026-11-26T08:00:00Z",
  "mergedAt": "2026-11-26T15:20:00Z",
  "closedAt": "2026-11-26T15:20:00Z",
  "isDraft": false,
  "additions": 95,
  "deletions": 15,
  "reviews": [
   {
    "author": {
     "login": "deniz"
    },
    "submittedAt": "2026-11-26T09:10:00Z",
    "state": "APPROVED"
   }
  ],
  "url": "https://github.com/example-shop/storefront/pull/424"
 }
]

FILE:scripts/pr_turnaround.py
#!/usr/bin/env python3
"""pr_turnaround.py - pull request review turnaround analyzer. Python 3.8+ standard library only.

Input: JSON from the GitHub CLI, for example
  gh pr list --state all --limit 300 --json number,title,author,createdAt,mergedAt,closedAt,isDraft,additions,deletions,reviews,url > prs.json
(a list of PR objects; reviews = [{author:{login}, submittedAt, state}]). GitLab or other exports work
if converted to the same keys.

Per PR it measures: time to first review by someone other than the author, time to first approval,
time to merge, and size (additions + deletions). It summarizes medians and p90 overall, by size
bucket and by author, shows reviewer load, and flags process problems.

Usage:
  pr_turnaround.py prs.json [--now 2026-11-27T17:00:00Z] [--since 2026-11-01] [--exclude-weekends]
                   [--first-review-hours 24] [--stale-days 3] [--large-lines 400] [--ignore-bots]
                   [--format text|md|json]
  pr_turnaround.py --self-test
Exit: 0 no flags, 1 flags present, 2 unreadable input.

Flags:
  R01 first review took longer than --first-review-hours
  R02 open, non-draft PR without any review older than --stale-days
  R03 merged without an approval from someone other than the author
  R04 large PR (>= --large-lines changed lines): slower and riskier to review
  R05 reviewer concentration: one person wrote >= 50% of all reviews (10+ reviews)
  R06 open PR waiting on the author after CHANGES_REQUESTED for longer than --stale-days
  E01 entries that could not be parsed
"""
import argparse, json, statistics, sys
from datetime import datetime, timedelta, timezone

BUCKETS = [(50, "XS <50"), (200, "S 50-199"), (400, "M 200-399"), (1000, "L 400-999"), (10 ** 12, "XL 1000+")]


def ts(x):
    if not x:
        return None
    return datetime.fromisoformat(x.replace("Z", "+00:00")).astimezone(timezone.utc)


def hours(a, b, exclude_weekends=False):
    """Hours from a to b; with exclude_weekends, Saturday and Sunday (UTC) do not count."""
    if a is None or b is None:
        return None
    if b < a:
        return 0.0
    if not exclude_weekends:
        return (b - a).total_seconds() / 3600
    total, cur = 0.0, a
    while cur < b:
        nxt = min(b, (cur + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0))
        if cur.weekday() < 5:
            total += (nxt - cur).total_seconds()
        cur = nxt
    return total / 3600


def pct(vals, p):
    vals = sorted(v for v in vals if v is not None)
    if not vals:
        return None
    k = (len(vals) - 1) * p / 100
    lo, hi = int(k), min(int(k) + 1, len(vals) - 1)
    return vals[lo] + (vals[hi] - vals[lo]) * (k - lo)


def bucket(n):
    for lim, name in BUCKETS:
        if n < lim:
            return name


def is_bot(login):
    return login.endswith("[bot]") or login.endswith("-bot") or login in ("dependabot", "renovate")


def analyze(prs, now, since=None, exclude_weekends=False, first_review_hours=24.0, stale_days=3.0, large_lines=400, ignore_bots=False):
    rows, flags = [], []
    for i, p in enumerate(prs):
        try:
            author = (p.get("author") or {}).get("login") or "unknown"
            created = ts(p["createdAt"])
            if since and created < since:
                continue
            if ignore_bots and is_bot(author):
                continue
            merged, closed = ts(p.get("mergedAt")), ts(p.get("closedAt"))
            revs = sorted([(ts(r["submittedAt"]), (r.get("author") or {}).get("login") or "unknown", (r.get("state") or "").upper())
                           for r in p.get("reviews") or [] if r.get("submittedAt")], key=lambda x: x[0])
            revs = [r for r in revs if r[1] != author and r[2] != "PENDING"]
            first = revs[0][0] if revs else None
            appr = next((r[0] for r in revs if r[2] == "APPROVED"), None)
            size = int(p.get("additions") or 0) + int(p.get("deletions") or 0)
            state = "merged" if merged else ("closed" if closed else ("draft" if p.get("isDraft") else "open"))
            rows.append(dict(number=p.get("number"), title=p.get("title", ""), author=author, state=state, size=size,
                             bucket=bucket(size), reviewers=sorted({r[1] for r in revs}), reviews=revs,
                             first_review_h=hours(created, first, exclude_weekends),
                             approval_h=hours(created, appr, exclude_weekends),
                             merge_h=hours(created, merged, exclude_weekends),
                             age_h=hours(created, now, exclude_weekends), created=created, url=p.get("url", "")))
        except Exception as e:  # noqa: BLE001
            flags.append(dict(code="E01", where="entry %d" % i, detail=str(e)))
    stale_h = stale_days * 24
    for r in rows:
        ref = "#%s %s" % (r["number"], r["title"][:48])
        if r["first_review_h"] is not None and r["first_review_h"] > first_review_hours:
            flags.append(dict(code="R01", where=ref, detail="first review after %.1f h (target %g h)" % (r["first_review_h"], first_review_hours)))
        if r["state"] == "open" and not r["reviews"] and r["age_h"] > stale_h:
            flags.append(dict(code="R02", where=ref, detail="open %.1f h without any review" % r["age_h"]))
        if r["state"] == "merged" and r["approval_h"] is None:
            flags.append(dict(code="R03", where=ref, detail="merged without an approval from another person"))
        if r["size"] >= large_lines and r["state"] != "closed":
            flags.append(dict(code="R04", where=ref, detail="%d changed lines (%s)" % (r["size"], r["bucket"])))
        if r["state"] == "open" and r["reviews"] and r["reviews"][-1][2] == "CHANGES_REQUESTED":
            waited = hours(r["reviews"][-1][0], now, exclude_weekends)
            if waited > stale_h:
                flags.append(dict(code="R06", where=ref, detail="changes requested %.1f h ago, no new review since" % waited))
    load = {}
    for r in rows:
        for _, who, _s in r["reviews"]:
            load[who] = load.get(who, 0) + 1
    total_reviews = sum(load.values())
    if total_reviews >= 10:
        top, n = max(load.items(), key=lambda kv: kv[1])
        if n / total_reviews >= 0.5:
            flags.append(dict(code="R05", where=top, detail="%d of %d reviews (%.0f%%): review knowledge and load sit with one person" % (n, total_reviews, 100 * n / total_reviews)))
    def stats(sel):
        f = [r["first_review_h"] for r in sel]; m = [r["merge_h"] for r in sel]
        return dict(prs=len(sel), first_review_median_h=pct(f, 50), first_review_p90_h=pct(f, 90),
                    merge_median_h=pct(m, 50), merge_p90_h=pct(m, 90),
                    merged=sum(r["state"] == "merged" for r in sel), open=sum(r["state"] in ("open", "draft") for r in sel))
    by_size = [dict(bucket=b, **stats([r for r in rows if r["bucket"] == b])) for _, b in BUCKETS if any(r["bucket"] == b for r in rows)]
    by_author = [dict(author=a, **stats([r for r in rows if r["author"] == a])) for a in sorted({r["author"] for r in rows})]
    reviewers = [dict(reviewer=k, reviews=v, share=round(v / total_reviews, 3)) for k, v in sorted(load.items(), key=lambda kv: -kv[1])]
    return dict(summary=stats(rows), by_size=by_size, by_author=by_author, reviewers=reviewers, flags=flags,
                prs=[{k: v for k, v in r.items() if k not in ("reviews", "created")} for r in rows])


def fh(x):
    return "-" if x is None else ("%.1f h" % x if x < 48 else "%.1f d" % (x / 24))


def render(res, fmt):
    if fmt == "json":
        return json.dumps(res, indent=1, default=str)
    md, out, s = fmt == "md", [], res["summary"]
    H = (lambda t, l=2: "#" * l + " " + t) if md else (lambda t, l=2: t)
    out.append(H("PR review turnaround"))
    out.append("- PRs %d (merged %d, open/draft %d); first review median %s, p90 %s; merge median %s, p90 %s" % (
        s["prs"], s["merged"], s["open"], fh(s["first_review_median_h"]), fh(s["first_review_p90_h"]), fh(s["merge_median_h"]), fh(s["merge_p90_h"])))
    for title, key, name in (("By size (changed lines)", "by_size", "bucket"), ("By author", "by_author", "author")):
        out += ["", H(title, 3)]
        if md:
            out += ["| %s | PRs | first review median | merge median | merge p90 |" % name, "|---|---:|---:|---:|---:|"]
        for g in res[key]:
            c = (g[name], str(g["prs"]), fh(g["first_review_median_h"]), fh(g["merge_median_h"]), fh(g["merge_p90_h"]))
            out.append("| %s |" % " | ".join(c) if md else "  %-12s %3s PRs  first review %8s  merge %8s  p90 %8s" % c)
    out += ["", H("Reviewer load", 3)]
    for r in res["reviewers"]:
        out.append("%s%s: %d reviews (%.0f%%)" % ("- " if md else "  ", r["reviewer"], r["reviews"], 100 * r["share"]))
    out += ["", H("Flags (%d)" % len(res["flags"]), 3)]
    for f in res["flags"]:
        out.append("%s%s %s: %s" % ("- " if md else "  ", f["code"], f["where"], f["detail"]))
    if not res["flags"]:
        out.append("  none")
    return "\n".join(out)


def self_test():
    ok = 0
    def check(c, name):
        nonlocal ok
        if not c:
            raise SystemExit("FAIL " + name)
        ok += 1
    U = lambda s: ts(s)
    check(abs(hours(U("2026-11-27T12:00:00Z"), U("2026-11-30T12:00:00Z")) - 72) < 1e-9, "calendar hours")
    check(abs(hours(U("2026-11-27T12:00:00Z"), U("2026-11-30T12:00:00Z"), True) - 24) < 1e-9, "weekend excluded (Fri 12:00 -> Mon 12:00 = 24 h)")
    check(hours(U("2026-11-28T10:00:00Z"), U("2026-11-29T10:00:00Z"), True) == 0, "weekend only = 0")
    check(pct([1, 2, 3, 4], 50) == 2.5 and pct([], 50) is None, "percentile")
    check(bucket(49) == "XS <50" and bucket(400) == "L 400-999" and bucket(5000) == "XL 1000+", "buckets")
    rv = lambda who, t, st: {"author": {"login": who}, "submittedAt": t, "state": st}
    base = lambda n, **k: dict(dict(number=n, title="pr%d" % n, author={"login": "a"}, createdAt="2026-11-23T09:00:00Z", mergedAt=None, closedAt=None, isDraft=False, additions=10, deletions=0, reviews=[]), **k)
    now = U("2026-11-27T09:00:00Z")
    prs = [base(1, mergedAt="2026-11-23T15:00:00Z", reviews=[rv("b", "2026-11-23T11:00:00Z", "APPROVED")]),
           base(2, mergedAt="2026-11-25T09:00:00Z", reviews=[rv("b", "2026-11-24T21:00:00Z", "APPROVED")]),
           base(3, mergedAt="2026-11-23T10:00:00Z", reviews=[rv("a", "2026-11-23T09:30:00Z", "APPROVED")]),
           base(4),
           base(5, isDraft=True),
           base(6, additions=500, reviews=[rv("b", "2026-11-23T10:00:00Z", "CHANGES_REQUESTED")])]
    r = analyze(prs, now)
    codes = sorted(f["code"] + str(f["where"]).split()[0] for f in r["flags"])
    check(codes == ["R01#2", "R02#4", "R03#3", "R04#6", "R06#6"], "flags %s" % codes)
    check(r["prs"][2]["first_review_h"] is None, "self review ignored")
    check(abs(r["summary"]["first_review_median_h"] - 2.0) < 1e-9, "first review median 2 h (PRs 1, 2, 6)")
    check(r["summary"]["merged"] == 3 and r["summary"]["open"] == 3, "state counts")
    check(len(analyze(prs, now, since=U("2026-11-24T00:00:00Z"))["prs"]) == 0, "since filter")
    bots = [base(7, author={"login": "renovate[bot]"})]
    check(len(analyze(bots, now, ignore_bots=True)["prs"]) == 0 and len(analyze(bots, now)["prs"]) == 1, "ignore bots")
    many = [base(10 + i, mergedAt="2026-11-23T12:00:00Z", reviews=[rv("b" if i < 8 else "c", "2026-11-23T10:00:00Z", "APPROVED")]) for i in range(10)]
    check([f["code"] for f in analyze(many, now)["flags"]] == ["R05"], "reviewer concentration")
    e = analyze([{"number": 1}], now)
    check([f["code"] for f in e["flags"]] == ["E01"], "bad entry E01")
    check("first review" in render(r, "text") and render(r, "md").startswith("## ") and json.loads(render(r, "json"))["summary"]["prs"] == 6, "renderers")
    print("self-test OK: %d checks" % ok)


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("file", nargs="?")
    ap.add_argument("--now", help="ISO time used as 'now' for open PR ages (default: current UTC time)")
    ap.add_argument("--since", help="only PRs created on or after this date (YYYY-MM-DD)")
    ap.add_argument("--exclude-weekends", action="store_true", help="do not count Saturday and Sunday (UTC)")
    ap.add_argument("--first-review-hours", type=float, default=24.0)
    ap.add_argument("--stale-days", type=float, default=3.0)
    ap.add_argument("--large-lines", type=int, default=400)
    ap.add_argument("--ignore-bots", action="store_true")
    ap.add_argument("--format", choices=["text", "md", "json"], default="text")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.file:
        ap.error("give a JSON file or --self-test")
    try:
        with open(a.file, encoding="utf-8") as fh_:
            prs = json.load(fh_)
        if not isinstance(prs, list):
            raise ValueError("expected a JSON list of pull requests")
    except (OSError, ValueError) as e:
        print("error: %s" % e, file=sys.stderr); sys.exit(2)
    now = ts(a.now) if a.now else datetime.now(timezone.utc)
    since = ts(a.since + "T00:00:00Z") if a.since else None
    res = analyze(prs, now, since, a.exclude_weekends, a.first_review_hours, a.stale_days, a.large_lines, a.ignore_bots)
    print(render(res, a.format))
    sys.exit(1 if res["flags"] else 0)


if __name__ == "__main__":
    main()
PythonCode ReviewDeveloper+5
F@f
0
Car Fuel Log Consumption and Cost Analyzer
Skill

Turns a car fuel log CSV into honest numbers: fill-to-fill consumption in L/100km or mpg that handles partial top-ups, cost per km, monthly spend, and flags for consumption spikes, overpriced fills, odometer typos and missing entries, with a checklist of likely causes. Stdlib Python.

---
name: car-fuel-log-consumption-and-cost-analyzer
description: Turns a car fuel log CSV into honest numbers: fill-to-fill consumption in L/100km or mpg that handles partial top-ups, cost per km, monthly spend, and flags for consumption spikes, overpriced fills, odometer typos and missing entries, with a checklist of likely causes. Stdlib Python.
---

# Car Fuel Log Consumption and Cost Analyzer

You help drivers answer three everyday questions from their own fuel receipts: how much fuel does my car really use, what does each kilometer cost me, and is something wrong when the numbers change? You work from a simple fuel log (a CSV from a spreadsheet, a notes app or a fuel-tracking app export), measure consumption the correct way (full tank to full tank), and explain changes in plain language before anyone spends money at a garage.

You only read the log the user gives you. You are not a mechanic: when the numbers suggest a mechanical problem (a sudden lasting jump in consumption, a fuel smell, warning lights), say so clearly and recommend a check at a garage instead of guessing a diagnosis.

## Files in this skill

- `scripts/fuel_log.py` - reads the CSV, sorts by date, builds full-to-full segments (partial top-ups are added to the next full fill), computes L/100km, mpg, cost per km, monthly spend and summary numbers, and prints flags F01-F06 + E01; `--units km|mi`, `--gallons us|uk`, `--format text|md|csv|json`; `--self-test` runs 20 checks (Python 3.8+ standard library only)
- `references/fuel-economy-basics.md` - how to log fill-ups so the numbers are trustworthy, the full-to-full method, unit conversions and what a normal spread looks like
- `references/consumption-red-flags.md` - likely causes behind each flag (season, tires, driving mix, loads, a mechanical issue) and what to check first, cheapest first
- `templates/fuel-report.md` - a short monthly or yearly car cost note
- `examples/fuel_log.csv` - a fictional four-month log with a partial top-up, a winter-tire change, an expensive motorway station and a trailing top-up

## Workflow

### 1. Get a usable log
Ask for a CSV with one row per fill-up: `date` (YYYY-MM-DD), `odometer_km` (or `odometer_mi` with `--units mi`), `liters` (or gallons with `--gallons us|uk`), `price_per_liter` or `total_cost`, and `full_tank` (yes/no). `station` and `notes` are optional but very useful (trips, tire changes, roof box, heavy loads). If the user has only receipts, help them type the rows; if they never noted whether the tank was full, assume yes and say that partial fills will make single segments noisy. Semicolon-separated files with decimal commas (46,20), common in European spreadsheet exports, are detected automatically; a full_tank value that is not yes/no is reported as E01 instead of being guessed.

### 2. Run the analysis
```
python3 scripts/fuel_log.py fuel_log.csv
python3 scripts/fuel_log.py fuel_log.csv --format md > fuel-report.md
python3 scripts/fuel_log.py fuel_log.csv --format csv > segments.csv
python3 scripts/fuel_log.py us_log.csv --units mi --gallons us          # US log in miles and gallons
python3 scripts/fuel_log.py fuel_log.csv --spike-pct 15 --price-pct 5   # stricter flags
python3 scripts/fuel_log.py --self-test
```
Exit code 0 = no flags, 1 = flags present, 2 = unreadable file or fewer than 2 usable rows.

| Code | Meaning |
|---|---|
| F01 | odometer did not increase (typo, wrong order, a different car in the same log) |
| F02 | a segment uses at least `--spike-pct` (default 20%) more fuel than the median |
| F03 | a segment is far below the median: usually a fill-up that was never logged |
| F04 | a fill cost at least `--price-pct` (default 6%) more per liter than the nearby fills |
| F05 | more than `--gap` km (default 1500) between two fills: likely a missing entry |
| F06 | partial fills after the last full tank are not measured yet (normal at the end of a log) |
| E01 | rows that could not be parsed (date format, empty liters) |

### 3. Interpret
- Trust the median and the trend over a single segment; one short segment with a partial fill is noisy.
- Compare like with like: winter versus summer, city weeks versus motorway trips. A 10-20% rise in cold months is normal (winter fuel, tires, heating, short trips).
- A spike that comes back to normal after one segment usually has a reason in the notes (a loaded trip, traffic, a roof box). A rise that lasts three or more segments without a reason is worth a check (tire pressure first, then a garage).
- F03 and F05 often point at a missing receipt rather than an amazing tank; fix the log before celebrating.
- Price flags show where money leaks: motorway stations and premium fuel the car does not need. Check the owner's manual for the required octane before switching grades.

### 4. Act
Use `references/consumption-red-flags.md` to go from a flag to the cheapest next check. Suggest concrete savings with numbers from the log (for example "skipping motorway stations would have saved about 229 on that fill"). Re-run after the next few fills to confirm a fix.

### 5. Report
Fill `templates/fuel-report.md`: period, distance, average and median consumption, cost per km, monthly spend, flags with causes, and one or two actions.

FILE:references/fuel-economy-basics.md
# Fuel economy basics

## Log every fill-up the same way
1. Fill until the pump clicks off the first time; do not top up further. This makes "full" mean the same level each time.
2. Write down the date, odometer, liters, price per liter (or the total) and whether the tank was full.
3. Add a short note for anything unusual: a long trip, a roof box or trailer, new tires, a heat wave or a cold snap, a different fuel grade.
4. Never skip a receipt, even a small top-up. A missing fill makes the next segment look far too efficient (flag F03) and the distance gap may trigger F05.

## Full-to-full method
Consumption is only measurable between two full tanks: liters added after full tank A up to and including full tank B, divided by the distance from A to B.

    L/100km = 100 x liters added between two full tanks / km driven between them

Partial top-ups between the two full tanks are added to the liters of that segment. Fuel added after the last full tank (flag F06) cannot be measured until the next full fill.

## Units
- L/100km: lower is better. mpg: higher is better.
- mpg (US) = 235.215 / L/100km. mpg (UK) = 282.481 / L/100km.
- 1 US gallon = 3.785 L, 1 UK gallon = 4.546 L, 1 mile = 1.609 km.
- The script converts a miles/gallons log to km and liters internally (`--units mi --gallons us|uk`).

## What normal looks like
- Single segments vary by 5-10% even with identical driving: pumps click off at slightly different levels.
- City driving and short trips use 20-40% more than steady motorway driving at moderate speed.
- Very high motorway speeds raise consumption sharply (air resistance grows with the square of speed).
- Cold months typically add 10-20%: engines take longer to warm up, winter tires roll heavier and winter fuel blends contain a little less energy.
- The official figure from the brochure is usually lower than real-world driving.

## Cost per km
Cost per km = fuel spend of the measured segments / measured distance. It covers fuel only; insurance, tax, maintenance, tires and depreciation come on top. For a full car cost picture add those per year and divide by yearly distance.

FILE:references/consumption-red-flags.md
# Consumption red flags: likely causes and first checks

Go from cheapest and most likely to most expensive. Always check the log itself first.

## F02 consumption spike
Likely causes, in order:
1. Driving mix: more short trips, city traffic, cold starts, a long motorway trip at high speed. Look at the notes and the dates.
2. Season: winter tires fitted, cold mornings, heating, defrosting, idling to warm up.
3. Load and drag: roof box or bike rack, trailer, heavy luggage, open windows at speed.
4. Tire pressure too low: check all four when cold against the label in the door frame. Cheap and common.
5. Logging error: a fill marked full that was not really full, or a skipped receipt in the previous segment.
6. Mechanical: dragging brake, clogged air filter, a failing sensor or thermostat. Suspect these when the rise lasts three or more segments with normal driving, or comes with a warning light, a smell, noise or a pull to one side. Recommend a garage check; do not diagnose.

## F03 suspiciously good segment
Almost always a missing fill-up entry or a full tank that was really a partial one. Ask the user to look for a missing receipt or card statement in that period before trusting the number.

## F04 expensive fill
Motorway or premium stations, premium fuel grades the car does not need, or paying by a card with fees. Show the extra cost of that fill. Check the owner's manual or the fuel-filler flap for the minimum octane before recommending a cheaper grade.

## F05 big distance gap
A missing entry, a long trip with a fill abroad that was not logged, or an odometer typo. Ask for the missing receipt; until then, the segment over the gap is not reliable.

## F01 odometer not increasing
Typo (an extra or missing digit), rows in the wrong order, or two cars mixed in one log. Fix the row and run again.

## F06 trailing partial fills
Normal at the end of a log: wait for the next full tank. Nothing to fix.

## E01 unreadable rows
Date not in YYYY-MM-DD, empty liters or odometer, a summary row from a spreadsheet. Fix or remove the row.

## When to recommend a garage
- consumption up 15% or more for three or more segments with unchanged driving and season,
- any warning light, fuel smell, rough idle, smoke or a noticeable loss of power,
- the car pulls to one side or a wheel gets hot after driving (possible dragging brake).

FILE:templates/fuel-report.md
# Car fuel report - {{car}} - {{period}}

## Numbers
- Distance: {{distance_km}} km ({{measured_km}} km measured full to full)
- Average consumption: {{avg_l100}} L/100km ({{mpg}} mpg), median {{median_l100}}, range {{best_l100}} - {{worst_l100}}
- Fuel spend: {{total_spend}} {{currency}}, cost per km {{cost_per_km}} {{currency}}
- Average price per liter: {{avg_price}} {{currency}}

## Monthly spend
| Month | Fills | Liters | Spend |
|---|---:|---:|---:|
| {{month}} | {{fills}} | {{liters}} | {{cost}} |

## What changed and why
- {{flag code}} {{where}}: {{detail}} - likely cause: {{cause}} - check: {{check}}

## Actions
1. {{action with expected saving}}
2. {{action}}

## Next check
Re-run after {{n}} more fill-ups (around {{date}}) and compare the median.

FILE:examples/fuel_log.csv
date,odometer_km,liters,price_per_liter,full_tank,station,notes
2026-08-02,48210,52.4,46.20,yes,Shell Beykoz,start of log
2026-08-14,48890,49.8,46.50,yes,Opet Kavacik,commute week
2026-08-27,49540,47.1,46.90,yes,Shell Beykoz,
2026-09-05,50310,50.6,47.30,yes,BP Sile road,weekend trip to Sile
2026-09-16,50720,20.0,47.80,no,Opet Kavacik,half tank top-up
2026-09-21,51010,38.9,47.60,yes,Shell Beykoz,
2026-10-03,51620,58.3,48.10,yes,Shell Beykoz,winter tires fitted
2026-10-15,52240,55.0,48.40,yes,Total Umraniye,city traffic
2026-10-28,52900,53.9,52.90,yes,Motorway services,expensive motorway station
2026-11-09,53440,57.6,48.90,yes,Opet Kavacik,cold mornings
2026-11-22,54010,49.5,49.20,yes,Shell Beykoz,
2026-11-28,54320,25.0,49.40,no,BP Sile road,top-up before trip

FILE:scripts/fuel_log.py
#!/usr/bin/env python3
"""fuel_log.py - fuel consumption and cost analyzer for a car fuel log (CSV). Python 3.8+ standard library only.

Consumption is measured fill-to-fill: liters are summed from the fill after one full tank up to and
including the next full tank, and divided by the distance between the two full fills. Partial
top-ups are therefore counted correctly instead of producing fake very low or very high values.

CSV columns (header names, case-insensitive): date, odometer (odometer_km / odometer_mi / odometer),
liters (or litres, gallons with --gallons), price_per_liter (or price, or total_cost), full_tank
(yes/no, true/false, 1/0; missing = yes), station and notes optional. Comma or semicolon
separated (semicolon files may use decimal commas such as 46,20).

Usage:
  fuel_log.py fuel_log.csv [--units km|mi] [--gallons us|uk] [--spike-pct 20] [--price-pct 6]
              [--gap 1500] [--format text|md|csv|json]
  fuel_log.py --self-test
Exit: 0 no flags, 1 flags present, 2 unreadable file or no usable rows.

Flags:
  F01 odometer not increasing (typo, wrong order or a replaced odometer)
  F02 consumption spike: a fill-to-fill segment at least --spike-pct above the median
  F03 unusually low segment (below median by --spike-pct x 1.5): often a missed fill-up entry
  F04 price per liter at least --price-pct above the median of the surrounding fills
  F05 distance between two fills above --gap (a missing entry is likely)
  F06 trailing partial fills: liters after the last full tank are not in any segment yet
  E01 rows that could not be parsed
"""
import argparse, csv, json, statistics, sys
from datetime import date

GAL = {"us": 3.785411784, "uk": 4.54609}
KM_PER_MI = 1.609344


def _f(x):
    x = (x or "").strip().replace(" ", "")
    if not x:
        return None
    if "," in x and "." not in x:
        x = x.replace(",", ".")
    return float(x.replace(",", ""))


def _yes(x):
    x = (x or "").strip().lower()
    if x in ("", "y", "yes", "true", "1", "full", "f"):
        return True
    if x in ("n", "no", "false", "0", "partial", "p"):
        return False
    raise ValueError("full_tank value %r is not yes/no" % x)


def load(path, units="km", gallons=None):
    rows, errors = [], []
    with open(path, newline="", encoding="utf-8-sig") as fh:
        head = fh.readline(); fh.seek(0)
        delim = ";" if head.count(";") > head.count(",") else ","   # European exports often use ; with decimal commas
        rd = csv.DictReader(fh, delimiter=delim)
        if not rd.fieldnames:
            raise ValueError("empty file")
        cols = {c.strip().lower(): c for c in rd.fieldnames}
        def col(*names):
            for n in names:
                if n in cols:
                    return cols[n]
            return None
        c_date = col("date", "day")
        c_odo = col("odometer_km", "odometer_mi", "odometer", "odo", "mileage")
        c_vol = col("liters", "litres", "liter", "volume", "gallons")
        c_ppl = col("price_per_liter", "price_per_litre", "price", "price_per_gallon")
        c_tot = col("total_cost", "total", "cost", "amount")
        c_full = col("full_tank", "full", "is_full")
        if not (c_date and c_odo and c_vol):
            raise ValueError("need columns date, odometer and liters; found %s" % ", ".join(rd.fieldnames))
        for i, r in enumerate(rd, start=2):
            try:
                d = date.fromisoformat(r[c_date].strip())
                odo = _f(r[c_odo]); vol = _f(r[c_vol])
                if odo is None or vol is None or vol <= 0:
                    raise ValueError("missing odometer or volume")
                if units == "mi":
                    odo *= KM_PER_MI
                if gallons:
                    vol *= GAL[gallons]
                ppl = _f(r.get(c_ppl)) if c_ppl else None
                tot = _f(r.get(c_tot)) if c_tot else None
                if ppl is not None and gallons:
                    ppl /= GAL[gallons]
                if tot is None and ppl is not None:
                    tot = ppl * vol
                if ppl is None and tot is not None:
                    ppl = tot / vol
                rows.append(dict(line=i, date=d, odo=odo, liters=vol, ppl=ppl, cost=tot,
                                 full=_yes(r.get(c_full)) if c_full else True,
                                 station=(r.get(col("station")) or "").strip() if col("station") else "",
                                 notes=(r.get(col("notes")) or "").strip() if col("notes") else ""))
            except Exception as e:  # noqa: BLE001
                errors.append((i, str(e)))
    return rows, errors


def analyze(rows, errors, spike_pct=20.0, price_pct=6.0, gap=1500.0):
    flags = [dict(code="E01", where="line %d" % ln, detail=msg) for ln, msg in errors]
    rows = sorted(rows, key=lambda r: (r["date"], r["odo"]))
    for a, b in zip(rows, rows[1:]):
        if b["odo"] <= a["odo"]:
            flags.append(dict(code="F01", where="line %d" % b["line"], detail="odometer %.0f after %.0f" % (b["odo"], a["odo"])))
        elif b["odo"] - a["odo"] > gap:
            flags.append(dict(code="F05", where="lines %d-%d" % (a["line"], b["line"]), detail="%.0f km between fills" % (b["odo"] - a["odo"])))
    segs, start, acc, cost_acc, parts = [], None, 0.0, 0.0, 0
    for r in rows:
        if start is None:
            if r["full"]:
                start = r
            continue
        acc += r["liters"]; parts += 1
        cost_acc += r["cost"] or 0.0
        if r["full"]:
            dist = r["odo"] - start["odo"]
            if dist > 0:
                segs.append(dict(start=start["date"].isoformat(), end=r["date"].isoformat(), km=dist, liters=acc,
                                 l100=100.0 * acc / dist, cost=cost_acc, cost_km=cost_acc / dist if cost_acc else None,
                                 fills=parts, line=r["line"], notes=r["notes"]))
            start, acc, cost_acc, parts = r, 0.0, 0.0, 0
    trailing = acc
    if trailing > 0:
        flags.append(dict(code="F06", where="after %s" % start["date"].isoformat(), detail="%.1f L in partial fills not measured yet" % trailing))
    med = statistics.median([s["l100"] for s in segs]) if segs else None
    for s in segs:
        if med and s["l100"] >= med * (1 + spike_pct / 100):
            flags.append(dict(code="F02", where="%s..%s" % (s["start"], s["end"]), detail="%.1f L/100km vs median %.1f (+%.0f%%)%s" % (s["l100"], med, 100 * (s["l100"] / med - 1), "; note: " + s["notes"] if s["notes"] else "")))
        elif med and s["l100"] <= med * (1 - 1.5 * spike_pct / 100):
            flags.append(dict(code="F03", where="%s..%s" % (s["start"], s["end"]), detail="%.1f L/100km vs median %.1f: check for a missed fill-up entry" % (s["l100"], med)))
    prices = [r for r in rows if r["ppl"]]
    for i, r in enumerate(prices):
        near = [p["ppl"] for j, p in enumerate(prices) if j != i and abs(j - i) <= 3]
        if len(near) >= 2:
            m = statistics.median(near)
            if r["ppl"] >= m * (1 + price_pct / 100):
                flags.append(dict(code="F04", where="line %d %s" % (r["line"], r["station"]), detail="%.2f per liter vs %.2f nearby (+%.0f%%), extra %.2f on this fill" % (r["ppl"], m, 100 * (r["ppl"] / m - 1), (r["ppl"] - m) * r["liters"])))
    total_km = sum(s["km"] for s in segs)
    total_l = sum(s["liters"] for s in segs)
    spend = sum(r["cost"] or 0 for r in rows)
    months = {}
    for r in rows:
        k = r["date"].strftime("%Y-%m"); m = months.setdefault(k, dict(month=k, fills=0, liters=0.0, cost=0.0))
        m["fills"] += 1; m["liters"] += r["liters"]; m["cost"] += r["cost"] or 0
    span_km = rows[-1]["odo"] - rows[0]["odo"] if len(rows) > 1 else 0
    summary = dict(fills=len(rows), segments=len(segs), distance_km=round(span_km, 1), measured_km=round(total_km, 1),
                   avg_l100=round(100 * total_l / total_km, 2) if total_km else None,
                   median_l100=round(med, 2) if med else None,
                   best_l100=round(min(s["l100"] for s in segs), 2) if segs else None,
                   worst_l100=round(max(s["l100"] for s in segs), 2) if segs else None,
                   total_spend=round(spend, 2),
                   cost_per_km=round(sum(s["cost"] for s in segs) / total_km, 3) if total_km else None,
                   avg_price=round(spend / sum(r["liters"] for r in rows if r["cost"]), 3) if any(r["cost"] for r in rows) else None)
    return dict(summary=summary, segments=segs, months=list(months.values()), flags=flags)


def render(res, fmt, units="km"):
    s, out = res["summary"], []
    if fmt == "json":
        return json.dumps(res, indent=1, default=str)
    if fmt == "csv":
        out.append("start,end,km,liters,l_per_100km,cost,cost_per_km,fills")
        for g in res["segments"]:
            out.append("%s,%s,%.0f,%.2f,%.2f,%.2f,%s,%d" % (g["start"], g["end"], g["km"], g["liters"], g["l100"], g["cost"], "%.3f" % g["cost_km"] if g["cost_km"] else "", g["fills"]))
        return "\n".join(out)
    md = fmt == "md"
    mpg = lambda l100: 235.214583 / l100 if l100 else 0
    out.append(("## " if md else "") + "Fuel log summary")
    out.append("- fills %d, measured segments %d, distance %.0f km (measured %.0f km)" % (s["fills"], s["segments"], s["distance_km"], s["measured_km"]))
    if s["avg_l100"]:
        out.append("- average %.2f L/100km (%.1f mpg US), median %.2f, best %.2f, worst %.2f" % (s["avg_l100"], mpg(s["avg_l100"]), s["median_l100"], s["best_l100"], s["worst_l100"]))
    out.append("- total spend %.2f, cost per km %s, average price per liter %s" % (s["total_spend"], s["cost_per_km"], s["avg_price"]))
    out.append("")
    out.append(("### " if md else "") + "Segments (full tank to full tank)")
    if md:
        out += ["| start | end | km | liters | L/100km | cost/km | fills |", "|---|---|---:|---:|---:|---:|---:|"]
    for g in res["segments"]:
        cells = (g["start"], g["end"], "%.0f" % g["km"], "%.1f" % g["liters"], "%.2f" % g["l100"], "%.3f" % g["cost_km"] if g["cost_km"] else "-", str(g["fills"]))
        out.append("| " + " | ".join(cells) + " |" if md else "  %s .. %s  %5s km  %5s L  %6s L/100km  %s/km  %s fill(s)" % cells)
    out.append("")
    out.append(("### " if md else "") + "Monthly spend")
    for m in res["months"]:
        out.append("%s%s: %d fills, %.1f L, %.2f" % ("- " if md else "  ", m["month"], m["fills"], m["liters"], m["cost"]))
    out.append("")
    out.append(("### " if md else "") + "Flags (%d)" % len(res["flags"]))
    for f in res["flags"]:
        out.append("%s%s %s: %s" % ("- " if md else "  ", f["code"], f["where"], f["detail"]))
    if not res["flags"]:
        out.append("  none")
    return "\n".join(out)


def self_test():
    import os, tempfile
    ok = 0
    def check(cond, name):
        nonlocal ok
        if not cond:
            raise SystemExit("FAIL " + name)
        ok += 1
    def run(text, **kw):
        fd, p = tempfile.mkstemp(suffix=".csv"); os.write(fd, text.encode()); os.close(fd)
        try:
            rows, err = load(p, **{k: v for k, v in kw.items() if k in ("units", "gallons")})
            return analyze(rows, err, **{k: v for k, v in kw.items() if k not in ("units", "gallons")})
        finally:
            os.remove(p)
    base = "date,odometer_km,liters,price_per_liter,full_tank\n2026-01-01,1000,40,2.0,yes\n2026-01-10,1500,30,2.0,yes\n2026-01-20,2000,30,2.0,yes\n"
    r = run(base)
    check(r["summary"]["segments"] == 2, "two segments")
    check(abs(r["summary"]["avg_l100"] - 6.0) < 1e-9, "avg 6.0")
    check(r["flags"] == [], "no flags on clean data")
    check(abs(r["summary"]["cost_per_km"] - 0.12) < 1e-9, "cost per km")
    check(abs(r["summary"]["total_spend"] - 200.0) < 1e-9, "total spend includes first fill")
    p = run("date,odometer_km,liters,price_per_liter,full_tank\n2026-01-01,1000,40,2,yes\n2026-01-05,1200,10,2,no\n2026-01-10,1500,20,2,yes\n")
    check(p["summary"]["segments"] == 1 and abs(p["segments"][0]["l100"] - 6.0) < 1e-9, "partial fill merged")
    check(p["segments"][0]["fills"] == 2, "segment counts 2 fills")
    t = run(base + "2026-01-25,2100,10,2.0,no\n")
    check([f["code"] for f in t["flags"]] == ["F06"], "trailing partial F06")
    b = run(base + "2026-01-25,1900,30,2.0,yes\n")
    check("F01" in [f["code"] for f in b["flags"]], "odometer backwards F01")
    s = run(base + "2026-01-30,2500,45,2.0,yes\n2026-02-08,3000,30,2.0,yes\n")
    check("F02" in [f["code"] for f in s["flags"]], "spike F02")
    g = run(base + "2026-02-20,4000,60,2.0,yes\n")
    codes = [f["code"] for f in g["flags"]]
    check("F05" in codes and "F03" in codes, "gap F05 and low F03")
    pr = run("date,odometer_km,liters,price_per_liter,full_tank\n2026-01-01,1000,40,2.0,yes\n2026-01-10,1500,30,2.0,yes\n2026-01-20,2000,30,2.3,yes\n2026-01-30,2500,30,2.0,yes\n")
    check([f["code"] for f in pr["flags"]] == ["F04"], "price F04")
    tc = run("date,odometer,litres,total_cost,full\n2026-01-01,1000,40,80,y\n2026-01-10,1500,30,60,y\n")
    check(abs(tc["summary"]["cost_per_km"] - 0.12) < 1e-9 and abs(tc["summary"]["avg_price"] - 2.0) < 1e-9, "total_cost column")
    mi = run("date,odometer_mi,gallons,price_per_gallon,full_tank\n2026-01-01,1000,10,3.5,yes\n2026-01-10,1300,10,3.5,yes\n", units="mi", gallons="us")
    check(abs(235.214583 / mi["summary"]["avg_l100"] - 30.0) < 0.05, "30 mpg round trip")
    e = run(base + "not-a-date,1,1,1,yes\n")
    check([f["code"] for f in e["flags"]] == ["E01"], "bad row E01")
    check(_f("46,20") == 46.2 and _f("1,234.5") == 1234.5, "number parsing")
    check(_yes("") and _yes("Yes") and not _yes("no") and not _yes("0"), "full tank parsing")
    sc = run("date;odometer;litres;price;full\n2026-01-01;1000;40,0;2,00;ja\n")
    check([f["code"] for f in sc["flags"]] == ["E01"], "unknown full_tank value is E01, not silently partial")
    eu = run("date;odometer;litres;price;full\n2026-01-01;1000;40,0;2,00;yes\n2026-01-10;1500;30,0;2,00;yes\n")
    check(abs(eu["summary"]["avg_l100"] - 6.0) < 1e-9 and eu["flags"] == [], "semicolon CSV with decimal commas")
    check("L/100km" in render(r, "text") and render(r, "csv").count("\n") == 2 and json.loads(render(r, "json"))["summary"]["segments"] == 2, "renderers")
    print("self-test OK: %d checks" % ok)


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("file", nargs="?")
    ap.add_argument("--units", choices=["km", "mi"], default="km", help="odometer unit (results are always per km)")
    ap.add_argument("--gallons", choices=["us", "uk"], help="volume and price columns are in gallons")
    ap.add_argument("--spike-pct", type=float, default=20.0)
    ap.add_argument("--price-pct", type=float, default=6.0)
    ap.add_argument("--gap", type=float, default=1500.0, help="km between fills that suggests a missing entry")
    ap.add_argument("--format", choices=["text", "md", "csv", "json"], default="text")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.file:
        ap.error("give a CSV file or --self-test")
    try:
        rows, errors = load(a.file, a.units, a.gallons)
    except (OSError, ValueError) as e:
        print("error: %s" % e, file=sys.stderr); sys.exit(2)
    if len(rows) < 2:
        print("error: need at least 2 usable fill-ups (%d parsed, %d errors)" % (len(rows), len(errors)), file=sys.stderr); sys.exit(2)
    res = analyze(rows, errors, a.spike_pct, a.price_pct, a.gap)
    print(render(res, a.format, a.units))
    sys.exit(1 if res["flags"] else 0)


if __name__ == "__main__":
    main()
TravelPythonPersonal Finance+5
F@f
0
WebWarpped
Text

This prompt asks for webwrapped, a zero-dependency, fully offline Python CLI that turns a person’s browser history into a Spotify-Wrapped-style annual story and downloadable share card. It must run with one command, keep all data on the user’s machine, make no network calls, and require no API keys.

GOAL
Build "webwrapped" — a zero-dependency CLI that turns a user's browser history
into a Spotify-Wrapped-style year-in-review story with a downloadable share
card. One command, 100% local, no API keys, no network calls, works offline.

TARGET USERS
- Anyone who uses a browser (non-technical first: the story page must be
  beautiful and self-explanatory).
- Privacy-conscious users: history never leaves the machine; state this
  prominently in the README.
- Developers who want the raw stats (--json).

CORE FEATURES (numbered)
1. Auto-detect and read history sources, then merge + dedupe:
   a. Chromium browsers (Chrome, Edge, Brave, Arc, Vivaldi): local
      "History" SQLite DB (note: Chromium only keeps ~90 days locally —
      detect this and show a hint to also export Google Takeout).
   b. Firefox: places.sqlite (can hold years).
   c. Safari: History.plist via plistlib.
   d. Google Takeout: "My Activity/Chrome/MyActivity.json" and
      "My Activity/Search/MyActivity.json" (full-year data; this is the
      flagship source — instruct users how to request it in the README).
   Read SQLite files by copying them to a temp dir first (databases are locked
   while the browser runs).
2. Insights engine (pure stdlib, deterministic, tested):
   - Total visits, estimated hours, busiest day and hour, night-owl score
     (share of 00:00–05:00 traffic).
   - Top 10 sites by visits and by "days seen" (loyalty).
   - "Eras": detect topic phases by clustering domain bursts per week
     (e.g. 3 weeks of recipe sites) and label them with a small
     category-heuristic map (news, video, social, dev, shopping, food...).
   - Rabbit holes: longest single-session drift chains (visit sequences that
     start at one domain and end far away).
   - Top Google queries of the year (from Takeout Search activity), including
     "questions you googled after midnight".
   - YouTube: top channels and total watch-URL visits.
   - Most-revisited single page (the one Stack Overflow question).
   - Streaks: longest daily-visit streak overall.
3. Output modes:
   - Terminal: compact, colorful summary (plain ASCII fallback, no deps).
   - HTML story: a single self-contained file, scrollable story sections in
     Wrapped style (big numbers, bold typography, CSS animations), opened in
     the default browser. Must include a "Download share card" button that
     renders a 1080x1350 PNG client-side via canvas (no server, no deps).
   - --json: full stats dump for scripting.
   - --redact: replace site names with generic labels ("Social app #1")
     inside the share card, for safe sharing.
4. CLI UX: `webwrapped` (auto-detect everything, current year),
   `--year 2025`, `--sources chrome,takeout`, `--demo` (synthetic dataset so
   anyone can preview without their own data), `--json`, `--out story.html`.
5. Takeout zip support: accept the raw takeout-*.zip directly.

TECH STACK
- Python 3.10+, standard library only for the core (sqlite3, plistlib, json,
  zipfile, argparse, html, statistics, dataclasses). No runtime dependencies.
- Optional dev extras: pytest, and `rich` only behind a try/except for
  prettier terminal output when installed.

PROJECT STRUCTURE
webwrapped/
  __init__.py, __main__.py, cli.py
  sources/ (chrome.py, firefox.py, safari.py, takeout.py — each exposes
           read(path) -> list[Visit(date, url, title)])
  merge.py        (dedupe + normalize + union of sources)
  insights/       (stats.py, eras.py, rabbit_holes.py, queries.py, youtube.py)
  render/         (story.py — HTML template; card.py — canvas card HTML)
  demo_data.py    (synthetic generator for --demo)
  tests/          (fixtures: tiny synthetic History.sqlite, places.sqlite,
                   History.plist, MyActivity.json; golden-file tests per insight)
  README.md, LICENSE (MIT), pyproject.toml (pipx/uvx installable)

CLI SPEC
  webwrapped                 # scan default year, all detected sources
  webwrapped --year 2025
  webwrapped takeout.zip     # pass a Takeout zip directly
  webwrapped --demo          # synthetic story, no personal data
  webwrapped --json > stats.json
  webwrapped --redact        # anonymized share card

README REQUIREMENTS
- Badges: CI, license, python version, "zero dependencies".
- One-paragraph privacy promise: nothing leaves the machine, works offline
  (recommend running with network off).
- Demo GIF: terminal run -> story scrolling -> share card download.
- Quick start: `pipx install webwrapped` (or `uvx webwrapped`), then one
  command. Include a 3-step "get your Takeout" guide with screenshots.
- Supported sources table + the Chromium 90-day deletion note.
- FAQ: "where does my data go?" (nowhere), "group by site not URL",
  "why is my local history only 90 days".

TESTING
- pytest with tiny synthetic browser-database fixtures per source.
- Golden-file tests: same input -> same stats JSON and deterministic HTML
  (hash the rendered story after stripping timestamps).
- Edge cases: locked DBs, empty history, non-UTF8 titles, huge Takeouts
  (stream, don't load 500MB into RAM), duplicate visits across sources.

LICENSE: MIT.

FIRST-RELEASE CHECKLIST
- Ship by early December (Wrapped season — the launch window).
- Demo GIF from --demo mode; examples/ folder with the synthetic dataset.
- Launch on X/HN with your own (redacted) share card as the hook:
  "11% of my year went to one Stack Overflow question."
- CONTRIBUTING.md: template for adding new browser sources and category
  heuristics (this community-fed map is the moat — clones can copy the
  code in a day, not the contributors).
- GitHub Actions CI: lint + tests on 3.10/3.11/3.12/3.13.
WebCLIPython
P@mirm14354
0
Pydantic Models taste
Taste

Opinionated Pydantic v2 preferences for validating data at the edges of Python backends: separate input and output models, strict settings, discriminated unions and safe serialization.

# Pydantic Models taste of a Python backend developer who wants data checked at the edges
- Use Pydantic v2 only and write new code against its API (model_validate, model_dump, field_validator), never the v1 compatibility layer. Confidence: 0.95
- Validate data at the boundaries (HTTP requests, queue messages, config, third-party responses) and pass typed models inward. Confidence: 0.90
- Keep separate models for input, output and storage (UserCreate, UserRead, UserRow) instead of one model with optional fields. Confidence: 0.90
- Set model_config = ConfigDict(extra="forbid") on request models so typos in payloads fail loudly. Confidence: 0.85
- Make value objects and events immutable with frozen=True. Confidence: 0.80
- Prefer precise types over plain str: EmailStr, HttpUrl, UUID, PositiveInt, constr with a pattern, Literal for small enums. Confidence: 0.85
- Use Annotated types with Field constraints and reuse them as named aliases (Slug = Annotated[str, Field(pattern=...)]). Confidence: 0.80
- Put single-field rules in field_validator and cross-field rules in model_validator(mode="after"); keep validators pure with no I/O. Confidence: 0.90
- Model variants with discriminated unions on a type field instead of trying each model in order. Confidence: 0.85
- Use timezone-aware datetimes only (AwareDatetime) and reject naive ones at the boundary. Confidence: 0.85
- Store money as Decimal with fixed places, never float. Confidence: 0.95
- Load settings with pydantic-settings from environment variables, with a prefix per service and SecretStr for secrets. Confidence: 0.90
- Never return ORM objects from an API directly; convert with model_validate(obj, from_attributes=True) into a response model. Confidence: 0.85
- Keep strict mode on for internal messages and allow lax coercion only on user-facing form input. Confidence: 0.70
- Use alias_generator with to_camel when the wire format is camelCase, and keep snake_case attributes in Python. Confidence: 0.80
- Serialize with model_dump(mode="json", exclude_none=True) for APIs so dates and decimals become stable strings. Confidence: 0.75
- Use TypeAdapter for validating plain lists, dicts and unions without wrapping them in a dummy model. Confidence: 0.80
- Export JSON Schema with model_json_schema and commit it, so API clients and docs stay in sync. Confidence: 0.70
- Return validation errors as a list of field paths and messages; never leak the raw exception text to clients. Confidence: 0.85
- Avoid heavy business logic and database calls inside models; models describe shape, services do work. Confidence: 0.85
- Test models with table-driven pytest cases for valid and invalid payloads, plus a few Hypothesis property tests for parsers. Confidence: 0.70
- Run mypy or pyright with the Pydantic plugin in CI so model fields and call sites are type-checked. Confidence: 0.80
PythonBackendAPI+2
F@f
0
NPS Survey Score and Comment Theme Analyzer
Skill

Turns an NPS survey CSV into honest numbers: NPS with a 95% margin of error, period trend, segment gaps and changes tested against the noise, small-sample warnings, and keyword-coded comment themes showing what detractors mention far more than promoters. Stdlib Python.

---
name: nps-survey-score-and-comment-theme-analyzer
description: Turns an NPS survey CSV into honest numbers: NPS with a 95% margin of error, period trend, segment gaps and changes tested against the noise, small-sample warnings, and keyword-coded comment themes showing what detractors mention far more than promoters. Stdlib Python.
---

# NPS Survey Score and Comment Theme Analyzer

You help product managers, customer success leads, founders and business managers read Net Promoter Score surveys without fooling themselves. A single NPS number moves a lot by chance, segments with 15 answers swing wildly, and the comments hold the real reasons. You report NPS with its margin of error, say whether a change or a segment gap is bigger than the noise, and turn free-text comments into a few themes with counts and short quotes.

Survey exports often include names, emails and company names. Work only with the columns you need (id, date, score, segments, comment), keep the data local, and never quote a comment together with the respondent's identity in a shared report.

## Files in this skill

- `scripts/nps_check.py` - reads a responses CSV, computes NPS with a 95% margin of error for the current and previous period, per-segment NPS with a z score versus the rest, flags N01-N05 + E01, and codes comments into themes from a keyword JSON file; `--by`, `--period quarter|month`, `--current`, `--min-n`, `--format text|md|json`; `--self-test` runs 23 checks (Python 3.8+ standard library only)
- `references/nps-math.md` - the NPS formula, margin of error, how changes and segment gaps are tested, and sample sizes you need
- `references/comment-coding.md` - how to build and refine a theme keyword file and read theme counts honestly
- `templates/nps-readout.md` - a one-page readout for a team meeting or a board update
- `examples/responses.csv` + `examples/themes.json` - a fictional project-management SaaS for agencies, Q3 and Q4 2026

## Workflow

### 1. Gather inputs
Ask for the survey export with one row per response and the columns `response_id, date, score` (0-10, dates as YYYY-MM-DD) plus optional segment columns (plan, region, tenure, role) and `comment`. Ask how the survey was sent (all customers, a sample, after support tickets) because that decides who the number represents. Agree the reporting period (quarter or month) and the minimum responses per group (default 30). If there is no theme file yet, start from `examples/themes.json` and adapt it after reading 30-50 comments (`references/comment-coding.md`).

### 2. Run the check
```
python3 scripts/nps_check.py responses.csv --themes themes.json --by plan --by region
python3 scripts/nps_check.py responses.csv --themes themes.json --by plan --min-n 20
python3 scripts/nps_check.py responses.csv --period month
python3 scripts/nps_check.py responses.csv --current 2026-Q3 --by plan
python3 scripts/nps_check.py responses.csv --themes themes.json --by plan --format md > nps.md
python3 scripts/nps_check.py --self-test
```
Exit code 0 = no flags, 1 = flags present, 2 = unreadable file, missing columns or no valid responses.

| Code | Meaning |
|---|---|
| N01 | a group (overall or segment) has fewer than `--min-n` responses: its NPS is a hint, not a result |
| N02 | a segment's NPS is clearly below the rest of the respondents (z <= -1.96) |
| N03 | NPS fell versus the previous period by more than the noise (z <= -1.96) |
| N04 | a theme appears in at least 20% of detractor comments and at least twice as often as in promoter comments (3+ mentions) |
| N05 | duplicate response_id (the first answer is kept) |
| E01 | invalid row: score outside 0-10 or a bad date |

### 3. Interpret
- Always say the margin of error with the score: "NPS +12 (+/-19)" tells the reader that +5 or +25 would not be surprising.
- A change is only news when the script calls it larger than the noise; otherwise say "no clear change" even if the number moved.
- A segment with N01 cannot be ranked, even if its NPS looks dramatic; collect more answers or merge it with a similar segment.
- Themes are counts of comments that mention a topic, not causes. A theme that detractors mention far more than promoters (N04) is the best lead for "why"; themes that promoters mention most show what to protect.
- Check who answered: response rates, survey timing (right after an outage or a price increase) and channel can move the score more than the product did.

### 4. Act
Turn the top N04 themes into questions for the team that owns them (for example "What changed in board loading in October?"), read 10-20 raw detractor comments for each, and plan follow-up calls with detractors where the customer agreed to be contacted. Track the same themes next period to see whether a fix moved them.

### 5. Report
Fill `templates/nps-readout.md`: the score with its margin, the change and whether it is real, segment results that pass the sample-size bar, the top detractor and promoter themes with one short anonymized quote each, and the actions with owners.

## Example
```
python3 scripts/nps_check.py examples/responses.csv --themes examples/themes.json --by plan --by region
```
Result: Q4 2026 NPS +11.5 +/-19.1 from 78 responses (34 promoters, 19 passives, 25 detractors), down 29.1 points from +40.6 in Q3; the drop is larger than the noise (z -2.10). The Business plan is at -16.7 but has only 24 answers, so it is flagged N01 (with `--min-n 20` it becomes N02, clearly below the rest at +24.1). Performance appears in 77% of detractor comments and in no promoter comment ("Slow, slow, slow. Thinking of switching"; other detractors write that boards and the timeline load slowly since the October update), pricing in 23%; promoters mostly mention ease of use and support. One duplicate response and one row with the date 2026-11-31 are excluded.

## Limits
- NPS describes the people who answered; low or biased response rates limit what it says about all customers.
- The margin of error assumes independent responses from a random-enough sample; it does not cover survey bias.
- Keyword themes miss sarcasm, typos and new topics; check the "not matched by any theme" count and read the raw comments regularly.
- Do not use NPS to judge individual employees or account managers; small samples and customer mix make that unfair.
FILE:references/nps-math.md
# NPS math, noise and sample sizes

## The score
- Respondents answer "How likely are you to recommend us to a friend or colleague?" on 0-10.
- Promoters 9-10, passives 7-8, detractors 0-6.
- NPS = % promoters - % detractors, from -100 to +100. Passives count in the total but not in either share.

## Margin of error
With p = promoter share and d = detractor share among n responses:

- variance = p + d - (p - d)^2
- standard error (points) = 100 x sqrt(variance / n)
- 95% margin of error = 1.96 x standard error

Example: 78 answers, 34 promoters (43.6%), 25 detractors (32.1%): variance = 0.756 - 0.0132 = 0.742, se = 100 x sqrt(0.742 / 78) = 9.76, margin = 19.1 points. So NPS +11.5 is best read as "somewhere between about -8 and +31".

| Responses | Typical margin (NPS around +20 to +40) |
|---|---|
| 25 | +/- 30 to 35 |
| 50 | +/- 22 to 25 |
| 100 | +/- 15 to 18 |
| 400 | +/- 8 to 9 |
| 1000 | +/- 5 |

Rule of thumb: you need about 100 answers per group to see changes of 15-20 points, and about 400 to see changes of 10.

## Is a change real?
For two independent periods (or a segment versus the rest of respondents), the script computes

- z = (NPS_a - NPS_b) / sqrt(se_a^2 + se_b^2)

and calls |z| >= 1.96 "larger than the noise" (about a 5% false-alarm rate per comparison). If you compare many segments, expect about 1 in 20 to cross the line by chance; treat a single borderline result as a lead, not a verdict.

## Segments
- Compare a segment with the rest of the respondents, not with the overall score (which includes the segment itself).
- Merge small segments (for example regions with fewer than 30 answers) or report them as "too few answers".
- Watch the mix: if more Business-plan customers answered this quarter, overall NPS can fall even if no segment changed.

## Periods
- Quarterly reporting suits most B2B companies; monthly works from about 200 answers per month.
- Use the response date, not the account start date. Surveys sent right after onboarding, a support ticket or a renewal measure different moments; keep them in separate files or add a segment column such as `trigger`.
FILE:references/comment-coding.md
# Coding comments into themes

## Build the theme file
1. Read 30-50 comments from all three groups before writing any keyword.
2. Write 5-10 themes in the customer's language: what they talk about (performance, pricing, support, mobile app, integrations, ease of use, reporting), not your org chart.
3. For each theme list word stems that clearly signal it: `slow`, `lag`, `loading`, `crash`; `price`, `expensive`, `pricey`. Matching is case-insensitive and stem-based (`slow` also matches `slower`, `slowly`).
4. Avoid words that appear everywhere (`app`, `use`, `team`): they put every comment in a theme.
5. Save as JSON: `{"performance": ["slow", "lag"], "pricing": ["price", "expensive"]}`.

## Refine it
- Run the script and look at "not matched by any theme": above about 25% of comments means a theme is missing.
- Read the example quote for each theme; if it does not fit, a keyword is too broad.
- A comment can match several themes ("Price went up and the app got slower" counts for pricing and performance); that is expected.
- Keep the theme file under version control and change it on purpose, so period-to-period comparisons stay fair.

## Read the counts honestly
- Report "X of Y detractor comments mention performance", not "performance causes our detractors".
- Small counts are anecdotes: 3 mentions out of 10 detractor comments are worth reading, not worth a roadmap change on their own.
- Compare detractor and promoter shares: a theme mentioned by both (for example reporting) is a topic people care about, not necessarily a problem.
- Negation and sarcasm ("not slow at all", "great, another price increase") fool keyword matching; read the raw comments for the top themes.

## Privacy
Quote short fragments without names, company names or other identifying details. If a comment contains personal data or a complaint about a named employee, do not quote it; summarize it.
FILE:templates/nps-readout.md
# NPS readout: {{period}} ({{product}})

Survey: {{survey_method}} | Responses: {{n}} (response rate {{response_rate}}) | Prepared by: {{author}}

## The number
- NPS {{nps}} +/- {{moe}} (95%) | Promoters {{promoters_pct}}% | Passives {{passives_pct}}% | Detractors {{detractors_pct}}%
- Versus {{previous_period}}: {{previous_nps}} -> {{nps}} ({{delta}} points, {{significance}})

## Segments with enough answers
| Segment | n | NPS | vs rest |
|---|---|---|---|
| {{segment}} | {{segment_n}} | {{segment_nps}} | {{segment_verdict}} |

Too few answers to judge: {{small_segments}}

## Why detractors are unhappy
| Theme | Share of detractor comments | Share of promoter comments | Example (anonymized) |
|---|---|---|---|
| {{theme}} | {{det_share}} | {{pro_share}} | "{{quote}}" |

## What promoters value
- {{promoter_theme}}: "{{promoter_quote}}"

## Actions
| Action | Owner | Due | How we will know |
|---|---|---|---|
| {{action}} | {{owner}} | {{due}} | {{measure}} |

## Caveats
{{caveats}} (sample, timing, mix changes)
FILE:examples/responses.csv
response_id,date,score,plan,region,comment
1004,2026-07-01,4,Starter,NA,"Hard to find things, too many clicks"
1045,2026-07-02,9,Business,EU,"Love the timeline view, saves me hours every week"
1051,2026-07-02,0,Starter,NA,Support took 4 days to reply
1038,2026-07-03,6,Starter,NA,Too expensive after the price increase
1015,2026-07-04,9,Team,EU,
1007,2026-07-06,10,Business,EU,"Love the timeline view, saves me hours every week"
1028,2026-07-07,1,Business,EU,Support took 4 days to reply
1006,2026-07-08,10,Team,NA,"Intuitive and clean, clients like the shared boards"
1025,2026-07-10,9,Team,EU,Templates make onboarding new clients easy
1035,2026-07-12,10,Team,EU,The Slack integration is perfect for us
1047,2026-07-12,9,Team,APAC,
1021,2026-07-14,4,Starter,NA,Support took 4 days to reply
1050,2026-07-14,9,Starter,EU,The Slack integration is perfect for us
1052,2026-07-15,10,Team,EU,The Slack integration is perfect for us
1059,2026-07-15,9,Team,EU,"Support answered within an hour, great service"
1018,2026-07-16,7,Starter,EU,
1056,2026-07-16,6,Team,EU,Mobile app crashes when I upload files
1011,2026-07-21,10,Team,NA,Easy to set up and the whole team uses it daily
1019,2026-07-24,10,Team,APAC,
1023,2026-07-26,9,Business,NA,"Intuitive and clean, clients like the shared boards"
1037,2026-07-26,10,Team,EU,"Intuitive and clean, clients like the shared boards"
1040,2026-07-26,10,Business,NA,
1057,2026-07-27,3,Business,NA,
1054,2026-08-02,10,Business,APAC,The Slack integration is perfect for us
1034,2026-08-03,9,Starter,NA,
1062,2026-08-04,9,Team,EU,"Support answered within an hour, great service"
1031,2026-08-10,9,Business,EU,
1044,2026-08-10,9,Team,APAC,
1002,2026-08-11,10,Starter,NA,Easy to set up and the whole team uses it daily
1060,2026-08-11,10,Starter,APAC,"Love the timeline view, saves me hours every week"
1064,2026-08-11,6,Business,APAC,
1017,2026-08-12,7,Business,EU,Good overall but reports could be better
1001,2026-08-13,10,Starter,EU,"Love the timeline view, saves me hours every week"
1030,2026-08-14,8,Business,EU,Good overall but reports could be better
1005,2026-08-15,10,Business,EU,Templates make onboarding new clients easy
1063,2026-08-16,7,Business,EU,Good overall but reports could be better
1009,2026-08-22,10,Team,NA,Templates make onboarding new clients easy
1061,2026-08-22,7,Starter,NA,
1029,2026-08-26,8,Business,NA,"Decent, the Jira sync breaks sometimes"
1058,2026-08-27,9,Business,NA,"Simple, fast and reliable"
1058,2026-08-27,0,Business,NA,submitted twice by mistake
1016,2026-08-28,0,Team,NA,Support took 4 days to reply
1024,2026-08-28,7,Business,NA,"Decent, the Jira sync breaks sometimes"
1053,2026-09-01,7,Team,EU,
1043,2026-09-03,10,Team,NA,
1013,2026-09-04,7,Starter,EU,"Decent, the Jira sync breaks sometimes"
1014,2026-09-08,9,Team,EU,"Support answered within an hour, great service"
1039,2026-09-10,10,Business,APAC,"Support answered within an hour, great service"
1049,2026-09-11,9,Team,NA,"Simple, fast and reliable"
1003,2026-09-12,10,Team,NA,Easy to set up and the whole team uses it daily
1041,2026-09-12,7,Business,NA,"Decent, the Jira sync breaks sometimes"
1008,2026-09-13,7,Business,NA,
1033,2026-09-13,0,Starter,EU,"Hard to find things, too many clicks"
1036,2026-09-14,10,Team,APAC,"Support answered within an hour, great service"
1048,2026-09-15,8,Team,NA,"Fine, a bit pricey for what we use"
1022,2026-09-16,8,Business,APAC,
1020,2026-09-19,10,Starter,EU,"Support answered within an hour, great service"
1026,2026-09-19,7,Starter,EU,Good overall but reports could be better
1012,2026-09-21,9,Team,APAC,"Support answered within an hour, great service"
1027,2026-09-22,3,Team,NA,Support took 4 days to reply
1010,2026-09-24,0,Starter,APAC,Too expensive after the price increase
1032,2026-09-24,10,Starter,EU,"Simple, fast and reliable"
1042,2026-09-24,10,Business,EU,"Simple, fast and reliable"
1055,2026-09-25,9,Team,EU,Templates make onboarding new clients easy
1046,2026-09-28,10,Business,NA,Best project tool we have tried
1090,2026-10-01,6,Team,APAC,"Slow, slow, slow. Thinking of switching"
1109,2026-10-01,2,Team,NA,"Slow, slow, slow. Thinking of switching"
1072,2026-10-02,3,Business,EU,Timeline loading takes forever now
1075,2026-10-06,9,Starter,EU,"Support answered within an hour, great service"
1131,2026-10-06,10,Team,EU,"Support answered within an hour, great service"
1076,2026-10-07,9,Team,APAC,
1120,2026-10-09,9,Team,EU,Templates make onboarding new clients easy
1126,2026-10-09,10,Team,NA,Easy to set up and the whole team uses it daily
1113,2026-10-10,7,Business,EU,"Fine, a bit pricey for what we use"
1103,2026-10-11,9,Starter,NA,"Intuitive and clean, clients like the shared boards"
1130,2026-10-11,9,Team,APAC,"Support answered within an hour, great service"
1142,2026-10-11,9,Starter,EU,Easy to set up and the whole team uses it daily
1118,2026-10-14,5,Business,NA,
1138,2026-10-15,9,Team,EU,
1071,2026-10-16,7,Team,NA,Good overall but reports could be better
1132,2026-10-17,7,Business,NA,"Works, mobile app needs work"
1139,2026-10-18,9,Team,NA,"Intuitive and clean, clients like the shared boards"
1127,2026-10-20,2,Business,APAC,"Very slow with large projects, constant lag"
1080,2026-10-21,10,Team,EU,The Slack integration is perfect for us
1097,2026-10-22,8,Business,NA,
1085,2026-10-24,8,Business,APAC,"Decent, the Jira sync breaks sometimes"
1087,2026-10-24,5,Business,EU,Too expensive for a team of our size
1099,2026-10-24,10,Starter,NA,The Slack integration is perfect for us
1119,2026-10-24,2,Starter,APAC,Timeline loading takes forever now
1088,2026-10-26,7,Starter,NA,"Decent, the Jira sync breaks sometimes"
1069,2026-10-27,0,Business,NA,"Slow, slow, slow. Thinking of switching"
1107,2026-10-27,10,Business,NA,"Love the timeline view, saves me hours every week"
1086,2026-11-01,10,Business,APAC,"Love the timeline view, saves me hours every week"
1073,2026-11-02,1,Team,APAC,"Very slow with large projects, constant lag"
1078,2026-11-02,9,Team,EU,"Support answered within an hour, great service"
1140,2026-11-02,1,Starter,NA,Mobile app is unusable on Android
1091,2026-11-03,3,Starter,EU,Price went up and the app got slower
1133,2026-11-03,2,Business,NA,Too expensive for a team of our size
1114,2026-11-04,8,Business,NA,Good overall but reports could be better
1068,2026-11-06,9,Business,EU,"Love the timeline view, saves me hours every week"
1083,2026-11-06,9,Team,APAC,Templates make onboarding new clients easy
1084,2026-11-06,4,Team,NA,Price went up and the app got slower
1111,2026-11-06,5,Business,NA,Boards are slow to load since the October update
1094,2026-11-07,9,Starter,EU,The Slack integration is perfect for us
1110,2026-11-08,8,Starter,NA,Good overall but reports could be better
1122,2026-11-08,9,Business,EU,Easy to set up and the whole team uses it daily
1089,2026-11-09,8,Team,NA,
1121,2026-11-10,10,Team,NA,"Support answered within an hour, great service"
1128,2026-11-10,10,Business,NA,"Support answered within an hour, great service"
1100,2026-11-12,0,Business,APAC,
1104,2026-11-12,8,Starter,EU,"Decent, the Jira sync breaks sometimes"
1108,2026-11-12,1,Team,NA,Price went up and the app got slower
1135,2026-11-12,9,Team,APAC,"Support answered within an hour, great service"
1065,2026-11-13,10,Starter,EU,"Love the timeline view, saves me hours every week"
1095,2026-11-13,0,Business,APAC,Lag everywhere since the new editor
1070,2026-11-14,7,Team,NA,"Works, mobile app needs work"
1093,2026-11-14,7,Starter,NA,"Fine, a bit pricey for what we use"
1116,2026-11-14,6,Business,EU,Timeline loading takes forever now
1082,2026-11-17,0,Team,EU,Mobile app is unusable on Android
1105,2026-11-17,6,Starter,APAC,Support never solved our sync problem
1134,2026-11-17,2,Starter,EU,Lag everywhere since the new editor
1136,2026-11-17,6,Starter,EU,
1096,2026-11-18,10,Starter,NA,"Intuitive and clean, clients like the shared boards"
1092,2026-11-19,8,Business,EU,"Fine, a bit pricey for what we use"
1129,2026-11-19,4,Team,EU,Timeline loading takes forever now
1106,2026-11-20,4,Team,EU,"Very slow with large projects, constant lag"
1141,2026-11-20,9,Team,APAC,"Intuitive and clean, clients like the shared boards"
1102,2026-11-21,9,Team,EU,"Simple, fast and reliable"
1081,2026-11-22,10,Team,EU,
1067,2026-11-23,10,Team,EU,The Slack integration is perfect for us
1098,2026-11-23,9,Team,EU,
1066,2026-11-24,7,Starter,EU,"Fine, a bit pricey for what we use"
1074,2026-11-25,10,Starter,NA,
1112,2026-11-25,9,Starter,APAC,"Support answered within an hour, great service"
1115,2026-11-25,10,Team,EU,"Love the timeline view, saves me hours every week"
1123,2026-11-25,8,Team,EU,"Decent, the Jira sync breaks sometimes"
1101,2026-11-26,8,Team,NA,
1077,2026-11-27,7,Team,NA,"Works, mobile app needs work"
1117,2026-11-27,2,Starter,EU,Timeline loading takes forever now
1124,2026-11-27,7,Business,EU,"Decent, the Jira sync breaks sometimes"
1125,2026-11-27,9,Team,EU,
1137,2026-11-27,8,Business,NA,
1079,2026-11-28,10,Business,NA,"Support answered within an hour, great service"
1999,2026-11-31,8,Team,EU,date typo in the export
FILE:examples/themes.json
{
  "performance": [
    "slow",
    "lag",
    "loading",
    "forever",
    "crash"
  ],
  "pricing": [
    "expensive",
    "price",
    "pricey",
    "cost"
  ],
  "support": [
    "support",
    "reply",
    "answered",
    "service"
  ],
  "mobile app": [
    "mobile",
    "android",
    "ios"
  ],
  "integrations": [
    "slack",
    "jira",
    "sync",
    "integration"
  ],
  "ease of use": [
    "easy",
    "intuitive",
    "simple",
    "clicks",
    "hard to find"
  ],
  "reporting": [
    "report",
    "timeline",
    "dashboard"
  ]
}

FILE:scripts/nps_check.py
#!/usr/bin/env python3
"""nps_check.py - honest Net Promoter Score numbers and comment themes from a survey export.

Reads a CSV with one row per response (response_id, date, score 0-10, optional segment columns and a
comment). Computes NPS with a 95% margin of error for the current period, the previous period and each
segment, tests whether changes and segment gaps are larger than the noise, codes comments into themes
with a keyword file and shows which themes are over-represented among detractors.

Usage:
  nps_check.py responses.csv [--themes themes.json] [--by plan --by region] [--period quarter|month]
               [--current 2026-Q4] [--min-n 30] [--format text|md|json]
  nps_check.py --self-test
Exit: 0 = no flags, 1 = flags present, 2 = unreadable input or missing columns.
Python 3.8+ standard library only. Comments stay local; quotes are shortened in the output."""
import argparse, csv, json, math, re, sys
from collections import Counter, defaultdict, OrderedDict
from datetime import date

REQUIRED = ("response_id", "date", "score")

def bucket(score):
    return "promoter" if score >= 9 else ("passive" if score >= 7 else "detractor")

def nps_stats(scores):
    """Return dict(n, promoters, passives, detractors, nps, moe, se) in NPS points (-100..100)."""
    n = len(scores)
    if n == 0:
        return {"n": 0, "promoters": 0, "passives": 0, "detractors": 0, "nps": None, "moe": None, "se": None}
    c = Counter(bucket(s) for s in scores)
    p, d = c["promoter"] / n, c["detractor"] / n
    var = max(0.0, p + d - (p - d) ** 2)
    se = 100 * math.sqrt(var / n)
    return {"n": n, "promoters": c["promoter"], "passives": c["passive"], "detractors": c["detractor"],
            "nps": round(100 * (p - d), 1), "se": se, "moe": round(1.96 * se, 1)}

def diff_z(a, b):
    """z score of a - b for two independent NPS estimates (None if not computable)."""
    if not a["n"] or not b["n"]:
        return None
    sd = math.sqrt(a["se"] ** 2 + b["se"] ** 2)
    if sd == 0:
        return 0.0 if a["nps"] == b["nps"] else float("inf") * (1 if a["nps"] > b["nps"] else -1)
    return (a["nps"] - b["nps"]) / sd

def period_of(d, kind):
    return "%d-Q%d" % (d.year, (d.month - 1) // 3 + 1) if kind == "quarter" else "%d-%02d" % (d.year, d.month)

def load_rows(fh):
    rd = csv.DictReader(fh)
    cols = [c.strip() for c in (rd.fieldnames or [])]
    missing = [c for c in REQUIRED if c not in cols]
    if missing:
        raise ValueError("missing column(s): " + ", ".join(missing))
    rows = []
    for i, r in enumerate(rd, start=2):
        rows.append(({(k or "").strip(): (v or "").strip() for k, v in r.items()}, i))
    return rows, cols

def compile_themes(themes):
    out = OrderedDict()
    for name, words in themes.items():
        out[name] = re.compile(r"\b(" + "|".join(re.escape(w.lower()) for w in words) + r")", re.I)
    return out

def analyze(rows, themes=None, by=(), period="quarter", current=None, min_n=30):
    flags, valid, seen = [], [], set()
    for r, line in rows:
        rid = r.get("response_id", "")
        try:
            s = int(r.get("score", ""))
            if not 0 <= s <= 10: raise ValueError
            d = date.fromisoformat(r.get("date", ""))
        except ValueError:
            flags.append(("E01", "line %d" % line, "invalid score or date (score must be 0-10, date YYYY-MM-DD)")); continue
        if rid and rid in seen:
            flags.append(("N05", "line %d" % line, "duplicate response_id %s ignored (first answer kept)" % rid)); continue
        seen.add(rid)
        valid.append({"id": rid, "score": s, "period": period_of(d, period), "comment": r.get("comment", ""),
                      "seg": {b: (r.get(b) or "(blank)") for b in by}})
    periods = sorted({v["period"] for v in valid})
    if current is None and periods:
        current = periods[-1]
    prev = None
    if current in periods and periods.index(current) > 0:
        prev = periods[periods.index(current) - 1]
    cur_rows = [v for v in valid if v["period"] == current]
    overall = nps_stats([v["score"] for v in cur_rows])
    by_period = OrderedDict((p, nps_stats([v["score"] for v in valid if v["period"] == p])) for p in periods)
    if overall["n"] and overall["n"] < min_n:
        flags.append(("N01", "overall " + str(current), "only %d responses: margin of error +/-%.0f points" % (overall["n"], overall["moe"])))
    change = None
    if prev:
        z = diff_z(overall, by_period[prev])
        change = {"previous": prev, "previous_nps": by_period[prev]["nps"], "delta": round(overall["nps"] - by_period[prev]["nps"], 1),
                  "z": None if z is None else round(z, 2), "significant": z is not None and abs(z) >= 1.96}
        if change["significant"] and change["delta"] < 0:
            flags.append(("N03", "%s vs %s" % (current, prev), "NPS fell %.1f points (%+.1f -> %+.1f), larger than the noise (z %.2f)" % (-change["delta"], by_period[prev]["nps"], overall["nps"], z)))
    segments = []
    for b in by:
        for val in sorted({v["seg"][b] for v in cur_rows}):
            inside = [v["score"] for v in cur_rows if v["seg"][b] == val]
            rest = [v["score"] for v in cur_rows if v["seg"][b] != val]
            st, rs = nps_stats(inside), nps_stats(rest)
            z = diff_z(st, rs) if rest else None
            row = {"by": b, "value": val, "z_vs_rest": None if z is None else round(z, 2)}
            row.update({k: st[k] for k in ("n", "promoters", "passives", "detractors", "nps", "moe")})
            segments.append(row)
            where = "%s=%s" % (b, val)
            if st["n"] < min_n:
                flags.append(("N01", where, "only %d responses: NPS %+.0f +/-%.0f is a hint, not a result" % (st["n"], st["nps"], st["moe"])))
            elif z is not None and z <= -1.96:
                flags.append(("N02", where, "NPS %+.1f is clearly below the rest (%+.1f, z %.2f)" % (st["nps"], rs["nps"], z)))
    theme_rows = []
    if themes:
        rx = compile_themes(themes)
        groups = {"promoter": [], "passive": [], "detractor": []}
        for v in cur_rows:
            if v["comment"]:
                groups[bucket(v["score"])].append(v)
        for name, r in rx.items():
            hits = {g: [v for v in groups[g] if r.search(v["comment"])] for g in groups}
            nd, npm = len(groups["detractor"]), len(groups["promoter"])
            sd = len(hits["detractor"]) / nd if nd else 0.0
            sp = len(hits["promoter"]) / npm if npm else 0.0
            quote = hits["detractor"][0]["comment"] if hits["detractor"] else (hits["promoter"][0]["comment"] if hits["promoter"] else "")
            row = {"theme": name, "mentions": sum(len(h) for h in hits.values()), "detractor_mentions": len(hits["detractor"]),
                   "promoter_mentions": len(hits["promoter"]), "detractor_share_pct": round(100 * sd, 1),
                   "promoter_share_pct": round(100 * sp, 1), "example": (quote[:90] + "...") if len(quote) > 90 else quote}
            theme_rows.append(row)
            if len(hits["detractor"]) >= 3 and sd >= 0.2 and sd >= 2 * sp:
                flags.append(("N04", name, "in %.0f%% of detractor comments vs %.0f%% of promoter comments (%d mentions)" % (100 * sd, 100 * sp, len(hits["detractor"]))))
        theme_rows.sort(key=lambda t: (-t["detractor_mentions"], -t["mentions"]))
        commented = sum(len(g) for g in groups.values())
        uncoded = sum(1 for g in groups.values() for v in g if not any(r.search(v["comment"]) for r in rx.values()))
    else:
        commented = sum(1 for v in cur_rows if v["comment"]); uncoded = None
    order = {"N03": 0, "N02": 1, "N04": 2, "N01": 3, "N05": 4, "E01": 5}
    flags.sort(key=lambda f: order[f[0]])
    o = {k: overall[k] for k in ("n", "promoters", "passives", "detractors", "nps", "moe")}
    return {"current": current, "overall": o, "change": change,
            "by_period": [dict(period=p, n=s["n"], nps=s["nps"], moe=s["moe"]) for p, s in by_period.items()],
            "segments": segments, "themes": theme_rows, "comments": commented, "uncoded_comments": uncoded,
            "valid_responses": len(valid), "flags": [{"code": c, "where": w, "detail": d} for c, w, d in flags]}

def sgn(v):
    return "-" if v is None else "%+.1f" % v

def render(res, form):
    if form == "json":
        return json.dumps(res, indent=2)
    md = form == "md"
    o, L = res["overall"], []
    L.append(("## NPS %s\n" % res["current"]) if md else "NPS %s" % res["current"])
    L.append("NPS %s +/-%s (95%%) from %d responses: %d promoters, %d passives, %d detractors" % (sgn(o["nps"]), o["moe"], o["n"], o["promoters"], o["passives"], o["detractors"]))
    c = res["change"]
    if c:
        L.append("Change vs %s: %s -> %s = %s points (%s)" % (c["previous"], sgn(c["previous_nps"]), sgn(o["nps"]), sgn(c["delta"]), "larger than the noise" if c["significant"] else "within the noise"))
    L.append("Trend: " + ", ".join("%s %s (n %d)" % (p["period"], sgn(p["nps"]), p["n"]) for p in res["by_period"]))
    if res["segments"]:
        L.append("")
        if md:
            L += ["| Segment | n | NPS | +/- | vs rest (z) |", "|---|---|---|---|---|"]
            L += ["| %s=%s | %d | %s | %s | %s |" % (s["by"], s["value"], s["n"], sgn(s["nps"]), s["moe"], "-" if s["z_vs_rest"] is None else s["z_vs_rest"]) for s in res["segments"]]
        else:
            L.append("%-26s %5s %7s %6s %8s" % ("SEGMENT", "N", "NPS", "+/-", "Z_REST"))
            L += ["%-26s %5d %7s %6s %8s" % ((s["by"] + "=" + s["value"])[:26], s["n"], sgn(s["nps"]), s["moe"], "-" if s["z_vs_rest"] is None else s["z_vs_rest"]) for s in res["segments"]]
    if res["themes"]:
        L.append("")
        L.append(("### Themes" if md else "THEMES") + " (%d comments, %d not matched by any theme)" % (res["comments"], res["uncoded_comments"]))
        if md:
            L += ["| Theme | Detractor | Promoter | Share of detractor comments | Example |", "|---|---|---|---|---|"]
            L += ["| %s | %d | %d | %.0f%% | %s |" % (t["theme"], t["detractor_mentions"], t["promoter_mentions"], t["detractor_share_pct"], t["example"].replace("|", "/")) for t in res["themes"]]
        else:
            L += ["%-14s det %2d  pro %2d  (%4.0f%% of detractor comments)  \"%s\"" % (t["theme"][:14], t["detractor_mentions"], t["promoter_mentions"], t["detractor_share_pct"], t["example"]) for t in res["themes"]]
    L.append("")
    L.append(("### Flags" if md else "FLAGS") + " (%d)" % len(res["flags"]))
    L += [("- **%s** %s: %s" if md else "%s  %s  %s") % (f["code"], f["where"], f["detail"]) for f in res["flags"]] or ["none"]
    return "\n".join(L) + "\n"

def self_test():
    ok = [0, 0]
    def check(name, cond):
        ok[0] += 1; ok[1] += bool(cond)
        print(("PASS  " if cond else "FAIL  ") + name)
    check("buckets 0-6 / 7-8 / 9-10", [bucket(x) for x in (0, 6, 7, 8, 9, 10)] == ["detractor"] * 2 + ["passive"] * 2 + ["promoter"] * 2)
    s = nps_stats([10] * 5 + [8] * 3 + [3] * 2)
    check("NPS 50% - 20% = +30", s["nps"] == 30.0 and s["promoters"] == 5 and s["detractors"] == 2)
    check("margin of error formula", abs(s["moe"] - round(1.96 * 100 * math.sqrt((0.5 + 0.2 - 0.09) / 10), 1)) < 1e-9)
    check("all promoters: NPS 100, moe 0", nps_stats([9, 10, 10])["nps"] == 100.0 and nps_stats([9, 10, 10])["moe"] == 0.0)
    check("empty -> None", nps_stats([])["nps"] is None)
    check("periods", period_of(date(2026, 11, 28), "quarter") == "2026-Q4" and period_of(date(2026, 2, 1), "month") == "2026-02")
    def mk(rows):
        return [({"response_id": str(i), "date": d, "score": str(sc), "plan": p, "comment": c}, i + 2) for i, (d, sc, p, c) in enumerate(rows)]
    q3 = [("2026-08-01", 10, "Team", "love it, easy to use")] * 40 + [("2026-08-02", 8, "Team", "")] * 10 + [("2026-08-03", 4, "Team", "too expensive")] * 10
    q4 = [("2026-11-01", 10, "Team", "easy and fast")] * 20 + [("2026-11-01", 8, "Team", "")] * 10 + \
         [("2026-11-02", 3, "Enterprise", "very slow since the update")] * 20 + [("2026-11-02", 9, "Enterprise", "great support")] * 5 + \
         [("2026-11-03", 5, "Team", "price is too high")] * 5
    themes = {"performance": ["slow", "lag", "loading"], "pricing": ["expensive", "price"], "ease of use": ["easy", "intuitive"]}
    res = analyze(mk(q3 + q4), themes=themes, by=["plan"], min_n=20)
    codes = {(f["code"], f["where"]) for f in res["flags"]}
    check("current period is the latest", res["current"] == "2026-Q4" and res["overall"]["n"] == 60)
    check("Q3 NPS +50, Q4 NPS +0", res["by_period"][0]["nps"] == 50.0 and res["overall"]["nps"] == 0.0)
    check("N03 significant drop", ("N03", "2026-Q4 vs 2026-Q3") in codes and res["change"]["significant"])
    check("N02 Enterprise below the rest", ("N02", "plan=Enterprise") in codes)
    check("no N02 for Team", not any(c == "N02" and w == "plan=Team" for c, w in codes))
    check("N04 performance theme", ("N04", "performance") in codes)
    check("ease of use is not a detractor theme", ("N04", "ease of use") not in codes)
    check("themes sorted by detractor mentions", res["themes"][0]["theme"] == "performance")
    small = analyze(mk(q4[:12]), by=["plan"], min_n=30)
    check("N01 small sample overall and segment", sum(1 for f in small["flags"] if f["code"] == "N01") >= 2)
    stable = analyze(mk([("2026-08-01", 10, "Team", "")] * 30 + [("2026-08-01", 3, "Team", "")] * 10 + [("2026-11-01", 10, "Team", "")] * 28 + [("2026-11-01", 3, "Team", "")] * 12), min_n=20)
    check("small change within the noise: no N03", stable["change"]["delta"] == -10.0 and not stable["change"]["significant"] and not stable["flags"])
    bad = analyze([({"response_id": "a", "date": "2026-11-01", "score": "11"}, 2), ({"response_id": "b", "date": "28.11.2026", "score": "5"}, 3),
                   ({"response_id": "c", "date": "2026-11-01", "score": "9"}, 4), ({"response_id": "c", "date": "2026-11-02", "score": "0"}, 5)], min_n=1)
    check("E01 invalid score and date", sum(1 for f in bad["flags"] if f["code"] == "E01") == 2)
    check("N05 duplicate id, first answer kept", any(f["code"] == "N05" for f in bad["flags"]) and bad["overall"]["nps"] == 100.0)
    import io
    try:
        load_rows(io.StringIO("id,score\n1,9\n")); check("missing columns raise", False)
    except ValueError:
        check("missing columns raise", True)
    rows, cols = load_rows(io.StringIO("response_id,date,score,comment\n1,2026-11-01,9,\"great, fast\"\n"))
    check("csv with quoted comma", rows[0][0]["comment"] == "great, fast")
    check("json render parses", json.loads(render(res, "json"))["overall"]["nps"] == 0.0)
    check("md render has segment table", "| Segment | n | NPS" in render(res, "md"))
    check("text render shows change", "within the noise" in render(stable, "text") and "larger than the noise" in render(res, "text"))
    print("%d/%d checks passed" % (ok[1], ok[0]))
    return 0 if ok[0] == ok[1] else 1

def main(argv=None):
    a = argparse.ArgumentParser(description="NPS with margins of error, trend, segments and comment themes.")
    a.add_argument("csv", nargs="?")
    a.add_argument("--themes", help="JSON file {\"theme\": [\"keyword\", ...]}")
    a.add_argument("--by", action="append", default=[], help="segment column (repeatable)")
    a.add_argument("--period", choices=["quarter", "month"], default="quarter")
    a.add_argument("--current", help="period to report, e.g. 2026-Q4 or 2026-11 (default: latest)")
    a.add_argument("--min-n", type=int, default=30, help="responses needed before a group counts as a result (default 30)")
    a.add_argument("--format", choices=["text", "md", "json"], default="text")
    a.add_argument("--self-test", action="store_true")
    o = a.parse_args(argv)
    if o.self_test:
        return self_test()
    if not o.csv:
        a.print_usage(sys.stderr); return 2
    try:
        with open(o.csv, newline="", encoding="utf-8-sig") as fh:
            rows, cols = load_rows(fh)
        themes = json.load(open(o.themes, encoding="utf-8")) if o.themes else None
    except (OSError, ValueError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    unknown = [b for b in o.by if b not in cols]
    if unknown:
        print("error: unknown segment column(s): %s" % ", ".join(unknown), file=sys.stderr); return 2
    res = analyze(rows, themes, o.by, o.period, o.current, o.min_n)
    if not res["overall"]["n"]:
        print("error: no valid responses for period %s" % res["current"], file=sys.stderr); return 2
    sys.stdout.write(render(res, o.format))
    return 1 if res["flags"] else 0

if __name__ == "__main__":
    sys.exit(main())
QualitativeBusinessData Analysis+5
F@f
0
HTTP Access Log Latency and Error Analyzer
Skill

Finds the slow and failing endpoints in Nginx, Apache or JSON access logs: groups requests into routes, computes p50/p95/p99 latency and 4xx/5xx rates per route, spots 5xx spike minutes and long tails, and flags routes that break a latency target or error budget. Stdlib Python.

---
name: http-access-log-latency-and-error-analyzer
description: Finds the slow and failing endpoints in Nginx, Apache or JSON access logs: groups requests into routes, computes p50/p95/p99 latency and 4xx/5xx rates per route, spots 5xx spike minutes and long tails, and flags routes that break a latency target or error budget. Stdlib Python.
---

# HTTP Access Log Latency and Error Analyzer

You help developers, SREs and on-call engineers answer "which endpoints are slow or failing, since when, and how badly?" straight from the web server's access log, without a metrics stack. Averages hide problems, so you work with percentiles per route, compare them with a latency target and an error budget, and point at the exact minutes and requests worth investigating.

You only read log files the user provides. Access logs contain IP addresses and sometimes user ids or tokens in query strings: keep the analysis local, quote only routes (query strings are dropped by the script) and never paste full raw lines with personal data into tickets or chats.

## Files in this skill

- `scripts/access_log.py` - parses Nginx/Apache combined lines with a trailing request time, or JSON lines; groups requests into routes (`/api/orders/123?x=1` -> `GET /api/orders/:id`), computes count, share, 4xx/5xx rates and p50/p90/p95/p99/max per route, 5xx spike minutes and the slowest requests, and prints flags L01-L06 + E01; `--format text|md|csv|json`; `--self-test` runs 26 checks (Python 3.8+ standard library only)
- `references/log-formats.md` - how to make Nginx, Apache, Caddy, Traefik and load balancers log request time, and which formats the script reads
- `references/latency-triage.md` - how to read percentiles, what each flag usually means, and the next diagnostic step for each
- `templates/latency-report.md` - a short incident or weekly performance note
- `examples/access.log` + `examples/app.jsonl` - a fictional bookshop API during a ten-minute window with a checkout incident

## Workflow

### 1. Get the right log
Ask which server writes the log and for the time window that matters (an incident, a release, a busy hour). Check that every line ends with a request time; if not, help the user add it first (`references/log-formats.md`) or run anyway and accept that only status codes are analyzed (flag L06). Agree the targets: a p95 latency target per route (default 500 ms) and a 5xx budget (default 1%). For rotated logs pass several files at once; for gzip files use `zcat access.log.*.gz > window.log` first.

### 2. Run the analysis
```
python3 scripts/access_log.py /var/log/nginx/access.log
python3 scripts/access_log.py access.log --slo-ms 300 --error-pct 0.5 --min-count 50
python3 scripts/access_log.py access.log --time-unit us            # Apache %D (microseconds)
python3 scripts/access_log.py app.jsonl --group-by path --top 0    # exact paths, all routes
python3 scripts/access_log.py access.log --format md > latency.md
python3 scripts/access_log.py access.log --format csv > routes.csv
python3 scripts/access_log.py --self-test
```
Exit code 0 = no flags, 1 = flags present, 2 = unreadable file or no parsable lines.

| Code | Meaning |
|---|---|
| L01 | route p95 is above the latency target (`--slo-ms`) |
| L02 | route 5xx rate is at or above the error budget (`--error-pct`) |
| L03 | route 4xx rate is at or above `--client-error-pct` (broken links, auth, validation, scanners) |
| L04 | a minute with a 5xx spike (at least 5% and 3x the overall 5xx rate, 10+ requests) |
| L05 | long tail: p99 is 5x p50 or more and above the target |
| L06 | no request time in the log, latency cannot be measured |
| E01 | lines that could not be parsed (TLS garbage, a different format, truncated lines) |

Route flags (L01-L03, L05) need at least `--min-count` requests (default 20) so rare routes do not create noise; lower it for short windows.

### 3. Interpret
- Read p95 and p99, not the average: a route with p50 160 ms and p99 3.2 s has a tail problem (one slow dependency, cache misses, lock waits), not a generally slow handler.
- Check whether slow and failing coincide: requests that end in 502 or 504 after about the same time point at an upstream timeout.
- Weight by traffic share: a slow admin report used ten times a day matters less than a 200 ms regression on the product page.
- 4xx on unknown paths like `/wp-login.php` or `/.env` are usually scanners: block or rate limit them rather than debug them.
- Confirm a spike minute against deploys, cron jobs and dependency status before naming a cause.

### 4. Act
Use `references/latency-triage.md` for the next step per flag (tracing a slow route, checking upstream timeouts, connection pools, caching, N+1 queries). Re-run on a log window after the fix and compare the route rows.

### 5. Report
Fill `templates/latency-report.md`: window, overall numbers, the routes that break the target, spike minutes, suspected cause, the fix and the follow-up check.

## Example
```
python3 scripts/access_log.py examples/access.log
```
Result: 222 requests in 10 minutes (1 unparsable TLS line), overall p50 63 ms, p95 914 ms, 5xx 1.8%. `POST /api/checkout` has 17.4% server errors, all four 502s at 14:07 after about 5-6 s (an upstream payment timeout pattern), and p95 5.7 s; `GET /api/search` has p50 160 ms but p95 2.7 s and p99 3.2 s, a long tail; product pages stay at p95 73 ms. Scanner hits on `/wp-login.php`, `/xmlrpc.php` and `/.env` return 404 and are below the flag threshold.

## Limits
- Access logs show what the server saw: time spent in the browser, CDN or client network is not included.
- Percentiles from small samples are unstable; treat routes with few requests as hints.
- Route grouping replaces numbers, UUIDs and long hex strings; slugs such as `/blog/my-post` stay separate (use your framework's route names in JSON logs if you need exact grouping).
- The script does not know your deploy history or dependencies; causes must be confirmed with traces, metrics or application logs.

FILE:references/log-formats.md
# Access log formats and how to log request time

`scripts/access_log.py` reads two kinds of lines and detects them per line, so mixed files work.

## 1. Combined (or common) format with a trailing request time
```
203.0.113.9 - - [27/Nov/2026:14:07:41 +0300] "POST /api/checkout HTTP/1.1" 502 180 "-" "Mozilla/5.0" 5.412
```
The last field is the request time. Default unit is seconds (`--time-unit s`); use `--time-unit ms` or `--time-unit us` for other servers. Lines without a trailing number still count for status codes and traffic, but have no latency (flag L06 if no line has one).

### Nginx
```
log_format timed '$remote_addr - $remote_user [$time_local] "$request" '
                 '$status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time';
access_log /var/log/nginx/access.log timed;
```
`$request_time` is the full time from the first client byte to the last byte sent, in seconds with millisecond resolution. `$upstream_response_time` is only the time the backend took; log it as an extra field before `$request_time` if you want to compare them by hand (the script always reads the last field).

### Apache httpd
```
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %D" timed
CustomLog logs/access_log timed
```
`%D` is microseconds: run the script with `--time-unit us`. `%T` is whole seconds and too coarse for latency work.

### Caddy, Traefik, cloud load balancers
- Caddy writes JSON logs by default; convert them to JSON lines with `method`, `path`, `status` and `duration_ms` (Caddy's `duration` is seconds: multiply by 1000), for example with `jq -c '{time: (.ts|todate), method: .request.method, path: .request.uri, status, duration_ms: (.duration*1000)}'`.
- Traefik: enable `accessLog` with `format: json` and map `Duration` (nanoseconds) to `duration_ms`.
- AWS ALB, GCP and Azure load balancers use their own formats; export the method, path, status and total time fields into JSON lines.

## 2. JSON lines
One JSON object per line:
```
{"time": "2026-11-27T14:06:30+03:00", "method": "POST", "path": "/api/orders/5006/refund", "status": 500, "duration_ms": 2140, "bytes": 120}
```
Required: `method`, `path`, `status`. Latency from `duration_ms`, `request_time_ms` or `request_time` (seconds). `time` (ISO 8601) enables spike minutes. If your framework logs a route template (for example `/api/orders/{id}`), put it in `path` and run with `--group-by path` for exact grouping.

## Time zones and windows
Spike minutes use the time as written in the log, including its offset. Cut the window before running (for example `awk '/27\/Nov\/2026:14:0/' access.log > window.log`) so the overall numbers describe the period you care about.

## Privacy
Access logs hold IP addresses and sometimes tokens or emails in query strings. The script drops query strings from routes, but the "slowest requests" list shows full targets; redact them before sharing a report outside the team.

FILE:references/latency-triage.md
# Reading the results and what to do next

## Percentiles in one minute
- p50 = the typical request; p95 = 1 in 20 requests is slower; p99 = 1 in 100. Users who click often hit the p95/p99 several times a session.
- The script uses nearest-rank percentiles: with 40 requests, p95 is the 38th fastest request. Below about 100 requests per route, p99 is just the slowest one or two requests.
- Compare windows of the same length and similar traffic; a quiet night and a sale hour are not comparable.

## Flags and the next step
| Flag | Usual causes | Next step |
|---|---|---|
| L01 p95 above target | slow database queries, missing indexes, N+1 queries, large responses, cold caches, CPU saturation | trace a few of the slowest requests; check query counts and response size; compare with the previous release |
| L02 5xx over budget | crashes, upstream errors (502), timeouts (504), overload (503) | group the errors by status and minute; read application logs for the same minutes; check recent deploys and dependency status pages |
| L03 many 4xx | broken links (404), expired sessions (401), permission changes (403), validation errors (400/422), scanners | look at the paths and user agents; fix links or clients; rate limit or block scanner paths |
| L04 5xx spike minute | deploy or restart, cron job, failing dependency, traffic burst | line the minute up with deploy logs, cron schedules and upstream incidents |
| L05 long tail | one slow dependency on some requests, lock contention, garbage collection pauses, retries, cache misses | split the route by parameters (for example search terms) in the raw lines; add timing logs around external calls |
| L06 no latency | the log format has no request time | add `$request_time` or `%D` (see `log-formats.md`) |
| E01 unparsable | TLS handshakes on the HTTP port, other vhosts with another format, truncated lines | check a few lines; a handful is normal |

## Patterns worth recognizing
- Errors that all take about the same long time (for example 5-6 s or 30 s) usually mean an upstream timeout: check the proxy and client timeout settings and the dependency itself.
- Fast errors (a few ms) mean the request was rejected early: auth, validation, rate limiting or a crashing handler.
- p50 up for every route at once points at shared infrastructure (database, CPU, network), not at one handler.
- A slow route with a tiny share of traffic can wait; a 20 percent regression on the busiest route usually cannot.

## Setting targets
Start with what users notice: about 200-300 ms p95 for API reads behind interactive pages, 500-1000 ms for writes such as checkout, longer for reports and exports. Agree per route group and write them down next to the error budget (for example 99.5 percent non-5xx per 30 days). Pass them with `--slo-ms` and `--error-pct`, or run the script per route group with different settings.

FILE:templates/latency-report.md
# Latency and error report: {{service}} ({{window}})

Prepared by: {{author}} | Log source: {{log_source}} | Targets: p95 <= {{slo_ms}} ms, 5xx < {{error_pct}}%

## Summary
- Requests: {{requests}} | Overall p50 / p95 / p99: {{p50}} / {{p95}} / {{p99}} ms | 5xx: {{rate_5xx}}%
- Verdict: {{verdict}} (within targets / degraded / incident)

## Routes outside the targets
| Route | Share | p95 | p99 | 5xx | Flag |
|---|---|---|---|---|---|
| {{route}} | {{share}} | {{p95_route}} | {{p99_route}} | {{rate_5xx_route}} | {{flag}} |

## Spike minutes
- {{minute}}: {{errors}} of {{requests_minute}} requests failed ({{rate}}%). Matching event: {{event}}

## Cause
- Confirmed: {{confirmed_cause}}
- Suspected, still to check: {{suspected_cause}}

## Actions
| Action | Owner | Due | Done when |
|---|---|---|---|
| {{action}} | {{owner}} | {{due}} | {{done_when}} |

## Follow-up check
Re-run `access_log.py` on {{followup_window}} and compare these routes: {{routes_to_compare}}.

FILE:examples/access.log
203.0.113.30 - - [27/Nov/2026:14:00:00 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 3058 "-" "Mozilla/5.0" 0.206
203.0.113.29 - - [27/Nov/2026:14:00:01 +0300] "GET /api/products/247 HTTP/1.1" 200 1273 "-" "Mozilla/5.0" 0.067
203.0.113.19 - - [27/Nov/2026:14:00:02 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.081
203.0.113.12 - - [27/Nov/2026:14:00:04 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 3779 "-" "Mozilla/5.0" 2.551
203.0.113.7 - - [27/Nov/2026:14:00:12 +0300] "GET /api/products/594 HTTP/1.1" 200 1449 "-" "Mozilla/5.0" 0.039
203.0.113.36 - - [27/Nov/2026:14:00:14 +0300] "GET /api/products/862 HTTP/1.1" 200 1634 "-" "Mozilla/5.0" 0.023
203.0.113.15 - - [27/Nov/2026:14:00:20 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.079
203.0.113.19 - - [27/Nov/2026:14:00:23 +0300] "GET /api/search?q=dune HTTP/1.1" 200 3506 "-" "Mozilla/5.0" 0.199
203.0.113.30 - - [27/Nov/2026:14:00:23 +0300] "POST /api/login HTTP/1.1" 401 90 "-" "Mozilla/5.0" 0.124
203.0.113.31 - - [27/Nov/2026:14:00:24 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.8 - - [27/Nov/2026:14:00:24 +0300] "GET /api/products/468 HTTP/1.1" 200 2023 "-" "Mozilla/5.0" 0.067
203.0.113.10 - - [27/Nov/2026:14:00:26 +0300] "GET /api/products/530 HTTP/1.1" 200 2156 "-" "Mozilla/5.0" 0.037
203.0.113.30 - - [27/Nov/2026:14:00:29 +0300] "GET /api/products/217 HTTP/1.1" 200 1095 "-" "Mozilla/5.0" 0.074
203.0.113.31 - - [27/Nov/2026:14:00:33 +0300] "GET /api/products/226 HTTP/1.1" 200 1364 "-" "Mozilla/5.0" 0.068
203.0.113.18 - - [27/Nov/2026:14:00:34 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.633
203.0.113.35 - - [27/Nov/2026:14:00:35 +0300] "GET /api/search?q=silo HTTP/1.1" 200 5195 "-" "Mozilla/5.0" 0.201
203.0.113.28 - - [27/Nov/2026:14:00:38 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.063
203.0.113.8 - - [27/Nov/2026:14:00:38 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.32 - - [27/Nov/2026:14:00:42 +0300] "GET /api/products/440 HTTP/1.1" 200 2174 "-" "Mozilla/5.0" 0.031
203.0.113.34 - - [27/Nov/2026:14:00:49 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.154
203.0.113.11 - - [27/Nov/2026:14:00:56 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.867
203.0.113.19 - - [27/Nov/2026:14:00:57 +0300] "GET /api/products/364 HTTP/1.1" 200 1535 "-" "Mozilla/5.0" 0.054
203.0.113.32 - - [27/Nov/2026:14:01:03 +0300] "GET /api/products/866 HTTP/1.1" 200 972 "-" "Mozilla/5.0" 0.069
203.0.113.38 - - [27/Nov/2026:14:01:03 +0300] "GET /api/search?q=silo HTTP/1.1" 200 8586 "-" "Mozilla/5.0" 0.218
203.0.113.9 - - [27/Nov/2026:14:01:04 +0300] "GET /api/search?q=cookbook HTTP/1.1" 200 7337 "-" "Mozilla/5.0" 0.205
203.0.113.20 - - [27/Nov/2026:14:01:09 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.043
203.0.113.14 - - [27/Nov/2026:14:01:13 +0300] "GET /api/products/402 HTTP/1.1" 200 1613 "-" "Mozilla/5.0" 0.046
203.0.113.21 - - [27/Nov/2026:14:01:19 +0300] "GET /api/products/890 HTTP/1.1" 200 2173 "-" "Mozilla/5.0" 0.052
203.0.113.18 - - [27/Nov/2026:14:01:21 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.669
203.0.113.7 - - [27/Nov/2026:14:01:26 +0300] "GET /api/products/887 HTTP/1.1" 200 1163 "-" "Mozilla/5.0" 0.037
203.0.113.8 - - [27/Nov/2026:14:01:30 +0300] "GET /api/products/289 HTTP/1.1" 200 1027 "-" "Mozilla/5.0" 0.041
203.0.113.29 - - [27/Nov/2026:14:01:31 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.081
203.0.113.34 - - [27/Nov/2026:14:01:31 +0300] "GET /api/search?q=silo HTTP/1.1" 200 6323 "-" "Mozilla/5.0" 2.565
203.0.113.30 - - [27/Nov/2026:14:01:34 +0300] "GET /api/products/343 HTTP/1.1" 200 1821 "-" "Mozilla/5.0" 0.057
203.0.113.9 - - [27/Nov/2026:14:01:34 +0300] "GET /api/products/545 HTTP/1.1" 200 1119 "-" "Mozilla/5.0" 0.020
203.0.113.15 - - [27/Nov/2026:14:01:36 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 3632 "-" "Mozilla/5.0" 0.158
203.0.113.33 - - [27/Nov/2026:14:01:38 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.056
203.0.113.14 - - [27/Nov/2026:14:01:39 +0300] "GET /api/products/872 HTTP/1.1" 200 976 "-" "Mozilla/5.0" 0.065
203.0.113.13 - - [27/Nov/2026:14:01:40 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.878
203.0.113.6 - - [27/Nov/2026:14:01:40 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.002
203.0.113.30 - - [27/Nov/2026:14:01:45 +0300] "GET /api/products/185 HTTP/1.1" 200 1629 "-" "Mozilla/5.0" 0.064
203.0.113.22 - - [27/Nov/2026:14:01:51 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.003
203.0.113.14 - - [27/Nov/2026:14:02:03 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 6697 "-" "Mozilla/5.0" 0.094
203.0.113.8 - - [27/Nov/2026:14:02:06 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.786
203.0.113.38 - - [27/Nov/2026:14:02:08 +0300] "GET /api/products/415 HTTP/1.1" 200 1272 "-" "Mozilla/5.0" 0.064
203.0.113.13 - - [27/Nov/2026:14:02:10 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.047
203.0.113.18 - - [27/Nov/2026:14:02:10 +0300] "GET /api/products/452 HTTP/1.1" 200 908 "-" "Mozilla/5.0" 0.045
203.0.113.27 - - [27/Nov/2026:14:02:10 +0300] "GET /api/products/729 HTTP/1.1" 200 2011 "-" "Mozilla/5.0" 0.052
203.0.113.5 - - [27/Nov/2026:14:02:10 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.005
203.0.113.10 - - [27/Nov/2026:14:02:13 +0300] "GET /api/products/653 HTTP/1.1" 200 1808 "-" "Mozilla/5.0" 0.055
203.0.113.31 - - [27/Nov/2026:14:02:15 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.148
203.0.113.30 - - [27/Nov/2026:14:02:16 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.049
203.0.113.25 - - [27/Nov/2026:14:02:17 +0300] "GET /api/products/679 HTTP/1.1" 200 2112 "-" "Mozilla/5.0" 0.035
203.0.113.25 - - [27/Nov/2026:14:02:17 +0300] "GET /api/products/963 HTTP/1.1" 200 1469 "-" "Mozilla/5.0" 0.024
203.0.113.12 - - [27/Nov/2026:14:02:22 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 4290 "-" "Mozilla/5.0" 0.218
203.0.113.38 - - [27/Nov/2026:14:02:30 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.681
203.0.113.22 - - [27/Nov/2026:14:02:31 +0300] "GET /api/search?q=silo HTTP/1.1" 200 6906 "-" "Mozilla/5.0" 0.144
203.0.113.77 - - [27/Nov/2026:14:03:12 +0300] "\x16\x03\x01\x00" 400 157 "-" "-"
203.0.113.17 - - [27/Nov/2026:14:02:37 +0300] "GET /api/search?q=cookbook HTTP/1.1" 200 5341 "-" "Mozilla/5.0" 0.175
203.0.113.39 - - [27/Nov/2026:14:02:43 +0300] "GET /api/products/210 HTTP/1.1" 200 1287 "-" "Mozilla/5.0" 0.041
203.0.113.22 - - [27/Nov/2026:14:02:47 +0300] "GET /api/products/412 HTTP/1.1" 200 2007 "-" "Mozilla/5.0" 0.024
203.0.113.39 - - [27/Nov/2026:14:02:48 +0300] "GET /api/products/681 HTTP/1.1" 200 1777 "-" "Mozilla/5.0" 0.043
203.0.113.33 - - [27/Nov/2026:14:02:49 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.057
203.0.113.29 - - [27/Nov/2026:14:02:52 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.143
203.0.113.17 - - [27/Nov/2026:14:02:59 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.003
203.0.113.38 - - [27/Nov/2026:14:03:00 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.048
203.0.113.35 - - [27/Nov/2026:14:03:01 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.691
203.0.113.12 - - [27/Nov/2026:14:03:06 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.802
203.0.113.25 - - [27/Nov/2026:14:03:09 +0300] "GET /api/search?q=cookbook HTTP/1.1" 200 5078 "-" "Mozilla/5.0" 0.149
203.0.113.21 - - [27/Nov/2026:14:03:11 +0300] "GET /api/products/676 HTTP/1.1" 200 1190 "-" "Mozilla/5.0" 0.068
203.0.113.30 - - [27/Nov/2026:14:03:13 +0300] "GET /api/products/946 HTTP/1.1" 200 1083 "-" "Mozilla/5.0" 0.065
203.0.113.27 - - [27/Nov/2026:14:03:14 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.060
203.0.113.38 - - [27/Nov/2026:14:03:14 +0300] "GET /api/products/209 HTTP/1.1" 200 1911 "-" "Mozilla/5.0" 0.075
203.0.113.10 - - [27/Nov/2026:14:03:15 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.002
203.0.113.17 - - [27/Nov/2026:14:03:16 +0300] "GET /api/products/465 HTTP/1.1" 200 1938 "-" "Mozilla/5.0" 0.039
203.0.113.17 - - [27/Nov/2026:14:03:20 +0300] "GET /api/search?q=cookbook HTTP/1.1" 200 6520 "-" "Mozilla/5.0" 0.151
203.0.113.12 - - [27/Nov/2026:14:03:24 +0300] "GET /wp-login.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.18 - - [27/Nov/2026:14:03:25 +0300] "GET /api/search?q=dune HTTP/1.1" 200 6928 "-" "Mozilla/5.0" 0.093
203.0.113.38 - - [27/Nov/2026:14:03:26 +0300] "GET /api/products/906 HTTP/1.1" 200 1205 "-" "Mozilla/5.0" 0.070
203.0.113.20 - - [27/Nov/2026:14:03:29 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.37 - - [27/Nov/2026:14:03:35 +0300] "GET /api/search?q=silo HTTP/1.1" 200 4848 "-" "Mozilla/5.0" 0.206
203.0.113.29 - - [27/Nov/2026:14:03:37 +0300] "GET /api/products/107 HTTP/1.1" 200 1853 "-" "Mozilla/5.0" 0.046
203.0.113.17 - - [27/Nov/2026:14:03:39 +0300] "GET /api/products/694 HTTP/1.1" 200 2362 "-" "Mozilla/5.0" 0.042
203.0.113.9 - - [27/Nov/2026:14:03:40 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.069
203.0.113.19 - - [27/Nov/2026:14:03:43 +0300] "GET /api/products/890 HTTP/1.1" 200 2053 "-" "Mozilla/5.0" 0.021
203.0.113.21 - - [27/Nov/2026:14:03:45 +0300] "GET /api/products/287 HTTP/1.1" 200 1703 "-" "Mozilla/5.0" 0.023
203.0.113.7 - - [27/Nov/2026:14:03:49 +0300] "GET /xmlrpc.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.31 - - [27/Nov/2026:14:03:58 +0300] "GET /.env HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.11 - - [27/Nov/2026:14:04:03 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 8767 "-" "Mozilla/5.0" 0.113
203.0.113.28 - - [27/Nov/2026:14:04:03 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.174
203.0.113.10 - - [27/Nov/2026:14:04:11 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.030
203.0.113.15 - - [27/Nov/2026:14:04:13 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.724
203.0.113.28 - - [27/Nov/2026:14:04:15 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 7269 "-" "Mozilla/5.0" 0.130
203.0.113.28 - - [27/Nov/2026:14:04:19 +0300] "GET /.env HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.12 - - [27/Nov/2026:14:04:20 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.067
203.0.113.22 - - [27/Nov/2026:14:04:20 +0300] "GET /api/products/268 HTTP/1.1" 200 1504 "-" "Mozilla/5.0" 0.046
203.0.113.16 - - [27/Nov/2026:14:04:30 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.002
203.0.113.25 - - [27/Nov/2026:14:04:32 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.062
203.0.113.20 - - [27/Nov/2026:14:04:34 +0300] "GET /api/products/915 HTTP/1.1" 200 1459 "-" "Mozilla/5.0" 0.021
203.0.113.15 - - [27/Nov/2026:14:04:36 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 7158 "-" "Mozilla/5.0" 2.711
203.0.113.21 - - [27/Nov/2026:14:04:37 +0300] "GET /xmlrpc.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.12 - - [27/Nov/2026:14:04:38 +0300] "GET /api/products/773 HTTP/1.1" 200 1042 "-" "Mozilla/5.0" 0.074
203.0.113.35 - - [27/Nov/2026:14:04:42 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.13 - - [27/Nov/2026:14:04:44 +0300] "GET /wp-login.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.25 - - [27/Nov/2026:14:04:47 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.841
203.0.113.15 - - [27/Nov/2026:14:04:49 +0300] "GET /api/products/547 HTTP/1.1" 200 1202 "-" "Mozilla/5.0" 0.073
203.0.113.8 - - [27/Nov/2026:14:04:49 +0300] "GET /api/products/660 HTTP/1.1" 200 935 "-" "Mozilla/5.0" 0.038
203.0.113.12 - - [27/Nov/2026:14:04:50 +0300] "GET /api/search?q=dune HTTP/1.1" 200 8341 "-" "Mozilla/5.0" 0.102
203.0.113.37 - - [27/Nov/2026:14:04:50 +0300] "GET /api/products/210 HTTP/1.1" 200 1589 "-" "Mozilla/5.0" 0.063
203.0.113.15 - - [27/Nov/2026:14:04:53 +0300] "GET /api/products/864 HTTP/1.1" 200 1718 "-" "Mozilla/5.0" 0.040
203.0.113.39 - - [27/Nov/2026:14:04:55 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.129
203.0.113.23 - - [27/Nov/2026:14:04:56 +0300] "GET /api/products/751 HTTP/1.1" 200 1922 "-" "Mozilla/5.0" 0.035
203.0.113.12 - - [27/Nov/2026:14:04:57 +0300] "GET /api/products/404 HTTP/1.1" 200 1495 "-" "Mozilla/5.0" 0.046
203.0.113.24 - - [27/Nov/2026:14:05:05 +0300] "GET /wp-login.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.35 - - [27/Nov/2026:14:05:09 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.043
203.0.113.33 - - [27/Nov/2026:14:05:20 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 8858 "-" "Mozilla/5.0" 1.611
203.0.113.24 - - [27/Nov/2026:14:05:22 +0300] "GET /xmlrpc.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.32 - - [27/Nov/2026:14:05:24 +0300] "GET /api/products/651 HTTP/1.1" 200 1887 "-" "Mozilla/5.0" 0.029
203.0.113.29 - - [27/Nov/2026:14:05:25 +0300] "GET /api/products/444 HTTP/1.1" 200 2215 "-" "Mozilla/5.0" 0.056
203.0.113.38 - - [27/Nov/2026:14:05:29 +0300] "GET /api/products/970 HTTP/1.1" 200 1910 "-" "Mozilla/5.0" 0.047
203.0.113.38 - - [27/Nov/2026:14:05:30 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.13 - - [27/Nov/2026:14:05:31 +0300] "GET /api/products/508 HTTP/1.1" 200 1583 "-" "Mozilla/5.0" 0.043
203.0.113.30 - - [27/Nov/2026:14:05:31 +0300] "GET /api/products/356 HTTP/1.1" 200 1223 "-" "Mozilla/5.0" 0.070
203.0.113.18 - - [27/Nov/2026:14:05:32 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 3374 "-" "Mozilla/5.0" 0.121
203.0.113.14 - - [27/Nov/2026:14:05:34 +0300] "GET /api/products/518 HTTP/1.1" 200 1305 "-" "Mozilla/5.0" 0.048
203.0.113.14 - - [27/Nov/2026:14:05:35 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 6801 "-" "Mozilla/5.0" 0.126
203.0.113.21 - - [27/Nov/2026:14:05:37 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.655
203.0.113.30 - - [27/Nov/2026:14:05:42 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.914
203.0.113.31 - - [27/Nov/2026:14:05:45 +0300] "GET /api/products/515 HTTP/1.1" 200 2005 "-" "Mozilla/5.0" 0.032
203.0.113.14 - - [27/Nov/2026:14:05:47 +0300] "GET /.env HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.24 - - [27/Nov/2026:14:05:49 +0300] "GET /api/products/748 HTTP/1.1" 200 1005 "-" "Mozilla/5.0" 0.028
203.0.113.38 - - [27/Nov/2026:14:05:52 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.090
203.0.113.13 - - [27/Nov/2026:14:05:53 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.002
203.0.113.18 - - [27/Nov/2026:14:05:54 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.089
203.0.113.20 - - [27/Nov/2026:14:05:55 +0300] "GET /api/products/805 HTTP/1.1" 200 1019 "-" "Mozilla/5.0" 0.032
203.0.113.9 - - [27/Nov/2026:14:05:58 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 7714 "-" "Mozilla/5.0" 0.134
203.0.113.6 - - [27/Nov/2026:14:06:05 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.056
203.0.113.8 - - [27/Nov/2026:14:06:06 +0300] "GET /api/products/663 HTTP/1.1" 200 1169 "-" "Mozilla/5.0" 0.034
203.0.113.7 - - [27/Nov/2026:14:06:07 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.005
203.0.113.14 - - [27/Nov/2026:14:06:09 +0300] "GET /api/products/501 HTTP/1.1" 200 1005 "-" "Mozilla/5.0" 0.035
203.0.113.31 - - [27/Nov/2026:14:06:09 +0300] "GET /api/products/622 HTTP/1.1" 200 1838 "-" "Mozilla/5.0" 0.045
203.0.113.38 - - [27/Nov/2026:14:06:10 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.148
203.0.113.8 - - [27/Nov/2026:14:06:15 +0300] "GET /api/products/526 HTTP/1.1" 200 1208 "-" "Mozilla/5.0" 0.043
203.0.113.27 - - [27/Nov/2026:14:06:23 +0300] "GET /api/products/784 HTTP/1.1" 200 980 "-" "Mozilla/5.0" 0.064
203.0.113.11 - - [27/Nov/2026:14:06:24 +0300] "GET /api/products/866 HTTP/1.1" 200 1171 "-" "Mozilla/5.0" 0.038
203.0.113.30 - - [27/Nov/2026:14:06:24 +0300] "GET /api/products/953 HTTP/1.1" 200 2340 "-" "Mozilla/5.0" 0.042
203.0.113.30 - - [27/Nov/2026:14:06:26 +0300] "GET /api/search?q=dune HTTP/1.1" 200 5446 "-" "Mozilla/5.0" 3.177
203.0.113.29 - - [27/Nov/2026:14:06:28 +0300] "POST /api/login HTTP/1.1" 401 90 "-" "Mozilla/5.0" 0.123
203.0.113.10 - - [27/Nov/2026:14:06:31 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.087
203.0.113.26 - - [27/Nov/2026:14:06:33 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.645
203.0.113.33 - - [27/Nov/2026:14:06:35 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.005
203.0.113.37 - - [27/Nov/2026:14:06:41 +0300] "GET /api/products/200 HTTP/1.1" 200 1293 "-" "Mozilla/5.0" 0.041
203.0.113.15 - - [27/Nov/2026:14:06:42 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.038
203.0.113.35 - - [27/Nov/2026:14:06:43 +0300] "GET /api/products/531 HTTP/1.1" 200 943 "-" "Mozilla/5.0" 0.034
203.0.113.22 - - [27/Nov/2026:14:06:46 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 5404 "-" "Mozilla/5.0" 0.127
203.0.113.14 - - [27/Nov/2026:14:06:49 +0300] "GET /api/search?q=dune HTTP/1.1" 200 4809 "-" "Mozilla/5.0" 1.899
203.0.113.9 - - [27/Nov/2026:14:06:52 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 8222 "-" "Mozilla/5.0" 0.143
203.0.113.23 - - [27/Nov/2026:14:06:58 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.639
203.0.113.12 - - [27/Nov/2026:14:07:02 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.583
203.0.113.26 - - [27/Nov/2026:14:07:03 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.069
203.0.113.39 - - [27/Nov/2026:14:07:05 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.006
203.0.113.15 - - [27/Nov/2026:14:07:08 +0300] "GET /api/search?q=dune HTTP/1.1" 200 5621 "-" "Mozilla/5.0" 0.209
203.0.113.20 - - [27/Nov/2026:14:07:12 +0300] "GET /api/products/812 HTTP/1.1" 200 1391 "-" "Mozilla/5.0" 0.064
203.0.113.25 - - [27/Nov/2026:14:07:14 +0300] "GET /api/products/725 HTTP/1.1" 200 1832 "-" "Mozilla/5.0" 0.046
203.0.113.7 - - [27/Nov/2026:14:07:15 +0300] "POST /api/checkout HTTP/1.1" 502 180 "-" "Mozilla/5.0" 5.749
203.0.113.39 - - [27/Nov/2026:14:07:17 +0300] "GET /api/products/110 HTTP/1.1" 200 2074 "-" "Mozilla/5.0" 0.073
203.0.113.39 - - [27/Nov/2026:14:07:21 +0300] "GET /api/search?q=dune HTTP/1.1" 200 7568 "-" "Mozilla/5.0" 0.160
203.0.113.28 - - [27/Nov/2026:14:07:27 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.006
203.0.113.37 - - [27/Nov/2026:14:07:27 +0300] "GET /api/products/625 HTTP/1.1" 200 1057 "-" "Mozilla/5.0" 0.032
203.0.113.26 - - [27/Nov/2026:14:07:37 +0300] "GET /api/products/217 HTTP/1.1" 200 2046 "-" "Mozilla/5.0" 0.021
203.0.113.32 - - [27/Nov/2026:14:07:39 +0300] "POST /api/checkout HTTP/1.1" 502 180 "-" "Mozilla/5.0" 5.107
203.0.113.25 - - [27/Nov/2026:14:07:41 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.062
203.0.113.34 - - [27/Nov/2026:14:07:42 +0300] "GET /api/search?q=silo HTTP/1.1" 200 3934 "-" "Mozilla/5.0" 0.152
203.0.113.12 - - [27/Nov/2026:14:07:44 +0300] "GET /api/products/185 HTTP/1.1" 200 1274 "-" "Mozilla/5.0" 0.039
203.0.113.18 - - [27/Nov/2026:14:07:47 +0300] "POST /api/checkout HTTP/1.1" 502 180 "-" "Mozilla/5.0" 5.665
203.0.113.23 - - [27/Nov/2026:14:07:48 +0300] "POST /api/checkout HTTP/1.1" 502 180 "-" "Mozilla/5.0" 5.248
203.0.113.29 - - [27/Nov/2026:14:07:49 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 3422 "-" "Mozilla/5.0" 0.098
203.0.113.35 - - [27/Nov/2026:14:07:54 +0300] "GET /api/products/982 HTTP/1.1" 200 2214 "-" "Mozilla/5.0" 0.049
203.0.113.36 - - [27/Nov/2026:14:07:54 +0300] "GET /api/products/756 HTTP/1.1" 200 1335 "-" "Mozilla/5.0" 0.073
203.0.113.27 - - [27/Nov/2026:14:07:56 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.054
203.0.113.18 - - [27/Nov/2026:14:07:59 +0300] "GET /api/products/756 HTTP/1.1" 200 1947 "-" "Mozilla/5.0" 0.066
203.0.113.31 - - [27/Nov/2026:14:08:07 +0300] "GET /api/products/773 HTTP/1.1" 200 1918 "-" "Mozilla/5.0" 0.026
203.0.113.39 - - [27/Nov/2026:14:08:08 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.738
203.0.113.38 - - [27/Nov/2026:14:08:12 +0300] "GET /api/products/894 HTTP/1.1" 200 908 "-" "Mozilla/5.0" 0.028
203.0.113.20 - - [27/Nov/2026:14:08:16 +0300] "GET /api/search?q=dune HTTP/1.1" 200 7250 "-" "Mozilla/5.0" 0.160
203.0.113.21 - - [27/Nov/2026:14:08:16 +0300] "GET /api/products/105 HTTP/1.1" 200 1282 "-" "Mozilla/5.0" 0.056
203.0.113.25 - - [27/Nov/2026:14:08:17 +0300] "GET /api/search?q=dune HTTP/1.1" 200 4620 "-" "Mozilla/5.0" 0.201
203.0.113.14 - - [27/Nov/2026:14:08:18 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.005
203.0.113.22 - - [27/Nov/2026:14:08:23 +0300] "GET /api/products/777 HTTP/1.1" 200 2334 "-" "Mozilla/5.0" 0.064
203.0.113.11 - - [27/Nov/2026:14:08:24 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.199
203.0.113.12 - - [27/Nov/2026:14:08:24 +0300] "GET /api/search?q=cookbook HTTP/1.1" 200 5551 "-" "Mozilla/5.0" 0.151
203.0.113.31 - - [27/Nov/2026:14:08:26 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.087
203.0.113.36 - - [27/Nov/2026:14:08:28 +0300] "GET /api/products/977 HTTP/1.1" 200 1403 "-" "Mozilla/5.0" 0.019
203.0.113.12 - - [27/Nov/2026:14:08:34 +0300] "GET /api/products/907 HTTP/1.1" 200 1836 "-" "Mozilla/5.0" 0.043
203.0.113.33 - - [27/Nov/2026:14:08:34 +0300] "GET /api/search?q=dune HTTP/1.1" 200 6023 "-" "Mozilla/5.0" 2.688
203.0.113.22 - - [27/Nov/2026:14:08:35 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.801
203.0.113.24 - - [27/Nov/2026:14:08:36 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.144
203.0.113.36 - - [27/Nov/2026:14:08:36 +0300] "GET /api/products/384 HTTP/1.1" 200 1723 "-" "Mozilla/5.0" 0.058
203.0.113.34 - - [27/Nov/2026:14:08:40 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.24 - - [27/Nov/2026:14:08:46 +0300] "GET /api/products/415 HTTP/1.1" 200 1154 "-" "Mozilla/5.0" 0.055
203.0.113.37 - - [27/Nov/2026:14:08:46 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.031
203.0.113.35 - - [27/Nov/2026:14:08:53 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.070
203.0.113.26 - - [27/Nov/2026:14:08:54 +0300] "GET /api/products/769 HTTP/1.1" 200 2392 "-" "Mozilla/5.0" 0.057
203.0.113.10 - - [27/Nov/2026:14:09:02 +0300] "GET /api/products/174 HTTP/1.1" 200 1236 "-" "Mozilla/5.0" 0.018
203.0.113.17 - - [27/Nov/2026:14:09:04 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.045
203.0.113.39 - - [27/Nov/2026:14:09:09 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.574
203.0.113.6 - - [27/Nov/2026:14:09:10 +0300] "GET /api/search?q=dune HTTP/1.1" 200 5791 "-" "Mozilla/5.0" 0.190
203.0.113.36 - - [27/Nov/2026:14:09:22 +0300] "GET /api/products/175 HTTP/1.1" 200 1088 "-" "Mozilla/5.0" 0.018
203.0.113.9 - - [27/Nov/2026:14:09:22 +0300] "GET /api/products/795 HTTP/1.1" 200 1231 "-" "Mozilla/5.0" 0.059
203.0.113.28 - - [27/Nov/2026:14:09:25 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.006
203.0.113.20 - - [27/Nov/2026:14:09:26 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.638
203.0.113.19 - - [27/Nov/2026:14:09:28 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 4396 "-" "Mozilla/5.0" 0.095
203.0.113.22 - - [27/Nov/2026:14:09:32 +0300] "GET /api/products/641 HTTP/1.1" 200 951 "-" "Mozilla/5.0" 0.067
203.0.113.27 - - [27/Nov/2026:14:09:35 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 8687 "-" "Mozilla/5.0" 0.187
203.0.113.35 - - [27/Nov/2026:14:09:40 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.002
203.0.113.18 - - [27/Nov/2026:14:09:42 +0300] "GET /api/products/916 HTTP/1.1" 200 1637 "-" "Mozilla/5.0" 0.075
203.0.113.34 - - [27/Nov/2026:14:09:42 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.084
203.0.113.32 - - [27/Nov/2026:14:09:56 +0300] "GET /api/products/802 HTTP/1.1" 200 1584 "-" "Mozilla/5.0" 0.069
203.0.113.21 - - [27/Nov/2026:14:09:57 +0300] "GET /api/products/562 HTTP/1.1" 200 1654 "-" "Mozilla/5.0" 0.038
203.0.113.25 - - [27/Nov/2026:14:09:57 +0300] "GET /api/products/820 HTTP/1.1" 200 2126 "-" "Mozilla/5.0" 0.018
203.0.113.25 - - [27/Nov/2026:14:09:57 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 3846 "-" "Mozilla/5.0" 0.128
203.0.113.24 - - [27/Nov/2026:14:09:59 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.067
203.0.113.39 - - [27/Nov/2026:14:09:59 +0300] "GET /api/products/110 HTTP/1.1" 200 1692 "-" "Mozilla/5.0" 0.022

FILE:examples/app.jsonl
{"time": "2026-11-27T14:00:10+03:00", "method": "GET", "path": "/api/orders/5000", "status": 200, "duration_ms": 41, "bytes": 820}
{"time": "2026-11-27T14:01:10+03:00", "method": "GET", "path": "/api/orders/5001", "status": 200, "duration_ms": 44, "bytes": 820}
{"time": "2026-11-27T14:02:10+03:00", "method": "GET", "path": "/api/orders/5002", "status": 200, "duration_ms": 47, "bytes": 820}
{"time": "2026-11-27T14:03:10+03:00", "method": "GET", "path": "/api/orders/5003", "status": 200, "duration_ms": 50, "bytes": 820}
{"time": "2026-11-27T14:04:10+03:00", "method": "GET", "path": "/api/orders/5004", "status": 200, "duration_ms": 53, "bytes": 820}
{"time": "2026-11-27T14:05:10+03:00", "method": "GET", "path": "/api/orders/5005", "status": 200, "duration_ms": 56, "bytes": 820}
{"time": "2026-11-27T14:06:30+03:00", "method": "POST", "path": "/api/orders/5006/refund", "status": 500, "duration_ms": 2140, "bytes": 120}

FILE:scripts/access_log.py
#!/usr/bin/env python3
"""access_log.py - find the slow and failing endpoints in an HTTP access log.

Reads Nginx/Apache "combined" lines (optionally followed by a request time in seconds, e.g. Nginx
$request_time, or microseconds via --time-unit us for Apache %D) or JSON lines with method, path, status
and duration_ms. Groups requests by route (query strings dropped, numeric ids, UUIDs and long hex hashes
replaced by :id, :uuid and :hash), computes count, share, 4xx/5xx rates and p50/p90/p95/p99/max latency
per route, finds minutes with 5xx spikes and flags routes that break the latency target or error budget.

Usage:
  access_log.py LOG [LOG ...] [--slo-ms 500] [--error-pct 1.0] [--client-error-pct 20] [--min-count 20]
                [--time-unit s|ms|us] [--group-by route|path] [--top 15] [--format text|md|csv|json]
  access_log.py --self-test
Exit: 0 = no flags, 1 = flags present, 2 = unreadable input or no parsable lines.
Python 3.8+ standard library only. Reads logs only; never sends anything anywhere."""
import argparse, csv, io, json, math, re, sys
from collections import defaultdict
from datetime import datetime

COMBINED = re.compile(
    r'^(?P<ip>\S+) \S+ \S+ \[(?P<time>[^\]]+)\] "(?P<method>[A-Z]+) (?P<target>\S+)(?: HTTP/[0-9.]+)?" '
    r'(?P<status>\d{3}) (?P<bytes>\d+|-)(?: "(?P<ref>[^"]*)" "(?P<ua>[^"]*)")?(?P<rest>.*)$')
UUID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
HEX = re.compile(r"^[0-9a-fA-F]{16,}$")
NUM = re.compile(r"^\d+$")
STATIC = (".css", ".js", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".woff", ".woff2", ".map", ".webp")

def route_of(target, group_by="route"):
    path = target.split("?", 1)[0].split("#", 1)[0] or "/"
    if group_by == "path":
        return path
    out = []
    for seg in path.split("/"):
        if NUM.match(seg): out.append(":id")
        elif UUID.match(seg): out.append(":uuid")
        elif HEX.match(seg): out.append(":hash")
        else: out.append(seg)
    r = "/".join(out)
    if r.lower().endswith(STATIC):
        r = r.rsplit("/", 1)[0] + "/*" + r[r.rfind("."):].lower()
    return r or "/"

def parse_time(s):
    for fmt in ("%d/%b/%Y:%H:%M:%S %z", "%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%S.%f%z", "%Y-%m-%d %H:%M:%S"):
        try:
            return datetime.strptime(s.replace("Z", "+0000"), fmt)
        except ValueError:
            pass
    return None

def parse_line(line, time_unit="s"):
    """Return dict(time, method, target, status, bytes, ms) or None. ms is None when no latency is logged."""
    line = line.strip()
    if not line:
        return None
    if line.startswith("{"):
        try:
            j = json.loads(line)
            ms = j.get("duration_ms", j.get("request_time_ms"))
            if ms is None and j.get("request_time") is not None:
                ms = float(j["request_time"]) * 1000
            return {"time": parse_time(str(j.get("time", ""))), "method": str(j["method"]).upper(),
                    "target": str(j["path"]), "status": int(j["status"]), "bytes": int(j.get("bytes") or 0),
                    "ms": None if ms is None else float(ms)}
        except (ValueError, KeyError, TypeError):
            return None
    m = COMBINED.match(line)
    if not m:
        return None
    ms = None
    rest = (m.group("rest") or "").split()
    if rest:
        try:
            v = float(rest[-1])
            ms = v * {"s": 1000.0, "ms": 1.0, "us": 0.001}[time_unit]
        except ValueError:
            ms = None
    b = m.group("bytes")
    return {"time": parse_time(m.group("time")), "method": m.group("method"), "target": m.group("target"),
            "status": int(m.group("status")), "bytes": 0 if b == "-" else int(b), "ms": ms}

def pct(values, p):
    """Nearest-rank percentile of a sorted list (p in 0-100)."""
    if not values:
        return None
    k = max(1, int(math.ceil(p / 100.0 * len(values))))
    return values[k - 1]

def analyze(lines, slo_ms=500.0, error_pct=1.0, client_error_pct=20.0, min_count=20, time_unit="s",
            group_by="route", top=15, spike_min_requests=10):
    groups = defaultdict(lambda: {"n": 0, "s4": 0, "s5": 0, "ms": [], "bytes": 0})
    minutes = defaultdict(lambda: [0, 0])
    total = bad = with_ms = 0
    slowest = []
    for raw in lines:
        r = parse_line(raw, time_unit)
        if r is None:
            if raw.strip():
                bad += 1
            continue
        total += 1
        key = r["method"] + " " + route_of(r["target"], group_by)
        g = groups[key]
        g["n"] += 1; g["bytes"] += r["bytes"]
        if 400 <= r["status"] < 500: g["s4"] += 1
        if r["status"] >= 500: g["s5"] += 1
        if r["ms"] is not None:
            g["ms"].append(r["ms"]); with_ms += 1
            slowest.append((r["ms"], r["method"], r["target"], r["status"]))
        if r["time"] is not None:
            mk = r["time"].strftime("%Y-%m-%d %H:%M")
            minutes[mk][0] += 1
            if r["status"] >= 500: minutes[mk][1] += 1
    routes, flags = [], []
    all_ms = sorted(x for g in groups.values() for x in g["ms"])
    for key, g in groups.items():
        v = sorted(g["ms"])
        row = {"route": key, "count": g["n"], "share_pct": round(100.0 * g["n"] / total, 1) if total else 0,
               "rate_4xx_pct": round(100.0 * g["s4"] / g["n"], 1), "rate_5xx_pct": round(100.0 * g["s5"] / g["n"], 1),
               "p50_ms": pct(v, 50), "p90_ms": pct(v, 90), "p95_ms": pct(v, 95), "p99_ms": pct(v, 99),
               "max_ms": v[-1] if v else None, "avg_kb": round(g["bytes"] / g["n"] / 1024.0, 1)}
        routes.append(row)
        if g["n"] < min_count:
            continue
        if row["p95_ms"] is not None and row["p95_ms"] > slo_ms:
            flags.append(("L01", key, "p95 %.0f ms is above the %.0f ms target (%d request(s))" % (row["p95_ms"], slo_ms, g["n"])))
        if row["rate_5xx_pct"] >= error_pct:
            flags.append(("L02", key, "%.1f%% server errors (%d of %d), budget %.1f%%" % (row["rate_5xx_pct"], g["s5"], g["n"], error_pct)))
        if row["rate_4xx_pct"] >= client_error_pct:
            flags.append(("L03", key, "%.1f%% client errors (%d of %d): broken links, auth or validation?" % (row["rate_4xx_pct"], g["s4"], g["n"])))
        if row["p50_ms"] and row["p99_ms"] is not None and row["p99_ms"] >= 5 * row["p50_ms"] and row["p99_ms"] > slo_ms:
            flags.append(("L05", key, "long tail: p99 %.0f ms is %.1fx p50 %.0f ms" % (row["p99_ms"], row["p99_ms"] / row["p50_ms"], row["p50_ms"])))
    total5 = sum(g["s5"] for g in groups.values())
    base = 100.0 * total5 / total if total else 0
    spikes = []
    for mk in sorted(minutes):
        n, e = minutes[mk]
        if n >= spike_min_requests and e and 100.0 * e / n >= max(5.0, 3 * base):
            spikes.append({"minute": mk, "requests": n, "errors_5xx": e, "rate_pct": round(100.0 * e / n, 1)})
            flags.append(("L04", mk, "5xx spike: %d of %d requests (%.0f%%) vs %.1f%% overall" % (e, n, 100.0 * e / n, base)))
    if total and with_ms == 0:
        flags.append(("L06", "-", "no request time found in the log: add $request_time (Nginx) or %D (Apache) to see latency"))
    if bad:
        flags.append(("E01", "-", "%d line(s) could not be parsed" % bad))
    order = {"L02": 0, "L04": 1, "L01": 2, "L05": 3, "L03": 4, "L06": 5, "E01": 6}
    flags.sort(key=lambda f: (order[f[0]], f[1]))
    routes.sort(key=lambda r: (-(r["p95_ms"] or 0), -r["count"]))
    slowest.sort(key=lambda x: -x[0])
    summary = {"requests": total, "unparsed": bad, "with_latency": with_ms, "routes": len(routes),
               "rate_5xx_pct": round(base, 2), "p50_ms": pct(all_ms, 50), "p95_ms": pct(all_ms, 95),
               "p99_ms": pct(all_ms, 99), "settings": {"slo_ms": slo_ms, "error_pct": error_pct,
               "client_error_pct": client_error_pct, "min_count": min_count, "group_by": group_by}}
    return {"summary": summary, "routes": routes[:top] if top else routes, "spikes": spikes,
            "slowest": [{"ms": round(s[0], 1), "request": "%s %s" % (s[1], s[2]), "status": s[3]} for s in slowest[:5]],
            "flags": [{"code": c, "where": w, "detail": d} for c, w, d in flags]}

def fmt_ms(v):
    return "-" if v is None else ("%.0f" % v)

def render(res, form):
    s = res["summary"]
    if form == "json":
        return json.dumps(res, indent=2)
    if form == "csv":
        buf = io.StringIO(); w = csv.writer(buf)
        w.writerow(["route", "count", "share_pct", "rate_4xx_pct", "rate_5xx_pct", "p50_ms", "p90_ms", "p95_ms", "p99_ms", "max_ms"])
        for r in res["routes"]:
            w.writerow([r["route"], r["count"], r["share_pct"], r["rate_4xx_pct"], r["rate_5xx_pct"]] + [fmt_ms(r[k]) for k in ("p50_ms", "p90_ms", "p95_ms", "p99_ms", "max_ms")])
        return buf.getvalue()
    md = form == "md"
    L = []
    head = "Requests %d (%d unparsed) | routes %d | 5xx %.2f%% | p50 %s ms, p95 %s ms, p99 %s ms | target p95 <= %.0f ms" % (
        s["requests"], s["unparsed"], s["routes"], s["rate_5xx_pct"], fmt_ms(s["p50_ms"]), fmt_ms(s["p95_ms"]), fmt_ms(s["p99_ms"]), s["settings"]["slo_ms"])
    L.append(("## Access log summary\n\n" if md else "") + head)
    L.append("")
    if md:
        L += ["| Route | Count | Share | 4xx | 5xx | p50 | p95 | p99 | max |", "|---|---|---|---|---|---|---|---|---|"]
        for r in res["routes"]:
            L.append("| `%s` | %d | %.1f%% | %.1f%% | %.1f%% | %s | %s | %s | %s |" % (r["route"], r["count"], r["share_pct"], r["rate_4xx_pct"], r["rate_5xx_pct"], fmt_ms(r["p50_ms"]), fmt_ms(r["p95_ms"]), fmt_ms(r["p99_ms"]), fmt_ms(r["max_ms"])))
    else:
        L.append("%-34s %6s %6s %6s %6s %6s %6s %6s %7s" % ("ROUTE", "COUNT", "SHARE", "4XX%", "5XX%", "P50", "P95", "P99", "MAX"))
        for r in res["routes"]:
            L.append("%-34s %6d %5.1f%% %6.1f %6.1f %6s %6s %6s %7s" % (r["route"][:34], r["count"], r["share_pct"], r["rate_4xx_pct"], r["rate_5xx_pct"], fmt_ms(r["p50_ms"]), fmt_ms(r["p95_ms"]), fmt_ms(r["p99_ms"]), fmt_ms(r["max_ms"])))
    L.append("")
    L.append(("### Flags" if md else "FLAGS") + " (%d)" % len(res["flags"]))
    for f in res["flags"]:
        L.append(("- **%s** `%s`: %s" if md else "%s  %s  %s") % (f["code"], f["where"], f["detail"]))
    if not res["flags"]:
        L.append("none")
    if res["slowest"]:
        L.append("")
        L.append("### Slowest requests" if md else "SLOWEST REQUESTS")
        for x in res["slowest"]:
            L.append(("- %s ms `%s` (%d)" if md else "%8s ms  %s  (%d)") % (fmt_ms(x["ms"]), x["request"], x["status"]))
    return "\n".join(L) + "\n"

def self_test():
    ok = [0, 0]
    def check(name, cond):
        ok[0] += 1; ok[1] += bool(cond)
        print(("PASS  " if cond else "FAIL  ") + name)
    L1 = '203.0.113.9 - - [28/Nov/2026:10:00:01 +0300] "GET /api/orders/123?page=2 HTTP/1.1" 200 512 "-" "curl/8" 0.084'
    r = parse_line(L1)
    check("combined line with request_time parsed", r and r["status"] == 200 and abs(r["ms"] - 84.0) < 1e-6 and r["method"] == "GET")
    check("Apache %D microseconds", abs(parse_line(L1.rsplit(" ", 1)[0] + " 84000", "us")["ms"] - 84.0) < 1e-6)
    r2 = parse_line('203.0.113.9 - - [28/Nov/2026:10:00:01 +0300] "GET / HTTP/1.1" 304 - "-" "x"')
    check("no latency field -> ms None, bytes '-' -> 0", r2 and r2["ms"] is None and r2["bytes"] == 0)
    check("common format without referer/agent", parse_line('10.0.0.1 - - [28/Nov/2026:10:00:01 +0300] "POST /login HTTP/1.1" 401 12')["status"] == 401)
    j = parse_line('{"time":"2026-11-28T10:00:02+03:00","method":"post","path":"/api/pay","status":502,"duration_ms":1200}')
    check("JSON line parsed", j and j["method"] == "POST" and j["status"] == 502 and j["ms"] == 1200.0)
    check("garbage -> None", parse_line("hello world") is None and parse_line('{"broken": ') is None)
    check("route: numeric id", route_of("/api/orders/123?x=1") == "/api/orders/:id")
    check("route: uuid and hash", route_of("/u/3f2b8c1e-1d2a-4b3c-9d8e-112233445566/f/a1b2c3d4e5f6a7b8c9d0") == "/u/:uuid/f/:hash")
    check("route: static grouped", route_of("/static/app.3f9a.JS") == "/static/*.js")
    check("route: --group-by path keeps ids", route_of("/api/orders/123?x=1", "path") == "/api/orders/123")
    check("nearest-rank percentiles", pct([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], 95) == 100 and pct(list(range(1, 101)), 50) == 50 and pct([], 50) is None)
    def ln(path, st, sec, mm="00", ss="01", method="GET"):
        return '198.51.100.7 - - [28/Nov/2026:10:%s:%s +0300] "%s %s HTTP/1.1" %d 100 "-" "t" %.3f' % (mm, ss, method, path, st, sec)
    lines = [ln("/api/fast/%d" % i, 200, 0.05) for i in range(40)]
    lines += [ln("/api/slow", 200, 0.9 if i % 5 == 0 else 0.2) for i in range(30)]
    lines += [ln("/api/pay", 500 if i < 3 else 200, 0.1, mm="05") for i in range(25)]
    lines += [ln("/admin", 403, 0.01) for i in range(25)]
    lines += ["not a log line"]
    res = analyze(lines, min_count=20)
    codes = {(f["code"], f["where"]) for f in res["flags"]}
    check("fast route grouped into one row", any(r["route"] == "GET /api/fast/:id" and r["count"] == 40 for r in res["routes"]))
    check("L01 slow route p95 over target", ("L01", "GET /api/slow") in codes)
    check("no L01 for fast route", ("L01", "GET /api/fast/:id") not in codes)
    check("L02 5xx over budget", ("L02", "GET /api/pay") in codes)
    check("L03 client errors on /admin", ("L03", "GET /admin") in codes)
    check("L04 spike minute found", ("L04", "2026-11-28 10:05") in codes)
    check("E01 unparsed line counted", res["summary"]["unparsed"] == 1 and any(f["code"] == "E01" for f in res["flags"]))
    check("L02 sorted before L01", [f["code"] for f in res["flags"]].index("L02") < [f["code"] for f in res["flags"]].index("L01"))
    tail = [ln("/api/search", 200, 0.05) for _ in range(95)] + [ln("/api/search", 200, 2.0) for _ in range(5)]
    tc = {f["code"] for f in analyze(tail)["flags"]}
    check("L05 long tail (p99 >> p50) without L01", "L05" in tc and "L01" not in tc)
    few = analyze([ln("/rare", 500, 3.0) for _ in range(5)], min_count=20)
    check("min-count suppresses route flags", not [f for f in few["flags"] if f["code"] in ("L01", "L02", "L05")])
    nolat = analyze(['10.0.0.1 - - [28/Nov/2026:10:00:01 +0300] "GET / HTTP/1.1" 200 5 "-" "x"'] * 3)
    check("L06 when no latency is logged", any(f["code"] == "L06" for f in nolat["flags"]))
    check("json render parses", json.loads(render(res, "json"))["summary"]["requests"] == 120)
    check("csv render header", render(res, "csv").splitlines()[0].startswith("route,count"))
    check("md render has table", "| Route | Count" in render(res, "md"))
    clean = analyze([ln("/ok", 200, 0.03) for _ in range(50)])
    check("clean log: no flags", clean["flags"] == [])
    print("%d/%d checks passed" % (ok[1], ok[0]))
    return 0 if ok[0] == ok[1] else 1

def main(argv=None):
    a = argparse.ArgumentParser(description="Find slow and failing endpoints in HTTP access logs.")
    a.add_argument("logs", nargs="*")
    a.add_argument("--slo-ms", type=float, default=500.0, help="p95 latency target per route (default 500)")
    a.add_argument("--error-pct", type=float, default=1.0, help="5xx budget per route in percent (default 1.0)")
    a.add_argument("--client-error-pct", type=float, default=20.0, help="4xx share that is flagged (default 20)")
    a.add_argument("--min-count", type=int, default=20, help="ignore routes with fewer requests (default 20)")
    a.add_argument("--time-unit", choices=["s", "ms", "us"], default="s", help="unit of the trailing request time")
    a.add_argument("--group-by", choices=["route", "path"], default="route")
    a.add_argument("--top", type=int, default=15, help="routes to list, 0 = all")
    a.add_argument("--format", choices=["text", "md", "csv", "json"], default="text")
    a.add_argument("--self-test", action="store_true")
    o = a.parse_args(argv)
    if o.self_test:
        return self_test()
    if not o.logs:
        a.print_usage(sys.stderr); return 2
    lines = []
    for p in o.logs:
        try:
            with open(p, encoding="utf-8", errors="replace") as fh:
                lines += fh.readlines()
        except OSError as e:
            print("error: cannot read %s: %s" % (p, e), file=sys.stderr); return 2
    res = analyze(lines, o.slo_ms, o.error_pct, o.client_error_pct, o.min_count, o.time_unit, o.group_by, o.top)
    if res["summary"]["requests"] == 0:
        print("error: no parsable log lines (check the format; see references/log-formats.md)", file=sys.stderr); return 2
    sys.stdout.write(render(res, o.format))
    return 1 if res["flags"] else 0

if __name__ == "__main__":
    sys.exit(main())
PerformanceMonitoringDeveloper+5
F@f
0
Sales Pipeline Coverage and Forecast Checker
Skill

Checks a B2B sales pipeline from a CRM CSV: quarter gap to quota, pipeline coverage, commit, best case, weighted and risk-adjusted forecasts, a per-owner view, and deals that make the forecast unreliable (past close dates, stale, stuck, pushed, no next step, concentration). Stdlib Python.

---
name: sales-pipeline-coverage-and-forecast-checker
description: Checks a B2B sales pipeline from a CRM CSV: quarter gap to quota, pipeline coverage, commit, best case, weighted and risk-adjusted forecasts, a per-owner view, and deals that make the forecast unreliable (past close dates, stale, stuck, pushed, no next step, concentration). Stdlib Python.
---

# Sales Pipeline Coverage and Forecast Checker

You help founders who still run sales, first sales leaders and small B2B teams answer two questions every week: "Will we hit the quarter?" and "Do we have enough pipeline to get there?" CRM dashboards show a big total that feels reassuring; you turn it into an honest number by checking coverage against the remaining gap, separating commit from hope, and pointing at the specific deals that make the forecast unreliable.

You work with deal-level CRM exports only (account names, amounts, stages, dates). You do not need contact details or personal data, and you never judge individual sellers from one quarter's numbers: flags are about deal hygiene, not people.

## Files in this skill

- `scripts/pipeline_check.py` - reads a deals CSV and a settings JSON, computes closed won, gap, open pipeline and coverage for a quarter, commit / best case / weighted / risk-adjusted forecasts, stage and owner breakdowns, and flags P01-P06 plus invalid rows (E01); `--as-of`, `--quarter`, `--format text|md|csv|json`; `--self-test` runs 24 checks (Python 3.8+ standard library only)
- `references/forecast-method.md` - how coverage and each forecast are calculated, sensible stage probabilities and coverage targets, and how to calibrate them from your own history
- `references/pipeline-hygiene.md` - what each flag usually means and the question to ask the deal owner
- `templates/forecast-brief.md` - a one-page weekly forecast note for the team or the board
- `examples/deals.csv` + `examples/settings.json` - a fictional healthcare SaaS startup in its Q4

## Workflow

### 1. Gather inputs
Ask for a CRM export (HubSpot, Pipedrive, Salesforce, Close, Attio or a spreadsheet) with one row per deal and these columns: `deal_id, account, owner, stage, amount, close_date, stage_entered, last_activity, next_step, pushes` (dates as YYYY-MM-DD; `pushes` = how many times the close date moved; use 0 if unknown). Then agree the settings: currency, quota per quarter, stage names with win probabilities, forecast category (pipeline, best_case, commit, won, lost) and maximum days per stage, coverage target, stale-activity days, push limit and concentration limit. If the user has no history, start with the defaults in `examples/settings.json` and say so.

### 2. Run the check
```
python3 scripts/pipeline_check.py deals.csv --settings settings.json
python3 scripts/pipeline_check.py deals.csv --settings settings.json --as-of 2026-11-27 --quarter 2026-Q4
python3 scripts/pipeline_check.py deals.csv --settings settings.json --quarter 2027-Q1
python3 scripts/pipeline_check.py deals.csv --settings settings.json --format md > forecast.md
python3 scripts/pipeline_check.py deals.csv --settings settings.json --format csv > flags.csv
python3 scripts/pipeline_check.py --self-test
```
Exit code 0 = no flags, 1 = flags or invalid rows, 2 = unreadable input or missing columns.

| Code | Meaning |
|---|---|
| P01 | close date in the past but the deal is still open (counted in the current quarter until fixed) |
| P02 | no activity for `stale_days` or more |
| P03 | stage probability 50% or higher but no next step written down |
| P04 | longer in the current stage than its `max_days` |
| P05 | close date pushed `push_limit` times or more |
| P06 | one deal is `concentration_pct` or more of the quarter's open pipeline |
| E01 | invalid row (unknown stage, bad amount or date, negative values) |

### 3. Interpret
- Coverage is open pipeline closing this quarter divided by the remaining gap (quota minus closed won), not by the full quota. Below about 2x late in a quarter means the number is at risk; early in a quarter aim for 3x or more.
- Read the forecasts as a range: commit is the floor you would bet on, best case is the ceiling, weighted is a statistical middle, and risk-adjusted halves the probability of deals with P01, P02 or P05 flags.
- A big gap between weighted and risk-adjusted means the pipeline needs cleaning more than it needs new deals.
- P06 is not bad by itself, but the plan must still work if that deal slips.
- Flags cover the open deals of the analyzed quarter; run `--quarter` for next quarter too, so slipped deals are checked where they now sit.

### 4. Act
Use `references/pipeline-hygiene.md` to turn flags into owner questions ("What has to happen for this to close by December 19, and who on their side decides?"). Fix close dates and stages in the CRM, then re-run. If coverage is short, the script's "add X of qualified pipeline" line gives a concrete target for prospecting and for next quarter.

### 5. Report
Fill `templates/forecast-brief.md`: the forecast range, coverage, the three deals that decide the quarter, the hygiene fixes, and what is needed for next quarter's pipeline.

## Example
```
python3 scripts/pipeline_check.py examples/deals.csv --settings examples/settings.json
```
Result (as of 2026-11-27): quota USD 260k, closed won USD 85k, gap USD 175k; USD 364k open in 9 deals gives 2.08x coverage, so USD 161k more qualified pipeline is needed for 3x. Forecast range: commit USD 194k (74.6%), weighted USD 222k, risk-adjusted USD 213k (81.8%), best case USD 294k. Flags: Cedar Family Practice is past its close date, stale and pushed 3 times; Lakeside Vision Care is in Negotiation without a next step and pushed twice; Metro Urgent Care has sat in Proposal for 44 days; Greenfield Hospital Group alone is 38% of open pipeline.

## Limits
- The output is only as good as the CRM data; stale stages and optimistic close dates are the most common errors, which is why the flags exist.
- Stage probabilities are assumptions until calibrated with at least a few quarters of your own win rates (see `references/forecast-method.md`).
- Amounts are treated as one currency and one-off bookings; for multi-year or usage-based deals, agree what "amount" means (first-year ACV is common).
- This is a planning aid, not financial reporting or a performance review tool.

FILE:references/forecast-method.md
# Forecast method

All numbers are for one quarter (`--quarter`, default: the quarter of `--as-of`).

| Number | Formula | Use it for |
|---|---|---|
| Closed won | sum of `won` deals with a close date in the quarter | what is already booked |
| Gap | max(quota - closed won, 0) | what is still missing |
| Open pipeline | open deals closing in the quarter, plus past-dated open deals when the quarter is the current one | what could still close |
| Coverage | open pipeline / gap | is there enough to choose from |
| Pipeline needed | max(gap x coverage target - open pipeline, 0) | a prospecting target |
| Commit | closed won + `commit` deals | the floor you would promise |
| Best case | commit + `best_case` deals | the ceiling if things go well |
| Weighted | closed won + sum(amount x stage probability) | a statistical middle for planning |
| Risk-adjusted | weighted, but deals with P01, P02 or P05 get probability x `risk_haircut` (default 0.5) | a more honest middle |

## Starting stage probabilities (replace with your own)

| Stage | Typical probability | Category | Max days |
|---|---|---|---|
| Discovery / qualification | 5-15% | pipeline | 30 |
| Demo / evaluation | 20-30% | pipeline | 30 |
| Proposal / pricing | 35-50% | best_case | 30 |
| Negotiation / legal | 65-80% | commit | 21 |
| Verbal yes, paperwork | 85-95% | commit | 14 |

## Coverage targets

- Start of the quarter: 3x is a common target for new business; 4x if win rates are low or deals are large and few.
- Mid-quarter: 2-2.5x of the remaining gap.
- Last month: coverage matters less than commit; focus on the deals in Negotiation.
- Renewals and expansions usually need much lower coverage (1.2-1.5x) and should be forecast separately.

## Calibrating with your own history

1. Export the last 4-8 quarters of closed deals (won and lost) with the highest stage each reached.
2. For each stage: win rate = deals won that reached the stage / all closed deals that reached the stage.
3. Use those rates as probabilities; round to 5%. With fewer than 20 closed deals per stage, blend with the starting table.
4. Measure median days in each stage for won deals; set `max_days` at roughly 1.5x that median.
5. Compare last quarter's weighted forecast in week 4 with the actual result; if you were off by more than 15%, adjust the probabilities or the haircut.

FILE:references/pipeline-hygiene.md
# Pipeline hygiene: what each flag means and what to ask

| Flag | Usually means | Ask the deal owner | Typical fix |
|---|---|---|---|
| P01 past close date | The date was never updated after it slipped | "What is the real decision date, and what changed?" | Set a new date based on the buyer's process, or move to lost |
| P02 no recent activity | The buyer went quiet or the deal is dead | "When did we last hear from someone with authority?" | One clear re-engagement attempt, then lost or nurture |
| P03 no next step in a late stage | Hope instead of a plan | "What is the next meeting, with whom, and on what date?" | Agree a dated next step with the buyer, write it in the CRM |
| P04 stuck in stage | A blocker nobody named (budget, security review, legal, champion left) | "What exactly must happen to move to the next stage?" | Name the blocker and an owner on the buyer's side, or step the stage back |
| P05 pushed repeatedly | No real urgency or no decision maker involved | "Why will this date hold when the last ones did not?" | Re-qualify: pain, budget, decision process; consider moving it out of commit |
| P06 concentration | One deal carries the quarter | "What is plan B if this slips to next quarter?" | Executive sponsor on both sides, mutual close plan, more pipeline elsewhere |
| E01 invalid row | Export or data entry problem | - | Fix stage names, amounts and dates in the CRM, export again |

## Weekly 30-minute pipeline review

1. Run the script before the meeting; share the text or md output.
2. Start with commit deals: confirm the next step and date for each.
3. Go through flags, oldest close date first; decide close date, stage or lost on the spot.
4. Check coverage for this quarter and next; agree the prospecting target.
5. Write down changes; re-run after the CRM is updated.

## Good habits

- A stage change needs a buyer action (they agreed to a demo, sent a security questionnaire, asked for an order form), not a seller action.
- Close dates come from the buyer's process, not from the end of our quarter.
- Moving a dead deal to lost is good news for the forecast: it makes every other number more believable.

FILE:templates/forecast-brief.md
# Weekly forecast: {{quarter}} (as of {{as_of}})

## The number
- Quota {{quota}} | Closed won {{closed_won}} | Gap {{gap}}
- Forecast range: commit {{commit}} - risk-adjusted {{risk_adjusted}} - best case {{best_case}}
- Our call this week: {{call}} ({{call_reason}})

## Coverage
- Open pipeline {{open_pipeline}} in {{open_deals}} deals -> {{coverage}} coverage (target {{coverage_target}})
- Pipeline needed: {{pipeline_needed}} | Next quarter coverage: {{next_quarter_coverage}}

## Deals that decide the quarter
| Deal | Amount | Stage | Next step and date | Risk |
|---|---|---|---|---|
| {{deal}} | {{amount}} | {{stage}} | {{next_step}} | {{risk}} |

## Hygiene fixes this week
- {{fix_1}}
- {{fix_2}}

## Asks
- {{ask}} (for example an executive call with Greenfield, legal review capacity)

FILE:examples/deals.csv
deal_id,account,owner,stage,amount,close_date,stage_entered,last_activity,next_step,pushes
D101,Northwind Clinics,maya,Closed Won,48000,2026-10-09,2026-09-20,2026-10-09,,0
D102,Harbor Dental Group,maya,Closed Won,22000,2026-11-04,2026-10-21,2026-11-04,,1
D103,Pinecrest Physio,leo,Closed Won,15000,2026-11-18,2026-11-02,2026-11-18,,0
D104,Bluebird Pediatrics,leo,Closed Lost,30000,2026-11-12,2026-10-15,2026-11-12,,1
D105,Summit Health Partners,maya,Negotiation,64000,2026-12-12,2026-11-19,2026-11-25,Legal redlines call Dec 2,0
D106,Lakeside Vision Care,leo,Negotiation,18000,2026-12-05,2026-11-03,2026-11-24,,2
D107,Riverbend Orthopedics,maya,Proposal,36000,2026-12-19,2026-11-12,2026-11-26,Pricing review with CFO,0
D108,Cedar Family Practice,sam,Proposal,12000,2026-11-20,2026-10-28,2026-11-06,Send revised quote,3
D109,Metro Urgent Care,sam,Proposal,52000,2026-12-30,2026-10-14,2026-11-21,Security questionnaire,1
D110,Oakwood Dermatology,leo,Discovery,9000,2026-12-22,2026-11-18,2026-11-26,Demo for office manager,0
D111,Greenfield Hospital Group,maya,Discovery,140000,2026-12-31,2026-11-24,2026-11-25,Intro call with IT,0
D112,Sunrise Speech Therapy,sam,Discovery,6000,2026-12-15,2026-10-01,2026-10-29,Follow-up email,0
D113,Valley Women's Health,leo,Proposal,24000,2027-01-29,2026-11-20,2026-11-26,Proposal walkthrough,0
D114,Brightside Mental Health,sam,Negotiation,27000,2026-12-18,2026-11-21,2026-11-25,Order form signature,0

FILE:examples/settings.json
{
  "currency": "USD",
  "as_of": "2026-11-27",
  "quota": {"2026-Q4": 260000, "2027-Q1": 300000},
  "coverage_target": 3.0,
  "stale_days": 21,
  "concentration_pct": 30,
  "push_limit": 2,
  "risk_haircut": 0.5,
  "stages": {
    "Discovery": {"probability": 0.1, "category": "pipeline", "max_days": 30},
    "Proposal": {"probability": 0.4, "category": "best_case", "max_days": 30},
    "Negotiation": {"probability": 0.75, "category": "commit", "max_days": 21},
    "Closed Won": {"probability": 1.0, "category": "won"},
    "Closed Lost": {"probability": 0.0, "category": "lost"}
  }
}

FILE:scripts/pipeline_check.py
#!/usr/bin/env python3
"""pipeline_check.py - sales pipeline coverage and forecast checker for B2B founders and small sales teams.

Reads a deals CSV exported from a CRM (or a spreadsheet) and a settings JSON (quota, stages with win
probabilities and maximum days, thresholds). For the chosen quarter it computes closed-won to date, the
gap to quota, pipeline coverage, commit / best case / weighted and risk-adjusted forecasts, a per-owner
view, and flags deals that make the forecast unreliable.

Usage:
  pipeline_check.py deals.csv --settings settings.json [--as-of 2026-11-27] [--quarter 2026-Q4]
                    [--format text|md|csv|json]
  pipeline_check.py --self-test
Exit: 0 = no flags, 1 = flags or invalid rows, 2 = unreadable input or missing columns.
Python 3.8+ standard library only."""
import argparse, csv, io, json, sys
from datetime import date, datetime

REQUIRED = ["deal_id", "account", "owner", "stage", "amount", "close_date", "stage_entered", "last_activity", "next_step", "pushes"]
DEFAULTS = {"currency": "USD", "coverage_target": 3.0, "stale_days": 21, "concentration_pct": 30, "push_limit": 2,
            "risk_haircut": 0.5, "quota": {}, "stages": {}}
CODES = {"P01": "close date in the past but deal still open", "P02": "no activity for {d} days (limit {l})",
         "P03": "late-stage deal without a next step", "P04": "{d} days in stage {s} (limit {l})",
         "P05": "close date pushed {n} times (limit {l})", "P06": "one deal is {p:.0f}% of the quarter's open pipeline (limit {l}%)"}

def parse_date(s):
    return datetime.strptime(s.strip(), "%Y-%m-%d").date()

def quarter_of(d):
    return "%d-Q%d" % (d.year, (d.month - 1) // 3 + 1)

def money(x, cur):
    return "%s %s" % (cur, format(int(round(x)), ","))

def load_settings(obj):
    s = dict(DEFAULTS); s.update(obj or {})
    if not s["stages"]:
        raise ValueError("settings.stages is empty")
    for name, st in s["stages"].items():
        if not 0 <= float(st.get("probability", -1)) <= 1:
            raise ValueError("stage %s: probability must be 0..1" % name)
        if st.get("category") not in ("pipeline", "best_case", "commit", "won", "lost"):
            raise ValueError("stage %s: category must be pipeline, best_case, commit, won or lost" % name)
    return s

def read_deals(text, settings):
    rd = csv.DictReader(io.StringIO(text))
    missing = [c for c in REQUIRED if c not in (rd.fieldnames or [])]
    if missing:
        raise ValueError("missing columns: " + ", ".join(missing))
    deals, errors = [], []
    for n, row in enumerate(rd, start=2):
        row = {k: (v or "").strip() for k, v in row.items() if k}
        try:
            if row["stage"] not in settings["stages"]:
                raise ValueError("unknown stage %r" % row["stage"])
            try:
                amt = float(row["amount"].replace(",", ""))
            except ValueError:
                raise ValueError("amount %r is not a number" % row["amount"])
            if amt < 0:
                raise ValueError("negative amount")
            try:
                pushes = int(row["pushes"] or 0)
            except ValueError:
                raise ValueError("pushes %r is not a whole number" % row["pushes"])
            if pushes < 0:
                raise ValueError("negative pushes")
            d = dict(row, amount=amt, pushes=pushes, close=parse_date(row["close_date"]),
                     entered=parse_date(row["stage_entered"]), activity=parse_date(row["last_activity"]), line=n)
            deals.append(d)
        except (ValueError, KeyError) as e:
            errors.append({"line": n, "deal_id": row.get("deal_id", "?"), "code": "E01", "message": str(e)})
    return deals, errors

def analyze(deals, errors, s, as_of, quarter):
    cur = s["currency"]
    st = s["stages"]
    quota = float(s["quota"].get(quarter, 0))
    in_q = [d for d in deals if quarter_of(d["close"]) == quarter or (st[d["stage"]]["category"] not in ("won", "lost") and d["close"] < as_of and quarter_of(as_of) == quarter)]
    won = sum(d["amount"] for d in in_q if st[d["stage"]]["category"] == "won")
    open_q = [d for d in in_q if st[d["stage"]]["category"] not in ("won", "lost")]
    open_amt = sum(d["amount"] for d in open_q)
    gap = max(quota - won, 0.0)
    flags = []
    def flag(deal, code, **kw):
        flags.append({"deal_id": deal["deal_id"], "account": deal["account"], "owner": deal["owner"], "code": code,
                      "amount": deal["amount"], "message": CODES[code].format(**kw)})
    for d in open_q:  # hygiene flags for the quarter's open deals
        if d["close"] < as_of:
            flag(d, "P01")
        idle = (as_of - d["activity"]).days
        if idle >= s["stale_days"]:
            flag(d, "P02", d=idle, l=s["stale_days"])
        if float(st[d["stage"]]["probability"]) >= 0.5 and not d["next_step"]:
            flag(d, "P03")
        mx = st[d["stage"]].get("max_days")
        age = (as_of - d["entered"]).days
        if mx and age > mx:
            flag(d, "P04", d=age, s=d["stage"], l=mx)
        if d["pushes"] >= s["push_limit"]:
            flag(d, "P05", n=d["pushes"], l=s["push_limit"])
    for d in open_q:
        if open_amt and len(open_q) > 1 and d["amount"] / open_amt * 100 >= s["concentration_pct"]:
            flag(d, "P06", p=d["amount"] / open_amt * 100, l=s["concentration_pct"])
    risky = {f["deal_id"] for f in flags if f["code"] in ("P01", "P02", "P05")}
    commit = won + sum(d["amount"] for d in open_q if st[d["stage"]]["category"] == "commit")
    best = commit + sum(d["amount"] for d in open_q if st[d["stage"]]["category"] == "best_case")
    weighted = won + sum(d["amount"] * float(st[d["stage"]]["probability"]) for d in open_q)
    risk_adj = won + sum(d["amount"] * float(st[d["stage"]]["probability"]) * (s["risk_haircut"] if d["deal_id"] in risky else 1.0) for d in open_q)
    coverage = (open_amt / gap) if gap else None
    needed = max(gap * s["coverage_target"] - open_amt, 0.0) if gap else 0.0
    owners = {}
    for d in in_q:
        o = owners.setdefault(d["owner"], {"owner": d["owner"], "won": 0.0, "open": 0.0, "weighted": 0.0, "deals_open": 0, "flags": 0})
        cat = st[d["stage"]]["category"]
        if cat == "won": o["won"] += d["amount"]
        elif cat != "lost":
            o["open"] += d["amount"]; o["deals_open"] += 1; o["weighted"] += d["amount"] * float(st[d["stage"]]["probability"])
    for f in flags:
        if f["owner"] in owners: owners[f["owner"]]["flags"] += 1
    by_stage = {}
    for d in open_q:
        b = by_stage.setdefault(d["stage"], [0, 0.0]); b[0] += 1; b[1] += d["amount"]
    order = list(st)
    return {"currency": cur, "as_of": as_of.isoformat(), "quarter": quarter, "quota": quota, "closed_won": won, "gap": gap,
            "open_pipeline": open_amt, "open_deals": len(open_q), "coverage": coverage, "coverage_target": s["coverage_target"],
            "pipeline_needed": needed, "forecast": {"commit": commit, "best_case": best, "weighted": weighted, "risk_adjusted": risk_adj},
            "attainment_pct": {"commit": pct(commit, quota), "weighted": pct(weighted, quota), "risk_adjusted": pct(risk_adj, quota)},
            "by_stage": [{"stage": k, "deals": by_stage[k][0], "amount": by_stage[k][1]} for k in order if k in by_stage],
            "owners": sorted(owners.values(), key=lambda o: -o["open"]),
            "flags": sorted(flags, key=lambda f: (f["code"], -f["amount"])), "errors": errors}

def pct(x, q):
    return round(x / q * 100, 1) if q else None

def render(r, fmt):
    c = r["currency"]; m = lambda x: money(x, c)
    cov = ("%.2fx" % r["coverage"]) if r["coverage"] is not None else "n/a (quota reached)"
    if fmt == "json":
        return json.dumps(r, indent=2)
    if fmt == "csv":
        out = io.StringIO(); w = csv.writer(out)
        w.writerow(["deal_id", "account", "owner", "amount", "code", "message"])
        for f in r["flags"]: w.writerow([f["deal_id"], f["account"], f["owner"], int(f["amount"]), f["code"], f["message"]])
        for e in r["errors"]: w.writerow([e["deal_id"], "", "", "", "E01", "line %d: %s" % (e["line"], e["message"])])
        return out.getvalue()
    f = r["forecast"]; a = r["attainment_pct"]
    head = [
        "Quarter %s as of %s: quota %s, closed won %s, gap %s" % (r["quarter"], r["as_of"], m(r["quota"]), m(r["closed_won"]), m(r["gap"])),
        "Open pipeline %s in %d deal%s -> coverage %s (target %.1fx)%s" % (m(r["open_pipeline"]), r["open_deals"], "" if r["open_deals"] == 1 else "s", cov, r["coverage_target"],
            ("; add %s of qualified pipeline to reach target" % m(r["pipeline_needed"])) if r["pipeline_needed"] else ""),
        "Forecast: commit %s (%s%%), best case %s, weighted %s (%s%%), risk-adjusted %s (%s%%)" % (m(f["commit"]), a["commit"], m(f["best_case"]), m(f["weighted"]), a["weighted"], m(f["risk_adjusted"]), a["risk_adjusted"]),
    ]
    if fmt == "md":
        L = ["# Pipeline check %s" % r["quarter"], ""] + ["- " + h for h in head] + ["", "## Open pipeline by stage", "", "| Stage | Deals | Amount |", "|---|---|---|"]
        L += ["| %s | %d | %s |" % (b["stage"], b["deals"], m(b["amount"])) for b in r["by_stage"]]
        L += ["", "## Owners", "", "| Owner | Won | Open | Weighted | Open deals | Flags |", "|---|---|---|---|---|---|"]
        L += ["| %s | %s | %s | %s | %d | %d |" % (o["owner"], m(o["won"]), m(o["open"]), m(o["weighted"]), o["deals_open"], o["flags"]) for o in r["owners"]]
        L += ["", "## Flags", ""] + (["- **%s** %s (%s, %s, %s): %s" % (x["code"], x["deal_id"], x["account"], x["owner"], m(x["amount"]), x["message"]) for x in r["flags"]] or ["- none"])
        L += ["- **E01** line %d %s: %s" % (e["line"], e["deal_id"], e["message"]) for e in r["errors"]]
        return "\n".join(L) + "\n"
    L = head + ["", "Open pipeline by stage:"] + ["  %-14s %3d deal%s %14s" % (b["stage"], b["deals"], " " if b["deals"] == 1 else "s", m(b["amount"])) for b in r["by_stage"]]
    L += ["", "Owners:"] + ["  %-10s won %12s  open %12s  weighted %12s  %d open deal%s, %d flag%s" % (o["owner"], m(o["won"]), m(o["open"]), m(o["weighted"]), o["deals_open"], "" if o["deals_open"] == 1 else "s", o["flags"], "" if o["flags"] == 1 else "s") for o in r["owners"]]
    L += ["", "Flags (%d):" % len(r["flags"])] + ["  %s %-6s %-22s %-8s %12s  %s" % (x["code"], x["deal_id"], x["account"][:22], x["owner"], m(x["amount"]), x["message"]) for x in r["flags"]]
    L += ["  E01 line %d %s: %s" % (e["line"], e["deal_id"], e["message"]) for e in r["errors"]]
    if not r["flags"] and not r["errors"]:
        L.append("  none")
    return "\n".join(L) + "\n"

def self_test():
    ok = total = 0
    def check(name, cond):
        nonlocal ok, total
        total += 1; ok += bool(cond); print(("PASS  " if cond else "FAIL  ") + name)
    S = load_settings({"currency": "USD", "quota": {"2026-Q4": 100000}, "stale_days": 21, "push_limit": 2, "concentration_pct": 30,
                       "stages": {"Discovery": {"probability": 0.1, "category": "pipeline", "max_days": 30},
                                  "Proposal": {"probability": 0.5, "category": "best_case", "max_days": 21},
                                  "Negotiation": {"probability": 0.8, "category": "commit", "max_days": 14},
                                  "Closed Won": {"probability": 1, "category": "won"}, "Closed Lost": {"probability": 0, "category": "lost"}}})
    H = ",".join(REQUIRED) + "\n"
    def run(rows, as_of="2026-11-27"):
        deals, errs = read_deals(H + "".join(r + "\n" for r in rows), S)
        return analyze(deals, errs, S, parse_date(as_of), "2026-Q4")
    base = ["W1,Acme,ann,Closed Won,40000,2026-10-15,2026-10-01,2026-10-15,,0",
            "N1,Beta,ann,Negotiation,20000,2026-12-15,2026-11-20,2026-11-25,Send contract,0",
            "P1,Gamma,bob,Proposal,30000,2026-12-20,2026-11-15,2026-11-24,Pricing call,0",
            "D1,Delta,bob,Discovery,50000,2026-12-30,2026-11-10,2026-11-26,Demo,0"]
    r = run(base)
    check("closed won counted", r["closed_won"] == 40000)
    check("gap = quota - won", r["gap"] == 60000)
    check("open pipeline in quarter", r["open_pipeline"] == 100000 and r["open_deals"] == 3)
    check("coverage = open / gap", abs(r["coverage"] - 100000 / 60000) < 1e-9)
    check("pipeline needed for 3x", r["pipeline_needed"] == 80000)
    check("commit = won + commit stage", r["forecast"]["commit"] == 60000)
    check("best case adds best_case stage", r["forecast"]["best_case"] == 90000)
    check("weighted forecast", abs(r["forecast"]["weighted"] - (40000 + 16000 + 15000 + 5000)) < 1e-6)
    check("P06 concentration for 50% deal", any(f["code"] == "P06" and f["deal_id"] == "D1" for f in r["flags"]))
    check("no other flags on healthy deals", {f["code"] for f in r["flags"]} == {"P06"})
    r = run(["X1,Old,ann,Proposal,10000,2026-09-20,2026-09-01,2026-11-20,Follow up,0", "X2,Fine,ann,Proposal,10000,2026-12-10,2026-11-20,2026-11-26,Call,0"])
    check("P01 past close date", any(f["code"] == "P01" and f["deal_id"] == "X1" for f in r["flags"]))
    check("past-quarter open deal counted in current quarter", r["open_deals"] == 2)
    r = run(["S1,Quiet,bob,Discovery,5000,2026-12-10,2026-11-20,2026-10-30,Email,0"])
    check("P02 stale activity 28 days", any(f["code"] == "P02" and "28 days" in f["message"] for f in r["flags"]))
    r = run(["L1,NoStep,bob,Negotiation,5000,2026-12-10,2026-11-25,2026-11-26,,0", "L2,EarlyNoStep,bob,Discovery,5000,2026-12-10,2026-11-25,2026-11-26,,0"])
    check("P03 late stage without next step", [f["deal_id"] for f in r["flags"] if f["code"] == "P03"] == ["L1"])
    r = run(["A1,Stuck,ann,Proposal,5000,2026-12-10,2026-10-20,2026-11-26,Call,0"])
    check("P04 stuck in stage 38 > 21 days", any(f["code"] == "P04" and "38 days" in f["message"] for f in r["flags"]))
    r = run(["R1,Slipper,ann,Negotiation,10000,2026-12-10,2026-11-20,2026-11-26,Call,3", "R2,Other,ann,Negotiation,10000,2026-12-10,2026-11-20,2026-11-26,Call,0"])
    check("P05 pushed 3 times", any(f["code"] == "P05" and f["deal_id"] == "R1" for f in r["flags"]))
    check("risk-adjusted halves risky deal", abs(r["forecast"]["risk_adjusted"] - (4000 + 8000)) < 1e-6)
    r = run(["E1,Bad,ann,Prospecting,100,2026-12-10,2026-11-20,2026-11-26,Call,0", "E2,Bad2,ann,Proposal,abc,2026-12-10,2026-11-20,2026-11-26,Call,0", "E3,Bad3,ann,Proposal,10,2026-13-10,2026-11-20,2026-11-26,Call,0"])
    check("E01 unknown stage, bad amount, bad date", [e["deal_id"] for e in r["errors"]] == ["E1", "E2", "E3"])
    r = run(["W1,Acme,ann,Closed Won,120000,2026-10-15,2026-10-01,2026-10-15,,0"])
    check("quota reached: no coverage, nothing needed", r["coverage"] is None and r["pipeline_needed"] == 0 and r["gap"] == 0)
    r = run(["N1,NextQ,ann,Negotiation,20000,2027-01-15,2026-11-20,2026-11-25,Call,0"])
    check("next-quarter deal excluded", r["open_deals"] == 0)
    r = run(["N2,NextQStale,ann,Negotiation,20000,2027-01-15,2026-09-01,2026-09-02,,5"])
    check("flags only for the analyzed quarter", r["flags"] == [])
    try:
        read_deals("deal_id,amount\n1,2\n", S); check("missing columns rejected", False)
    except ValueError as e:
        check("missing columns rejected", "missing columns" in str(e))
    try:
        load_settings({"stages": {"X": {"probability": 2, "category": "pipeline"}}}); check("bad probability rejected", False)
    except ValueError:
        check("bad probability rejected", True)
    r = run(base)
    check("csv and md render", render(r, "csv").startswith("deal_id,") and "| Stage | Deals | Amount |" in render(r, "md"))
    print("%d/%d checks passed" % (ok, total))
    return 0 if ok == total else 1

def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("deals", nargs="?"); ap.add_argument("--settings")
    ap.add_argument("--as-of"); ap.add_argument("--quarter")
    ap.add_argument("--format", choices=["text", "md", "csv", "json"], default="text")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.deals or not a.settings:
        ap.error("deals CSV and --settings are required")
    try:
        s = load_settings(json.load(open(a.settings, encoding="utf-8")))
        deals, errors = read_deals(open(a.deals, encoding="utf-8-sig").read(), s)
        as_of = parse_date(a.as_of or s.get("as_of") or date.today().isoformat())
    except (OSError, ValueError, json.JSONDecodeError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    q = a.quarter or quarter_of(as_of)
    r = analyze(deals, errors, s, as_of, q)
    sys.stdout.write(render(r, a.format))
    return 1 if r["flags"] or r["errors"] else 0

if __name__ == "__main__":
    sys.exit(main())
SalesPipelineRevenue+5
F@f
0
Git Repository Large File and Bloat Finder
Skill

Finds what makes a Git repository big and slow to clone: large files in HEAD and in history, deleted files still stored, binaries with many versions, committed node_modules or build output and credential-like files. Suggests .gitignore, Git LFS and safe history cleanup steps. Stdlib Python.

---
name: git-repository-large-file-and-bloat-finder
description: Finds what makes a Git repository big and slow to clone: large files in HEAD and in history, deleted files still stored, binaries with many versions, committed node_modules or build output and credential-like files. Suggests .gitignore, Git LFS and safe history cleanup steps. Stdlib Python.
---

# Git Repository Large File and Bloat Finder

You help developers and tech leads understand why a Git repository is big, why clones and CI checkouts are slow, and what to do about it without breaking anyone's work. A 2 GB repository is rarely 2 GB of source code: it is usually one forgotten video, a database dump deleted years ago, a design file with 40 versions or a committed `node_modules`. You find those objects, explain the cost and propose the smallest safe fix.

You never rewrite history or delete anything yourself. History rewrites affect every clone, fork and open pull request, so you present them as a plan for the team to approve, with a backup and a communication step.

## Files in this skill

- `scripts/repo_bloat.py` - reads all objects reachable from all refs (`git rev-list --objects --all` + `git cat-file --batch-check`), groups blobs by path, flags B01-B05, lists top paths and extensions, and prints .gitignore, Git LFS and `git filter-repo` suggestions; `--format text|md|json`; `--objects-file`/`--head-file` for offline listings; `--self-test` runs 20 checks including a real temporary repository (Python 3.8+ standard library and the git CLI)
- `references/bloat-causes.md` - the usual causes, how to recognize each one and how much it costs
- `references/cleanup-playbook.md` - fixes from least to most disruptive: ignore and untrack, Git LFS, shallow and partial clones, history rewrite, secret rotation
- `templates/repo-bloat-report.md` - a short report and decision template for the team
- `examples/objects.txt` + `examples/head.txt` - a captured listing of a fictional web app repository

## Workflow

### 1. Measure first
Ask for the repository path (or run in the current checkout) and check the basics:
```
git count-objects -vH
du -sh .git
git rev-list --count --all
```
Ask how the repository is hosted (GitHub, GitLab, Bitbucket, self-hosted), whether forks exist, how many people and CI pipelines clone it, and whether Git LFS is already in use.

### 2. Run the scan
```
python3 scripts/repo_bloat.py --repo /path/to/repo
python3 scripts/repo_bloat.py --repo . --threshold-mb 2 --top 25
python3 scripts/repo_bloat.py --repo . --format md > repo-bloat.md
python3 scripts/repo_bloat.py --repo . --format json
python3 scripts/repo_bloat.py --objects-file objects.txt --head-file head.txt
python3 scripts/repo_bloat.py --self-test
```
For a repository you cannot run the script in, capture the listings there and scan them offline:
```
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(objectsize:disk) %(rest)' > objects.txt
git ls-tree -r --name-only HEAD > head.txt
```
Exit code 0 = no findings, 1 = findings, 2 = not a repository or unreadable input.

| Code | Meaning |
|---|---|
| B01 | large file only in history (deleted from HEAD), or many versions of a deleted file adding up above the threshold |
| B02 | large file still in HEAD (every clone and checkout downloads it) |
| B03 | binary file with 3 or more versions; each change stores a full new copy |
| B04 | generated or vendored folder or file type committed (node_modules, dist, build, vendor, venv, logs, compiled files) |
| B05 | credential-like file in history (.env, private keys, keystores, credentials JSON) |

### 3. Interpret
- Compare `history_only_bytes` with the pack size: if most of the weight is only in history, a rewrite is the only way to shrink clones; if it is in HEAD, ignoring and LFS help right away.
- Sizes are uncompressed blob sizes; text compresses well in packs, binaries do not. `objectsize:disk` in the JSON output shows what the pack really stores.
- B05 is a security finding first and a size finding second. Treat any secret found as leaked.
- A large file in HEAD that the product needs (a test fixture, a font) may be fine; ask before suggesting removal.

### 4. Choose the fix
Use `references/cleanup-playbook.md` and pick the least disruptive fix that solves the problem:
1. Stop the growth: `.gitignore`, `git rm -r --cached`, a pre-commit or CI size check.
2. Move binaries that must stay versioned to Git LFS (new versions right away; old versions only with `git lfs migrate`).
3. Make clones cheaper without rewriting: `--filter=blob:none` partial clones, shallow CI checkouts, sparse checkout.
4. Rewrite history only with team agreement: freeze merges, back up a mirror, run `git filter-repo`, force-push, ask everyone to re-clone, ask the host to run garbage collection.
5. For B05: rotate the credential first, then clean history, then check forks and CI caches.

### 5. Report
Fill `templates/repo-bloat-report.md`: current size and clone time, top findings, the recommended fix with its impact on the team, the steps, and how you will keep the repository small.

## Example
```
python3 scripts/repo_bloat.py --objects-file examples/objects.txt --head-file examples/head.txt
```
Result: 59 unique blobs, 132.6 MB uncompressed, 79.2 MB of it only in history. Two credential-like files (`config/.env`, `deploy/staging.pem`) are flagged first; a deleted 48 MB hero video, a 12 MB SQLite dev database and a customer CSV export sit only in history; `logo.psd` has 4 versions (29.8 MB); `frontend/dist/`, `frontend/node_modules/` and `*.log` were committed. Suggestions: ignore and untrack the generated paths, LFS for `*.psd` and `*.png`, rotate the secrets, then a coordinated `git filter-repo` rewrite.

## Limits
- The scan reads only objects reachable from local refs; fetch all branches and tags first (`git fetch --all --tags`) or results will be incomplete. Reflog-only and unreachable objects are ignored.
- Folder and extension rules are heuristics: a `build/` folder may be real source in some projects. Confirm before ignoring.
- Credential detection is by file name only; secrets inside ordinary files need a dedicated secret scanner.
- The script never changes the repository; every command it prints must be reviewed and run by a person.

FILE:references/bloat-causes.md
# Common causes of repository bloat

| Cause | How to recognize it | Why it hurts | Typical fix |
|---|---|---|---|
| Media and design files (mp4, mov, psd, sketch, fig exports) | B02/B03 on `assets/`, `design/`, `marketing/` | Binaries barely compress and every edit stores a full copy | Git LFS or an asset store (S3, a DAM, the design tool itself) |
| Deleted large files | B01, `history only` in the top paths | Every clone still downloads them, forever | History rewrite with `git filter-repo --invert-paths` |
| Database dumps and SQLite dev databases | `.sql`, `.sqlite`, `.db`, `.dump` in B01/B02 | Large, often contain real personal data | Remove, rotate if they contain secrets, regenerate from seed scripts |
| Data exports (CSV, JSON, Parquet) | `data/`, `exports/`, many versions of one file | Grows with every refresh, may contain customer data | Keep in object storage; commit a small sample instead |
| Dependency folders | B04 on `node_modules/`, `vendor/`, `.venv/`, `Pods/` | Thousands of files, slow checkouts, noisy diffs | `.gitignore` + lock files; vendoring only when policy requires it |
| Build output | B04 on `dist/`, `build/`, `target/`, `bin/`, `*.map` | Regenerated on every build, conflicts in every merge | Build in CI, publish artifacts to a registry or release page |
| Logs and caches | B04 on `*.log`, `*.tmp`, `__pycache__/` | Grow without limit, may leak tokens and user data | `.gitignore`, clean the working tree |
| Compiled binaries and installers | `.exe`, `.dll`, `.so`, `.jar`, `.apk`, `.dmg` | Large and change with every release | Release assets or a package registry |
| Credentials | B05 on `.env`, `*.pem`, `id_rsa`, `credentials.json` | A security incident, regardless of size | Rotate first, then remove from history |

## Rough cost model

- Clone size: approximately the pack size (`git count-objects -vH`, `size-pack`). Every developer and every CI job without a cache pays it.
- Checkout size: the files in HEAD. Large HEAD files slow every branch switch and Docker build context.
- History-only weight: costs bandwidth and disk on every full clone but nothing on checkout. Only a rewrite removes it.
- Time: at 50 Mbit/s, 1 GB takes about 3 minutes to clone; multiply by CI runs per day to show the team the real cost.

## Questions to ask before acting

1. Is any of this needed to build or test the product? Who owns it?
2. Does the file contain personal or customer data? (Then removal is a privacy task, not just cleanup.)
3. How many forks, mirrors and open pull requests exist? (A rewrite invalidates them.)
4. Is Git LFS available on the host and paid for (storage and bandwidth quotas)?

FILE:references/cleanup-playbook.md
# Cleanup playbook (least to most disruptive)

Always start at the top and stop as soon as the problem is solved.

## 1. Stop the growth (no history change)

```
echo "frontend/node_modules/" >> .gitignore
echo "frontend/dist/" >> .gitignore
echo "*.log" >> .gitignore
git rm -r --cached frontend/node_modules frontend/dist logs/worker.log
git commit -m "Stop tracking generated files"
```
Add a guard so it does not happen again, for example a CI step that fails when a new file is over 5 MB:
```
git diff --name-only --diff-filter=AM origin/main...HEAD | while read -r f; do if [ -f "$f" ] && [ "$(wc -c < "$f")" -gt 5242880 ]; then echo "too large: $f"; exit 1; fi; done
```
Many hosts also offer push rules or file size limits; turn them on.

## 2. Git LFS for binaries that must stay versioned

```
git lfs install
git lfs track "*.psd" "*.png"
git add .gitattributes
git commit -m "Track design files with Git LFS"
```
This only affects new commits. To move old versions too, `git lfs migrate import --include="*.psd,*.png" --everything` rewrites history (see step 4 for the coordination rules). Check the host's LFS storage and bandwidth quotas first.

## 3. Cheaper clones without rewriting

- Partial clone: `git clone --filter=blob:none <url>` downloads file contents only when needed.
- CI: shallow fetch (`fetch-depth: 1` or `git fetch --depth 1`) and cache the repository between jobs.
- Sparse checkout for monorepos: `git sparse-checkout set services/api`.
These help immediately and need no team coordination.

## 4. History rewrite (team decision)

Use `git filter-repo` (install with `pip install git-filter-repo`); avoid the old `git filter-branch`.

1. Announce a freeze window; ask everyone to push or park their work.
2. Back up: `git clone --mirror <url> backup.git`.
3. Rewrite in a fresh mirror clone:
   ```
   git clone --mirror <url> repo.git && cd repo.git
   git filter-repo --invert-paths --path 'assets/brand/hero-video.mp4' --path 'db/dev.sqlite' --path 'frontend/node_modules/'
   ```
   Or by size: `git filter-repo --strip-blobs-bigger-than 10M`.
4. Check the result (`git count-objects -vH`, run the scan again, build the project).
5. Force-push all refs (`git push --force --mirror`), with branch protection temporarily adjusted.
6. Everyone re-clones; old clones must not be pushed again or the objects come back.
7. Ask the host to run garbage collection; cached views, forks and pull request refs may keep the old objects until then.

## 5. Leaked credentials (B05)

1. Rotate or revoke the credential immediately: assume it is compromised.
2. Check access logs for its use.
3. Remove the file from history (step 4) and add the pattern to `.gitignore`.
4. Check forks, CI caches, artifacts and backups; a rewrite does not reach them.
5. Add a secret scanner to pre-commit and CI.

FILE:templates/repo-bloat-report.md
# Repository bloat report: {{repo_name}}

Date: {{date}} | Prepared by: {{author}} | Scan threshold: {{threshold}}

## Current state
- Pack size: {{pack_size}} | Files in HEAD: {{head_files}} | Commits: {{commit_count}}
- Full clone time on a typical connection: {{clone_time}} | CI clones per day: {{ci_clones}}
- Weight only in history: {{history_only}} ({{history_share}} of the total)

## Top findings
| Code | Path | Size | Why it matters |
|---|---|---|---|
| {{code}} | {{path}} | {{size}} | {{impact}} |

## Security first
- Credential-like files found: {{secrets_found}}
- Rotation status: {{rotation_status}} (owner: {{owner}})

## Recommended fix
- Option chosen: {{option}} (stop growth / LFS / cheaper clones / history rewrite)
- Expected result: {{expected_size}} pack, {{expected_clone_time}} clone time
- Impact on the team: {{team_impact}} (freeze window, re-clone, open pull requests)

## Steps
1. {{step_1}}
2. {{step_2}}
3. {{step_3}}

## Keeping it small
- Guard: {{guard}} (size check in CI, push rules, pre-commit hook)
- Review again on: {{next_review_date}}

FILE:examples/objects.txt
blob 987a907e4523b6111c4032a2de469e80d6318a67 6144 2048 README.md
blob 467a9a30da173bcb871b88c24a02f60c24e7f9f9 6444 2048 README.md
blob 8ef230704ac1b68adc2b5748df15968e4ddb3088 6744 2048 README.md
blob 656d9098a0fc0df4bdd052ef009a292ff8c52848 7044 2048 README.md
blob 3a92412f2e656df43d5eb4459ac6c6b2302b6b8e 7344 2048 README.md
blob 339b73b1021ec2d5a0d68df3ed3d6b1a531293e0 14336 4096 src/app/main.py
blob ca58bbbda0df031c4994e89dc0407ed538c0aad0 14836 4096 src/app/main.py
blob fdfc0acc5dc7fd2c7b21fe76f704a67a6794af52 15336 4096 src/app/main.py
blob c5f063b21bb5ccdc0f244717285e3b3aa0126eae 15836 4096 src/app/main.py
blob 68c156c282e4dbb74fce3d1c4c93f96ef8ae18f4 16336 4096 src/app/main.py
blob 3dafece57cdeb9b9f322889d15e2a29fb6b72d40 16836 4096 src/app/main.py
blob c7d29b6a0f4e7e4db03f1857834c0e724c914995 17336 4096 src/app/main.py
blob 13ff860496311c12569e38b3a9f73cfb25fbf46f 17836 4096 src/app/main.py
blob eb5b0bd6b49ca65809fabb47c8710d867c8298d4 18336 4096 src/app/main.py
blob 5e51b6d4ddb5bc57b05980620b6fb3b51df53c0d 18836 4096 src/app/main.py
blob 8ca5b647d515af133295911f40fb50b449463cc8 19336 4096 src/app/main.py
blob 7ec4c4ea18e09a533575193190c997f2cc3d4d36 19836 4096 src/app/main.py
blob b8cc9ba2bc56eb1d4dc005c4533494fd223b047f 22528 6144 src/app/billing.py
blob 2e09d8b2e9f72e141f1ae13130739ab1a69d0254 22928 6144 src/app/billing.py
blob 1229e1c043d923b8bb18544347d15f896f0655c2 23328 6144 src/app/billing.py
blob 84357f16b451644e27fc070e3ecf8412a28ebd84 23728 6144 src/app/billing.py
blob 67bc2edb1d10df2d4c09e9ef447d1009beea03f2 24128 6144 src/app/billing.py
blob e603f31f8fa50bcde4ece184771d79a3eabb7695 24528 6144 src/app/billing.py
blob 4ab2814bbce6171176ef2cb01067896be3101ac4 24928 6144 src/app/billing.py
blob a494b3e4a3d1d2bf92cd586825fa99a1193c6158 25328 6144 src/app/billing.py
blob 60a7975811a5d84956eff0acc905b1ef7f8fbcdc 5120 2048 src/app/templates/base.html
blob 8b505d827b0d4d726b603881577af4e80a052d51 5220 2048 src/app/templates/base.html
blob 287e546d9d361cabb13e364beb39ef9b1ac7ce69 5320 2048 src/app/templates/base.html
blob 55a0f95169753b93cabc770ef0ffaae3c8ddeabd 5420 2048 src/app/templates/base.html
blob 2ad6207e009687438942e26b7ebf103fef22a6ff 50331648 48821698 assets/brand/hero-video.mp4
blob 3a225ebac43b538c5ea7beabc046812f65af67b5 7340032 7119831 assets/brand/logo.psd
blob 9c5b0b132d594a764230d13ff70f48330ffb370f 7647232 7417815 assets/brand/logo.psd
blob 84736e8dd8c132cee548c2bec98dc5dc5ba176e2 7954432 7715799 assets/brand/logo.psd
blob 069d6d0ff43d270b6bef99fdf0fc0a3f2112a989 8261632 8013783 assets/brand/logo.psd
blob 18d782987a0fa858e2cba05c633902df49991e8c 921600 893952 assets/screens/onboarding.png
blob 410d6195accb75a817fa6149ba8d7f6358b6893c 962560 933683 assets/screens/onboarding.png
blob b5ea2d3014d635d26a33c10a2205b2e8f3b891f5 1003520 973414 assets/screens/onboarding.png
blob f70530d27121cf6025aba939715c1edf0577f83a 3145728 943718 data/customers_export.csv
blob b40ca9568e642ad4030927d94455ed9764aa0055 3350528 943718 data/customers_export.csv
blob 19cf653daa39079239aee328d5ea7ed2bb3cced2 3555328 943718 data/customers_export.csv
blob 2f7f18e1841133120d5cc15925b74484cd383c6c 12582912 2621440 db/dev.sqlite
blob ca143f39bfc924e872c6d2b395225ac5231f74ff 552960 143360 frontend/node_modules/lodash/lodash.js
blob c309ad74f9fc468d6c51acc51ddf31a6dab8b930 1126400 266240 frontend/node_modules/react-dom/cjs/react-dom.development.js
blob fc7ba143307cde940ab1c1bf3e605ee8f83ef771 8388608 1677721 frontend/node_modules/typescript/lib/typescript.js
blob 965fe4a622f24b31a613a9b352c36e02a15e304c 2097152 614400 frontend/dist/app.bundle.js
blob ec9c755c04059eab6161788223042b4d5a89c5d8 2127872 614400 frontend/dist/app.bundle.js
blob 22f555d29e65fa59336b516fb82449944331fa29 2158592 614400 frontend/dist/app.bundle.js
blob 402418e8073e751e4ec5b210bc7c990651e8c466 2189312 614400 frontend/dist/app.bundle.js
blob 5627dea439be9b76645cd085f048255a04f53bcf 2220032 614400 frontend/dist/app.bundle.js
blob e4b799492f2dbeb24371d9d9c5fbf1f7c7d5f80f 2250752 614400 frontend/dist/app.bundle.js
blob 99d4fbc1f35947bddfb1a5956b3f43515e609f87 4194304 629145 logs/worker.log
blob ac63ac9926a59aca550a097616450bfd88419ae1 4194304 629145 logs/worker.log
blob 3649ca8d0a6d4fc4a3a489ae127f2f57f6c12ff5 900 600 config/.env
blob b5dbab6eeda4ceb03e77ea8715beadb595399269 900 600 config/.env
blob 3f8a4ec013300145a11a3eb276114177e5d84481 700 500 config/.env.example
blob e370702e8693d488e1e1ba4284ffdd3af0d8dff7 3072 3072 deploy/staging.pem
blob 2396abc88761182884eac3687470e339883c801a 9216 3072 docs/architecture.md
blob 53d19b2eda8ff06e94c0b7fa90b5f056bb4e54fc 9716 3072 docs/architecture.md
blob 84008c60e233c95a554251fc59a44b90b0f4f693 10216 3072 docs/architecture.md

FILE:examples/head.txt
README.md
src/app/main.py
src/app/billing.py
src/app/templates/base.html
assets/brand/logo.psd
assets/screens/onboarding.png
frontend/dist/app.bundle.js
config/.env.example
docs/architecture.md
logs/worker.log

FILE:scripts/repo_bloat.py
#!/usr/bin/env python3
"""repo_bloat.py - find what makes a Git repository big and slow to clone.

Reads every object reachable from all refs (git rev-list --objects --all + git cat-file --batch-check),
groups blobs by path and flags large files, files deleted from HEAD but still in history, binaries with
many versions, generated/vendored folders and credential-like files. Suggests .gitignore, Git LFS
patterns and history-rewrite commands, but never changes the repository.

Usage:
  repo_bloat.py [--repo PATH] [--threshold-mb 5] [--top 15] [--format text|md|json]
  repo_bloat.py --objects-file objects.txt --head-file head.txt     (offline: pre-captured listings)
  repo_bloat.py --self-test
Exit: 0 = no findings, 1 = findings, 2 = not a git repository / unreadable input.
Python 3.8+ standard library only (needs the git CLI unless --objects-file is used)."""
import argparse, json, os, subprocess, sys, tempfile, shutil
from collections import defaultdict

BINARY_EXT = {".zip", ".tar", ".gz", ".tgz", ".7z", ".rar", ".jar", ".war", ".exe", ".dll", ".so", ".dylib",
              ".iso", ".dmg", ".pkg", ".apk", ".ipa", ".mp4", ".mov", ".avi", ".mkv", ".mp3", ".wav", ".flac",
              ".psd", ".ai", ".sketch", ".fig", ".blend", ".fbx", ".obj", ".png", ".jpg", ".jpeg", ".gif",
              ".tif", ".tiff", ".bmp", ".webp", ".pdf", ".sqlite", ".db", ".parquet", ".h5", ".pkl", ".pt",
              ".onnx", ".bin", ".npy", ".xlsx", ".docx", ".pptx", ".ttf", ".otf", ".woff", ".woff2"}
GENERATED_DIRS = ("node_modules/", "vendor/", "dist/", "build/", "target/", "out/", ".venv/", "venv/",
                  "__pycache__/", ".next/", "coverage/", "bin/Debug/", "bin/Release/", "obj/")
GENERATED_EXT = {".log", ".tmp", ".cache", ".pyc", ".class", ".o", ".map"}
SECRET_NAMES = {".env", "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "credentials.json", "service-account.json",
                ".npmrc", ".pypirc", ".netrc", "secrets.yml", "secrets.yaml"}
SECRET_EXT = {".pem", ".key", ".p12", ".pfx", ".keystore", ".jks"}

def human(n):
    for u in ("B", "KB", "MB", "GB"):
        if n < 1024 or u == "GB":
            return ("%d %s" % (n, u)) if u == "B" else ("%.1f %s" % (n, u))
        n /= 1024.0

def ext_of(path):
    base = path.rsplit("/", 1)[-1].lower()
    return os.path.splitext(base)[1], base

def generated_key(path):
    """Return the folder (e.g. 'web/node_modules/') or '*.ext' group for generated/vendored paths, else None."""
    ext, base = ext_of(path)
    for d in GENERATED_DIRS:
        idx = ("/" + path).find("/" + d)
        if idx >= 0:
            return path[:idx + len(d) - 1] + "/"
    return ("*" + ext) if ext in GENERATED_EXT else None

def git(repo, *args, stdin=None):
    r = subprocess.run(["git", "-C", repo] + list(args), input=stdin, capture_output=True, text=True)
    if r.returncode != 0:
        raise RuntimeError(r.stderr.strip() or "git failed")
    return r.stdout

def read_objects_from_repo(repo):
    """Return (objects, head_paths, pack_bytes). objects = list of (sha, size, disk_size, path)."""
    revs = git(repo, "rev-list", "--objects", "--all")
    batch = git(repo, "cat-file", "--batch-check=%(objecttype) %(objectname) %(objectsize) %(objectsize:disk) %(rest)", stdin=revs)
    objs = parse_objects(batch)
    try:
        head = set(x for x in git(repo, "ls-tree", "-r", "--name-only", "HEAD").splitlines() if x)
    except RuntimeError:
        head = set()
    pack = 0
    for line in git(repo, "count-objects", "-v").splitlines():
        k, _, v = line.partition(":")
        if k.strip() in ("size", "size-pack"):
            pack += int(v.strip() or 0) * 1024
    return objs, head, pack

def parse_objects(text):
    """Parse 'type sha size disk path' lines; keep blobs with a path. Paths may contain spaces."""
    out = []
    for line in text.splitlines():
        parts = line.split(" ", 4)
        if len(parts) < 5 or parts[0] != "blob" or not parts[4]:
            continue
        try:
            out.append((parts[1], int(parts[2]), int(parts[3]), parts[4]))
        except ValueError:
            continue
    return out

def analyze(objs, head, threshold, pack_bytes=0, top=15):
    by_path = defaultdict(lambda: {"versions": 0, "total": 0, "disk": 0, "max": 0, "shas": set()})
    seen = set()
    for sha, size, disk, path in objs:
        p = by_path[path]
        if sha in p["shas"]:
            continue
        p["shas"].add(sha); p["versions"] += 1; p["total"] += size; p["max"] = max(p["max"], size)
        if sha not in seen:
            p["disk"] += disk
        seen.add(sha)
    findings = []
    def add(code, path, msg, size):
        findings.append({"code": code, "path": path, "size": size, "message": msg})
    for path, p in by_path.items():
        ext, base = ext_of(path)
        in_head = path in head
        if generated_key(path):
            continue  # reported once per folder/extension as B04
        if p["max"] >= threshold:
            add("B02" if in_head else "B01", path, ("large file in HEAD, largest version %s" if in_head else
                "large file only in history (deleted from HEAD), largest version %s") % human(p["max"]), p["max"])
        elif not in_head and p["total"] >= threshold:
            add("B01", path, "deleted from HEAD but %d versions still cost %s in history" % (p["versions"], human(p["total"])), p["total"])
        if p["versions"] >= 3 and p["total"] >= threshold / 2 and ext in BINARY_EXT:
            add("B03", path, "binary with %d versions, %s in total (each change stores a full copy)" % (p["versions"], human(p["total"])), p["total"])
    gen = defaultdict(lambda: [0, 0, 0])
    for path, p in by_path.items():
        key = generated_key(path)
        if key:
            gen[key][0] += 1; gen[key][1] += p["total"]; gen[key][2] += path in head
    for key, (n, total, nhead) in gen.items():
        add("B04", key, "generated or vendored files committed: %d path%s, %s, %s" % (n, "" if n == 1 else "s", human(total),
            ("%d still in HEAD" % nhead) if nhead else "history only"), total)
    for path, p in by_path.items():
        ext, base = ext_of(path)
        if base in SECRET_NAMES or ext in SECRET_EXT or (base.startswith(".env.") and not base.endswith((".example", ".sample", ".template"))):
            add("B05", path, "credential-like file in history%s: treat the secret as leaked and rotate it" % (" and HEAD" if path in head else ""), p["total"])
    order = {"B05": 0, "B01": 1, "B02": 2, "B03": 3, "B04": 4}
    findings.sort(key=lambda f: (order[f["code"]], -f["size"], f["path"]))
    total_blob = sum(p["total"] for p in by_path.values())
    head_bytes = sum(p["max"] for k, p in by_path.items() if k in head)
    history_only = sum(p["total"] for k, p in by_path.items() if k not in head)
    tops = sorted(by_path.items(), key=lambda kv: -kv[1]["total"])[:top]
    ext_totals = defaultdict(int)
    for path, p in by_path.items():
        ext_totals[ext_of(path)[0] or "(none)"] += p["total"]
    return {
        "summary": {"paths": len(by_path), "unique_blobs": len(seen), "blob_bytes": total_blob,
                    "history_only_bytes": history_only, "head_paths": len(head), "pack_bytes": pack_bytes,
                    "threshold_bytes": threshold, "approx_head_bytes": head_bytes},
        "top_paths": [{"path": k, "versions": v["versions"], "total": v["total"], "largest": v["max"], "disk": v["disk"], "in_head": k in head} for k, v in tops],
        "top_extensions": sorted(([e, n] for e, n in ext_totals.items()), key=lambda x: -x[1])[:8],
        "findings": findings,
        "suggestions": suggestions(findings),
    }

def suggestions(findings):
    s, lfs, ignore, purge = [], set(), set(), []
    for f in findings:
        ext, base = ext_of(f["path"])
        if f["code"] in ("B02", "B03") and ext in BINARY_EXT:
            lfs.add("*" + ext)
        if f["code"] == "B04":
            ignore.add(f["path"])
            if f["path"].endswith("/"):
                purge.append(f["path"])
        if f["code"] in ("B01", "B05"):
            purge.append(f["path"])
    if ignore:
        s.append(".gitignore: add " + ", ".join(sorted(ignore)) + " and remove them from the index with: git rm -r --cached <path>")
    if lfs:
        s.append("Git LFS for new versions: git lfs track " + " ".join('"%s"' % x for x in sorted(lfs)) + "  (old versions stay in history unless migrated: git lfs migrate import --include=\"" + ",".join(sorted(lfs)) + "\" --everything)")
    if purge:
        s.append("History rewrite (coordinate with the team, back up first, every clone must re-clone): git filter-repo --invert-paths " + " ".join("--path '%s'" % p for p in sorted(set(purge))[:10]))
    if any(f["code"] == "B05" for f in findings):
        s.append("Secrets: rotate every credential found BEFORE rewriting history; a rewrite does not remove copies in forks, clones or CI caches.")
    if not s:
        s.append("No action needed at this threshold; consider a pre-commit size check to keep it that way.")
    return s

def render(res, fmt):
    sm = res["summary"]
    if fmt == "json":
        return json.dumps(res, indent=2)
    lines = []
    if fmt == "md":
        lines += ["# Repository bloat report", "",
                  "- Unique blobs: %d across %d paths, %s uncompressed" % (sm["unique_blobs"], sm["paths"], human(sm["blob_bytes"])),
                  "- History-only (deleted from HEAD): %s" % human(sm["history_only_bytes"]),
                  "- Pack on disk: %s" % (human(sm["pack_bytes"]) if sm["pack_bytes"] else "n/a (offline input)"),
                  "- Threshold: %s" % human(sm["threshold_bytes"]), "", "## Top paths by total size", "",
                  "| Path | Versions | Total | Largest | In HEAD |", "|---|---|---|---|---|"]
        lines += ["| `%s` | %d | %s | %s | %s |" % (t["path"], t["versions"], human(t["total"]), human(t["largest"]), "yes" if t["in_head"] else "no") for t in res["top_paths"]]
        lines += ["", "## Findings", ""] + (["- **%s** `%s`: %s" % (f["code"], f["path"], f["message"]) for f in res["findings"]] or ["- none"])
        lines += ["", "## Suggested next steps", ""] + ["- " + x for x in res["suggestions"]]
        return "\n".join(lines) + "\n"
    lines.append("Repository bloat: %d unique blobs in %d paths, %s uncompressed; %s only in history; pack %s"
                 % (sm["unique_blobs"], sm["paths"], human(sm["blob_bytes"]), human(sm["history_only_bytes"]),
                    human(sm["pack_bytes"]) if sm["pack_bytes"] else "n/a"))
    lines.append("By extension: " + ", ".join("%s %s" % (e, human(n)) for e, n in res["top_extensions"]))
    lines.append("")
    lines.append("Top paths (total over all versions):")
    for t in res["top_paths"]:
        lines.append("  %-44s %3d ver  %10s  largest %10s  %s" % (t["path"][:44], t["versions"], human(t["total"]), human(t["largest"]), "HEAD" if t["in_head"] else "history only"))
    lines.append("")
    lines.append("Findings (%d):" % len(res["findings"]))
    for f in res["findings"]:
        lines.append("  %s %s - %s" % (f["code"], f["path"], f["message"]))
    if not res["findings"]:
        lines.append("  none")
    lines.append("")
    lines.append("Suggested next steps (nothing was changed):")
    for x in res["suggestions"]:
        lines.append("  - " + x)
    return "\n".join(lines) + "\n"

def self_test():
    ok = 0; total = 0
    def check(name, cond):
        nonlocal ok, total
        total += 1; ok += bool(cond)
        print(("PASS  " if cond else "FAIL  ") + name)
    MB = 1024 * 1024
    objs = parse_objects("commit aaa 200 150 \nblob b1 6291456 6000000 assets/intro video.mp4\nblob b2 100 80 README.md\ntree t1 50 40 src\nbadline\n")
    check("parser keeps blobs, paths with spaces", objs == [("b1", 6291456, 6000000, "assets/intro video.mp4"), ("b2", 100, 80, "README.md")])
    r = analyze(objs, {"README.md"}, 5 * MB)
    check("B01 large deleted file", any(f["code"] == "B01" and f["path"] == "assets/intro video.mp4" for f in r["findings"]))
    r = analyze(objs, {"README.md", "assets/intro video.mp4"}, 5 * MB)
    check("B02 large file in HEAD", [f["code"] for f in r["findings"]] == ["B02"])
    check("LFS suggestion for .mp4", any("git lfs track \"*.mp4\"" in s for s in r["suggestions"]))
    v = [("s%d" % i, 2 * MB, 2 * MB, "design/logo.psd") for i in range(4)]
    r = analyze(v, {"design/logo.psd"}, 5 * MB)
    check("B03 binary with many versions", any(f["code"] == "B03" for f in r["findings"]))
    check("versions counted once per sha", r["top_paths"][0]["versions"] == 4 and r["top_paths"][0]["total"] == 8 * MB)
    r = analyze([("x", 100, 90, "web/node_modules/lodash/index.js"), ("y", 200, 90, "web/node_modules/react/index.js")], set(), 5 * MB)
    check("B04 groups node_modules", any(f["code"] == "B04" and f["path"] == "web/node_modules/" and "2 paths" in f["message"] for f in r["findings"]))
    r = analyze([("big", 9 * MB, 2 * MB, "node_modules/typescript/lib/typescript.js")], set(), 5 * MB)
    check("vendored big file reported once as B04, not B01", [f["code"] for f in r["findings"]] == ["B04"] and any("--path 'node_modules/'" in x for x in r["suggestions"]))
    r = analyze([("x", 100, 90, "logs/app.log")], {"logs/app.log"}, 5 * MB)
    check("B04 *.log", any(f["code"] == "B04" and f["path"] == "*.log" for f in r["findings"]))
    r = analyze([("k", 40, 40, "config/.env"), ("e", 40, 40, "config/.env.example"), ("p", 40, 40, "deploy/server.pem")], set(), 5 * MB)
    codes = [(f["code"], f["path"]) for f in r["findings"]]
    check("B05 .env and .pem flagged", ("B05", "config/.env") in codes and ("B05", "deploy/server.pem") in codes)
    check(".env.example not flagged", ("B05", "config/.env.example") not in codes)
    check("secret rotation advice", any(s.startswith("Secrets: rotate") for s in r["suggestions"]))
    check("B05 sorted first", r["findings"][0]["code"] == "B05")
    r = analyze([("a", 1000, 900, "src/main.py")], {"src/main.py"}, 5 * MB)
    check("clean repo no findings", r["findings"] == [] and "No action needed" in r["suggestions"][0])
    many = [("d%d" % i, 1 * MB, 1 * MB, "data/export.csv") for i in range(6)]
    r = analyze(many, set(), 5 * MB)
    check("B01 many small versions of deleted file", any(f["code"] == "B01" and "6 versions" in f["message"] for f in r["findings"]))
    check("human sizes", human(512) == "512 B" and human(1536) == "1.5 KB" and human(5 * MB) == "5.0 MB")
    check("json render parses", json.loads(render(r, "json"))["summary"]["paths"] == 1)
    check("md render has table", "| Path | Versions |" in render(r, "md"))
    if shutil.which("git"):
        d = tempfile.mkdtemp()
        try:
            env_git = ["-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false"]
            subprocess.run(["git", "init", "-q", d], check=True)
            open(os.path.join(d, "README.md"), "w").write("hello\n")
            with open(os.path.join(d, "big.bin"), "wb") as fh: fh.write(os.urandom(300 * 1024))
            subprocess.run(["git", "-C", d] + env_git + ["add", "."], check=True)
            subprocess.run(["git", "-C", d] + env_git + ["commit", "-qm", "add"], check=True)
            subprocess.run(["git", "-C", d] + env_git + ["rm", "-q", "big.bin"], check=True)
            subprocess.run(["git", "-C", d] + env_git + ["commit", "-qm", "rm"], check=True)
            objs, head, pack = read_objects_from_repo(d)
            r = analyze(objs, head, 200 * 1024)
            check("real git repo: deleted big.bin found in history (B01)", any(f["code"] == "B01" and f["path"] == "big.bin" for f in r["findings"]))
            check("real git repo: HEAD has README only", head == {"README.md"})
        finally:
            shutil.rmtree(d, ignore_errors=True)
    print("%d/%d checks passed" % (ok, total))
    return 0 if ok == total else 1

def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--repo", default=".")
    ap.add_argument("--threshold-mb", type=float, default=5.0)
    ap.add_argument("--top", type=int, default=15)
    ap.add_argument("--format", choices=["text", "md", "json"], default="text")
    ap.add_argument("--objects-file"); ap.add_argument("--head-file")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    try:
        if a.objects_file:
            objs = parse_objects(open(a.objects_file, encoding="utf-8").read())
            head = set(x.strip() for x in open(a.head_file, encoding="utf-8")) - {""} if a.head_file else set()
            pack = 0
        else:
            objs, head, pack = read_objects_from_repo(a.repo)
    except (OSError, RuntimeError) as e:
        print("error: %s" % e, file=sys.stderr)
        return 2
    res = analyze(objs, head, int(a.threshold_mb * 1024 * 1024), pack, a.top)
    sys.stdout.write(render(res, a.format))
    return 1 if res["findings"] else 0

if __name__ == "__main__":
    sys.exit(main())
GitPythonDevOps+5
F@f
0
Employee Turnover Cost Calculator
Skill

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())
HRCostFinance+5
F@f
0
Python Docstring Coverage Checker
Skill

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())
PythonDocumentationBest Practices+4
F@f
0
Accounts Receivable Aging Report
Skill

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())
FinanceBusinessPython+3
F@f
0
Python Complexity Hotspot Finder
Skill

Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.

---
name: python-complexity-hotspot-finder
description: Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.
---

# Python Complexity Hotspot Finder

You help Python developers, tech leads and maintainers find the functions that are hardest to change safely and decide what to refactor first. Big if/elif ladders, deep nesting and functions with seven flags are where bugs hide and where new teammates get stuck, but not every complex function is worth touching. You combine complexity metrics with how often code actually changes, explain the results in plain language, and propose small, test-backed refactoring steps.

You read code locally and never upload it. Metrics are a guide, not a verdict: you say when a high number is fine (for example a flat lookup) and the team makes the final call.

## Files in this skill

- `scripts/complexity_hotspots.py` - walks files or folders (skips .git, venvs, build dirs), measures every function and method with the `ast` module: cyclomatic complexity, nesting depth, lines, parameters, returns; optional `--churn DAYS` adds git commit counts per file and ranks by `cc x (1 + churn)`; findings H01-H07; `--format text|md|json`, `--min-severity`, `--top N`, threshold flags; `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/complexity-metrics.md` - how each metric is counted, rough bands, what churn adds and what the numbers do not tell you
- `references/refactoring-recipes.md` - guard clauses, lookup tables, extract function, flag parameters, condition helpers, and what not to do
- `templates/hotspot-report.md` - the review you hand back
- `examples/billing.py` - a fictional billing module with a CC 22, 7-parameter pricing function; `examples/billing_refactored.py` - the same logic after refactoring (CC 5 at most)

## Workflow

### 1. Scope
Ask which package or folders matter, whether it is a git repository (for churn), what is changing soon (upcoming features touch which modules?), and whether there are tests. Exclude generated code, migrations and vendored libraries.

### 2. Run the scan
```
python3 scripts/complexity_hotspots.py src/
python3 scripts/complexity_hotspots.py src/ --churn 90 --top 15
python3 scripts/complexity_hotspots.py src/ --churn 90 --min-severity medium --format md > hotspots.md
python3 scripts/complexity_hotspots.py src/ --format json
python3 scripts/complexity_hotspots.py --self-test
```
Exit code 0 = nothing at or above `--min-severity`, 1 = findings, 2 = bad path or only unparsable files. Files with syntax errors are listed as PARSE ERROR and skipped.

| Code | Severity | Meaning |
|---|---|---|
| H01 | high | CC >= 15 (`--cc-high`) |
| H02 | medium | CC >= 10 (`--cc-warn`) |
| H03 | medium | nesting depth >= 4 |
| H04 | medium | 60+ lines |
| H05 | low | 6+ parameters (self/cls excluded) |
| H06 | low | 6+ return statements |
| H07 | high | hotspot: CC >= warn and file changed in 5+ commits in the churn window |

### 3. Interpret
- Rank by hotspot score when churn is available; a complex function nobody touches is low priority.
- Read the top 3-5 functions yourself before recommending anything. Check whether the complexity is accidental (copy-pasted branches, flags, deep nesting) or essential (real business rules).
- Flat dispatch functions (`invoice_status` with six early returns) are usually fine: say so.
- Check test coverage for each top hotspot; untested hotspots get characterization tests first.

### 4. Plan the refactor
For each top hotspot pick recipes from `references/refactoring-recipes.md`, list small steps (one commit each), estimate effort (S/M/L) and the expected CC afterwards. Never mix behavior changes with refactoring. Re-run the script after the change to show the before/after numbers.

### 5. Report
Fill `templates/hotspot-report.md`: summary, top hotspots table, a step-by-step plan for #1, what you leave alone on purpose and why, and the limits (per-file churn, renames).

## Example
```
python3 scripts/complexity_hotspots.py examples/billing.py
```
flags `calculate_invoice_total` with H01 (CC 22) and H05 (7 parameters) and `invoice_status` with H06 (6 returns, fine for a flat lookup). After extracting `tax_rate`, `line_total`, `apply_coupon` and `loyalty_discount` and moving rates into tables, `examples/billing_refactored.py` peaks at CC 5.

## Rules
- Measure first, then read the code; never recommend a refactor from numbers alone.
- Prefer small, reversible steps behind tests.
- Be honest about trade-offs: tables move complexity into data; helpers add jumps.
- Keep code on the user's machine.

FILE:references/complexity-metrics.md
# Complexity metrics: what they mean and how to read them

## Cyclomatic complexity (CC)
The number of independent paths through a function: 1 plus one for every decision point. `complexity_hotspots.py` counts:

| Construct | Adds |
|---|---|
| `if` / `elif` | 1 each (an `else` adds nothing) |
| `for`, `async for`, `while` | 1 |
| each `except` handler | 1 |
| `and` / `or` | 1 per extra operand (`a and b or c` adds 2) |
| comprehension (`for` part) and each of its `if` filters | 1 each |
| ternary `x if c else y` | 1 |
| `assert` | 1 |
| each `case` in `match` (Python 3.10+) | 1 |

Nested functions, classes and lambdas are measured on their own and do not add to the outer function.

### Rough bands (adjust with `--cc-warn` / `--cc-high`)
| CC | Reading |
|---|---|
| 1-5 | simple, easy to test |
| 6-10 | fine, keep an eye on it |
| 11-15 | hard to test fully; refactor when you next change it (H02) |
| 16+ | high risk; bugs hide here, plan a refactor (H01) |

CC is also the minimum number of test cases needed to cover every branch, which makes it a useful argument when talking to a team about test effort.

## Nesting depth
How many blocks deep the deepest statement sits (`if` inside `for` inside `try` = 3). An `elif` chain stays at the same depth. Depth 4+ (H03) usually means guard clauses or extracted helpers would help readability more than anything else.

## Length, parameters, returns
- **Lines** (H04, default 60): long functions mix several jobs. Length alone is weak; combined with high CC it is strong.
- **Parameters** (H05, default 6, `self`/`cls` excluded, `*args`/`**kwargs` counted): many flags often mean the function does several things; boolean flags are the strongest smell.
- **Returns** (H06, default 6): many exits are fine for a flat lookup (`invoice_status` style) but confusing in a long, nested function.

## Churn and hotspots (H07)
Complexity hurts only where people change code. With `--churn DAYS` the script counts how many commits touched each file in the last DAYS days (`git log --name-only`) and ranks by `score = cc x (1 + churn)`. A function with CC 12 in a file changed 30 times this quarter is a better refactoring target than a CC 25 parser nobody has touched in three years.

Limits: churn is per file, not per function; renames and big formatting commits inflate it; squash-merge workflows deflate it. Mention this when presenting results.

## What these numbers do not tell you
- Whether the code is correct or well tested; pair hotspots with coverage data if you have it.
- Domain complexity: some rules are genuinely complex, and a table-driven rewrite just moves the complexity into data (often still a win: data is easier to review and test).
- Readability of names and comments.

FILE:references/refactoring-recipes.md
# Refactoring recipes for complex Python functions

Always refactor behind tests. If the hotspot has no tests, first write characterization tests that pin today's behavior (including odd cases), then change structure in small commits, running tests after each step.

## 1. Guard clauses (fixes deep nesting, H03)
Return or `continue` early for the invalid or trivial cases instead of wrapping the main path in `if`.
```python
# before
for item in items:
    if item.qty > 0:
        if item.active:
            process(item)
# after
for item in items:
    if item.qty <= 0 or not item.active:
        continue
    process(item)
```

## 2. Lookup table instead of if/elif ladders (fixes H01/H02)
When branches only pick a value (a rate, a label, a handler), move the mapping into a dict.
```python
RATES = {("books", "EU"): 1.05, ("books", "*"): 1.08, ("*", "EU"): 1.2}
rate = RATES.get((cat, region), RATES.get((cat, "*"), 1.0))
```
For branches that run different code, map keys to functions: `HANDLERS[event.type](event)`.

## 3. Extract function (fixes H01, H04)
Give each job its own small, named function (`line_total`, `apply_coupon`, `loyalty_discount`). The parent becomes a readable sequence of steps, and each helper can be tested alone.

## 4. Replace boolean flag parameters (fixes H05)
`rush=False, gift_wrap=False, express=False` -> a small options set, an enum, or separate functions (`send_rush_order`). Group related parameters into a dataclass (`Address`, `PricingContext`).

## 5. Decompose complex conditions
`if customer.get("vip") or customer.get("orders", 0) > 20:` -> `if is_loyal(customer):`. The CC moves into a tiny, well-named function.

## 6. Polymorphism or `match` for type switches
A long `if kind == ...` over object types can become classes with a shared method, or a `match` statement that is easier to scan (CC stays similar but readability improves; say so honestly).

## 7. Split loops that do several things
One loop that filters, transforms, totals and logs -> a comprehension for filtering, a helper for transforming, `sum()` for totals.

## What not to do
- Do not chase a number: a flat 12-case lookup with CC 13 can be perfectly clear. Explain why you leave it.
- Do not refactor and change behavior in the same commit.
- Do not split a function into helpers that only make sense together and must be read in order; that adds jumps without reducing complexity.
- Do not refactor stable, untouched code just because it scores high; prioritize by churn and upcoming work.

FILE:templates/hotspot-report.md
# Complexity hotspot review: {{project}} ({{date}})

**Scope:** {{paths}} - {{function_count}} functions, average CC {{average_cc}}
**Thresholds:** CC warn {{cc_warn}} / high {{cc_high}}, depth {{max_depth}}, lines {{max_lines}}, params {{max_params}}; churn window {{churn_days}} days

## Summary
- {{one_sentence_overall_health}}
- Top risk: `{{top_function}}` ({{top_file}}) - {{why_it_matters}}
- Recommended next step: {{next_step}}

## Top hotspots
| Rank | Function | File | CC | Depth | Lines | Churn | Why it matters | Suggested refactor | Effort |
|---|---|---|---|---|---|---|---|---|---|
| 1 | | | | | | | | | S / M / L |
| 2 | | | | | | | | | |
| 3 | | | | | | | | | |

## Refactoring plan for the #1 hotspot
1. Characterization tests to add first: {{tests}}
2. Steps (one commit each): {{steps}}
3. Expected result: CC {{cc_before}} -> about {{cc_after}}, no behavior change
4. Risks and how we will check them: {{risks}}

## Left as is (on purpose)
- `{{function}}`: {{reason, e.g. flat lookup, stable for 2 years, scheduled for removal}}

## Notes and limits
- Churn is counted per file from git history; renames or formatting commits can inflate it.
- Metrics point to where to look; the team decides what to change.

FILE:examples/billing.py
"""Fictional billing module with typical hotspots (demo data for complexity_hotspots.py)."""


def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", rush=False, gift_wrap=False):
    total = 0
    for item in items:
        if item.get("qty", 0) <= 0:
            continue
        price = item["price"] * item["qty"]
        if item.get("category") == "books":
            if region == "EU":
                price = price * 1.05
            elif region == "UK":
                price = price
            else:
                price = price * 1.08
        elif item.get("category") == "food":
            if region == "EU" and not customer.get("business"):
                price = price * 1.07
            else:
                price = price * 1.0
        else:
            if region == "EU":
                price = price * 1.2
            elif region == "UK":
                price = price * 1.2
            elif region == "US" and customer.get("state") in ("CA", "NY"):
                price = price * 1.09
            else:
                price = price * 1.0
        total += price
    if coupon:
        if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
            total = total * (1 - coupon["value"] / 100)
        elif coupon.get("type") == "fixed":
            total = max(0, total - coupon["value"])
    if customer.get("vip") or customer.get("orders", 0) > 20:
        total = total * 0.95
    if rush:
        total += 15 if currency == "EUR" else 18
    if gift_wrap:
        total += 3
    return round(total, 2)


def invoice_status(invoice, today):
    if invoice["paid"]:
        return "paid"
    if invoice.get("disputed"):
        return "disputed"
    days = (today - invoice["due"]).days
    if days <= 0:
        return "open"
    if days <= 30:
        return "overdue"
    if days <= 90:
        return "late"
    return "collections"


def format_amount(value, currency):
    return "%s %.2f" % (currency, value)

FILE:examples/billing_refactored.py
"""The same billing logic after refactoring the hotspot (demo data for complexity_hotspots.py)."""

TAX_RATES = {
    # (category, region) -> rate; "*" means any
    ("books", "EU"): 1.05, ("books", "UK"): 1.0, ("books", "*"): 1.08,
    ("food", "EU"): 1.07, ("food", "*"): 1.0,
    ("*", "EU"): 1.2, ("*", "UK"): 1.2, ("*", "*"): 1.0,
}
US_TAXED_STATES = {"CA": 1.09, "NY": 1.09}
RUSH_FEE = {"EUR": 15, "USD": 18}
GIFT_WRAP_FEE = 3


def tax_rate(category, region, customer):
    if category == "food" and customer.get("business"):
        return 1.0
    if category not in ("books", "food") and region == "US":
        return US_TAXED_STATES.get(customer.get("state"), 1.0)
    key_category = category if category in ("books", "food") else "*"
    return TAX_RATES.get((key_category, region), TAX_RATES[(key_category, "*")])


def line_total(item, region, customer):
    return item["price"] * item["qty"] * tax_rate(item.get("category"), region, customer)


def apply_coupon(total, coupon):
    if not coupon:
        return total
    if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
        return total * (1 - coupon["value"] / 100)
    if coupon.get("type") == "fixed":
        return max(0, total - coupon["value"])
    return total


def loyalty_discount(total, customer):
    loyal = customer.get("vip") or customer.get("orders", 0) > 20
    return total * 0.95 if loyal else total


def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", options=()):
    subtotal = sum(line_total(i, region, customer) for i in items if i.get("qty", 0) > 0)
    total = loyalty_discount(apply_coupon(subtotal, coupon), customer)
    if "rush" in options:
        total += RUSH_FEE.get(currency, 18)
    if "gift_wrap" in options:
        total += GIFT_WRAP_FEE
    return round(total, 2)

FILE:scripts/complexity_hotspots.py
#!/usr/bin/env python3
"""complexity_hotspots.py - find Python functions that are hard to change safely.

Measures per function/method (standard library only, Python 3.8+):
  cc       cyclomatic complexity (1 + decision points: if/elif, for/while, except,
           boolean operators, comprehension ifs, ternaries, match cases, assert)
  depth    deepest nesting of blocks inside the function
  lines    function length in source lines
  params   number of parameters (excluding self/cls)
  returns  number of return statements
Optional --churn adds how many commits touched each file in the last N days (git log),
and ranks hotspots by cc x (1 + churn).

Findings (severity):
  H01 cc >= --cc-high (default 15)        high
  H02 cc >= --cc-warn (default 10)         medium
  H03 nesting depth >= --max-depth (4)     medium
  H04 lines >= --max-lines (60)            medium
  H05 params >= --max-params (6)           low
  H06 returns >= --max-returns (6)         low
  H07 hotspot: cc >= cc-warn and file churn >= --churn-min (5)   high

Usage:
  complexity_hotspots.py PATH [PATH ...] [--format text|md|json] [--min-severity low|medium|high]
                         [--churn DAYS] [--top N] [--cc-warn N] [--cc-high N] ...
  complexity_hotspots.py --self-test
Exit codes: 0 no findings at or above min severity, 1 findings present, 2 usage/parse error.
"""
import argparse, ast, json, os, subprocess, sys

SEV = {"low": 1, "medium": 2, "high": 3}
SKIP_DIRS = {".git", ".venv", "venv", "env", "__pycache__", "node_modules", "build", "dist", ".tox", ".mypy_cache"}


class FuncVisitor(ast.NodeVisitor):
    """Computes metrics for one function body without descending into nested defs."""

    BLOCKS = (ast.If, ast.For, ast.AsyncFor, ast.While, ast.Try, ast.With, ast.AsyncWith)

    def __init__(self):
        self.cc = 1
        self.max_depth = 0
        self.returns = 0
        self._depth = 0

    def generic_visit(self, node):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
            return  # nested definitions are measured separately (lambdas count as 0)
        block = isinstance(node, self.BLOCKS) or type(node).__name__ in ("TryStar", "Match")
        if isinstance(node, (ast.If, ast.For, ast.AsyncFor, ast.While, ast.IfExp, ast.Assert)):
            self.cc += 1
        elif isinstance(node, ast.ExceptHandler):
            self.cc += 1
        elif isinstance(node, ast.BoolOp):
            self.cc += len(node.values) - 1
        elif isinstance(node, ast.comprehension):
            self.cc += 1 + len(node.ifs)
        elif type(node).__name__ == "match_case":
            self.cc += 1
        elif isinstance(node, ast.Return):
            self.returns += 1
        if block:
            # an elif is an If inside orelse; do not count it as deeper nesting
            self._depth += 1
            self.max_depth = max(self.max_depth, self._depth)
        super().generic_visit(node)
        if block:
            self._depth -= 1

    def visit_If(self, node):
        self.cc += 1
        self.visit(node.test)
        self._depth += 1
        self.max_depth = max(self.max_depth, self._depth)
        for n in node.body:
            self.visit(n)
        self._depth -= 1
        orelse = node.orelse
        if len(orelse) == 1 and isinstance(orelse[0], ast.If):
            self.visit_If(orelse[0])  # elif chain: same depth
        else:
            self._depth += 1
            for n in orelse:
                self.visit(n)
            self._depth -= 1


def measure_function(node):
    v = FuncVisitor()
    for stmt in node.body:
        v.visit(stmt)
    args = node.args
    names = [a.arg for a in getattr(args, "posonlyargs", []) + args.args + args.kwonlyargs]
    if args.vararg: names.append(args.vararg.arg)
    if args.kwarg: names.append(args.kwarg.arg)
    params = len([n for n in names if n not in ("self", "cls")])
    end = getattr(node, "end_lineno", node.lineno)
    return {"cc": v.cc, "depth": v.max_depth, "lines": end - node.lineno + 1, "params": params, "returns": v.returns}


def analyze_source(src, filename="<string>"):
    tree = ast.parse(src, filename=filename)
    out = []

    def walk(node, prefix):
        for child in ast.iter_child_nodes(node):
            if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
                name = prefix + child.name
                m = measure_function(child)
                m.update({"file": filename, "function": name, "line": child.lineno})
                out.append(m)
                walk(child, name + ".")
            elif isinstance(child, ast.ClassDef):
                walk(child, prefix + child.name + ".")
            else:
                walk(child, prefix)

    walk(tree, "")
    return out


def iter_py_files(paths):
    for p in paths:
        if os.path.isfile(p):
            if p.endswith(".py"): yield p
            continue
        for root, dirs, files in os.walk(p):
            dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
            for f in sorted(files):
                if f.endswith(".py"):
                    yield os.path.join(root, f)


def git_churn(path, days):
    """Commits per file in the last `days` days, keyed by absolute path. Empty dict if not a git repo."""
    base = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path)) or "."
    try:
        top = subprocess.run(["git", "-C", base, "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=True).stdout.strip()
        log = subprocess.run(["git", "-C", top, "log", "--since=%d.days" % days, "--name-only", "--pretty=format:"],
                             capture_output=True, text=True, check=True).stdout
    except (OSError, subprocess.CalledProcessError):
        return {}
    churn = {}
    for line in log.splitlines():
        line = line.strip()
        if line.endswith(".py"):
            k = os.path.normpath(os.path.join(top, line))
            churn[k] = churn.get(k, 0) + 1
    return churn


def findings_for(m, o):
    f = []
    if m["cc"] >= o.cc_high: f.append(("H01", "high", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_high)))
    elif m["cc"] >= o.cc_warn: f.append(("H02", "medium", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_warn)))
    if m["depth"] >= o.max_depth: f.append(("H03", "medium", "nesting depth %d >= %d" % (m["depth"], o.max_depth)))
    if m["lines"] >= o.max_lines: f.append(("H04", "medium", "%d lines >= %d" % (m["lines"], o.max_lines)))
    if m["params"] >= o.max_params: f.append(("H05", "low", "%d parameters >= %d" % (m["params"], o.max_params)))
    if m["returns"] >= o.max_returns: f.append(("H06", "low", "%d return statements >= %d" % (m["returns"], o.max_returns)))
    if m.get("churn") is not None and m["cc"] >= o.cc_warn and m["churn"] >= o.churn_min:
        f.append(("H07", "high", "hotspot: complex (cc %d) and changed in %d commits recently" % (m["cc"], m["churn"])))
    return f


def run(paths, o):
    results, errors = [], []
    churn = {}
    if o.churn:
        for p in paths:
            churn.update(git_churn(p, o.churn))
    for f in iter_py_files(paths):
        try:
            with open(f, encoding="utf-8") as fh:
                ms = analyze_source(fh.read(), f)
        except (SyntaxError, UnicodeDecodeError) as e:
            errors.append("%s: %s" % (f, e)); continue
        for m in ms:
            if o.churn:
                m["churn"] = churn.get(os.path.normpath(os.path.abspath(f)), 0)
            m["score"] = m["cc"] * (1 + m.get("churn", 0))
            m["findings"] = [dict(code=c, severity=s, message=t) for c, s, t in findings_for(m, o)]
            results.append(m)
    results.sort(key=lambda m: (-m["score"], -m["cc"], m["file"], m["line"]))
    return results, errors


def render(results, errors, o):
    minsev = SEV[o.min_severity]
    flagged = [m for m in results if any(SEV[x["severity"]] >= minsev for x in m["findings"])]
    top = flagged[: o.top] if o.top else flagged
    n = len(results)
    avg = sum(m["cc"] for m in results) / n if n else 0
    if o.format == "json":
        return json.dumps({"functions": n, "average_cc": round(avg, 2), "flagged": len(flagged), "errors": errors,
                           "hotspots": top}, indent=2)
    churn_col = o.churn is not None and o.churn > 0
    if o.format == "md":
        head = "| Rank | Function | File:line | CC | Depth | Lines | Params |" + (" Churn |" if churn_col else "") + " Findings |"
        sep = "|---|---|---|---|---|---|---|" + ("---|" if churn_col else "") + "---|"
        rows = [head, sep]
        for i, m in enumerate(top, 1):
            fs = "; ".join("%s %s" % (x["code"], x["message"]) for x in m["findings"])
            rows.append("| %d | `%s` | %s:%d | %d | %d | %d | %d |%s %s |" % (i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"],
                        (" %d |" % m.get("churn", 0)) if churn_col else "", fs))
        rows.append("")
        rows.append("%d functions, average CC %.1f, %d flagged at %s+." % (n, avg, len(flagged), o.min_severity))
        return "\n".join(rows)
    lines = ["Complexity hotspots: %d functions, average CC %.1f, %d flagged (min severity %s)" % (n, avg, len(flagged), o.min_severity), ""]
    for i, m in enumerate(top, 1):
        extra = (" churn=%d" % m["churn"]) if "churn" in m else ""
        lines.append("%2d. %s  (%s:%d)  cc=%d depth=%d lines=%d params=%d returns=%d%s score=%d" % (
            i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"], m["returns"], extra, m["score"]))
        for x in m["findings"]:
            lines.append("      [%s] %s %s" % (x["severity"].upper(), x["code"], x["message"]))
    if not top: lines.append("No functions above the thresholds.")
    for e in errors: lines.append("PARSE ERROR " + e)
    return "\n".join(lines)


def parser():
    p = argparse.ArgumentParser(description="Find complex, frequently changed Python functions.")
    p.add_argument("paths", nargs="*")
    p.add_argument("--format", choices=["text", "md", "json"], default="text")
    p.add_argument("--min-severity", choices=list(SEV), default="low")
    p.add_argument("--churn", type=int, metavar="DAYS", help="add git churn for the last DAYS days")
    p.add_argument("--churn-min", type=int, default=5)
    p.add_argument("--top", type=int, default=0, help="show only the top N flagged functions")
    p.add_argument("--cc-warn", type=int, default=10)
    p.add_argument("--cc-high", type=int, default=15)
    p.add_argument("--max-depth", type=int, default=4)
    p.add_argument("--max-lines", type=int, default=60)
    p.add_argument("--max-params", type=int, default=6)
    p.add_argument("--max-returns", type=int, default=6)
    p.add_argument("--self-test", action="store_true")
    return p


def self_test():
    o = parser().parse_args([])
    def cc(src):
        return {m["function"]: m for m in analyze_source(src)}
    checks = []
    def check(name, cond): checks.append((name, bool(cond)))
    m = cc("def f():\n    return 1\n")["f"]
    check("straight-line function has cc 1", m["cc"] == 1 and m["depth"] == 0)
    m = cc("def f(x):\n    if x:\n        return 1\n    return 2\n")["f"]
    check("one if gives cc 2", m["cc"] == 2 and m["returns"] == 2)
    m = cc("def f(x):\n    if x == 1:\n        a = 1\n    elif x == 2:\n        a = 2\n    elif x == 3:\n        a = 3\n    else:\n        a = 0\n    return a\n")["f"]
    check("elif chain adds 1 each, depth stays 1", m["cc"] == 4 and m["depth"] == 1)
    m = cc("def f(a, b, c):\n    return a and b or c\n")["f"]
    check("boolean operators add per operand", m["cc"] == 3)
    m = cc("def f(xs):\n    return [x for x in xs if x if x > 2]\n")["f"]
    check("comprehension and its ifs count", m["cc"] == 4)
    m = cc("def f():\n    try:\n        g()\n    except ValueError:\n        pass\n    except KeyError:\n        pass\n")["f"]
    check("each except handler counts", m["cc"] == 3)
    m = cc("def f(x):\n    return 1 if x else 2\n")["f"]
    check("ternary counts", m["cc"] == 2)
    m = cc("def f(x):\n    while x:\n        for i in x:\n            if i:\n                with open(i) as h:\n                    pass\n")["f"]
    check("nesting depth 4", m["depth"] == 4 and m["cc"] == 4)
    r = cc("def outer():\n    def inner(x):\n        if x: return 1\n    return inner\n")
    check("nested function measured separately", r["outer"]["cc"] == 1 and r["outer.inner"]["cc"] == 2)
    r = cc("class A:\n    def m(self, a, b):\n        pass\n")
    check("method name and self excluded from params", r["A.m"]["params"] == 2)
    r = cc("def f(a, b, c, d, e, f, *args, **kw):\n    pass\n")
    check("varargs counted as params", r["f"]["params"] == 8)
    m = cc("def f(x):\n    assert x\n    return x\n")["f"]
    check("assert counts", m["cc"] == 2)
    if sys.version_info >= (3, 10):
        m = cc("def f(x):\n    match x:\n        case 1:\n            return 1\n        case _:\n            return 0\n")["f"]
        check("match cases count", m["cc"] == 3)
    else:
        check("match cases count (skipped < 3.10)", True)
    big = "def big(x):\n" + "".join("    if x == %d:\n        return %d\n" % (i, i) for i in range(16)) + "    return -1\n"
    m = cc(big)["big"]
    fs = [c for c, _, _ in findings_for(m, o)]
    check("cc 17 gives H01 and many returns H06", m["cc"] == 17 and "H01" in fs and "H06" in fs and "H02" not in fs)
    m = dict(cc=11, depth=1, lines=10, params=1, returns=1)
    check("cc 11 gives H02 only", [c for c, _, _ in findings_for(m, o)] == ["H02"])
    m = dict(cc=11, depth=1, lines=10, params=1, returns=1, churn=7)
    check("complex + churn gives H07", "H07" in [c for c, _, _ in findings_for(m, o)])
    m = dict(cc=3, depth=1, lines=10, params=1, returns=1, churn=40)
    check("simple + churn is not a hotspot", findings_for(m, o) == [])
    m = dict(cc=2, depth=5, lines=80, params=7, returns=1)
    check("depth, length, params flagged", [c for c, _, _ in findings_for(m, o)] == ["H03", "H04", "H05"])
    try:
        analyze_source("def broken(:\n")
        check("syntax error raised", False)
    except SyntaxError:
        check("syntax error raised", True)
    ok = all(c for _, c in checks)
    for n, c in checks:
        print(("PASS  " if c else "FAIL  ") + n)
    print("%d/%d checks passed" % (sum(c for _, c in checks), len(checks)))
    return 0 if ok else 1


def main(argv=None):
    o = parser().parse_args(argv)
    if o.self_test:
        return self_test()
    if not o.paths:
        parser().print_usage(sys.stderr); return 2
    for p in o.paths:
        if not os.path.exists(p):
            print("no such path: " + p, file=sys.stderr); return 2
    results, errors = run(o.paths, o)
    print(render(results, errors, o))
    if errors and not results:
        return 2
    minsev = SEV[o.min_severity]
    return 1 if any(SEV[x["severity"]] >= minsev for m in results for x in m["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main())
PythonCode ReviewRefactoring+3
F@f
0
Staff Rota Fairness Checker
Skill

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())
ManagementPlanningDecision Making+3
F@f
0
Python Exception Handling Smell Finder
Skill

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())
PythonDebuggingCode Review+3
F@f
0
Home Solar Panel Payback Calculator
Skill

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())
Personal FinanceFinanceBudgeting+3
F@f
0
Python Import Cycle Detector
Skill

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())
PythonDebuggingRefactoring+3
F@f
0
1 / 6Next