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

Fatih Kadir Akın

@f

developer. github star. head of AX at automattic.com for spacefast.com, builder of prompts.chat

fka.devgithubsupport me
786prompts
565bots
68teams
141upvotes received
7contributions
Joined 12 months ago
1696 contributions in the last year
Dec
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
M
W
F
Less
More
Surrealist Haute Couture Fashion Illustration (Theme + 3-Color Palette Template)
TrendingImage
Surrealist Haute Couture Fashion Illustration (Theme + 3-Color Palette Template)

A fill-in-the-blanks image prompt for full-body surrealist haute couture fashion illustrations: pick a [theme] and three colors to get a sculptural, avant-garde gown, headpiece and handbag on a clean white background.

A full-body fashion illustration of one elegant model wearing a [theme]-inspired surrealist haute couture gown, avant-garde deconstructivist silhouette, sculptural tailoring, intricate 3D embroidery, layered velvet, translucent organza, pleated silk, elaborate [theme]-inspired headpiece, artistic handbag, flowing architectural forms, sophisticated [color1] and [color2] palette with [color3] accents, refined fashion illustration, dreamy editorial aesthetic, clean white background, 4K
Image GenerationTemplateSurreal+2
F@f
0
TrendingVideo
Tiny Delivery Girl, Giant City: Hand-Drawn 2D Character in a Photorealistic New York (Mixed-Reality Video Prompt)

A whimsical mixed-media video prompt: a miniature hand-drawn 2D delivery girl braves a gigantic photorealistic New York street, from gusts of traffic wind and a coffee-lid boat ride to a pizza-slice landing, with sound design and compositing notes.

Create a whimsical mixed-reality animation featuring a miniature hand-drawn 2D young woman with long black hair, a pink hoodie, denim shorts, white sneakers, and a tiny red delivery backpack exploring a gigantic photorealistic New York street. She encounters a massive pedestrian crossing where passing cars create powerful gusts of wind that nearly blow her away, climbs onto a giant sneaker left on the pavement, slides down a newspaper stand, discovers a giant hot-dog cart where she narrowly escapes a rolling pickle, sails across a huge puddle using a discarded coffee cup lid as a boat, and gets lifted into the air by a gust of wind using her delivery bag as an improvised parachute. Finally, she lands on top of a giant pizza slice and celebrates triumphantly until a human hand suddenly picks up the slice, leaving her dangling in disbelief.
Combine expressive hand-drawn 2D animation with photorealistic urban environments, exaggerated scale, playful physics, cinematic macro close-ups, smooth camera movements, and seamless mixed-media compositing. Include realistic city ambience, traffic, footsteps, car horns, street vendor sounds, water splashes, wind, and playful comedic sound effects. No dialogue. Ultra-detailed visuals, consistent character design, cinematic depth of field, and high-end commercial animation quality.
Video GenerationCinematicCharacter Consistency+2
F@f
0
TrendingVideo
A Father's Little Chef: Heartwarming 3D Animated Pancake Comedy (Vertical Video Prompt)

A vertical, Japanese-style 3D animated family comedy prompt: a 3-year-old girl in an oversized chef hat surprises her father with a slightly burnt pancake, with dialogue beats, final shot, style, consistency and negative prompt included.

Create a heartwarming, hilarious, ultra-realistic Japanese-style 3D animated family comedy in vertical 9:16 format.

A cute 3-year-old Japanese girl with short black bobbed hair, chubby cheeks, sparkling eyes, and pink pajamas decides to surprise her father with breakfast.

Wearing an oversized chef hat, she struggles to prepare pancakes in the kitchen. She accidentally spills flour everywhere, gets chocolate on her face, and finally serves her father a funny-looking, slightly burnt pancake.

🎙️ Girl: "Papa! I made this for you!"

Her father takes a bite, struggles to hide his reaction, and says, "Delicious!"

The little girl notices his watery eyes and innocently asks, "Papa, are you crying because it's so yummy?"

The mother walks in, tastes the pancake, and bursts into laughter. The father hugs his little daughter and kisses her forehead.

Final Shot: The little girl proudly poses like a professional chef while her parents laugh.

Style: High-end Japanese 3D animation, adorable characters, expressive faces, realistic movements, warm lighting, cinematic camera angles, funny sound effects, natural Japanese dialogue, and heartwarming family moments.

Consistency: Maintain identical characters, clothing, facial features, and kitchen throughout.

Negative: No distorted faces, extra fingers, flickering, scene jumps, subtitles, text, or watermark.
Video GenerationCinematicCharacter Consistency+2
F@f
0
Terminal UI App taste
Taste

Opinionated conventions for keyboard-first terminal UI apps: TUI frameworks, responsive rendering, accessible colors and scriptable modes.

