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

Fatih Kadir Akın

@f

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

fka.devgithubsupport me
886prompts
586bots
68teams
148upvotes received
7contributions
Joined 12 months ago
1831 contributions in the last year
Dec
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
M
W
F
Less
More
Technical SEO taste
Taste

Opinionated technical SEO preferences for web apps: server-rendered HTML, one canonical URL per page, real titles and meta, structured data, sitemaps, fast Core Web Vitals and no accidental noindex.

# Technical SEO taste of a web developer who wants pages search engines can read on the first request
- Serve meaningful HTML from the server (SSR or static generation) for every page that should rank; do not rely on client-only rendering. Confidence: 0.90
- Give every indexable page exactly one canonical URL and set a self-referencing rel="canonical" tag. Confidence: 0.90
- Pick one host and trailing-slash style and 301-redirect every other variant (http, www, uppercase, trailing slash) to it. Confidence: 0.90
- Write a unique, specific title tag of roughly 50-60 characters and a meta description for each page from real page data. Confidence: 0.85
- Use one h1 per page and a logical heading order that mirrors the content structure. Confidence: 0.75
- Use clean, readable, lowercase, hyphenated URLs and keep them stable; when one must change, add a permanent redirect. Confidence: 0.90
- Return real HTTP status codes: 404 or 410 for missing content, never a soft 404 that answers 200 with an error page. Confidence: 0.95
- Generate the XML sitemap automatically from the database with lastmod dates and list only canonical, indexable URLs. Confidence: 0.85
- Keep robots.txt small, never block CSS or JS needed to render, and do not use it to hide pages that should be noindexed. Confidence: 0.85
- Make noindex on preview, staging and internal search pages an environment default, and test that production does not ship it. Confidence: 0.95
- Add JSON-LD structured data (Article, Product, BreadcrumbList, Organization) that matches the visible content exactly. Confidence: 0.80
- Set Open Graph and Twitter card tags with an absolute image URL so shared links render a proper preview. Confidence: 0.85
- Treat Core Web Vitals (LCP, INP, CLS) as release criteria and monitor them with real-user data, not only lab scores. Confidence: 0.80
- Give images width and height, descriptive alt text and modern formats, and lazy-load everything below the fold except the LCP image. Confidence: 0.85
- Link between related pages with plain anchor tags and descriptive anchor text; avoid navigation that only works through onClick handlers. Confidence: 0.90
- Handle paginated and filtered lists with crawlable links and canonicalize or noindex parameter combinations that create near-duplicate pages. Confidence: 0.75
- For multilingual sites, use separate URLs per language with hreflang annotations including x-default, never language switching by cookie only. Confidence: 0.85
- Do not hide primary content behind tabs, interactions or infinite scroll that require JavaScript events to load. Confidence: 0.70
- Check Search Console coverage and crawl reports after every major release or migration. Confidence: 0.80
- Prefer fewer, deeper pages over thin auto-generated pages for every keyword variation. Confidence: 0.75
Best PracticesPerformanceFrontend+2
F@f
0
Godot Game Project taste
Taste

Opinionated Godot 4 project preferences: small composable scenes, typed GDScript, signals up and calls down, autoloads kept rare, resources for data and a clean export pipeline.

# Godot Game Project taste of an indie developer who wants scenes that stay small and reusable
- Build the game from small composable scenes, each with a single clear responsibility, instead of one giant level scene. Confidence: 0.90
- Use static typing in GDScript everywhere: typed variables, parameters and return types, and enable the untyped declaration warnings. Confidence: 0.90
- Follow "call down, signal up": parents call methods on children, children emit signals and never reach up the tree. Confidence: 0.90
- Avoid long get_node paths and get_parent chains; use @export node references or unique names (%Name) inside a scene. Confidence: 0.85
- Keep autoloads to a few true global services such as save system, audio and scene transitions, not a dumping ground for state. Confidence: 0.85
- Store game data like items, enemies and levels in custom Resource classes (.tres) instead of hardcoded dictionaries. Confidence: 0.85
- Remember that Resources are shared by default; call duplicate() or enable resource_local_to_scene when each instance needs its own copy. Confidence: 0.80
- Put physics and movement in _physics_process and visuals and input polling in _process, and never assume a fixed frame time. Confidence: 0.85
- Define actions in the Input Map and read Input.is_action_pressed; never check raw keycodes in gameplay code. Confidence: 0.95
- Use a simple state machine (enum with match or state nodes) for player and enemy behavior instead of piles of booleans. Confidence: 0.80
- Set collision layers and masks deliberately and name every layer in Project Settings. Confidence: 0.85
- Organize folders by feature (player/, enemies/, ui/) with each scene next to its script and assets, not by file type. Confidence: 0.75
- Pool frequently spawned objects like bullets and particles when profiling shows instancing cost, not before. Confidence: 0.70
- Use the built-in profiler and monitors before optimizing, and move hot loops to C# or GDExtension only when measured. Confidence: 0.75
- Load big scenes with ResourceLoader.load_threaded_request behind a loading screen instead of freezing the main thread. Confidence: 0.70
- Save games to user:// as versioned JSON or ConfigFile data and never use var_to_bytes with objects for untrusted save files. Confidence: 0.80
- Commit the project with a proper .gitignore that excludes .godot/ and export output, and use Git LFS for large binary assets. Confidence: 0.90
- Keep export presets in version control without secrets and build release exports from CI with a pinned Godot version. Confidence: 0.75
- Write unit tests for pure game logic with GUT or gdUnit4 and keep that logic outside of node scripts where possible. Confidence: 0.65
- Use Tweens and AnimationPlayer for feel and polish instead of hand-written interpolation code in _process. Confidence: 0.80
Best PracticesPerformanceArchitecture+2
F@f
0
Data Privacy Engineering taste
Taste

Opinionated data privacy engineering preferences: collect less, classify PII in the schema, keep it out of logs, encrypt and tokenize sensitive fields, and make deletion and export requests boring.

# Data Privacy Engineering taste of a backend engineer who treats PII like radioactive material
- Collect the minimum data a feature needs and write down why each personal field exists before adding a column. Confidence: 0.95
- Mark PII and sensitive columns in the schema itself (comments, annotations or a data catalog) so tooling can find them. Confidence: 0.85
- Never log raw emails, phone numbers, tokens, addresses or request bodies; log stable internal ids and redact at the logger level. Confidence: 0.95
- Keep personal data in a small number of well-known tables instead of copying it into every service and event payload. Confidence: 0.85
- Put internal ids, not emails or names, into events, URLs, analytics and error trackers. Confidence: 0.90
- Encrypt highly sensitive fields at the application level with keys in a KMS, on top of disk encryption. Confidence: 0.75
- Tokenize or hash identifiers used for joins and analytics; use a keyed hash (HMAC) so values cannot be reversed with a lookup table. Confidence: 0.80
- Define a retention period for every personal data store and enforce it with a scheduled job, not a policy document. Confidence: 0.90
- Build account deletion as a real pipeline that reaches the primary database, search indexes, caches, object storage and third-party processors. Confidence: 0.90
- Prefer hard deletes or irreversible anonymization for user deletion requests; soft-deleted rows still count as stored data. Confidence: 0.80
- Make data export a tested feature that produces a machine-readable archive of everything stored about a user. Confidence: 0.75
- Remember that backups keep deleted data; document how long they live and make sure restores re-apply pending deletions. Confidence: 0.70
- Keep an up-to-date list of subprocessors and what personal data each one receives. Confidence: 0.80
- Never copy production personal data into staging or local environments; use synthetic or properly anonymized datasets. Confidence: 0.95
- Gate access to production data with least privilege, short-lived credentials and an audit log of who queried what. Confidence: 0.90
- Store consent as versioned records with timestamp and purpose, not as a single boolean column. Confidence: 0.80
- Load analytics and marketing scripts only after consent, and test that they really stay off when consent is declined. Confidence: 0.85
- Strip EXIF and other metadata such as GPS location from user-uploaded images before storing or serving them. Confidence: 0.80
- Add automated checks in CI or code review that flag new PII fields and new third-party data flows. Confidence: 0.65
- Write privacy requirements as acceptance criteria and tests, the same way you write security requirements. Confidence: 0.75
Best PracticesSecurityArchitecture+2
F@f
0
Colorful Kites Flying High Above a Windy Hilltop Meadow
1
Image
Colorful Kites Flying High Above a Windy Hilltop Meadow

Photoreal bright windy afternoon on a green hilltop meadow: four colorful kites, a red and yellow diamond, a blue delta, an orange box kite and a small green diamond with ribbon tails, fly high on lines tied to wooden stakes under a deep blue sky. Step 1 of the Hilltop Kites workflow.

A photorealistic, bright afternoon photograph of four colorful kites flying high above a green hilltop meadow on a windy day. In the upper half of the sky: a large red and yellow diamond kite with a long red ribbon tail, a blue delta kite with a white stripe and twin blue and white ribbon tails, an orange box kite, and a small green diamond kite with a long yellow ribbon tail. The kites fly at different heights and angles, clearly apart from each other, each with a thin taut line running down to a wooden stake hammered into the grass in the lower part of the frame.

The meadow on the hilltop is covered in tall grass and small white and yellow wildflowers; a weathered wooden fence crosses the left side, and a canvas picnic blanket with a wicker basket lies near the stakes. Beyond the hill, rolling green and golden fields, a line of dark hedgerows and soft blue hills fade into the distance under a deep blue sky with a few large white cumulus clouds.

Clear, crisp afternoon sunlight from the right, strong colors on the kite fabric with soft translucent glow where the sun shines through, long gentle shadows in the grass. 35 mm lens, low angle from the grass looking up toward the kites, everything sharp from the stakes to the kites.

Joyful, free, breezy mood with natural colors. No people, no hands, no animals, no birds, no water, no buildings, no readable text, numbers, letters or logos on the kites or the basket. Landscape 16:9.
WorkflowCinematicRealism+4
F@f
0
Soft 3D Render of a Gingerbread House Village on a Snowy Cake Board
Image
Soft 3D Render of a Gingerbread House Village on a Snowy Cake Board

A cheerful stylized 3D render of a tiny gingerbread village on a round snowy cake board: three iced gingerbread houses with glowing sugar-glass windows, a peppermint path, frosted pine trees, a candy-cane lamp post and a blue candy pond, in soft warm studio light with golden bokeh.

A soft, cheerful 3D render of a tiny gingerbread house village built on a round cake board covered in snowy white royal icing, seen from a slightly high three-quarter angle like a cozy holiday diorama. Three gingerbread houses of different sizes stand close together: a tall narrow house with a steep roof of overlapping chocolate-button shingles, a wide cottage with a roof of white icing scallops and a round candy window, and a tiny bakery with a striped red and white awning made of peppermint candy. Every house has thick white icing piped along its edges like snow, small gumdrop decorations in red, green and gold, and warm yellow light glowing from sugar-glass windows.

Between the houses: a winding path of crushed peppermint pieces, a little forest of frosted green pine trees dusted with powdered sugar, a candy-cane lamp post with a glowing gumdrop, a tiny gingerbread fence and a round frozen pond made of blue hard candy. Small heaps of powdered sugar snow lie on the roofs and around the edge of the board.

Soft studio lighting with a warm key light from the front left and a cool blue rim light from behind, gentle ambient occlusion, subtle subsurface scattering in the icing and the candy, and a soft-focus background of warm golden bokeh. Smooth, slightly stylized shapes with real-looking textures: baked gingerbread with tiny sugar crystals, glossy hard candy, matte icing.

Playful, sweet, festive December mood with rich warm browns, crisp whites and candy colors. No people, no figures, no animals, no readable text, letters, numbers or logos. Square 1:1.
CreativeStyleVisual Style+2
F@f
0
Luthier's Workbench with an Unfinished Violin in Warm Afternoon Light
Image
Luthier's Workbench with an Unfinished Violin in Warm Afternoon Light

Photoreal close-up of a luthier's walnut workbench in raking afternoon light: an unfinished stringless violin with fresh f-holes, its flamed maple back propped beside it, curled shavings, gouges, a brass finger plane, clamps and a finished amber violin glowing in the background.

A photorealistic close-up photograph of a luthier's workbench in a quiet old workshop on a late autumn afternoon. In the center lies an unfinished violin, face up, without strings, neck or varnish: its spruce top shows a fine straight grain in pale honey tones, the two elegant f-holes are freshly cut with crisp edges, and the carved scroll of a separate neck rests beside it. Next to it stands the matching violin back in flamed maple, propped up at an angle so its tiger-stripe figure catches the light like rippling silk.

Around them on the worn walnut bench: curled wood shavings, a small brass finger plane, a row of gouges with rounded wooden handles, a pair of wooden spool clamps, a thin steel scraper, a small pot of hide glue with a brush, a pencil and a paper template of a violin outline. Behind, slightly out of focus, a pegboard with saws and calipers, and a finished varnished violin hanging from a hook, glowing amber-red.

Warm, low afternoon sunlight comes through a small-paned window on the left, raking across the bench so every shaving, gouge edge and the wood grain of the top are sharply defined, with soft dust motes floating in the beam; the background falls into warm shadow. 90 mm lens, f/4, slightly above bench height, the f-holes and the flamed maple back tack-sharp, gentle depth falloff toward the window.

Calm, patient, handcrafted mood with rich natural wood tones of spruce, maple and walnut. No people, no hands, no faces, no strings on the unfinished violin, no readable text, labels, brand names or logos. Landscape 4:3.
MacroRealismPhotography+3
F@f
0
Key Account Quarterly Business Review Plan (YAML)
Text

Plan a quarterly business review a key B2B customer wants to attend, in YAML: internal account health prep, pre-read, timed agenda, results vs the customer's goals with business value, honest problems and fixes, feature request answers, next-quarter plan, one commercial ask and a follow-up email.

1role: >-
2 You are an experienced B2B customer success and account management lead. You help account
3 managers and founders run quarterly business reviews (QBRs) that customers actually want to
4 attend: short, built on the customer's own goals and numbers, honest about problems, and ending
5 with agreed next steps. You push back on QBRs that are only a product demo, a usage dump or a
6 disguised upsell pitch, and you make sure every claim is backed by data the team really has.
7
8context:
9 account: "${account:Northwind Logistics, a 600-employee freight company, customer for 2 years}"
10 our_product: "${product:a route planning and delivery tracking SaaS used by their dispatch team}"
...+89 more lines
YAMLB2BMeetings+4
F@f
0
Act as a Doctor Appointment Preparation Coach
Text

Get the most out of a short doctor visit: an urgent-signs check first, a one-sentence opening, a clear symptom timeline with a daily log, a priority list, smart questions, what to bring, tips for during the visit, an after-visit notes template and a printable appointment card.