# Terminal UI App taste of a developer who builds fast, keyboard-first terminal interfaces
- Pick a mature TUI framework (Bubble Tea, Ratatui, Textual, Ink) instead of writing raw escape codes. Confidence: 0.90
- Use an Elm-style model, update and view architecture so state changes are easy to test without a terminal. Confidence: 0.80
- Render in the alternate screen buffer and always restore the terminal on exit, panic or Ctrl+C. Confidence: 0.95
- Make every action reachable by keyboard and show the main shortcuts in a footer bar. Confidence: 0.90
- Offer a ? key that opens a full help overlay listing all key bindings for the current view. Confidence: 0.85
- Support both arrow keys and vim-style hjkl navigation, and never require a mouse, though mouse support is welcome. Confidence: 0.80
- Use q or Esc to go back or quit, and ask for confirmation only before destructive actions. Confidence: 0.85
- Never block the render loop on I/O; run network and disk work in the background and show a spinner or progress bar. Confidence: 0.90
- Redraw only on state changes or at a capped frame rate, not in a busy loop. Confidence: 0.80
- Handle terminal resize events and lay out with flexible constraints that still work at 80x24. Confidence: 0.90
- Respect NO_COLOR, detect color depth, and fall back gracefully from truecolor to 256 and 16 colors. Confidence: 0.85
- Never use color as the only signal; pair it with symbols, labels or bold text. Confidence: 0.85
- Use a small, consistent palette tied to the terminal theme instead of hard-coded bright colors. Confidence: 0.75
- Provide a non-interactive mode (flags, --json output) for every important action so the tool works in scripts and CI. Confidence: 0.90
- Detect when stdout is not a TTY and switch to plain output automatically. Confidence: 0.90
- Add fuzzy filtering with / to any list longer than one screen. Confidence: 0.80
- Write logs to a file (opt-in with --debug), never to the screen the UI is drawing on. Confidence: 0.85
- Store config in the XDG config directory as TOML or YAML, and let users remap key bindings there. Confidence: 0.75
- Test views with golden snapshot files of rendered output at fixed terminal sizes. Confidence: 0.75
- Test in the common terminals (iTerm2, Windows Terminal, GNOME Terminal, tmux) before a release, including Unicode width cases. Confidence: 0.70
- Keep startup under about 100 ms so opening the app feels instant. Confidence: 0.70
- Ship a single static binary or a pipx/npm install path, with a short animated demo GIF in the README. Confidence: 0.70
Best PracticesCLITooling+2
F@f
0
Swift Package taste
Taste

Opinionated conventions for building and releasing Swift packages: Package.swift setup, strict concurrency, Swift Testing, DocC and semver.

# Swift Package taste of a developer who ships small, well-tested Swift libraries
- Use Swift Package Manager as the only distribution method for new libraries, and skip CocoaPods and Carthage specs unless users ask. Confidence: 0.85
- Set the swift-tools-version to the oldest toolchain you really test on, and raise it on purpose in a minor release. Confidence: 0.80
- Declare explicit platform minimums in Package.swift (.iOS, .macOS, .watchOS, .tvOS, .visionOS) instead of relying on defaults. Confidence: 0.85
- Keep one focused library product per package; split optional integrations into separate targets users can opt into. Confidence: 0.80
- Use the standard layout (Sources/<Target>, Tests/<Target>Tests) and avoid custom path settings. Confidence: 0.90
- Enable Swift 6 language mode and strict concurrency checking, and mark public types Sendable where it is true. Confidence: 0.80
- Keep the public API small: default to internal, and make each public symbol a deliberate decision. Confidence: 0.90
- Prefer value types and protocols with small requirements over class hierarchies in public APIs. Confidence: 0.80
- Offer async/await APIs first, and add completion-handler or Combine wrappers only when users need them. Confidence: 0.75
- Avoid third-party dependencies in a library; when one is needed, use a version range from: a major version, never a branch or exact revision. Confidence: 0.85
- Write tests with Swift Testing (@Test, #expect) for new code and keep XCTest only where it is already used. Confidence: 0.75
- Run CI on macOS and Linux with swift build and swift test, plus xcodebuild for each Apple platform you claim to support. Confidence: 0.85
- Write DocC documentation for every public symbol and include at least one article showing the main use case. Confidence: 0.80
- Host the docs on the Swift Package Index and keep a .spi.yml so builds and documentation stay green there. Confidence: 0.70
- Follow semantic versioning with plain tags like 1.4.0, without a v prefix, so SPM resolves them. Confidence: 0.90
- Use @available and deprecation messages with a renamed: hint one minor release before removing an API. Confidence: 0.85
- Keep resources in a Resources folder declared with .process and access them only through Bundle.module. Confidence: 0.75
- Format with swift-format or SwiftFormat and lint with SwiftLint in CI, using a config committed to the repo. Confidence: 0.70
- Avoid build plugins and macros unless they remove real boilerplate, because they slow builds and need extra trust prompts. Confidence: 0.65
- Ship a privacy manifest (PrivacyInfo.xcprivacy) when the library touches required-reason APIs. Confidence: 0.75
- Keep Package.resolved out of library repositories, but commit it in apps and example projects. Confidence: 0.80
- Include a runnable example app or snippet in the README that compiles in CI. Confidence: 0.70
- Keep a CHANGELOG.md with Added, Changed, Deprecated and Fixed sections for every release. Confidence: 0.80
Best PracticesiOSTooling+2
F@f
0
Refactoring taste
Taste

Opinionated habits for safe, incremental refactoring: characterization tests, small green steps, strangler fig and clean pull requests.

# Refactoring taste of an engineer who changes structure without changing behavior
- Never mix a refactor and a behavior change in the same commit; reviewers should be able to verify each one alone. Confidence: 0.95
- Get the code under characterization tests that pin today's behavior before touching legacy code, even if that behavior looks wrong. Confidence: 0.90
- Refactor in small steps that keep the build green, committing after each one instead of in one giant branch. Confidence: 0.90
- Use the IDE's automated refactorings (rename, extract function, move, inline) before editing by hand, because they are safer and faster. Confidence: 0.85
- Refactor the code you are about to change ("make the change easy, then make the easy change") rather than scheduling cleanup sprints. Confidence: 0.85
- Follow the rule of three: tolerate one duplication, and extract an abstraction only on the third real copy. Confidence: 0.80
- Prefer inlining a premature abstraction back to concrete code over adding more parameters and flags to keep it alive. Confidence: 0.80
- Replace boolean flag arguments with two well-named functions or an explicit options object. Confidence: 0.80
- Extract a function when you need a comment to explain what a block does, and use the comment as the function name. Confidence: 0.75
- Replace nested conditionals with guard clauses and early returns. Confidence: 0.85
- Introduce parameter objects or value types when the same three or more arguments travel together. Confidence: 0.70
- Push side effects (I/O, time, randomness) to the edges so the core logic becomes pure and easy to test. Confidence: 0.85
- Use the strangler fig pattern for large rewrites: route traffic piece by piece to the new code instead of a big-bang switch. Confidence: 0.90
- Put risky structural changes behind a feature flag or a parallel run that compares old and new results. Confidence: 0.75
- Use expand and contract for public interfaces: add the new API, migrate callers, then delete the old one in a later release. Confidence: 0.90
- Delete dead code instead of commenting it out; version control remembers it. Confidence: 0.95
- Run a codemod (jscodeshift, ts-morph, Comby, OpenRewrite) for mechanical changes across more than a handful of files. Confidence: 0.75
- Keep refactoring pull requests under about 400 changed lines, or split them into a reviewed series. Confidence: 0.70
- Put pure formatting or move-only changes in their own commit and add it to .git-blame-ignore-revs. Confidence: 0.80
- Use churn and complexity together to pick targets; refactor files that change often and are hard to read, not stable ugly ones. Confidence: 0.80
- Avoid renaming widely used concepts unless the team agrees on the new term and the whole codebase moves at once. Confidence: 0.65
- Write down why a refactor is happening in the PR description, with the problem it unblocks. Confidence: 0.85
- Stop when the code is clear enough for the next change; refactoring has no finish line and is not a goal by itself. Confidence: 0.80
Best PracticesSoftwareRefactoring+2
F@f
0
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())
CostBusinessDecision Making+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())
Best PracticesQualityDocumentation+4
F@f
0
Rain Trickling Down a Café Window Beside a Steaming Glass of Tea at Dusk
1
Image
Rain Trickling Down a Café Window Beside a Steaming Glass of Tea at Dusk

Photoreal cozy dusk inside a quiet café: a glass of amber tea with a thin ribbon of steam on a wooden window ledge beside a book, raindrops running down the pane and a blurred blue-hour street glowing with warm bokeh. Step 1 of the Rainy Café Window workflow.

A photorealistic close-up photograph taken inside a quiet café at dusk, looking out through a large rain-covered window. On the wooden window ledge in the foreground stands a clear glass cup of amber black tea on a small saucer, with a thin ribbon of steam rising from it, next to a closed hardcover book with a linen bookmark and a small ceramic jar of sugar cubes.

The window glass is covered in raindrops of many sizes; several larger drops leave thin wavy trails as they run down the pane. Outside, softly out of focus, an empty evening street glows in blue-hour light, with warm round bokeh from street lamps, shop signs blurred beyond recognition and the faint red and white lights of distant traffic. Inside, warm tungsten light from a lamp to the right falls on the cup and the ledge, making the tea glow and the drops on the glass sparkle.

50 mm lens at table height, shallow depth of field: the cup, the steam and the nearest raindrops tack-sharp, the street a dreamy blur of warm and cool lights. A calm, cozy, reflective mood, contrast between the cold blue evening outside and the warm interior. No people, no animals, no readable text or logos. Widescreen 16:9.
WorkflowCinematicRealism+3
F@f
0
Hand-Decorated Ukrainian Pysanky Eggs with Wax-Resist Folk Patterns
Image
Hand-Decorated Ukrainian Pysanky Eggs with Wax-Resist Folk Patterns

A still-life photo of five hand-decorated Ukrainian pysanky eggs with fine wax-resist folk patterns (star rosette, wheat and pine, meanders, sun spiral, dotted grids) in a willow basket on linen, with a kistka stylus, beeswax, a candle and dye jars in soft window light.

A still-life photograph of five hand-decorated Ukrainian pysanky eggs made with the traditional wax-resist method, arranged in a shallow handwoven willow basket on an unbleached linen cloth. Each egg carries a different geometric folk pattern drawn in fine, crisp lines: an eight-pointed star rosette in white and yellow on deep red, wheat ears and pine branches in gold and green on black, a band of endless meanders and little triangles in orange and red, a sun motif with spiraling rays on rich blue, and dotted grids with tiny crosses and diamonds on burgundy. The lines are slightly uneven in places, showing the handwork, with small glossy and matte areas on the dyed shells.

Beside the basket lie the tools of the craft: a traditional kistka stylus with a little brass funnel, a beeswax block, a thin beeswax candle with a soft flame, and three small glass jars of dye in red, yellow and blue. A dried sprig of wheat lies across the cloth.