Act as a Doctor Appointment Preparation Coach. You are a calm, practical patient advocate with years of experience helping people get the most out of short medical appointments. You know that a typical visit lasts only 10 to 15 minutes, that patients often forget their most important question until they are back in the car, and that doctors make better decisions when symptoms are described clearly, in order, with dates and numbers. You never diagnose, never suggest treatments or medication changes, and you always tell me when something sounds urgent enough to call a doctor or emergency services instead of waiting for the appointment.

About me and the appointment:
- Who the appointment is for: me, a 46-year-old woman, generally healthy, mild asthma since childhood
- Type of appointment: a 15-minute visit with my family doctor, in person
- When: next Tuesday at 09:30
- The main reason I booked it: tiredness and headaches for about 6 weeks, worse in the afternoons
- Other things I would like to mention if there is time: a mole on my shoulder that looks darker, trouble sleeping, my asthma inhaler running out
- Medicines and supplements I take: salbutamol inhaler as needed, vitamin D 1000 IU daily, ibuprofen for headaches 3-4 times a week
- Relevant history: no surgeries, mother has thyroid problems, father had high blood pressure
- What I have already tried: drinking more water, less coffee after lunch, going to bed earlier on weekdays
- What worries me most: that it is something serious, and that I will be told it is just stress without any tests
- Practical details: I may bring my partner; English is my second language; I take the bus and have a meeting at 11:00

Help me in this order:

1. Quick questions. Ask up to 4 short questions that would most improve my preparation (for example whether the headaches wake me up, whether anything else changed in the last few months, or what I expect from the visit). If I say "skip", continue with sensible assumptions and list them.

2. Urgent check first. Before anything else, tell me in plain words which signs mean I should NOT wait for the appointment and should call a doctor today or emergency services now (for example a sudden severe headache, weakness or numbness on one side, confusion, chest pain or trouble breathing). Keep it short and calm.

3. My one-sentence opening. Write the first sentence I will say to the doctor: the main problem, how long it has lasted and what has changed, so the most important issue comes first and is not lost at the end of the visit.

4. Symptom story. Turn my notes into a short, clear timeline the doctor can follow in under a minute: when it started, how often, how strong (0-10), what makes it better or worse, what I have tried, and how it affects work, sleep and daily life. Tell me which numbers to track until the appointment and give me a simple daily log table for the days before it.

5. Priority list. Sort everything I want to mention into "must discuss today", "if there is time" and "book a separate visit", and explain why. Make sure my top concern gets the most time.

6. Questions to ask. Give me 6 to 8 clear questions for the main problem, such as what the possible causes are, which tests make sense and why, what I can do in the meantime, which warning signs mean I should come back sooner, and when we will know more. Add 2 questions to ask if I am told "it is probably stress" so I can ask politely what would make the doctor look further.

7. What to bring. A checklist: my medication list with doses, the symptom log, previous test results or letters, my insurance or health card, my inhaler, glasses, and a written list of questions. Mention what to tell the doctor about the ibuprofen and supplements, and that I should ask before stopping or changing anything.

8. During the visit. Practical tips: how to bring my partner in usefully (taking notes, reminding me of my list), how to ask the doctor to slow down or explain a word, how to repeat back the plan to check I understood it, and how to ask for a written summary or a follow-up booking.

9. After the visit. A short template to write down the doctor's answers: what was decided, tests ordered and when results come, what to do at home, warning signs to watch, and the follow-up date.

Rules:
- Never diagnose, guess a disease or suggest medicines, doses or stopping a treatment; that is the doctor's job.
- Always put safety first: if anything in my notes sounds urgent, say so clearly at the start.
- Keep everything specific to my situation and appointment length; no generic health articles.
- Use short, simple sentences that are easy to read for someone whose first language is not English.
- Respect my worries and help me say them out loud in a calm, respectful way.
- End with a one-page "appointment card" I can print or keep on my phone: the opening sentence, the top 3 points, my questions, the medication list and the after-visit notes template.
ChecklistCoachCommunication+4
F@f
0
Calendar Meeting Load and Focus Time Analyzer
Skill

Measures meeting load and focus time from an .ics calendar export: expands recurring meetings, drops declined, free and cancelled events, and reports weekly meeting share, focus blocks, back-to-back chains, double bookings, late meetings, no-lunch days and costly series. Stdlib Python.

---
name: calendar-meeting-load-and-focus-time-analyzer
description: Measures meeting load and focus time from an .ics calendar export: expands recurring meetings, drops declined, free and cancelled events, and reports weekly meeting share, focus blocks, back-to-back chains, double bookings, late meetings, no-lunch days and costly series. Stdlib Python.
---

# Calendar Meeting Load and Focus Time Analyzer

You help managers, founders and busy individual contributors see where their working week really goes. Most people feel that they "have too many meetings" but cannot say how many hours, which series cost the most, or why there is never a two-hour block left for deep work. You take a plain calendar export, measure it honestly, and turn the numbers into a short calendar reset plan: what to cut, shorten, merge, move to async, or protect.

A calendar shows invitations, not how valuable each meeting is. Some heavy weeks are right (planning, hiring, a launch). Use the numbers to start a conversation about trade-offs, never to judge a person or a team, and always ask what the person wants more time for before recommending cuts.

## Files in this skill

- `scripts/meeting_load.py` - reads an iCalendar (.ics) export, unfolds lines, converts time zones (TZID, UTC, Windows zone names), expands recurring meetings (RRULE DAILY/WEEKLY/MONTHLY with INTERVAL, COUNT, UNTIL, BYDAY incl. "1TH"/"-1FR", BYMONTHDAY, EXDATE, moved or cancelled instances via RECURRENCE-ID), skips cancelled, declined (with `--me`), free/transparent and all-day events, treats all-day "Out of office" or "Vacation" events as days off, and reports per day and ISO week: meeting hours and load, focus blocks, fragmented time, back-to-back chains, double bookings, meetings outside working hours, days without lunch, and series ranked by person-hours and cost; flags M01-M09; `--format text|md|json|csv`, `--fail-on`, `--self-test` runs 30 checks (Python 3.9+ standard library only)
- `references/meeting-load-metrics.md` - what each number means, sensible ranges, and how to read them for managers and makers
- `references/calendar-export-and-ics-notes.md` - how to export from Google Calendar, Outlook and Apple Calendar, and the ICS details that change the numbers
- `templates/calendar-reset-plan.md` - a one-page plan: numbers, decisions per series, protected focus time and a check-in date
- `examples/head-of-product.ics` - two fictional weeks of a head of product at a 60-person startup (standup, 1:1s, leadership sync, biweekly product review, monthly all-hands, a moved 1:1, a declined demo, a cancelled sync, a day off and an evening call with a US partner)

## Workflow

### 1. Get the export and the person's goals
Ask for an .ics export of the last 2-4 normal working weeks (see `references/calendar-export-and-ics-notes.md`) and the person's email address as it appears in invitations. Then ask three questions: what are your working hours and time zone, what do you need more time for (deep work, customers, coaching the team, thinking), and which meetings do you think are most and least valuable?

### 2. Run the analysis
```
python3 scripts/meeting_load.py calendar.ics --me you@company.com --since 2026-11-23 --until 2026-12-04
python3 scripts/meeting_load.py calendar.ics --me you@company.com --workday 08:30-17:30 --tz Europe/Istanbul
python3 scripts/meeting_load.py calendar.ics --me you@company.com --hourly-cost 75 --format md > meeting-load.md
python3 scripts/meeting_load.py calendar.ics --me you@company.com --focus-min 90 --max-load 50   # maker vs manager settings
python3 scripts/meeting_load.py calendar.ics --format csv > meetings.csv                          # one row per meeting
python3 scripts/meeting_load.py calendar.ics --me you@company.com --fail-on medium                # e.g. a weekly reminder job
python3 scripts/meeting_load.py --self-test
```
Without `--since/--until` the window runs from the first to the last one-off (non-recurring) meeting in the file, because a series can start months earlier and open-ended series never end; pass both dates for exact periods. Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable file or bad option.

| Code | Severity | Signal |
|---|---|---|
| M01 | medium / high | weekly meetings take `--max-load` (default 40%) or more of working time (high at 1.5x) |
| M02 | medium | fewer than `--min-focus-blocks` (default 3) free blocks of `--focus-min` (default 120) minutes in a week |
| M03 | low | a chain of 3+ meetings with less than 5 minutes between them |
| M04 | medium | two accepted meetings overlap (double booking) |
| M05 | low / medium | a meeting before or after working hours (medium on a day off or non-working day) |
| M06 | low | a recurring meeting with `--large` (default 8) or more people, with its person-hours and cost |
| M07 | low | a recurring meeting of 30+ minutes that you organize without an agenda in the invite |
| M08 | info | something the script could not read exactly (unsupported rule, unknown time zone, bad line) |
| M09 | low | a working day with meetings and no free 30 minutes in the `--lunch` window |

### 3. Read the numbers with the person
Use `references/meeting-load-metrics.md`. Start with the week view (load and focus blocks), then the top series by person-hours: a few recurring meetings usually explain most of the load. Check the flags for quick wins: double bookings, meetings on days off, evening calls that could rotate, missing agendas.

### 4. Decide per series
For each of the top 5-8 series agree one decision: keep, shorten (60 -> 45 or 30 -> 25), lower the frequency, make attendance optional for some people, replace with an async update, merge with another meeting, or end it. Protect at least 2-3 focus blocks per week as real calendar events, and move recurring meetings to cluster on fewer days if possible.

### 5. Write the plan and check again
Fill `templates/calendar-reset-plan.md` with the numbers before and the target after, the decision per series, the protected focus blocks and who needs to be told. Run the script again after 2-4 weeks with the same settings and compare.

## Rules
- Never share someone's calendar details beyond the person who asked; summaries for a team use series names and totals, not private event titles.
- Person-hours and cost are rough estimates; say so and never present them as exact.
- A meeting that looks expensive can be the most valuable hour of the week; ask before recommending a cut.
- Recommend changes the person can make themselves first (their own meetings, declining, shortening); for meetings owned by others, suggest how to raise it.
- Use the same settings when comparing periods; changing working hours or `--focus-min` changes every number.
- Mention any M08 note, because unsupported rules or unknown time zones can make the numbers too low or too high.

FILE:references/meeting-load-metrics.md
# Meeting load metrics

## The core numbers
- **Meeting hours** - the time inside working hours covered by at least one accepted, busy meeting. Overlapping meetings are counted once (you can only be in one place), and double bookings are reported separately.
- **Load** - meeting hours divided by available working hours (working days only; days off from all-day "Out of office" events are removed). This is the number most people underestimate.
- **Focus block** - a free stretch of at least `--focus-min` minutes (default 120) inside working hours. Two hours is the usual minimum for writing, design, analysis or coding; use 90 for people whose work comes in shorter pieces.
- **Fragmented time** - free gaps shorter than 30 minutes between meetings. It looks free on the calendar but is rarely usable.
- **Back-to-back chain** - three or more meetings with less than 5 minutes between them: no break, no notes, late starts.
- **Person-hours** - duration times the number of people who did not decline. A 90-minute weekly meeting with 10 people costs 15 person-hours a week. Multiply by an average loaded hourly cost for a rough money figure.
- **Recurring share** - how much meeting time comes from recurring series. High shares (over 60%) mean the calendar runs on autopilot: the best place to cut.

## Rough ranges (adapt to the role)
| Role | Typical load | Focus blocks per week |
|---|---|---|
| Individual contributor (engineer, designer, analyst) | 10-25% | 6-10 |
| Team lead / senior IC | 25-40% | 4-6 |
| Manager of managers, head of function | 40-60% | 2-4 |
| Founder / CEO in a small company | 40-70% (spiky) | 2-3, protected on purpose |

Above about 60% for several weeks almost everyone loses the time to prepare, follow up and think; work moves into evenings.

## How to read the week
1. Load and focus blocks together: a 45% load with 4 focus blocks is fine; a 35% load with 0 focus blocks means the meetings are spread badly.
2. Top series by person-hours: usually 3-5 series explain half the load.
3. Flags for quick wins: double bookings, meetings on days off, missing agendas, evening calls that could rotate between time zones.
4. Days without lunch and long chains: small fixes (25/50-minute defaults, a lunch hold) make a big difference.

## What the numbers cannot tell
- Whether a meeting was useful, or what would happen without it.
- Work done outside the calendar (chat, email, reviews) and meetings that never made it into the calendar.
- Private events and events from other calendars that were not exported.

FILE:references/calendar-export-and-ics-notes.md
# Calendar export and ICS notes

## Exporting
- **Google Calendar** (web): Settings -> Settings for my calendars -> choose the calendar -> "Export calendar" downloads a zip with one .ics per calendar. Or Settings -> Import & export -> Export for all calendars.
- **Outlook** (desktop, Windows): File -> Save Calendar -> choose a date range and "Full details" -> .ics. Outlook on the web: Settings -> Calendar -> Shared calendars -> Publish a calendar, then download the ICS link.
- **Apple Calendar** (macOS): select the calendar in the sidebar -> File -> Export -> Export...
- **Fastmail, Proton, Nextcloud**: calendar settings -> export or the CalDAV/ICS link.

Export the work calendar only, and remove private calendars before sharing the file with anyone.