Soft window daylight from the left, gentle shadows, warm natural colors, close-up with shallow depth of field so the front egg's patterns are tack-sharp and the jars fall softly out of focus. No people, no hands, no text or letters on the eggs. Landscape 4:3.
CreativePatternsPhotography+3
F@f
0
Vintage Snow Globe of a Tiny Winter Village with a Lit Chapel at Night
Image
Vintage Snow Globe of a Tiny Winter Village with a Lit Chapel at Night

A macro studio photo of a vintage snow globe: a tiny winter village with a lit white chapel, snowy timber cottages and frosted firs inside the glass, snowflakes swirling, a turned wooden base with a brass band, warm window glow and string-light bokeh on a dark winter night.

A close-up studio photograph of a vintage glass snow globe on a dark walnut shelf. Inside the clear water-filled dome sits a tiny handmade winter village: a small white chapel with a slim steeple and warm yellow light glowing from its arched windows, a pair of little timber cottages with snow-covered roofs and glowing windows, a few frosted fir trees and a narrow path winding up a snowy hill. Fine white snowflakes swirl gently through the water, a few settling on the roofs.

The globe stands on a turned wooden base with a thin brass band, slightly worn at the edges. Soft curved reflections and a warm highlight bend across the glass; the glowing windows cast a faint golden light into the snow inside. Behind the globe, out of focus, a dark wintry window with blurred warm string-light bokeh. Warm low-key lighting from the side, deep blue and charcoal shadows, a cozy, nostalgic holiday mood.

Macro lens, shallow depth of field with the chapel and cottages tack-sharp through the glass, slight refraction at the dome's edges, rich contrast between warm window light and cool snow. No people, no figures inside the globe, no readable text or logos. Portrait 3:4.
CreativeVintageMacro+3
F@f
0
Office Holiday Party Plan Builder (JSON)
Text

Plan an inclusive end-of-year office party as one JSON object: concept, date and run of show, venue checks, food for every diet, optional activities, remote colleagues, recognition and gifts, a budget that adds up, timeline, invitation texts, safety, risks and a day-of checklist.

1{
2 "role": "You are an experienced office manager and people-operations lead who plans inclusive, well-run end-of-year team celebrations on a sensible budget.",
3 "task": "Plan the company's end-of-year holiday party and return the full plan as one valid JSON object that follows output_format exactly.",
4 "inputs": {
5 "company": "${company:a 60-person software company with one office and 15 remote employees}",
6 "headcount_expected": "${headcount:55 in person, 15 joining online}",
7 "date_window": "${date_window:a weekday evening between December 10 and December 19}",
8 "budget_total": "${budget:6000 EUR including venue, food, drinks and gifts}",
9 "location": "${location:Berlin city center}",
10 "format_preference": "${format:dinner and games at a rented venue, with a short online part for remote colleagues}",
...+121 more lines
JSONTemplateAppreciation+5
F@f
0
Act as a Legacy Codebase Onboarding Guide
Text

Get productive in an unfamiliar legacy codebase safely: orientation questions, a day-one safety checklist, a reading strategy from entry points and git churn, a one-page architecture sketch, a careful plan for your first task, a questions log and a two-week ramp-up plan.

Act as a Legacy Codebase Onboarding Guide. You are a patient senior engineer who has joined many unfamiliar, poorly documented codebases and knows how to become productive in one without breaking things. I have just joined a team (or inherited a project) and need to understand an existing codebase quickly and safely.

My situation:
- Codebase: a 9-year-old monolith web app with a REST API, background jobs and a relational database
- Main languages and frameworks: Python, Django, Celery, PostgreSQL, some jQuery on the frontend
- Size and age: about 250k lines, 40 contributors over the years, 5 still active
- State of docs and tests: an outdated README, a few wiki pages, patchy unit tests, no architecture diagram
- My role and experience: backend developer, 4 years of experience, new to this domain
- My first assignment: fix a bug where invoice emails are sometimes sent twice
- Time I have to ramp up: 2 weeks
- People I can ask: one tech lead with little free time, a product manager, a retired original author reachable by email

Guide me through the onboarding in this order:

1. Orientation questions. Before giving a plan, ask me up to 5 short questions whose answers would change your advice the most (for example how deployments happen, whether there is a staging environment, who is on call). If I say "skip", continue with sensible assumptions and list them.

2. Day 1 safety checklist. What to set up and verify before touching code: getting the app and tests running locally, read-only access to logs and the production database replica, where secrets live and what never to commit, how to run one test, how a change reaches production and how it is rolled back.

3. Build a mental map. Give me a step-by-step reading strategy that does not try to read everything: start from entry points (routes, CLI commands, job schedulers, message consumers), follow one real request end to end, find the core domain models and the 5-10 files that change most often (show git commands such as `git log --format=format: --name-only | sort | uniq -c | sort -rn | head -30`), identify the oldest and scariest areas, and note configuration and feature flags. Tell me what to write down while reading.

4. Architecture sketch. Show me how to draw a one-page map of the system as a text diagram: components, data stores, external services, queues and the direction of calls. Give a template I can fill in and tell me which questions to ask the tech lead to confirm it in 20 minutes.

5. First task plan. For my first assignment, explain how to find the relevant code (search terms, logs, tracing one example), how to reproduce the problem, how to write a characterization test that pins the current behavior before changing it, how to keep the change small, and what to check in review. Point out typical legacy traps: hidden side effects, global state, implicit ordering, timezone and encoding issues, code paths only used by one big customer, and dead code that is not actually dead.

6. Questions log. Give me a format for a running questions log (question, where I looked, answer, who answered, date) and explain how to batch questions so I respect busy colleagues' time.

7. Two-week ramp-up plan. A day-by-day plan for 2 weeks with concrete goals (for example "Day 3: trace the checkout request end to end and draw it"), each with a small output I can show my lead.

8. Leave it better. Suggest 3-5 small, low-risk improvements a newcomer is perfectly placed to make (README setup steps, a glossary of domain terms, a diagram, a missing test, removing a confusing warning) and how to propose them without sounding critical of the people who built the system.

Rules:
- Be practical and specific to my stack; show real commands and file patterns where useful, but never invent facts about my codebase: when something depends on code you have not seen, say what to look for instead.
- Prefer safe, reversible steps; flag anything that could affect production data or customers.
- Keep each section short and scannable, with checklists where they help.
- End with the 3 things I should do first tomorrow morning.
ArchitectureDocumentationDeveloper+5
F@f
0
Zebra Robe Luxury Fashion Editorial on a Beige Sofa (Reference-Photo Portrait)
TrendingImage
Zebra Robe Luxury Fashion Editorial on a Beige Sofa (Reference-Photo Portrait)

Turn a reference photo into a luxury fashion editorial: the subject lounges on a beige sofa in a zebra-print robe, with soft studio light and a high-end magazine look.

Ultra-realistic luxury fashion editorial photograph of the woman in the reference image.

Keep her hair as in the reference, styled in loose, flowing waves, swept back from her forehead and cascading over her right shoulder. Natural luminous skin with visible pores, delicate microtexture, subtle peach blush and minimal elegant makeup.

She wears a luxurious oversized black-and-white zebra-patterned robe dress made of soft, thick, textured fabric. Deep V-shaped neckline with relaxed off-the-shoulder styling, revealing her collarbones and shoulders. Voluminous long sleeves, loosely draped fabric and a matching belt tied at the waist. A short, elegant necklace of large white pearls rests around her neck.

The woman reclines comfortably on a large beige upholstered sofa with wide, softly padded back cushions. Her body is slightly angled, shoulders relaxed, one arm extended along the sofa while the other rests naturally near her lap. The flowing zebra-patterned fabric covers her legs.

She looks directly into the camera with a calm, confident, slightly serious expression. Relaxed lips, effortless sophisticated pose.

Medium-close portrait, photographed from a slightly elevated frontal angle. Soft natural daylight from the left, warm neutral tones, delicate shadows, realistic fabric texture and subtle highlights on her face and hair, matching the reference.

Minimalist beige interior, understated luxury atmosphere, intimate high-fashion editorial photography, natural skin texture without excessive retouching, realistic hair strands, subtle analog film grain, refined cinematic composition.
Nano BananaImage GenerationPhotography+2
F@f
0
TrendingVideo
The Blonde Woman With the Black Umbrella: 30-Second Street Comedy in 8 Timed Scenes (Seedance Prompt)

A 30-second Seedance street comedy in 8 timed scenes: a blonde woman with a black umbrella and a run of small mishaps on a city street, with shot-by-shot timing, camera moves and comic beats.

THE BLONDE WOMAN WITH THE BLACK UMBRELLA

Duration: 30 Seconds
Aspect Ratio: 16:9
Style: Photorealistic live-action, cinematic urban comedy.

MAIN CHARACTER:
A stylish young blonde woman with long wavy hair, wearing a long black coat, white shirt, black tie, black trousers, and leather boots. She carries a white takeaway coffee cup and a closed black umbrella. Maintain identical appearance throughout.

LOCATION:
A cloudy New York-style street with wet pavement, stone buildings, fountain, yellow taxi, subway entrance, fruit shop, and red-carpet entrance.

SCENE 1 (0–3s): OPEN MANHOLE
The woman uses her umbrella to push a loose metal manhole cover back into place while casually walking and drinking coffee.

SCENE 2 (3–7s): FOUNTAIN COIN
She knocks a coin into a stone fountain using her umbrella. A little girl nearby happily raises her arms without falling into the water.

SCENE 3 (7–11s): YELLOW TAXI
Passing a yellow taxi, she interferes with a suited man's movement using her umbrella. He loses balance and falls backward while she walks away calmly.

SCENE 4 (11–15s): DOG WALKER
She catches several red dog leashes with her umbrella, tangling them together. The confused man raises his hands as the dogs gather around him.

SCENE 5 (15–19s): MOUSE AND PIZZA
A tiny gray mouse struggles to move an oversized pepperoni pizza beside a green subway entrance. A cardboard tube and the woman's black boots remain visible.

SCENE 6 (19–23s): FOOD TRAY
She interferes with a suited man's movement using her umbrella as he carries a tray of small cups outside a fruit shop. He struggles to keep everything balanced.

SCENE 7 (23–27s): RED CARPET
She confidently walks past a grand red-carpet entrance. A security guard raises his hand while formally dressed guests watch her.

SCENE 8 (27–30s): FINAL SHOT
She stops near a glass entrance, takes a sip of coffee, looks directly into the camera, and gives a subtle mischievous smile.

CINEMATOGRAPHY:
Smooth tracking shots, cinematic wide angles, realistic close-ups, natural movement, shallow depth of field, and consistent lighting.

AUDIO:
Natural city ambience, footsteps, fountain splash, taxi traffic, barking dogs, rattling objects, and coffee sipping.

NEGATIVE PROMPT:
No character changes, no missing props, no cartoon effects, no distorted faces, no extra limbs, no child falling into water, no animal substitutions, no duplicated characters, no subtitles, no watermark.

FINAL RESULT: A seamless 30-second photorealistic street comedy with all eight scenes in the exact order.
Video GenerationSeedanceCinematic+2
F@f
0
Performance Profiling taste
Taste

Opinionated habits for measuring and fixing performance problems: profilers, benchmarks, percentiles and evidence-backed optimizations.

# Performance Profiling taste of an engineer who measures before optimizing anything
- Never optimize without a reproducible benchmark or production profile that shows the hot path first. Confidence: 0.95
- Write down the target before starting (for example "p95 under 200 ms at 500 rps") and stop once it is met. Confidence: 0.85
- Profile in an environment close to production: optimized build, realistic data size and the same CPU architecture. Confidence: 0.90
- Use sampling profilers (perf, py-spy, async-profiler, pprof, Chrome DevTools) before instrumenting ones, because they barely change what they measure. Confidence: 0.85
- Read flame graphs for wide frames, not tall stacks; the widest box near the top is usually the place to work on. Confidence: 0.85
- Keep continuous profiling running in production (Pyroscope, Parca, Datadog) so regressions can be compared with last week. Confidence: 0.70
- Look at wall-clock time and CPU time separately; a slow request that is mostly waiting needs tracing, not a CPU profile. Confidence: 0.90
- Use distributed tracing to find which service or query owns the latency before profiling any single process. Confidence: 0.80
- Report latency as percentiles (p50, p95, p99) with sample counts, never averages alone. Confidence: 0.95
- Warm up before measuring and run each benchmark enough times to report variance, using tools like hyperfine, criterion, BenchmarkDotNet or pytest-benchmark. Confidence: 0.85
- Change one thing at a time and keep before and after numbers in the pull request description. Confidence: 0.90
- Check the algorithm and the number of round trips (N+1 queries, chatty APIs) before micro-optimizing code. Confidence: 0.90
- Run `EXPLAIN ANALYZE` on the slow query with production-like statistics before adding an index or rewriting it. Confidence: 0.85
- Profile memory as a separate pass: allocation rate, heap growth and GC pauses, using heap snapshots or allocation profilers. Confidence: 0.80
- Treat lock contention and thread pool saturation as first-class suspects in concurrent services, and profile off-CPU time to see them. Confidence: 0.70
- Prefer caching only after proving the work is repeated and the data can tolerate staleness. Confidence: 0.80
- Keep micro-benchmarks in the repository next to the code they measure, and run the critical ones in CI with a regression threshold. Confidence: 0.70
- Pin CPU frequency and isolate benchmark runners, or use instruction counts, so CI noise does not trigger false alarms. Confidence: 0.60
- For frontend work, profile on a throttled mid-range device and track Core Web Vitals from real users, not only Lighthouse on a laptop. Confidence: 0.80
- Leave a short comment next to any non-obvious optimization explaining the measurement that justified it. Confidence: 0.85
- Remove an optimization that no longer shows up in profiles if it makes the code harder to read. Confidence: 0.65
- Share profiles as files or links in the incident or PR so others can reproduce the analysis. Confidence: 0.75
Best PracticesPerformanceSoftware+2
F@f
0
Deno Project taste
Taste

Opinionated Deno conventions for secure, zero-config TypeScript servers and tools: permissions, JSR imports, testing and publishing.

# Deno Project taste of a TypeScript developer who wants secure, zero-config server code
- Start with `deno init` and keep a single `deno.json` for tasks, imports, lint, fmt and compiler options; no separate tsconfig or eslintrc. Confidence: 0.90
- Pin dependencies in the `imports` map of `deno.json` with `jsr:` and `npm:` specifiers, and keep version numbers out of source files. Confidence: 0.90
- Prefer JSR packages, starting with `@std/*`, over npm equivalents when both exist. Confidence: 0.80
- Commit `deno.lock` and run CI with `--frozen` so a dependency can never change silently. Confidence: 0.90
- Grant the narrowest permissions possible, scoped to hosts and paths (`--allow-net=api.example.com`, `--allow-read=./data`); never `-A` outside quick local experiments. Confidence: 0.95
- Write the permission flags into the `deno.json` tasks so every developer runs the app with the same sandbox. Confidence: 0.85
- Use `Deno.serve` with a plain `(req: Request) => Response` handler, and add Hono only when routing grows beyond a few paths. Confidence: 0.80
- Stick to Web standard APIs (`fetch`, `Request`, `URL`, `crypto.subtle`, streams) before reaching for Deno-only or Node-compat APIs. Confidence: 0.85
- Treat `node:` imports and npm packages as an escape hatch and keep them out of core domain modules. Confidence: 0.70
- Keep TypeScript strict as Deno ships it and never weaken compiler options to silence errors. Confidence: 0.90
- Use `deno fmt` and `deno lint` with default rules; argue about logic, not formatting. Confidence: 0.85
- Write tests with `Deno.test` and `@std/assert` next to the code as `*_test.ts` files. Confidence: 0.85
- Run `deno test` with the same narrow permissions as production, so missing grants fail in CI and not at runtime. Confidence: 0.75
- Use `t.step` for grouped scenarios and rely on the built-in resource and op sanitizers to catch leaked timers and sockets. Confidence: 0.70
- Collect coverage with `deno test --coverage` and `deno coverage --lcov` without extra tooling. Confidence: 0.65
- Run `deno check` in CI on every entry point, including scripts that are not imported by the main app. Confidence: 0.80
- Read configuration through a single typed module that validates `Deno.env` once at startup and fails fast on missing values. Confidence: 0.85
- Use the `--env-file` flag for local `.env` files instead of a dotenv dependency. Confidence: 0.75
- Use Deno KV for small queues, counters and session data when deploying to Deno Deploy; use Postgres once relations matter. Confidence: 0.60
- Ship single-binary internal tools with `deno compile`, embedding only the permissions the tool needs. Confidence: 0.75
- Publish shared libraries to JSR with explicit `exports`, JSDoc on every public symbol and no slow types, and check them with `deno publish --dry-run`. Confidence: 0.85
- Handle shutdown by listening for `SIGTERM` with `Deno.addSignalListener` and awaiting `server.shutdown()`. Confidence: 0.70
- Use `deno task` for every repeated command instead of a Makefile or npm scripts. Confidence: 0.80
Best PracticesSecurityBackend+2
F@f
0
Ruby Gem taste
Taste

Opinionated conventions for building, testing and releasing small, dependable Ruby gems with clean gemspecs and safe publishing.

# Ruby Gem taste of a maintainer who ships small, dependable gems with boring releases
- Scaffold new gems with `bundle gem <name> --test=rspec --ci=github --linter=rubocop` and keep the generated layout instead of inventing a custom one. Confidence: 0.80
- Keep the gemspec as the single source of truth for metadata, required Ruby version and runtime dependencies; the Gemfile only adds development tools. Confidence: 0.90
- Set `required_ruby_version` explicitly and support only Ruby versions that still receive security fixes. Confidence: 0.85
- Build `spec.files` from `git ls-files` filtered to `lib`, `sig`, `exe`, LICENSE, README and CHANGELOG so tests and fixtures never ship in the package. Confidence: 0.85
- Add as few runtime dependencies as possible and give each one a pessimistic constraint like `~> 2.3`, never an unbounded `>=`. Confidence: 0.90
- Do not commit `Gemfile.lock` for a library; let CI resolve fresh dependencies so breakage shows up early. Confidence: 0.65
- Namespace everything under one top-level module that matches the gem name, and never monkey-patch core classes from a library. Confidence: 0.95
- Use Zeitwerk for gems with many files, and plain `require_relative` for small ones. Confidence: 0.70
- Expose configuration through a `configure` block that yields a plain configuration object with documented defaults. Confidence: 0.80
- Define a base `<GemName>::Error < StandardError` and raise specific subclasses so callers can rescue the whole family. Confidence: 0.90
- Add `# frozen_string_literal: true` to every Ruby file. Confidence: 0.80
- Write tests in RSpec with `--require spec_helper`, random order and `disable_monkey_patching!` turned on. Confidence: 0.80
- Run CI on a matrix of all supported Rubies plus `head`, with `head` allowed to fail. Confidence: 0.85
- Enforce style with RuboCop (or Standard) in CI, and keep project-wide disables in `.rubocop.yml` instead of inline comments. Confidence: 0.75
- Ship RBS signatures in `sig/` for the public API, or at least YARD types, so editors and Steep can check callers. Confidence: 0.60
- Document every public method with YARD and keep a runnable quick-start example at the top of the README. Confidence: 0.80
- Follow Semantic Versioning strictly and keep `VERSION` in `lib/<gem>/version.rb` as the only place the version lives. Confidence: 0.95
- Maintain a CHANGELOG in Keep a Changelog format and update it in the same pull request as the change. Confidence: 0.85
- Deprecate before removing: warn through `Kernel#warn` with `category: :deprecated` for at least one minor release. Confidence: 0.85
- Publish from CI with RubyGems trusted publishing on a tagged release instead of running `gem push` from a laptop. Confidence: 0.85
- Require MFA for every owner by setting `rubygems_mfa_required` to "true" in the gemspec metadata. Confidence: 0.95
- Set `source_code_uri`, `changelog_uri` and `bug_tracker_uri` in the metadata so rubygems.org links back to the repository. Confidence: 0.75
- Keep optional integrations (Rails, Sidekiq) behind separate requires such as `require "<gem>/rails"` so they never load by default. Confidence: 0.80
- Test the packaged gem, not only the repo: build it in CI, install it into a clean bundle and run a smoke script. Confidence: 0.70
Best PracticesSoftwareOpen Source+2
F@f
0
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())
AccountingBusinessDecision Making+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())
Best PracticesRefactoringEngineering+3
F@f
0
Red Maple Leaves Drifting Down a Mossy Mountain Stream in Autumn
1
Image
Red Maple Leaves Drifting Down a Mossy Mountain Stream in Autumn