## Details that change the numbers
- **Time zones**: events carry `TZID=...`, UTC times end in `Z`, and Outlook may use Windows names such as "Turkey Standard Time". The script converts everything to `--tz` (default: the file's `X-WR-TIMEZONE`). Pass `--tz` explicitly if you travel or the file has no calendar time zone.
- **Recurring meetings**: a series is one VEVENT with an `RRULE`; skipped dates are `EXDATE`; a moved or cancelled single meeting is a second VEVENT with the same `UID` and a `RECURRENCE-ID`. Supported: DAILY, WEEKLY, MONTHLY with INTERVAL, COUNT, UNTIL, BYDAY (also "1TH", "-1FR") and BYMONTHDAY. Anything else (for example YEARLY or BYSETPOS) is counted once and reported as M08.
- **Declined meetings**: only visible when `--me` is your address as it appears in the ATTENDEE lines; otherwise declined meetings are counted as busy.
- **Free vs busy**: events marked "Free" (`TRANSP:TRANSPARENT`) are not counted. Many focus-time tools create busy events; those are counted as meetings, which is usually what you want to see - or exclude them by marking them free.
- **All-day events** are never counted as meetings. All-day events named like "Out of office", "OOO", "Vacation", "Holiday", "Day off", "Leave" or "Sick" make that day a day off.
- **Attendees**: rooms and resources (`CUTYPE=ROOM/RESOURCE`) and people who declined are not counted for person-hours. Large distribution lists appear as one attendee, so all-hands costs are often too low.
- **Exports from someone else's calendar** may hide titles ("Busy") and attendees; load numbers still work, series names and costs do not.

FILE:templates/calendar-reset-plan.md
# Calendar reset plan: {{name}}, {{role}}

**Period measured:** {{from}} to {{to}} ({{N}} working days, working hours {{09:00-18:00}}, {{time zone}})  
**What I want more time for:** {{e.g. product strategy, customer conversations, coaching the team}}

## Numbers now and target
| Metric | Now | Target in 4 weeks |
|---|---|---|
| Meeting load (share of working time) | {{42%}} | {{30-35%}} |
| Focus blocks of 2+ hours per week | {{4}} | {{6}} |
| Back-to-back chains per week | {{2}} | {{0-1}} |
| Days without a lunch break | {{2}} | {{0}} |
| Meetings outside working hours per week | {{1}} | {{0-1, rotating}} |

## Decisions per series
| Series | People | h/week | Decision | Owner | Told by |
|---|---|---|---|---|---|
| {{Leadership sync}} | {{10}} | {{1.75}} | {{shorten 90 -> 60, written pre-read}} | {{CEO}} | {{date}} |
| {{Daily standup}} | {{9}} | {{1.25}} | {{3x per week + async updates}} | {{eng lead}} | {{date}} |
| {{Product review}} | {{12}} | {{0.75}} | {{agenda in invite, optional for 4 people}} | {{me}} | {{date}} |

## Protected time
- Focus blocks: {{Tue 09:45-12:00, Thu 13:00-16:00, Fri 13:00-17:00}} as busy events named "Focus"
- Lunch: {{12:30-13:15 daily hold}}
- Meeting-light day: {{Friday}}

## Defaults from now on
- New meetings 25 or 50 minutes, agenda in the invite, decision owner named.
- Recurring meetings reviewed every quarter; any series without a clear purpose ends.
- Evening calls across time zones rotate between the two sides.

## Check-in
Re-run the analysis on {{date}} with the same settings and compare with the numbers above.

FILE:examples/head-of-product.ics
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp//Calendar Export//EN
CALSCALE:GREGORIAN
METHOD:PUBLISH
X-WR-CALNAME:Alex Morgan
X-WR-TIMEZONE:Europe/Istanbul
BEGIN:VTIMEZONE
TZID:Europe/Istanbul
BEGIN:STANDARD
DTSTART:19700101T000000
TZOFFSETFROM:+0300
TZOFFSETTO:+0300
TZNAME:+03
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
UID:standup@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261123T093000
DTEND;TZID=Europe/Istanbul:20261123T094500
RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR
EXDATE;TZID=Europe/Istanbul:20261204T093000
SUMMARY:Daily standup
ORGANIZER;CN=Jonas:mailto:jonas@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
END:VEVENT
BEGIN:VEVENT
UID:one-on-one-sam@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261123T100000
DTEND;TZID=Europe/Istanbul:20261123T103000
RRULE:FREQ=WEEKLY;BYDAY=MO
SUMMARY:1:1 Alex / Sam
DESCRIPTION:Shared agenda doc: wins, blockers, career goals, feedback both
  ways.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
END:VEVENT
BEGIN:VEVENT
UID:one-on-one-sam@example.com
DTSTAMP:20261205T080000Z
RECURRENCE-ID;TZID=Europe/Istanbul:20261130T100000
DTSTART;TZID=Europe/Istanbul:20261201T160000
DTEND;TZID=Europe/Istanbul:20261201T163000
SUMMARY:1:1 Alex / Sam (moved)
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
END:VEVENT
BEGIN:VEVENT
UID:one-on-one-priya@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261125T100000
DTEND;TZID=Europe/Istanbul:20261125T103000
RRULE:FREQ=WEEKLY;BYDAY=WE
SUMMARY:1:1 Alex / Priya
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
END:VEVENT
BEGIN:VEVENT
UID:ceo-1on1@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261126T110000
DTEND;TZID=Europe/Istanbul:20261126T114500
RRULE:FREQ=WEEKLY;BYDAY=TH
SUMMARY:1:1 with CEO
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
END:VEVENT
BEGIN:VEVENT
UID:leadership-sync@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261124T140000
DTEND;TZID=Europe/Istanbul:20261124T153000
RRULE:FREQ=WEEKLY;BYDAY=TU
SUMMARY:Leadership sync
DESCRIPTION:Standing agenda: metrics, hiring, top risks, decisions needed 
 this week.
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
END:VEVENT
BEGIN:VEVENT
UID:product-review@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261118T150000
DTEND;TZID=Europe/Istanbul:20261118T163000
RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=WE
SUMMARY:Product review
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
END:VEVENT
BEGIN:VEVENT
UID:design-critique@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261126T140000
DTEND;TZID=Europe/Istanbul:20261126T150000
RRULE:FREQ=WEEKLY;BYDAY=TH
SUMMARY:Design critique
DESCRIPTION:Bring 1-2 designs in progress; 15 minutes each; decisions go i
 nto the design log.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
END:VEVENT
BEGIN:VEVENT
UID:all-hands@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261106T170000
DTEND;TZID=Europe/Istanbul:20261106T180000
RRULE:FREQ=MONTHLY;BYDAY=1TH
SUMMARY:All-hands
DESCRIPTION:Company update, team demos and open Q&A.
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
END:VEVENT
BEGIN:VEVENT
UID:us-partner@example.com
DTSTAMP:20261205T080000Z
DTSTART:20261123T153000Z
DTEND:20261123T161500Z
RRULE:FREQ=WEEKLY;BYDAY=MO
SUMMARY:US partner sync
ORGANIZER;CN=Partner.Lead:mailto:partner.lead@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Partner.Lead;PARTSTAT=ACCEPTED:mailto:partner.lead@example.com
END:VEVENT
BEGIN:VEVENT
UID:sprint-planning@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261123T130000
DTEND;TZID=Europe/Istanbul:20261123T143000
RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=MO
SUMMARY:Sprint planning
DESCRIPTION:Sprint goal, capacity, top backlog items, risks.
ORGANIZER;CN=Jonas:mailto:jonas@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-012@example.com
DTSTAMP:20261205T080000Z
DTSTART:20261123T080000Z
DTEND:20261123T090000Z
SUMMARY:Customer call: Northwind
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Customer.Ops;PARTSTAT=ACCEPTED:mailto:customer.ops@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-013@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261123T120000
DTEND;TZID=Europe/Istanbul:20261123T130000
SUMMARY:Pricing workshop
DESCRIPTION:Decide the 2027 price list proposal.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-014@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261124T100000
DTEND;TZID=Europe/Istanbul:20261124T120000
SUMMARY:Roadmap offsite prep
DESCRIPTION:Draft the H1 roadmap themes for the offsite.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-015@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261124T153000
DTEND;TZID=Europe/Istanbul:20261124T160000
SUMMARY:Vendor demo: analytics tool
ORGANIZER;CN=Vendor:mailto:vendor@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=DECLINED:mailto:alex@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-016@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261124T160000
DTEND;TZID=Europe/Istanbul:20261124T170000
SUMMARY:Interview: Senior PM
ORGANIZER;CN=Nina:mailto:nina@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-017@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261125T110000
DTEND;TZID=Europe/Istanbul:20261125T120000
SUMMARY:Customer advisory call
ORGANIZER;CN=Carlos:mailto:carlos@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-018@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261125T130000
DTEND;TZID=Europe/Istanbul:20261125T140000
SUMMARY:Analytics deep dive
DESCRIPTION:Activation funnel drop in week 47.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-019@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261125T163000
DTEND;TZID=Europe/Istanbul:20261125T173000
SUMMARY:Interview: Product Designer
ORGANIZER;CN=Nina:mailto:nina@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-020@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261126T130000
DTEND;TZID=Europe/Istanbul:20261126T140000
SUMMARY:Focus time
TRANSP:TRANSPARENT
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-021@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261126T143000
DTEND;TZID=Europe/Istanbul:20261126T150000
SUMMARY:Pricing page review
ORGANIZER;CN=Yuki:mailto:yuki@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-022@example.com
DTSTAMP:20261205T080000Z
DTSTART;VALUE=DATE:20261127
DTEND;VALUE=DATE:20261128
SUMMARY:Out of office
END:VEVENT
BEGIN:VEVENT
UID:evt-023@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261130T110000
DTEND;TZID=Europe/Istanbul:20261130T120000
SUMMARY:Board deck review
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-024@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261130T143000
DTEND;TZID=Europe/Istanbul:20261130T160000
SUMMARY:Quarterly planning
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-025@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261201T100000
DTEND;TZID=Europe/Istanbul:20261201T110000
SUMMARY:Customer interview 1
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Customer.A;PARTSTAT=ACCEPTED:mailto:customer.a@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-026@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261201T110000
DTEND;TZID=Europe/Istanbul:20261201T120000
SUMMARY:Customer interview 2
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Customer.B;PARTSTAT=ACCEPTED:mailto:customer.b@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-027@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261201T120000
DTEND;TZID=Europe/Istanbul:20261201T123000
SUMMARY:Sales handoff: Acme
ORGANIZER;CN=Carlos:mailto:carlos@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-028@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261202T110000
DTEND;TZID=Europe/Istanbul:20261202T120000
SUMMARY:Engineering estimate session
ORGANIZER;CN=Jonas:mailto:jonas@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-029@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261202T120000
DTEND;TZID=Europe/Istanbul:20261202T130000
SUMMARY:Lunch and learn: AI in support
ORGANIZER;CN=Lena:mailto:lena@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-030@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261202T130000
DTEND;TZID=Europe/Istanbul:20261202T140000
SUMMARY:Partner call: Globex
ORGANIZER;CN=Carlos:mailto:carlos@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Partner.B;PARTSTAT=ACCEPTED:mailto:partner.b@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-031@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261203T090000
DTEND;TZID=Europe/Istanbul:20261203T093000
SUMMARY:Investor update prep
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-032@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261203T120000
DTEND;TZID=Europe/Istanbul:20261203T130000
SUMMARY:Customer QBR: Initech
ORGANIZER;CN=Carlos:mailto:carlos@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Customer.C;PARTSTAT=ACCEPTED:mailto:customer.c@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-033@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261204T100000
DTEND;TZID=Europe/Istanbul:20261204T110000
SUMMARY:Weekly metrics review
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-034@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261204T150000
DTEND;TZID=Europe/Istanbul:20261204T153000
SUMMARY:Feature flag cleanup sync
STATUS:CANCELLED
ORGANIZER;CN=Jonas:mailto:jonas@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-035@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261204T160000
DTEND;TZID=Europe/Istanbul:20261204T170000
SUMMARY:Team retro
DESCRIPTION:What went well, what to change, one experiment for next sprint.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
END:VEVENT
END:VCALENDAR

FILE:scripts/meeting_load.py
#!/usr/bin/env python3
"""meeting_load.py - measure meeting load and focus time from an iCalendar (.ics) export.

Reads one person's calendar export (Google Calendar, Outlook, Apple Calendar, Fastmail ...),
expands recurring meetings (RRULE DAILY/WEEKLY/MONTHLY with INTERVAL, COUNT, UNTIL, BYDAY,
BYMONTHDAY, EXDATE and moved or cancelled instances via RECURRENCE-ID), drops cancelled,
declined, free (transparent) and all-day events, and measures, per day and ISO week inside
working hours: meeting hours and share of the working week, focus blocks, fragmented time,
back-to-back chains, double bookings, meetings outside working hours, days without a lunch
break, and the recurring series that cost the most person-hours. Flags M01-M09 + E01.

Usage:
  meeting_load.py CALENDAR.ics [--me EMAIL] [--tz Europe/Istanbul] [--since YYYY-MM-DD] [--until YYYY-MM-DD]
                  [--workday 09:00-18:00] [--workdays mon-fri] [--focus-min 120] [--max-load 40]
                  [--min-focus-blocks 3] [--large 8] [--hourly-cost 0] [--lunch 11:30-14:00]
                  [--format text|md|json|csv] [--fail-on none|info|low|medium|high]
  meeting_load.py --self-test
Exit: 0 ok, 1 flags at or above --fail-on, 2 unreadable input. Python 3.9+ (zoneinfo), standard library only.
"""
import argparse, csv, io, json, re, sys
from datetime import date, datetime, timedelta, timezone

try:
    from zoneinfo import ZoneInfo
except ImportError:  # pragma: no cover
    ZoneInfo = None

SEV = {"info": 0, "low": 1, "medium": 2, "high": 3}
DAYS = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"]
WIN_TZ = {"Turkey Standard Time": "Europe/Istanbul", "W. Europe Standard Time": "Europe/Berlin",
          "GMT Standard Time": "Europe/London", "Romance Standard Time": "Europe/Paris",
          "Eastern Standard Time": "America/New_York", "Pacific Standard Time": "America/Los_Angeles",
          "Central Standard Time": "America/Chicago", "UTC": "UTC"}


# ---------------------------------------------------------------- ICS parsing
def unfold(text):
    return re.sub(r"\r?\n[ \t]", "", text).replace("\r\n", "\n").split("\n")


def parse_prop(line):
    """'DTSTART;TZID=Europe/Istanbul:20261124T100000' -> ('DTSTART', {'TZID': 'Europe/Istanbul'}, '20261124T100000')"""
    m = re.match(r'^([A-Za-z0-9-]+)((?:;[^:;]+=(?:"[^"]*"|[^:;]*))*):(.*)$', line)
    if not m:
        return None
    params = {}
    for p in re.findall(r';([^=;]+)=("[^"]*"|[^:;]*)', m.group(2)):
        params[p[0].upper()] = p[1].strip('"')
    return m.group(1).upper(), params, m.group(3)


def unescape(v):
    return v.replace("\\n", "\n").replace("\\N", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")


def get_zone(name, notes):
    if not name:
        return None
    name = WIN_TZ.get(name, name)
    if name.upper() in ("UTC", "Z", "GMT"):
        return timezone.utc
    if ZoneInfo:
        try:
            return ZoneInfo(name)
        except Exception:
            pass
    notes.add("unknown time zone %r, treated as the analysis time zone" % name)
    return None


def parse_dt(value, params, default_tz, notes):
    """Returns (aware datetime or date, is_all_day)."""
    v = value.strip()
    if params.get("VALUE") == "DATE" or re.fullmatch(r"\d{8}", v):
        return date(int(v[:4]), int(v[4:6]), int(v[6:8])), True
    m = re.fullmatch(r"(\d{8})T(\d{6})(Z?)", v)
    if not m:
        raise ValueError("bad date-time %r" % value)
    dt = datetime.strptime(m.group(1) + m.group(2), "%Y%m%d%H%M%S")
    if m.group(3) == "Z":
        return dt.replace(tzinfo=timezone.utc), False
    tz = get_zone(params.get("TZID"), notes) or default_tz
    return dt.replace(tzinfo=tz), False


def parse_duration(v):
    m = re.fullmatch(r"([+-])?P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?", v.strip())
    if not m:
        raise ValueError("bad duration %r" % v)
    sign = -1 if m.group(1) == "-" else 1
    w, d, h, mi, s = (int(x or 0) for x in m.groups()[1:])
    return sign * timedelta(weeks=w, days=d, hours=h, minutes=mi, seconds=s)


def parse_ics(text, default_tz, notes):
    events, cur, depth = [], None, []
    cal_tz = None
    for line in unfold(text):
        if not line.strip():
            continue
        p = parse_prop(line)
        if not p:
            notes.add("skipped an unreadable line: %s" % line[:60])
            continue
        name, params, value = p
        if name == "BEGIN":
            depth.append(value.upper())
            if value.upper() == "VEVENT":
                cur = {"attendees": [], "exdates": [], "raw": {}}
            continue
        if name == "END":
            if depth and depth[-1] == "VEVENT" and cur is not None:
                events.append(cur); cur = None
            if depth:
                depth.pop()
            continue
        if name == "X-WR-TIMEZONE" and not cal_tz:
            cal_tz = value.strip()
        if cur is None or depth[-1] != "VEVENT":
            continue
        cur["raw"][name] = (params, value)
        if name == "ATTENDEE":
            cur["attendees"].append({"email": value.lower().replace("mailto:", "").strip(),
                                     "partstat": params.get("PARTSTAT", "NEEDS-ACTION").upper(),
                                     "role": params.get("ROLE", "REQ-PARTICIPANT").upper(),
                                     "cutype": params.get("CUTYPE", "INDIVIDUAL").upper()})
        elif name == "EXDATE":
            cur["exdates"] += [(params, x) for x in value.split(",")]
    return events, cal_tz


def parse_rrule(v):
    r = {}
    for part in v.split(";"):
        if "=" in part:
            k, val = part.split("=", 1); r[k.upper()] = val
    return r


def expand(start, rule, window_start, window_end, notes, uid):
    """Yield instance starts (aware datetimes) for a supported RRULE."""
    freq = rule.get("FREQ", "").upper()
    interval = int(rule.get("INTERVAL", "1") or 1)
    count = int(rule["COUNT"]) if "COUNT" in rule else None
    until = None
    if "UNTIL" in rule:
        u = rule["UNTIL"]
        until = datetime.strptime(u[:15], "%Y%m%dT%H%M%S").replace(tzinfo=timezone.utc) if "T" in u else \
            datetime(int(u[:4]), int(u[4:6]), int(u[6:8]), 23, 59, 59, tzinfo=start.tzinfo)
    unsupported = set(rule) - {"FREQ", "INTERVAL", "COUNT", "UNTIL", "BYDAY", "BYMONTHDAY", "WKST"}
    if freq not in ("DAILY", "WEEKLY", "MONTHLY") or unsupported:
        notes.add("recurring event %s uses an unsupported rule (%s); only its first instance is counted" % (uid, ";".join("%s=%s" % kv for kv in rule.items())))
        yield start
        return
    byday = [d.strip() for d in rule.get("BYDAY", "").split(",") if d.strip()]
    produced = 0
    limit = window_end + timedelta(days=1)

    def emit(dt):
        nonlocal produced
        if until and dt > until:
            return False
        if count is not None and produced >= count:
            return False
        produced += 1
        return True

    if freq == "DAILY":
        d = start
        while d <= limit:
            if not byday or DAYS[d.weekday()] in byday:
                if not emit(d): return
                yield d
            d = d + timedelta(days=interval)
    elif freq == "WEEKLY":
        days = sorted(DAYS.index(x[-2:]) for x in byday) if byday else [start.weekday()]
        week0 = start - timedelta(days=start.weekday())
        k = 0
        while True:
            wk = week0 + timedelta(weeks=k * interval)
            if wk > limit:
                return
            for wd in days:
                d = wk + timedelta(days=wd)
                if d < start:
                    continue
                if d > limit:
                    return
                if not emit(d): return
                yield d
            k += 1
    else:  # MONTHLY
        y, m = start.year, start.month
        while True:
            first = start.replace(year=y, month=m, day=1)
            if first > limit:
                return
            cands = []
            if "BYMONTHDAY" in rule:
                for md in rule["BYMONTHDAY"].split(","):
                    try:
                        cands.append(first.replace(day=int(md)))
                    except ValueError:
                        pass
            elif byday:
                for bd in byday:
                    mm = re.fullmatch(r"([+-]?\d)?([A-Z]{2})", bd)
                    n, wd = int(mm.group(1) or 0), DAYS.index(mm.group(2))
                    days_in = [first + timedelta(days=i) for i in range(31) if (first + timedelta(days=i)).month == m]
                    match = [d for d in days_in if d.weekday() == wd]
                    if n == 0:
                        cands += match
                    elif -len(match) <= n <= len(match) and n != 0:
                        cands.append(match[n - 1] if n > 0 else match[n])
            else:
                try:
                    cands.append(first.replace(day=start.day))
                except ValueError:
                    pass
            for d in sorted(cands):
                if d < start:
                    continue
                if d > limit:
                    return
                if not emit(d): return
                yield d
            m += interval
            while m > 12:
                m -= 12; y += 1


def build_instances(events, tz, window_start, window_end, me, notes):
    """Returns (instances, skipped_counts, all_day_off_dates)."""
    insts, skipped, days_off = {}, {"cancelled": 0, "declined": 0, "free": 0, "all_day": 0}, set()
    overrides = {}
    masters = []
    for ev in events:
        raw = ev["raw"]
        if "DTSTART" not in raw:
            notes.add("event without DTSTART skipped"); continue
        try:
            st, allday = parse_dt(raw["DTSTART"][1], raw["DTSTART"][0], tz, notes)
            if "DTEND" in raw:
                en, _ = parse_dt(raw["DTEND"][1], raw["DTEND"][0], tz, notes)
            elif "DURATION" in raw:
                en = st + parse_duration(raw["DURATION"][1])
            else:
                en = st + (timedelta(days=1) if allday else timedelta(0))
        except ValueError as e:
            notes.add("event %s skipped: %s" % (raw.get("UID", ({}, "?"))[1], e)); continue
        ev["start"], ev["end"], ev["allday"] = st, en, allday
        ev["uid"] = raw.get("UID", ({}, "no-uid-%d" % id(ev)))[1].strip()
        ev["summary"] = unescape(raw.get("SUMMARY", ({}, "(no title)"))[1]).strip()
        ev["status"] = raw.get("STATUS", ({}, "CONFIRMED"))[1].strip().upper()
        ev["transp"] = raw.get("TRANSP", ({}, "OPAQUE"))[1].strip().upper()
        ev["description"] = unescape(raw.get("DESCRIPTION", ({}, ""))[1]).strip()
        org = raw.get("ORGANIZER", ({}, ""))[1].lower().replace("mailto:", "").strip()
        ev["organizer"] = org
        if "RECURRENCE-ID" in raw:
            rid, _ = parse_dt(raw["RECURRENCE-ID"][1], raw["RECURRENCE-ID"][0], tz, notes)
            overrides[(ev["uid"], rid)] = ev
        else:
            masters.append(ev)

    def keep(ev, st):
        if ev["status"] == "CANCELLED":
            skipped["cancelled"] += 1; return False
        if ev["allday"]:
            skipped["all_day"] += 1
            if ev["transp"] != "TRANSPARENT" and re.search(r"out of office|\booo\b|vacation|holiday|day off|leave|sick", ev["summary"], re.I):
                d = st
                while d < ev["end"]:
                    days_off.add(d); d += timedelta(days=1)
            return False
        if ev["transp"] == "TRANSPARENT":
            skipped["free"] += 1; return False
        mine = [a for a in ev["attendees"] if me and a["email"] == me]
        if mine and mine[0]["partstat"] == "DECLINED":
            skipped["declined"] += 1; return False
        return True

    def add(ev, st):
        en = st + (ev["end"] - ev["start"])
        if isinstance(st, datetime):
            st, en = st.astimezone(tz), en.astimezone(tz)
            if en <= window_start or st >= window_end + timedelta(days=1):
                return
        elif not (window_start.date() <= st <= window_end.date()):
            return
        if not keep(ev, st):
            return
        people = [a for a in ev["attendees"] if a["cutype"] not in ("ROOM", "RESOURCE") and a["partstat"] != "DECLINED"]
        n = max(len(people), 1)
        insts[(ev["uid"], st)] = {"uid": ev["uid"], "summary": ev["summary"], "start": st, "end": en,
                                  "attendees": n, "recurring": "RRULE" in ev["raw"] or ev.get("_override_of_series", False),
                                  "organizer_is_me": bool(me) and ev["organizer"] == me, "has_agenda": len(ev["description"]) >= 20}

    for ev in masters:
        st = ev["start"]
        if "RRULE" in ev["raw"] and not ev["allday"]:
            ex = set()
            for params, x in ev["exdates"]:
                try:
                    ex.add(parse_dt(x, params, tz, notes)[0])
                except ValueError:
                    pass
            for s in expand(st, parse_rrule(ev["raw"]["RRULE"][1]), window_start, window_end, notes, ev["uid"]):
                if s in ex:
                    continue
                ov = overrides.pop((ev["uid"], s), None)
                if ov is not None:
                    ov["_override_of_series"] = True
                    ov["raw"].setdefault("RRULE", ev["raw"]["RRULE"])
                    if not ov["attendees"]:
                        ov["attendees"] = ev["attendees"]
                    if not ov["description"]:
                        ov["description"] = ev["description"]
                    add(ov, ov["start"])
                else:
                    add(ev, s)
        else:
            add(ev, st)
    for (uid, rid), ov in overrides.items():   # overrides whose master was outside the file
        add(ov, ov["start"])
    return sorted(insts.values(), key=lambda i: (i["start"], i["end"])), skipped, days_off


# ---------------------------------------------------------------- analysis
def hm(s):
    h, m = s.split(":"); return int(h) * 60 + int(m)


def parse_workdays(s):
    s = s.lower().replace(" ", "")
    names = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
    if "-" in s and "," not in s:
        a, b = s.split("-"); return set(range(names.index(a[:3]), names.index(b[:3]) + 1))
    return {names.index(x[:3]) for x in s.split(",")}


def analyze(text, me=None, tzname=None, since=None, until=None, workday="09:00-18:00", workdays="mon-fri",
            focus_min=120, max_load=40.0, min_focus_blocks=3, large=8, hourly_cost=0.0, lunch="11:30-14:00"):
    notes = set()
    me = (me or "").lower() or None
    m = re.search(r"^X-WR-TIMEZONE:(.+)$", text, re.M)
    tzname = tzname or (m.group(1).strip() if m else "UTC")
    tz = get_zone(tzname, notes) or timezone.utc
    events, _ = parse_ics(text, tz, notes)
    if not events:
        raise ValueError("no VEVENT found; is this an .ics calendar export?")
    w0, w1 = [hm(x) for x in workday.split("-")]
    l0, l1 = [hm(x) for x in lunch.split("-")]
    wdays = parse_workdays(workdays)
    # window: default = first .. last non-recurring timed event (a series' first DTSTART can be months old,
    # and open-ended series would run forever); without one-off events: first timed event + 13 days
    starts, singles = [], []
    for ev in events:
        if "DTSTART" in ev["raw"]:
            try:
                st, ad = parse_dt(ev["raw"]["DTSTART"][1], ev["raw"]["DTSTART"][0], tz, notes)
            except ValueError:
                continue
            if not ad:
                starts.append(st.astimezone(tz))
                if "RRULE" not in ev["raw"]:
                    singles.append(st.astimezone(tz))
    if (not since or not until) and not starts:
        raise ValueError("no timed events; pass --since and --until")
    midnight = lambda dt: dt.replace(hour=0, minute=0, second=0, microsecond=0)
    ws = datetime.strptime(since, "%Y-%m-%d").replace(tzinfo=tz) if since else midnight(min(singles or starts))
    if until:
        we = datetime.strptime(until, "%Y-%m-%d").replace(tzinfo=tz)
    else:
        we = midnight(max(singles)) if singles else ws + timedelta(days=13)
    if we < ws:
        raise ValueError("--until is before --since")
    insts, skipped, days_off = build_instances(events, tz, ws, we, me, notes)
    days = {}
    d = ws.date()
    while d <= we.date():
        days[d] = {"date": d, "work": d.weekday() in wdays and d not in days_off, "off": d in days_off, "meetings": []}
        d += timedelta(days=1)
    for i in insts:
        if i["start"].date() in days:
            days[i["start"].date()]["meetings"].append(i)
    flags = []

    def flag(code, sev, msg, when=""):
        flags.append({"code": code, "severity": sev, "message": msg, "when": when})

    day_rows, weeks = [], {}
    overlaps_total, b2b_total, outside_total, no_lunch_days = 0, 0, 0, []
    for d, info in sorted(days.items()):
        ms = info["meetings"]
        mins = lambda dt: dt.hour * 60 + dt.minute
        # clip to the day
        ivs = []
        for i in ms:
            a = mins(i["start"]); b = mins(i["end"]) if i["end"].date() == d else 24 * 60
            ivs.append((a, b, i))
        outside = [i for a, b, i in ivs if not info["work"] or a < w0 or b > w1]
        outside_total += len(outside)
        for i in outside:
            where = "outside working hours" if info["work"] else ("on a day off" if info["off"] else "on a non-working day")
            flag("M05", "low" if info["work"] else "medium", "%s %s-%s %s: %s" % (
                d.isoformat(), i["start"].strftime("%H:%M"), i["end"].strftime("%H:%M"), where, i["summary"]), d.isoformat())
        # overlaps
        srt = sorted(ivs, key=lambda x: x[0])
        for k in range(1, len(srt)):
            for j in range(k):
                if srt[j][1] > srt[k][0]:
                    overlaps_total += 1
                    flag("M04", "medium", "%s double-booked: %s and %s" % (d.isoformat(), srt[j][2]["summary"], srt[k][2]["summary"]), d.isoformat())
        # merged busy time within working hours
        busy = []
        for a, b, _ in srt:
            a, b = max(a, w0), min(b, w1)
            if b <= a:
                continue
            if busy and a <= busy[-1][1]:
                busy[-1][1] = max(busy[-1][1], b)
            else:
                busy.append([a, b])
        meet_min = sum(b - a for a, b in busy)
        avail = (w1 - w0) if info["work"] else 0
        gaps, cur = [], w0
        for a, b in busy:
            if a > cur: gaps.append((cur, a))
            cur = max(cur, b)
        if cur < w1: gaps.append((cur, w1))
        if not info["work"]:
            gaps = []
        focus = [g for g in gaps if g[1] - g[0] >= focus_min]
        frag = [g for g in gaps if g[1] - g[0] < 30]
        # back-to-back chains: 3+ meetings with < 5 min between them
        chains, run = 0, 1
        for k in range(1, len(srt)):
            if srt[k][0] - srt[k - 1][1] < 5 and srt[k][0] >= srt[k - 1][0]:
                run += 1
            else:
                chains += run >= 3; run = 1
        chains += run >= 3
        b2b_total += chains
        if chains:
            flag("M03", "low", "%s has %d back-to-back chain(s) of 3+ meetings without a break" % (d.isoformat(), chains), d.isoformat())
        lunch_free = any(min(b, l1) - max(a, l0) >= 30 for a, b in gaps)
        if info["work"] and ms and not lunch_free:
            no_lunch_days.append(d.isoformat())
            flag("M09", "low", "%s has no free 30 minutes between %s and %s for lunch" % (d.isoformat(), lunch.split("-")[0], lunch.split("-")[1]), d.isoformat())
        row = {"date": d.isoformat(), "weekday": d.strftime("%a"), "workday": info["work"], "day_off": info["off"],
               "meetings": len(ms), "meeting_min": meet_min, "available_min": avail,
               "focus_blocks": len(focus), "focus_min": sum(b - a for a, b in focus),
               "fragmented_min": sum(b - a for a, b in frag), "b2b_chains": chains, "outside_hours": len(outside)}
        day_rows.append(row)
        iso = d.isocalendar()
        wk = weeks.setdefault("%d-W%02d" % (iso[0], iso[1]), {"week": "%d-W%02d" % (iso[0], iso[1]), "meetings": 0, "meeting_min": 0,
                                                             "available_min": 0, "focus_blocks": 0, "focus_min": 0, "fragmented_min": 0,
                                                             "b2b_chains": 0, "outside_hours": 0, "workdays": 0})
        for k in ("meetings", "meeting_min", "available_min", "focus_blocks", "focus_min", "fragmented_min", "b2b_chains", "outside_hours"):
            wk[k] += row[k]
        wk["workdays"] += info["work"]
    for wk in weeks.values():
        wk["load_pct"] = round(100.0 * wk["meeting_min"] / wk["available_min"], 1) if wk["available_min"] else 0.0
        if wk["workdays"] >= 3:
            if wk["load_pct"] >= max_load * 1.5:
                flag("M01", "high", "%s meeting load %.1f%% of working time (limit %.0f%%)" % (wk["week"], wk["load_pct"], max_load), wk["week"])
            elif wk["load_pct"] >= max_load:
                flag("M01", "medium", "%s meeting load %.1f%% of working time (limit %.0f%%)" % (wk["week"], wk["load_pct"], max_load), wk["week"])
            if wk["focus_blocks"] < min_focus_blocks:
                flag("M02", "medium", "%s only %d focus block(s) of %d+ min (goal %d per week)" % (wk["week"], wk["focus_blocks"], focus_min, min_focus_blocks), wk["week"])
    # series
    series = {}
    for i in insts:
        key = i["uid"] if i["recurring"] else "one-off:" + i["summary"]
        s = series.setdefault(key, {"title": i["summary"], "recurring": i["recurring"], "instances": 0, "minutes": 0,
                                    "attendees": 0, "person_hours": 0.0, "organizer_is_me": i["organizer_is_me"], "has_agenda": i["has_agenda"]})
        dur = (i["end"] - i["start"]).total_seconds() / 60
        s["instances"] += 1; s["minutes"] += dur; s["attendees"] = max(s["attendees"], i["attendees"])
        s["person_hours"] += dur / 60 * i["attendees"]
    n_weeks = max(1.0, len(days) / 7.0)
    for s in series.values():
        s["hours_per_week"] = round(s["minutes"] / 60 / n_weeks, 2)
        s["person_hours"] = round(s["person_hours"], 1)
        s["cost"] = round(s["person_hours"] * hourly_cost, 2) if hourly_cost else None
        if s["recurring"] and s["attendees"] >= large:
            flag("M06", "low", "large recurring meeting '%s': %d people, %.1f person-hours in the period%s" % (
                s["title"], s["attendees"], s["person_hours"], (", about %.0f in cost" % s["cost"]) if s["cost"] else ""))
        if s["recurring"] and s["organizer_is_me"] and not s["has_agenda"] and s["minutes"] / max(s["instances"], 1) >= 30:
            flag("M07", "low", "recurring meeting you organize without an agenda in the invite: '%s'" % s["title"])
    for n in sorted(notes):
        flag("M08", "info", n)
    total_meet = sum(r["meeting_min"] for r in day_rows); total_avail = sum(r["available_min"] for r in day_rows)
    summary = {"calendar_tz": tzname, "from": ws.date().isoformat(), "to": we.date().isoformat(), "me": me,
               "meetings": len(insts), "meeting_hours": round(total_meet / 60, 1), "available_hours": round(total_avail / 60, 1),
               "load_pct": round(100.0 * total_meet / total_avail, 1) if total_avail else 0.0,
               "focus_blocks": sum(r["focus_blocks"] for r in day_rows), "focus_hours": round(sum(r["focus_min"] for r in day_rows) / 60, 1),
               "fragmented_hours": round(sum(r["fragmented_min"] for r in day_rows) / 60, 1),
               "double_bookings": overlaps_total, "b2b_chains": b2b_total, "outside_hours_meetings": outside_total,
               "days_without_lunch": len(no_lunch_days), "days_off": sorted(x.isoformat() for x in days_off), "skipped": skipped,
               "recurring_share_pct": round(100.0 * sum((i["end"] - i["start"]).total_seconds() for i in insts if i["recurring"]) /
                                            max(1, sum((i["end"] - i["start"]).total_seconds() for i in insts)), 1)}
    flags.sort(key=lambda f: (-SEV[f["severity"]], f["code"], f["when"]))
    top = sorted(series.values(), key=lambda s: -s["person_hours"])
    return {"summary": summary, "weeks": [weeks[k] for k in sorted(weeks)], "days": day_rows, "series": top, "flags": flags,
            "events": [{"date": i["start"].date().isoformat(), "start": i["start"].strftime("%H:%M"), "end": i["end"].strftime("%H:%M"),
                        "minutes": int((i["end"] - i["start"]).total_seconds() // 60), "title": i["summary"], "attendees": i["attendees"],
                        "recurring": i["recurring"]} for i in insts]}


# ---------------------------------------------------------------- output
def render(res, fmt, top=8):
    s = res["summary"]
    if fmt == "json":
        return json.dumps(res, indent=2, default=str)
    if fmt == "csv":
        out = io.StringIO(); w = csv.writer(out)
        w.writerow(["date", "start", "end", "minutes", "title", "attendees", "recurring"])
        for e in res["events"]:
            w.writerow([e["date"], e["start"], e["end"], e["minutes"], e["title"], e["attendees"], int(e["recurring"])])
        return out.getvalue().rstrip("\n")
    md = fmt == "md"
    L = ["## Meeting load %s to %s" % (s["from"], s["to"]) if md else "Meeting load %s to %s (%s)" % (s["from"], s["to"], s["calendar_tz"])]
    L.append("%d meetings, %.1f h of %.1f h working time = %.1f%% load; %d focus blocks (%.1f h); %.1f h fragmented; recurring %.1f%% of meeting time" % (
        s["meetings"], s["meeting_hours"], s["available_hours"], s["load_pct"], s["focus_blocks"], s["focus_hours"], s["fragmented_hours"], s["recurring_share_pct"]))
    sk = s["skipped"]
    L.append("Skipped: %d cancelled, %d declined, %d free/transparent, %d all-day%s" % (sk["cancelled"], sk["declined"], sk["free"], sk["all_day"],
             ("; days off: " + ", ".join(s["days_off"])) if s["days_off"] else ""))
    L.append("")
    if md:
        L += ["| Week | Meetings | Meeting h | Load | Focus blocks | Focus h | Fragmented h | B2B chains | Outside hours |", "|---|---|---|---|---|---|---|---|---|"]
        for w in res["weeks"]:
            L.append("| %s | %d | %.1f | %.1f%% | %d | %.1f | %.1f | %d | %d |" % (w["week"], w["meetings"], w["meeting_min"] / 60, w["load_pct"], w["focus_blocks"],
                     w["focus_min"] / 60, w["fragmented_min"] / 60, w["b2b_chains"], w["outside_hours"]))
        L += ["", "| Series | Recurring | People | h/week | Person-hours |" + (" Cost |" if res["series"] and res["series"][0]["cost"] is not None else ""),
              "|---|---|---|---|---|" + ("---|" if res["series"] and res["series"][0]["cost"] is not None else "")]
        for x in res["series"][:top]:
            L.append("| %s | %s | %d | %.2f | %.1f |%s" % (x["title"], "yes" if x["recurring"] else "no", x["attendees"], x["hours_per_week"], x["person_hours"],
                     (" %.0f |" % x["cost"]) if x["cost"] is not None else ""))
        L += ["", "| Code | Severity | Finding |", "|---|---|---|"] + ["| %s | %s | %s |" % (f["code"], f["severity"], f["message"]) for f in res["flags"]]
    else:
        L.append("By week          meetings  meet h   load   focus blocks  focus h  frag h  b2b  outside")
        for w in res["weeks"]:
            L.append("  %-14s %8d %7.1f %5.1f%% %13d %8.1f %7.1f %4d %8d" % (w["week"], w["meetings"], w["meeting_min"] / 60, w["load_pct"],
                     w["focus_blocks"], w["focus_min"] / 60, w["fragmented_min"] / 60, w["b2b_chains"], w["outside_hours"]))
        L += ["", "By day"]
        for r in res["days"]:
            if r["workday"] or r["meetings"]:
                L.append("  %s %s %2d meetings %5.1f h meetings, %d focus block(s)%s" % (r["date"], r["weekday"], r["meetings"], r["meeting_min"] / 60,
                         r["focus_blocks"], " (day off)" if r["day_off"] else ""))
        L += ["", "Top series by person-hours"]
        for x in res["series"][:top]:
            L.append("  %-34s %-9s %3d people %5.2f h/week %6.1f person-h%s" % (x["title"][:34], "recurring" if x["recurring"] else "one-off", x["attendees"],
                     x["hours_per_week"], x["person_hours"], ("  cost %.0f" % x["cost"]) if x["cost"] is not None else ""))
        L += ["", "Flags"] + (["  %s %-6s %s" % (f["code"], f["severity"], f["message"]) for f in res["flags"]] or ["  none"])
    return "\n".join(L)


# ---------------------------------------------------------------- self-test
def self_test():
    checks = []
    def ok(n, c): checks.append((n, bool(c)))
    ok("unfold", unfold("SUMMARY:Long\r\n  title\r\nX:1") == ["SUMMARY:Long title", "X:1"])
    ok("prop params", parse_prop('ATTENDEE;CN="Doe, Jane";PARTSTAT=DECLINED:mailto:j@x.io') == ("ATTENDEE", {"CN": "Doe, Jane", "PARTSTAT": "DECLINED"}, "mailto:j@x.io"))
    ok("duration", parse_duration("PT1H30M") == timedelta(minutes=90) and parse_duration("P1D") == timedelta(days=1))
    n = set(); utc = timezone.utc
    ok("dt utc", parse_dt("20261124T070000Z", {}, utc, n)[0].hour == 7)
    ist = get_zone("Europe/Istanbul", n)
    ok("dt tzid to utc", parse_dt("20261124T100000", {"TZID": "Europe/Istanbul"}, utc, n)[0].astimezone(utc).hour == 7)
    ok("windows tz name", get_zone("Turkey Standard Time", n) is not None)
    ok("all-day", parse_dt("20261127", {"VALUE": "DATE"}, utc, n)[1] is True)
    st = datetime(2026, 11, 23, 9, 30, tzinfo=ist)
    W0, W1 = datetime(2026, 11, 23, tzinfo=ist), datetime(2026, 12, 4, tzinfo=ist)
    daily = list(expand(st, parse_rrule("FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR"), W0, W1, n, "u"))
    ok("daily weekdays", len(daily) == 10 and all(d.weekday() < 5 for d in daily))
    ok("weekly interval 2", [d.day for d in expand(st, parse_rrule("FREQ=WEEKLY;INTERVAL=2;BYDAY=WE"), W0, W1 + timedelta(days=14), n, "u")] == [25, 9])
    ok("count", len(list(expand(st, parse_rrule("FREQ=DAILY;COUNT=3"), W0, W1, n, "u"))) == 3)
    ok("until", [d.day for d in expand(st, parse_rrule("FREQ=WEEKLY;UNTIL=20261201T000000Z"), W0, W1, n, "u")] == [23, 30])
    ok("monthly 1st thursday", [d.day for d in expand(datetime(2026, 11, 5, 16, 0, tzinfo=ist), parse_rrule("FREQ=MONTHLY;BYDAY=1TH"), W0, W1, n, "u")][:2] == [5, 3])
    ok("monthly last friday", [d.day for d in expand(datetime(2026, 11, 27, 16, 0, tzinfo=ist), parse_rrule("FREQ=MONTHLY;BYDAY=-1FR"), W0, W1 + timedelta(days=30), n, "u")] == [27, 25])
    n2 = set(); list(expand(st, parse_rrule("FREQ=YEARLY"), W0, W1, n2, "y"))
    ok("unsupported noted", any("unsupported" in x for x in n2))
    cal = "\n".join([
        "BEGIN:VCALENDAR", "X-WR-TIMEZONE:Europe/Istanbul",
        "BEGIN:VEVENT", "UID:standup", "SUMMARY:Standup", "DTSTART;TZID=Europe/Istanbul:20261123T093000", "DTEND;TZID=Europe/Istanbul:20261123T094500",
        "RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR", "EXDATE;TZID=Europe/Istanbul:20261125T093000", "ORGANIZER:mailto:me@x.io",
        "ATTENDEE;PARTSTAT=ACCEPTED:mailto:me@x.io"] + ["ATTENDEE;PARTSTAT=ACCEPTED:mailto:p%d@x.io" % i for i in range(8)] + ["END:VEVENT",
        "BEGIN:VEVENT", "UID:standup", "RECURRENCE-ID;TZID=Europe/Istanbul:20261126T093000", "SUMMARY:Standup", "STATUS:CANCELLED",
        "DTSTART;TZID=Europe/Istanbul:20261126T093000", "DTEND;TZID=Europe/Istanbul:20261126T094500", "END:VEVENT",
        "BEGIN:VEVENT", "UID:a", "SUMMARY:Planning", "DTSTART:20261123T070000Z", "DTEND:20261123T090000Z", "END:VEVENT",
        "BEGIN:VEVENT", "UID:b", "SUMMARY:Review", "DTSTART;TZID=Europe/Istanbul:20261123T110000", "DURATION:PT1H", "END:VEVENT",
        "BEGIN:VEVENT", "UID:c", "SUMMARY:Sync", "DTSTART;TZID=Europe/Istanbul:20261123T113000", "DTEND;TZID=Europe/Istanbul:20261123T123000", "END:VEVENT",
        "BEGIN:VEVENT", "UID:d", "SUMMARY:Lunch talk", "DTSTART;TZID=Europe/Istanbul:20261123T123000", "DTEND;TZID=Europe/Istanbul:20261123T140000", "END:VEVENT",
        "BEGIN:VEVENT", "UID:e", "SUMMARY:US call", "DTSTART;TZID=Europe/Istanbul:20261124T190000", "DTEND;TZID=Europe/Istanbul:20261124T200000", "END:VEVENT",
        "BEGIN:VEVENT", "UID:f", "SUMMARY:Declined thing", "DTSTART;TZID=Europe/Istanbul:20261124T100000", "DTEND;TZID=Europe/Istanbul:20261124T110000",
        "ATTENDEE;PARTSTAT=DECLINED:mailto:me@x.io", "END:VEVENT",
        "BEGIN:VEVENT", "UID:g", "SUMMARY:Focus", "TRANSP:TRANSPARENT", "DTSTART;TZID=Europe/Istanbul:20261124T140000", "DTEND;TZID=Europe/Istanbul:20261124T160000", "END:VEVENT",
        "BEGIN:VEVENT", "UID:h", "SUMMARY:Out of office", "DTSTART;VALUE=DATE:20261127", "DTEND;VALUE=DATE:20261128", "END:VEVENT",
        "BEGIN:VEVENT", "UID:z", "SUMMARY:End marker", "DTSTART;TZID=Europe/Istanbul:20261127T100000", "DTEND;TZID=Europe/Istanbul:20261127T101500", "END:VEVENT",
        "END:VCALENDAR"])
    r = analyze(cal, me="me@x.io")
    sm = r["summary"]; codes = {f["code"] for f in r["flags"]}
    by = {d["date"]: d for d in r["days"]}
    ok("standup exdate + cancelled override", sum(1 for e in r["events"] if e["title"] == "Standup") == 3)
    ok("skipped counts", sm["skipped"]["declined"] == 1 and sm["skipped"]["free"] == 1 and sm["skipped"]["cancelled"] == 1 and sm["skipped"]["all_day"] == 1)
    ok("utc converted", any(e["title"] == "Planning" and e["start"] == "10:00" for e in r["events"]))
    ok("double booking (3 overlapping pairs)", "M04" in codes and sm["double_bookings"] == 3)
    ok("merged meeting minutes (overlaps counted once)", by["2026-11-23"]["meeting_min"] == 15 + 240)
    ok("b2b chain", by["2026-11-23"]["b2b_chains"] == 1 and "M03" in codes)
    ok("no lunch", "M09" in codes)
    ok("outside hours + day off", sm["outside_hours_meetings"] == 3 and any(f["code"] == "M05" and "day off" in f["message"] for f in r["flags"]))
    ok("day off", "2026-11-27" in sm["days_off"] and by["2026-11-27"]["workday"] is False)
    ok("large recurring", "M06" in codes)
    ok("no agenda organizer", "M07" not in codes)  # standup is 15 min
    ok("focus block monday afternoon", by["2026-11-23"]["focus_blocks"] == 1 and by["2026-11-23"]["focus_min"] == 240)
    ok("window from events", sm["from"] == "2026-11-23" and sm["to"] == "2026-11-27")
    ok("csv", render(r, "csv").splitlines()[0].startswith("date,start,end"))
    ok("md", "| Week |" in render(r, "md"))
    try:
        analyze("hello"); ok("no events error", False)
    except ValueError:
        ok("no events error", True)
    bad = [x for x, c in checks if not c]
    if bad:
        print("self-test FAILED: " + ", ".join(bad)); return 1
    print("self-test OK: %d checks" % len(checks)); return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description="Meeting load and focus time from an .ics calendar export.")
    ap.add_argument("calendar", nargs="?")
    ap.add_argument("--me", help="your email address, to drop meetings you declined and find the ones you organize")
    ap.add_argument("--tz", help="analysis time zone (default: X-WR-TIMEZONE of the file, else UTC)")
    ap.add_argument("--since"); ap.add_argument("--until")
    ap.add_argument("--workday", default="09:00-18:00"); ap.add_argument("--workdays", default="mon-fri")
    ap.add_argument("--focus-min", type=int, default=120, help="minimum free minutes that count as a focus block")
    ap.add_argument("--max-load", type=float, default=40.0, help="weekly meeting share of working time that raises M01")
    ap.add_argument("--min-focus-blocks", type=int, default=3)
    ap.add_argument("--large", type=int, default=8, help="attendees that make a recurring meeting large (M06)")
    ap.add_argument("--hourly-cost", type=float, default=0.0, help="average loaded cost per person-hour, for cost estimates")
    ap.add_argument("--lunch", default="11:30-14:00")
    ap.add_argument("--top", type=int, default=8)
    ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
    ap.add_argument("--fail-on", choices=["none", "info", "low", "medium", "high"], default="none")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.calendar:
        ap.error("CALENDAR.ics is required")
    try:
        text = open(a.calendar, encoding="utf-8-sig").read()
        res = analyze(text, a.me, a.tz, a.since, a.until, a.workday, a.workdays, a.focus_min, a.max_load,
                      a.min_focus_blocks, a.large, a.hourly_cost, a.lunch)
    except (OSError, ValueError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    print(render(res, a.format, a.top))
    if a.fail_on != "none" and any(SEV[f["severity"]] >= SEV[a.fail_on] for f in res["flags"]):
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
ReportData AnalysisLeadership+4
F@f
0
Python Unused and Missing Dependency Finder
Skill

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

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

# Python Unused and Missing Dependency Finder

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

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

## Files in this skill

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

## Workflow

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

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

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

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

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

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

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

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

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

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

## Common mismatches

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[tool.ruff]
line-length = 100

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

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

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

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

from shopapp import reports

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


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


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


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


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

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

import csv
import os
from typing import TYPE_CHECKING

from openpyxl import Workbook

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

if TYPE_CHECKING:
    from mypy_boto3_s3 import S3Client


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


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

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

from shopapp.api import app

fake = Faker()
client = TestClient(app)


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


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

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

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

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

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

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


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


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


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


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


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


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


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


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

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

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

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

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

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

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

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


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


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


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


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


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


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


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

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

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

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


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


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


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


if __name__ == "__main__":
    sys.exit(main())
QualityDeveloperCleanup+4
F@f
0
TrendingVideo
The Golden Star Run: 30-Second Christmas Market Chain Reaction (Seedance Prompt)

A timestamped 10-shot, 30-second Seedance storyboard: one continuous tracking shot follows a glowing golden star ornament through a snowy Alpine Christmas market, past a tuba, a carousel, an ice rink and gingerbread houses, until a woman catches it without looking up. Uses a reference image for the woman.

Use the uploaded reference image for the woman. Keep her exactly as she appears in the reference image: same face, hair, outfit, body and proportions in every shot she appears in, with no changes at any point.

Cinematic, photorealistic comedy-adventure short film, 16:9, 30 seconds, 24fps, shot on a full-frame cinema camera with anamorphic lenses, warm string-light glow against deep blue winter dusk, falling light snow, natural film grain, realistic motion blur and physics. After the first shot, the whole video is one fast, smooth, continuous tracking shot with no cuts that follows a single hand-sized, glowing golden star ornament with a long trail of golden sparkles as it flies through a chain of surprising mini-scenes. The golden star is large, bright and clearly visible in the center of the frame in every shot, glowing and slowly spinning, never hidden and never out of frame. No on-screen text or logos. Fun, magical, satisfying tone.

Setting: a snowy Alpine village Christmas market at dusk, with wooden stalls, strings of warm lights, a clock tower, cobblestone lanes covered in light snow, an outdoor ice rink, a carousel, a brass band and a cozy outdoor cafe at the end of the lane.

Shot 1 (0–3s): Low, slow drift down a snowy cobblestone lane under glowing string lights, a clock tower in the distance, snowflakes in the air. A little boy in a woolly hat and red scarf stands at a toy stall with a wooden spoon as a catapult, grins, and flicks the glowing golden star into the air.

Shot 2 (3–6s): The star flies through the stall and bounces off the bell of a giant brass tuba played by a bearded man. The tuba blasts a huge "BWAAH" that shakes a pile of snow off a roof. The man's cheeks puff up and his eyes widen.

Shot 3 (6–9s): The star spins through the center ring of a carousel, between two painted horses. A little girl riding one of them looks around with her mouth open as it passes.

Shot 4 (9–12s): The star sails over the ice rink, passing between the arms of a skater who does a perfect spin. Ice crystals spray into the lights in slow motion.

Shot 5 (12–15s): The star taps a hanging glass bauble, setting off a row of baubles that chime like bells one after another across the market, while a plump reindeer in a harness turns its head and sniffs the air.

Shot 6 (15–18s): The star zips past a hot-chocolate stall where a man pours cocoa into a mug. The steam swirls around it and a mountain of whipped cream tips and lands on a woman's red hat. She looks up, shocked, then laughs.

Shot 7 (18–21s): The star flies over a long table of gingerbread houses and knocks a tiny gingerbread man into the air. He tumbles and lands feet-first on the roof of a gingerbread house, as if it was planned.

Shot 8 (21–24s): The star flies through a wooden archway of golden fairy lights, and a cat sitting on a wall turns its head to follow it with wide, curious eyes. A tourist in a big knitted hat looks up with a thumbs-up.

Shot 9 (24–27s): The star enters a quiet, narrow snowy alley lined with wooden walls, its trail of golden sparkles drifting down like fireflies behind it.

Shot 10 (27–30s): The alley opens onto a cozy outdoor cafe terrace with warm lights. The woman sits at a wooden table, sipping a drink and looking at her phone. Without looking up, she raises her free hand and catches the glowing golden star in mid-air, then lays it down on the table, still glowing softly. She smiles to herself and says in English: "Bullseye."

Audio: The woman speaks only in clear English, in a young, calm, natural female voice, with only the final line "Bullseye." No other dialogue. Only sounds that match what is visible: a soft whoosh and a bright sparkle sound as the star flies, wooden clicks, a loud tuba blast, carousel music, skates scraping on ice, glass bauble chimes, a reindeer's huff, laughter and chatter in the market, a soft snow hush, and a satisfying "tink" when she catches the star.
StoryboardVideo GenerationSeedance+3
F@f
1
Premium Beverage Advertising Poster: Custom Brand Lifestyle Campaign (JSON Template)
TrendingImage
Premium Beverage Advertising Poster: Custom Brand Lifestyle Campaign (JSON Template)

A fill-in JSON template for photorealistic, art-directed drink campaign posters: enter your brand, tagline, product, flavor, ingredients, setting and pose to get a lifestyle hero shot with a custom logo, big headline, benefit cards and a condensation-covered hero cup.

{
  "task": "Create a premium, photorealistic commercial beverage advertising poster using the user's custom inputs.",

  "format": {
    "aspect_ratio": "3:4",
    "orientation": "Vertical",
    "quality": "Ultra high resolution",
    "visual_style": "Luxury beverage campaign, cinematic lifestyle photography, premium editorial art direction"
  },

  "user_defined_inputs": {
    "brand_name": "[ENTER BRAND NAME]",
    "brand_tagline": "[ENTER BRAND TAGLINE OR GENERATE ONE]",
    "main_subject": "[UPLOAD IMAGE OR DESCRIBE SUBJECT]",
    "subject_gender": "[USER DEFINED]",
    "subject_outfit": "[USER DEFINED OR AI GENERATED]",
    "subject_pose": "[DESCRIBE EXACT POSE OR GENERATE A CREATIVE NEW POSE]",
    "product_name": "[ENTER BEVERAGE NAME]",
    "product_flavor": "[ENTER FLAVOR]",
    "fruits_or_ingredients": "[ENTER FRUITS OR INGREDIENTS]",
    "environment": "[ENTER SETTING OR LET AI CHOOSE]",
    "headline": "[ENTER HEADLINE OR GENERATE ONE]",
    "color_palette": "[OPTIONAL COLOR PREFERENCE]"
  },

  "creative_direction": {
    "concept": "Create an eye-catching premium beverage campaign with a distinctive lifestyle photography aesthetic.",
    "composition": "Build a sophisticated advertising layout combining a prominent human subject, hero beverage product, oversized typography, and carefully arranged ingredient elements.",
    "brand_identity": "Create a distinctive visual identity around the user-provided brand name. Design a minimal botanical or custom brand logo and use it consistently on the poster and beverage packaging.",
    "art_direction": "Professional international beverage advertising campaign with sophisticated typography, realistic product styling, premium photography, and carefully balanced graphic elements."
  },

  "subject_direction": {
    "identity": "Use the uploaded reference image when provided. Preserve recognizable facial characteristics and natural appearance.",
    "pose": "Follow the user-defined pose precisely. If no pose is specified, invent a completely different, natural, editorial pose.",
    "pose_variations": [
      "Standing confidently while holding the drink",
      "Walking naturally through an outdoor location",
      "Sitting casually on a modern café chair",
      "Leaning against a balcony or architectural structure",
      "Taking a sip while looking away from camera",
      "Holding the beverage towards the camera",
      "Relaxed over-the-shoulder pose",
      "Seated on outdoor steps with the product",
      "Dynamic mid-stride lifestyle pose",
      "Looking directly into the camera with the drink at waist level"
    ],
    "expression": "Natural, confident, relaxed, editorial expression.",
    "styling": "Contemporary premium fashion styling appropriate to the environment and beverage campaign."
  },

  "product_presentation": {
    "hero_product": "A beautifully designed transparent cup or glass filled with the specified beverage.",
    "packaging": "Print the exact user-defined brand name clearly on the cup.",
    "details": [
      "Realistic condensation droplets",
      "Visible ice cubes",
      "Natural beverage color",
      "Fresh ingredient garnish",
      "Realistic liquid transparency",
      "Premium commercial product photography",
      "Accurate hand and cup proportions"
    ],
    "placement": "Make the beverage a prominent visual focal point without obscuring the subject."
  },

  "ingredients_and_environment": {
    "ingredients": "Use only the user-specified fruits, herbs, or ingredients. Arrange them naturally around the beverage.",
    "environment": "Build a visually rich setting based on the user-defined location.",
    "details": "Add realistic environmental elements, natural foliage, atmospheric depth, subtle reflections, and complementary decorative elements.",
    "creativity": "Avoid repeating the same fruit arrangement, background, or decorative composition across generations."
  },

  "poster_layout": {
    "top_section": "Custom brand logo and brand tagline.",
    "headline_section": "Large, expressive headline with sophisticated typography.",
    "product_section": "New product badge, product name, flavor description, and ingredient information.",
    "benefit_section": "Four or five compact benefit cards with elegant minimal icons.",
    "hero_section": "Large lifestyle photograph featuring the subject and beverage.",
    "background_typography": "Oversized brand lettering integrated subtly into the background.",
    "footer": "Minimal branding and supporting product information.",
    "qr_code": "Do not include QR codes, barcodes, or fake scannable graphics."
  },

  "typography": {
    "headline": "Bold editorial serif or expressive handwritten typography.",
    "product_name": "Strong uppercase modern sans-serif.",
    "brand_name": "Distinctive premium logo typography.",
    "supporting_text": "Clean, readable, professionally aligned typography.",
    "accuracy": "Preserve exact user-provided brand and product names. Avoid random characters and unnecessary text."
  },

  "photography": {
    "style": "Photorealistic luxury commercial photography.",
    "lens": "35mm or 50mm editorial photography look.",
    "lighting": "Natural sunlight, soft cinematic highlights, realistic shadows.",
    "skin": "Natural skin texture, realistic complexion, no plastic skin or excessive retouching.",
    "depth": "Beautifully controlled depth of field with realistic background separation.",
    "color_grading": "Premium natural color grading with balanced highlights and shadows."
  },

  "negative_prompt": [
    "Repeated pose from previous generations",
    "Generic stock photography",
    "Plastic-looking skin",
    "Overprocessed faces",
    "Distorted hands",
    "Extra fingers",
    "Incorrect brand spelling",
    "Random typography",
    "Fake QR codes",
    "Unrequested fruits or ingredients",
    "Floating objects without realistic interaction",
    "Poor product proportions",
    "Flat lighting",
    "Cluttered composition",
    "Watermarks",
    "Unnecessary decorative graphics",
    "Low resolution"
  ],

  "final_instruction": "Generate a complete, professionally art-directed beverage advertising poster. Treat every user-defined field as an important creative constraint. Invent complementary design details intelligently. Prioritize a genuinely different pose, subject placement, camera angle, environment, and composition whenever a new variation is requested. Do not simply recolor or rearrange an existing poster. Maintain premium commercial realism, sophisticated branding, and excellent visual hierarchy."
}
JSONImage GenerationBranding+4
F@f
0
Elixir OTP taste
Taste

Opinionated Elixir OTP preferences: supervision trees designed on purpose, GenServers only for state, Task.Supervisor for async work, Registry for naming, telemetry and let-it-crash without silent failures.

# Elixir OTP taste of a backend developer who trusts supervisors more than try/rescue
- Design the supervision tree on paper first and choose one_for_one, rest_for_one or one_for_all deliberately for each supervisor. Confidence: 0.85
- Use a GenServer only when you need state, serialization or a lifecycle; plain modules and functions are the default. Confidence: 0.90
- Never put a single GenServer on the hot path for every request; it becomes a bottleneck, so shard with a pool or use ETS for reads. Confidence: 0.90
- Keep handle_call fast; move slow work to a Task and reply later with GenServer.reply when needed. Confidence: 0.80
- Start fire-and-forget or parallel work under a Task.Supervisor, never with bare spawn. Confidence: 0.95
- Use Task.async_stream with max_concurrency and timeout for bounded parallel work over collections. Confidence: 0.85
- Name dynamic processes through Registry and start them with DynamicSupervisor instead of building atoms from user input. Confidence: 0.95
- Let it crash for unexpected errors, but return {:ok, _} and {:error, _} tuples for expected failures the caller can handle. Confidence: 0.90
- Use with blocks for happy-path pipelines over tagged tuples instead of nested case statements. Confidence: 0.80
- Set explicit max_restarts and max_seconds when the defaults would hide a crash loop or take down the whole app too eagerly. Confidence: 0.65
- Avoid storing large binaries or long-lived lists in process state; watch mailbox length and memory per process. Confidence: 0.80
- Use ETS (or persistent_term for rarely changing config) for shared read-heavy data instead of a GenServer that answers lookups. Confidence: 0.80
- Put configuration that depends on the environment in config/runtime.exs and read it at startup, not with compile-time Application.get_env in module attributes. Confidence: 0.90
- Emit :telemetry events for important operations and attach handlers for metrics and logs instead of logging inside every function. Confidence: 0.80
- Use Oban (or another persistent queue) for jobs that must survive restarts; in-memory processes are not a job queue. Confidence: 0.85
- Write tests with start_supervised! so processes are cleaned up between tests, and use async: true whenever state is not global. Confidence: 0.85
- Run Credo and Dialyzer (or the built-in type checker) in CI and keep typespecs on public functions. Confidence: 0.70
- Use mix release for deployment and connect nodes with libcluster only when you truly need distribution. Confidence: 0.75
- Prefer Phoenix.PubSub over hand-rolled process messaging for broadcasting across nodes. Confidence: 0.75
- Use Logger metadata like request_id and user_id rather than string-concatenating context into messages. Confidence: 0.80
Best PracticesPerformanceArchitecture+1
F@f
0
Test Fixtures and Seed Data taste
Taste

Opinionated test fixtures and seed data preferences: factories over giant fixture files, per-test isolation, deterministic data, a real database in tests and separate dev seeds that never touch production.

# Test Fixtures and Seed Data taste of a backend developer who wants tests that never flake
- Use small factory functions with sensible defaults and per-test overrides instead of one huge shared fixture file. Confidence: 0.90
- Each test creates exactly the data it asserts on; never depend on rows another test or a global seed happened to insert. Confidence: 0.95
- Isolate tests with a transaction rolled back after each test, or truncate tables between tests when transactions are not possible. Confidence: 0.85
- Run integration tests against the same database engine as production in a container, not an in-memory substitute with different behavior. Confidence: 0.90
- Apply real migrations to the test database at the start of the run instead of a hand-maintained schema dump. Confidence: 0.85
- Make generated data deterministic: seed the fake-data library and freeze the clock so failures reproduce exactly. Confidence: 0.90
- Generate unique values (emails, slugs) with a sequence or random suffix so parallel tests never collide on unique constraints. Confidence: 0.85
- Keep factories next to the domain model and build valid objects by default; tests should opt in to invalid states explicitly. Confidence: 0.80
- Prefer building objects in memory for unit tests and persisting only in tests that actually need the database. Confidence: 0.80
- Name fixtures by intent, like paidCustomer or expiredSubscription, not user1 and user2. Confidence: 0.75
- Keep golden files and JSON fixtures small, reviewed and regenerated by a script, never edited by hand into drift. Confidence: 0.70
- Keep development seed data separate from test data; seeds exist to make the app usable locally, not to make tests pass. Confidence: 0.85
- Make seed scripts idempotent with upserts so running them twice is safe. Confidence: 0.90
- Guard seed and reset scripts so they refuse to run when the database URL points at production. Confidence: 1.00
- Never copy raw production data into dev or test; use synthetic data or an anonymized, masked snapshot. Confidence: 0.95
- Seed one realistic account per main role (admin, member, viewer) with documented local credentials. Confidence: 0.75
- Include awkward data in seeds: long names, Unicode, empty lists and many rows, so UI and pagination bugs show up early. Confidence: 0.75
- Stub external HTTP calls at the network boundary with recorded responses, and refresh recordings on a schedule. Confidence: 0.80
- Fail the test run on leaked data: assert tables are empty after the suite when using truncate isolation. Confidence: 0.60
- Keep the full integration suite under a few minutes in CI by parallelizing across database schemas or containers. Confidence: 0.70
Best PracticesDatabaseBackend+2
F@f
0
Image Optimization taste
Taste

Opinionated web image optimization preferences: modern formats with fallbacks, responsive srcset, explicit dimensions, lazy loading below the fold, an image CDN and LCP-first priorities.

# Image Optimization taste of a frontend engineer who watches the LCP number
- Serve AVIF first with WebP as the fallback through <picture> or content negotiation, and keep JPEG/PNG only as the last resort. Confidence: 0.85
- Use an image CDN or framework image component that resizes, converts and caches on the fly instead of committing many hand-exported sizes. Confidence: 0.85
- Always set width and height (or aspect-ratio) on every image so the browser reserves space and layout shift stays near zero. Confidence: 1.00
- Use srcset with width descriptors plus an honest sizes attribute; a wrong sizes value silently downloads images twice as large as needed. Confidence: 0.90
- Add loading="lazy" to images below the fold, and never to the hero or LCP image. Confidence: 0.95
- Give the LCP image fetchpriority="high" and preload it when it is set from CSS or discovered late. Confidence: 0.85
- Add decoding="async" to non-critical images so decoding does not block the main thread. Confidence: 0.70
- Cap generated widths at around 2x the largest rendered size; 4000px originals never need to reach a phone. Confidence: 0.85
- Pick quality per format instead of one global value: roughly 50-60 for AVIF, 70-80 for WebP and JPEG, and check visually on real photos. Confidence: 0.75
- Use SVG for icons, logos and simple illustrations, run it through SVGO, and inline only the few icons needed above the fold. Confidence: 0.85
- Never use images for text, buttons or UI chrome that CSS can draw. Confidence: 0.80
- Strip EXIF and GPS metadata from user uploads before serving them, for both privacy and bytes. Confidence: 0.95
- Process user uploads asynchronously into fixed variants and serve originals only to their owner. Confidence: 0.80
- Cache optimized images with long immutable max-age and content-hashed URLs instead of purging caches by hand. Confidence: 0.90
- Use a tiny blurred placeholder or dominant-color background for large images, not a spinner. Confidence: 0.70
- Prefer CSS object-fit and object-position over cropping the same photo into many art-directed files, unless the crop really changes the subject. Confidence: 0.70
- Replace animated GIFs with muted, looping, autoplaying MP4 or WebM video. Confidence: 0.90
- Write meaningful alt text for content images and empty alt="" for decorative ones; never leave alt off. Confidence: 1.00
- Set an image budget per page (for example under 500 KB on mobile for the initial view) and fail CI when Lighthouse or a bundle check goes over it. Confidence: 0.70
- Measure with field data (CrUX or RUM LCP) rather than only a lab run on a fast laptop. Confidence: 0.80
- Do not lazy load images inside carousels with JavaScript tricks when native lazy loading already works. Confidence: 0.65
Best PracticesPerformanceOptimization+2
F@f
0
Toy Train Circling a Snowy Miniature Village Under a Christmas Tree
1
Image
Toy Train Circling a Snowy Miniature Village Under a Christmas Tree

Photoreal cozy evening under a decorated Christmas tree: a vintage-style toy steam train with red, green and cream carriages runs on an oval track around a miniature snowy ceramic village with glowing windows, lit by warm fairy lights. Step 1 of the Holiday Toy Train workflow.

A photorealistic, warm evening photograph of a toy steam train running around a miniature snowy village on the floor under a decorated Christmas tree in a cozy living room. A small vintage-style toy train, a glossy black locomotive with red wheels and brass details pulling three carriages in red, green and cream, runs on an oval of silver track laid on a fluffy white felt "snow" blanket. The locomotive is in the front-right part of the oval, coming slightly toward the viewer.

Inside the oval sits a tiny village of ceramic houses with snow-covered roofs and warm glowing windows, a little church with a steeple, bottle-brush pine trees dusted with white, and a small frozen pond made from a round mirror. Above, the lower branches of a real fir tree hang into the frame, decorated with glass baubles in red, gold and deep green and strings of small warm-white fairy lights. A few wrapped presents in plain kraft paper with red and green ribbons stand at the edge of the felt. In the soft background: a wooden floor, part of a knitted armchair and a window showing a dark blue evening.

Warm light from the fairy lights and the village windows against cool blue window light; soft bokeh highlights in the tree. 35 mm lens at low height just above the floor, the train and the village tack-sharp, the tree branches slightly soft. Cozy, nostalgic family-holiday mood, natural colors.

No people, no hands, no animals or pets, no smoke or steam, no screens, no readable text, numbers, labels or logos on the train, houses or presents. Landscape 16:9.
WorkflowVintageCinematic+4
F@f
0
Botanical Watercolor Plate of Winter Citrus Fruits and Blossoms
Image
Botanical Watercolor Plate of Winter Citrus Fruits and Blossoms

A vintage-style botanical watercolor plate of winter citrus on textured paper: a blood orange whole and halved, a lemon with white blossoms and a translucent wheel, a cut pomelo and a kumquat branch, in layered transparent washes with soft shadows and a thin sepia border.

A vintage-style botanical watercolor plate of winter citrus, painted with the precision of a 19th-century scientific illustration on warm off-white cold-press watercolor paper. The page is arranged in a balanced grid with generous white space between the subjects.

Top row: a whole blood orange with a deep red-orange blush on its dimpled rind and two glossy dark green leaves on a short woody stem; next to it the same fruit cut in half, showing ruby and crimson segments with lighter streaks and a pale pith ring. Middle row: a whole bright lemon with a pointed tip and a leafy twig with three small white star-shaped blossoms and pink-tinged buds; a thin lemon wheel seen straight on, translucent pale yellow segments radiating like a wheel. Bottom row: a large pale green-yellow pomelo, cut open to show thick white pith and pale pink flesh; and a small branch of kumquats, four tiny oval orange fruits among narrow leaves, one cut lengthwise to show its seeds.

Painting style: fine graphite underdrawing faintly visible in places, layered transparent washes, crisp edges on the leaves, soft wet-in-wet blooms on the rinds, tiny white highlights left as bare paper on the glossy skins, delicate veins on the leaves, and soft gray-violet shadows under each fruit. A thin hand-ruled sepia border frames the page, and the paper shows a gentle texture and slight age-toned edges.

Fresh, bright, calm and scholarly mood with clean natural colors: oranges, lemon yellow, ruby red, pale pink and deep leaf greens. No people, no hands, no labels, no numbers, no captions, no readable text, letters, signatures or logos. Portrait 3:4.
CreativeReferenceVintage+3
F@f
0
Wooden Honeycomb Frame Dripping Golden Honey into a Glass Jar in Morning Light
Image
Wooden Honeycomb Frame Dripping Golden Honey into a Glass Jar in Morning Light

Photoreal macro of a freshly uncapped wooden honeycomb frame on a rustic table: glowing amber cells, a slow ribbon of honey folding into a glass jar, a honey dipper, wax cappings and an uncapping fork, backlit by soft morning sun in a farmhouse kitchen.

A photorealistic close-up photograph of a freshly harvested wooden honeycomb frame on a rustic farmhouse table in early morning light. The frame stands upright, slightly angled toward the viewer, its pale pine edges worn and sticky. Most of the comb is still sealed with smooth ivory-white wax caps; the lower third has been freshly uncapped, revealing hundreds of perfect hexagonal cells brimming with glossy amber honey. A thick, slow ribbon of honey runs from the bottom edge of the comb and folds into a small round glass jar below, which is already half full and glowing like liquid gold.

Around it on the weathered oak table: a wooden honey dipper resting in a shallow ceramic dish, a few broken pieces of honeycomb on a linen cloth, a stainless steel uncapping fork with a wooden handle, a small pile of pale wax cappings, and a sprig of dried lavender. A few drops of honey have fallen on the wood and catch the light.

Soft, low morning sunlight from behind and to the left shines through the honey and the thin wax, so the cells glow warm amber and gold and the edges of the comb are rim-lit; the background falls away into a soft, blurred farmhouse kitchen with a window and a hint of green garden outside. 100 mm macro lens, f/4, eye level with the honey ribbon, the uncapped cells and the honey stream tack-sharp, gentle depth of falloff toward the back.

Warm, fresh, natural harvest mood with rich honey tones and natural colors. No bees, no people, no hands, no faces, no readable text, labels or logos. Landscape 4:3.
Food PhotographyMacroRealism+3
F@f
0
Third-Party API Outage Response Plan (JSON)
Text

Prepare for the day a payment, email, auth or AI API you depend on goes down: a dependency map, detection rules, graceful degradation per flow, safeguards with concrete settings, a first-60-minutes timeline, honest customer messages, recovery and reconciliation, in JSON.

1{
2 "role": "You are a calm, practical site reliability engineer who has handled many outages caused by services a team does not control: payment providers, email and SMS gateways, authentication providers, cloud APIs, maps, search and AI model APIs. You help a development team prepare a response plan for when one critical third-party API is down, slow or returning errors, so that the product degrades gracefully, customers are told the truth, no data or money is lost, and the team recovers cleanly when the provider comes back. You are honest about what the team can and cannot control.",
3 "context": {
4 "product_and_stack": "${product:a B2B SaaS invoicing app with about 3,000 paying companies; Node.js API, PostgreSQL, a job queue, React front end, hosted on one cloud provider}",
5 "dependency": "${dependency:the payment provider API used for card payments, saved cards, subscription renewals and payout webhooks}",
6 "how_we_use_it": "${usage:synchronous calls at checkout, nightly renewal batch, incoming webhooks for payment status, a daily payout report}",
7 "past_incidents": "${history:two provider incidents last year: 40 minutes of 500 errors at checkout, and 6 hours of delayed webhooks that caused duplicate payment-reminder emails}",
8 "current_safeguards": "${safeguards:5-second timeout, 3 retries without backoff, no circuit breaker, provider status page checked by hand, no idempotency keys on renewals}",
9 "monitoring": "${monitoring:API error-rate and latency dashboards, an on-call rotation of 4 engineers, alerts in chat}",
10 "contract_and_support": "${support:standard plan, support by ticket only, published SLA of 99.95% monthly uptime with service credits}",
...+113 more lines
JSONMonitoringSRE+4
F@f
0
Act as a Rescue Dog Decompression Coach
Text

Help an adopted adult rescue dog settle in: home prep, an hour-by-hour arrival day, the first 3 days of decompression, a 3-week routine with alone-time practice, a step-by-step cat introduction, child safety rules, red flags and a one-page fridge sheet.

Act as a Rescue Dog Decompression Coach. You are a calm, experienced shelter volunteer and certified dog trainer who has helped hundreds of families through the first weeks with an adopted adult dog. You know that a rescue dog arriving in a new home is often stressed, tired and confused, and that what looks like "bad behavior" in the first days is usually fear, overload or a dog who simply does not know the rules yet. You use only kind, reward-based methods and you are honest about when a problem needs a vet or a qualified behavior professional. I want my new dog to feel safe with us, and I want our family to stay patient and realistic.

About my dog and home:
- The dog: Mira, a 3-year-old mixed-breed female, about 18 kg, spent 5 months in a shelter after being found as a stray
- What the shelter told us: friendly with adults, unsure around men with hats, walks well on a harness, unknown history with cats and children, house-trained at the foster home
- Arrival date: she comes home this Saturday
- Our home: 2-bedroom apartment on the 3rd floor with a small balcony, no garden, park 10 minutes away, busy street outside
- Who lives here: two adults, a 9-year-old son, and an older indoor cat
- Our daily schedule: both adults work, one from home 3 days a week; the son is at school until 15:30
- What we already have: crate, bed, harness, 2 leashes, bowls, the same food as the shelter, a few chew toys
- What worries us most: the first meeting with the cat, being left alone on office days, pulling or barking at other dogs on the street

Help me in this order:

1. Quick questions. Ask up to 4 short questions that would most change your advice (for example how the dog behaved in the car, whether the cat has a dog-free floor or room, or if anyone in the family is nervous around dogs). If I say "skip", continue with sensible assumptions and list them.

2. Before she arrives. A short checklist to prepare the home: a quiet "safe zone" away from the front door and the busy street, what to put in it, baby gates or closed doors for the cat, things to put away (shoes, cables, food on counters, the cat's litter box out of reach), ID tag and microchip details, and the vet and emergency vet numbers on the fridge.

3. Day 1. An hour-by-hour plan for arrival day: the car ride, a quiet toilet stop before going in, entering on a leash, showing her water and the safe zone, letting her sniff and hide if she wants, no visitors, no bath, no pet-shop trips, and how the 9-year-old can say hello without hugging or following her.

4. The first 3 days. What decompression means in practice: low stimulation, short calm walks on quiet routes at quiet times, lots of sleep, sniffing games, hand feeding a few pieces of food, and simply sitting nearby without demanding attention. What is normal (not eating much, sleeping a lot, hiding, accidents, being very clingy or very distant) and what is not normal and needs a vet call.

5. The first 3 weeks. A simple weekly plan for building routine and trust: fixed times for meals, walks and rest; the first short alone-time practice (starting with seconds and minutes, never a full workday at once); house-training refresh; introducing the harness and leash habits; and 3 tiny skills to teach with treats (name response, "touch" and settling on a mat).

6. Cat introduction. A step-by-step plan over several days or weeks: scent swapping, eating on opposite sides of a closed door, seeing each other through a gate with the dog on a leash, short supervised meetings, and the exact body-language signs that mean go slower or stop. Make it clear the cat always has an escape route and a dog-free space.

7. Child safety rules. Five clear house rules for my son, explained so a 9-year-old understands them (for example: let her come to you, no hugging, leave her alone when she is eating, sleeping or in her safe zone), plus one fun, safe job he can do with her.

8. The first 3 months. What usually changes as she settles, why some new behaviors (barking at sounds, reacting to dogs, testing furniture rules) may appear after a few weeks, and how to respond calmly.

9. Red flags. List the signs that mean we should call a vet (pain, not eating for more than a day or two, vomiting or diarrhea that does not stop, limping) and the signs that mean we need a qualified behavior professional (growling or snapping that gets worse, panic when left alone, freezing or stiffening around the child or the cat). Tell us what NOT to do in those moments: no punishment, no forcing, no "letting them sort it out".

Rules:
- Use only kind, reward-based methods; never suggest shock, prong or choke collars, alpha rolls, shouting or punishment.
- Keep everything specific to my dog, home, family and schedule; no generic dog facts.
- Do not diagnose medical or behavior problems; when in doubt, say who to call.
- Be realistic: tell me that progress is not a straight line and that some dogs need more than 3 months.
- Use short, friendly sentences we can read aloud as a family.
- End with a one-page fridge sheet: the daily routine for week 1, the 5 child rules, the cat introduction stages with "go slower" signs, and the red flags with who to call.
BeginnerTrainingChecklist+4
F@f
0
Support Ticket SLA Breach Analyzer
Skill

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

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

# Support Ticket SLA Breach Analyzer

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

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

## Files in this skill

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

## Workflow

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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


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


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

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

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

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


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


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


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


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


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


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


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


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

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

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


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


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


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


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


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


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


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


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


def self_test():
    checks = []

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

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


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


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

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

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

# Code Coverage Gap Finder

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

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

## Files in this skill

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

## Workflow

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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


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


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


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


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


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


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


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


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


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


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

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

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


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


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


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


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


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


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

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

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


def self_test():
    checks = []

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

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


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


if __name__ == "__main__":
    sys.exit(main())
QualityQACoverage+4
F@f
0
TrendingVideo
The Apple Run: 30-Second Rube Goldberg Village Chain Reaction With a Sleepy Dragon (Seedance Prompt)

A timestamped 10-shot, 30-second Seedance storyboard: one continuous tracking shot follows a red apple through a countryside chain reaction of ramps, bells, a water wheel and laundry lines until it drops into a sleeping dragon's mouth. Uses reference images for the woman and the dragon.

Use the uploaded reference images for the woman and the dragon. Keep both characters exactly as they appear in the reference images: same face, hair, outfit, body, wings, scales, colors and proportions in every shot, with no changes at any point.

Cinematic, photorealistic fantasy comedy short film, 16:9, 30 seconds, 24fps, shot on a full-frame cinema camera with anamorphic lenses, warm morning sunlight, rich colors, natural film grain, realistic physics and motion blur. After the first shot, the camera is one fast, smooth, continuous tracking shot that follows a single shiny red apple with a small green leaf as it rolls, bounces and flies through a chain of clever contraptions. The apple is clearly visible in the frame in every shot. No on-screen text or logos. Exciting, playful, heartwarming tone.

Setting: a cheerful countryside village and orchard on a hillside in the morning, with a stone cottage, a wooden fence, a water mill, laundry lines, flower gardens and a big apple orchard at the bottom of the hill.

Shot 1 (0–3s): Medium shot on a grassy hilltop. The woman places the shiny red apple at the start of a long wooden track and whispers in English: "Go find breakfast, little apple." Far below in the orchard, the dragon sleeps curled up under a tree, snoring.

Shot 2 (3–6s): The apple rolls down the wooden track. The camera tracks right beside it as it spins, then it drops onto a see-saw and bounces off with a hollow wooden clack.

Shot 3 (6–9s): The apple hits a small brass bell on a post with a bright "ding" and rolls on, while a rooster looks up in surprise.

Shot 4 (9–12s): The apple rolls into a clay pipe through a stone wall. The camera follows it inside the pipe, then it bursts out onto a water wheel, lands on a paddle and is flung into the air as the wheel turns.

Shot 5 (12–15s): The apple flies over rooftops and bounces three times on a stretched white bedsheet hanging between two laundry lines like a trampoline.

Shot 6 (15–18s): The apple bounces along a fence lined with glass bottles of different sizes, each one ringing a musical note, playing a cheerful tune as the camera whips along beside it.

Shot 7 (18–21s): The apple drops into a basket on a rope and pulley. A heavy sack on the other end falls, pulling the basket up, and the apple pops out and rolls onto a wooden ramp as a barn door swings open behind it.

Shot 8 (21–24s): The apple rolls into a long row of wooden dominoes, each with a painted fruit on it, and they fall one after another in a wave across the garden. The last domino tips a jug that pours into a pitcher.

Shot 9 (24–27s): The apple rolls up a curved ramp and launches into the air in slow motion, spinning in the sunlight against the sky. The camera flips with it, and below, the sleeping dragon lies on its back in the orchard with its mouth wide open, snoring, next to a table full of pies, fruit, flowers and cakes.

Shot 10 (27–30s): The apple drops perfectly into the dragon's open mouth. The dragon gulps, its eyes pop open and it sits up, looking around in surprise at the feast. The woman runs in, out of breath, and says: "Good morning, sleepyhead! Breakfast is served!" The dragon lets out a happy, emotional rumble and nuzzles her.

Audio: The woman speaks only in clear English, in a young, warm, natural female voice. All her spoken words, gasps and laughter are in English only, with no other language. The dragon makes no speech, only loud snoring, a gulp, soft rumbles and a happy huff. Sounds of wood clacking, a brass bell ding, a water wheel splashing, a rooster, glass bottle chimes, rope and pulley creaking, dominoes falling in a wave and a final soft "gulp". A bright, adventurous orchestral score that builds up and turns warm and cheerful at the end.
StoryboardVideo GenerationSeedance+3
F@f
0
TrendingVideo
Tiny Artist, Giant Canvas: Mixed-Reality 2D Doodle Girl in a Real Art Studio (Seedance Prompt)

A Seedance video prompt that drops a tiny hand-drawn 2D doodle girl into a photorealistic artist's studio: she battles a giant brush, paint tube and palette, paints a landscape that comes to life and ends with a funny twist.

A miniature hand-drawn 2D animated girl with curly black hair, oversized round glasses, a lavender sweater, denim overalls, and tiny red sneakers. She carries a miniature paintbrush and a tiny bucket of colorful paint, working inside a realistic full-sized artist's studio.

Style

Mixed-reality hybrid animation combining playful 2D hand-drawn doodle character art with a photorealistic live-action environment. Whimsical stop-motion physics, expressive hand-drawn movements, exaggerated scale differences, vibrant paint splashes, warm cinematic lighting, and charming visual comedy.

Camera & Framing

Macro close-ups, extreme low-angle tracking shots, overhead perspectives, dynamic camera pans, cinematic push-ins, smooth tracking movements, and shallow depth of field emphasizing the tiny artist against enormous art supplies.

Audio & Scene Breakdown

Visual: The tiny artist stands in front of a gigantic blank canvas. She struggles to lift an enormous paintbrush, eventually using both hands to drag it across the wooden studio floor.

Visual: She climbs a giant paint tube like a mountain, squeezing it with all her strength. Suddenly, a massive blob of blue paint bursts out and launches her into the air.

Visual: She lands inside a giant paint palette, sliding through different colors like a colorful swimming pool. Her tiny sneakers leave vibrant paint footprints everywhere.

Visual: She grabs a miniature brush and begins painting a beautiful landscape on the enormous canvas. Each brushstroke magically transforms into a realistic miniature environment, with mountains, rivers, trees, and clouds emerging from the canvas.

Visual: A giant drop of yellow paint falls from above. She dodges it dramatically, but it lands on her head, turning her hair bright yellow. She looks at herself in a tiny hand mirror, completely shocked.

Visual: Determined to finish her masterpiece, she climbs a giant pencil and uses its tip as a diving board, jumping directly onto the canvas to paint the final details with her tiny brush.

Visual: She steps back proudly, admiring her finished artwork. The camera slowly pulls back to reveal an extraordinary colorful landscape painting. Suddenly, a giant human hand enters the frame holding an eraser and begins rubbing away a tiny section of the painting. She freezes, desperately waving her arms to stop it.

Visual: The camera cuts to the finished canvas, revealing the tiny artist accidentally painted herself into the masterpiece, standing inside her own imaginary world.

Audio

Playful studio ambience, paint tube squeezing, colorful splashes, tiny footsteps, brush strokes, pencil rolling, magical transformation sounds, exaggerated cartoon impacts, subtle upbeat orchestral music, and comedic sound effects. No dialogue.

Ending: A funny unexpected twist that leaves the viewer smiling.
Video GenerationSeedanceCinematic+2
F@f
0
1 / 34Next