Photoreal misty autumn morning at a clear mountain stream: water slips over mossy stones into a quiet pool where red maple leaves float, crimson and gold maples lean over the banks and soft sun rays break through the mist. Step 1 of the Autumn Mountain Stream workflow.

A photorealistic photograph of a small, clear mountain stream flowing through an autumn forest on a calm, misty morning. The water runs gently over smooth grey stones covered with bright green moss and cascades down a few low steps, forming small white ribbons of water and a quiet pool in the foreground. Japanese maple and beech trees lean over the stream from both banks, their leaves in glowing crimson, scarlet, orange and gold. Dozens of red maple leaves float on the dark surface of the pool, a few are caught against the mossy stones, and a few are falling through the air. Thin morning mist hangs between the trunks in the background, and soft rays of sunlight break through the canopy and touch the water.

Shot like a professional nature photograph: 24 mm lens low near the water at the edge of the pool, looking upstream, strong depth with the stream leading back into the misty forest, sharp foreground stones and floating leaves, slightly softer background, rich red and gold against deep green moss and dark water, gentle natural light. No people, no animals, no buildings, no text. Landscape 16:9.
WorkflowCinematicRealism+2
F@f
0
Italian Majolica Charger Plate of a Hare Among Wild Strawberries
Image
Italian Majolica Charger Plate of a Hare Among Wild Strawberries

A top-down photo of a hand-painted Renaissance-style Italian majolica charger: a brown hare among wild strawberries in the center medallion, a rim of acanthus leaves, lemons and pomegranates in cobalt, copper green, yellow and orange on milky tin glaze, with crazing and small chips on linen.

A top-down photograph of a large round hand-painted Italian majolica charger plate in the Renaissance tin-glazed style. In the center, inside a circular medallion, a brown hare sits upright among wild strawberry plants, with tiny white flowers, trefoil leaves and bright red berries, on a soft green meadow under a pale sky. Around the medallion, the wide rim is painted with a symmetrical border of curling acanthus leaves, little lemons and pomegranates, and thin concentric rings, all in the classic majolica palette: cobalt blue, copper green, antimony yellow, manganese purple-brown and warm orange on a thick milky-white tin glaze.

Render it like real hand-painted earthenware: slightly uneven brushstrokes and pooled color where the glaze is thicker, fine crazing in the glaze, a softly glossy surface with one gentle window highlight, a few tiny chips and wear marks on the outer edge revealing the buff clay underneath. The plate lies on a rough natural linen cloth with soft daylight from the upper left and a subtle shadow under the rim. Even, sharp focus across the whole plate. No text, no signatures, no people. Square 1:1.
DesignCreativeVisual Style+2
F@f
0
Handmade Ship in a Bottle: A Three-Masted Clipper in an Antique Glass Bottle
Image
Handmade Ship in a Bottle: A Three-Masted Clipper in an Antique Glass Bottle

A macro studio photo of a handmade ship in a bottle: a tiny three-masted clipper with linen sails and thread rigging on a carved putty sea beside a little lighthouse, inside old greenish glass with a wax-sealed cork, resting on a sea chart by a brass magnifier in warm lamp light.

A close-up studio photograph of a handmade ship in a bottle: a tiny three-masted clipper sailing ship with cream linen sails, a dark varnished wooden hull with a thin red stripe, and fine thread rigging, sitting inside a clear antique glass bottle lying on its side. The ship rests on a sea of carved and painted putty in deep blue-green with white wave crests curling around the bow, and a tiny lighthouse with a red cap stands on a small rocky island at one end of the scene. The bottle has a slightly greenish tint, small air bubbles and gentle ripples in the old glass, a cork stopper sealed with a twist of faded red wax and a short length of tarred twine around the neck.

The bottle rests on a wooden cradle on an old sea chart spread over a walnut desk, next to a brass magnifying glass and a pair of long thin modelling tweezers, slightly out of focus. Warm lamp light from the left makes soft highlights and curved reflections on the glass and casts a faint caustic glow onto the chart; background softly falls off into warm darkness. Macro lens, shallow depth of field with the ship and rigging tack-sharp through the glass, rich wood browns, sea greens and warm brass tones, the calm, patient feel of a craftsperson's desk. No people, no hands, no readable text or labels on the chart. Portrait 3:4.
VintageMacroRealism+3
F@f
0
Internal Hackathon Plan Builder (YAML)
Text

Plan an internal hackathon as one YAML document: theme and success measures, a timeline from 4 weeks before to 2 weeks after, idea prompts and cross-functional teams, logistics and data rules, a judging rubric, follow-through for winning ideas, budget, ready-to-post messages and risks.

1role: >-
2 You are an experienced engineering leader and event organizer who has run internal
3 hackathons for small startups and for product teams inside larger companies. You design
4 hackathons that are fun, inclusive and safe, that do not burn people out, and that end with
5 a few ideas that actually ship instead of a pile of forgotten demos.
6
7context:
8 company: "${company:a 60-person B2B SaaS company, about 25 engineers}"
9 format: "${format:hybrid; office in one city plus remote people in 3 time zones}"
10 dates_and_length: "${dates:2 days, Thursday-Friday, during working hours}"
...+81 more lines
YAMLCollaborationEngineering+5
F@f
0
1 / 30Next