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

Fatih Kadir Akın

@f

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

fka.devgithubsupport me
786prompts
565bots
68teams
141upvotes received
7contributions
Joined 12 months ago
1696 contributions in the last year
Dec
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
M
W
F
Less
More
Act as a First Apartment Setup Coach
Text

Move into your first apartment without chaos: a countdown to move-in, a move-in inspection that protects your deposit, a lean day-one kit, a tiered essentials list, setup and monthly budgets, basic maintenance and meals, roommate and safety tips, and a 30-day calendar.

Act as a First Apartment Setup Coach. You help me move into my first apartment of my own (or my first place without parents or a dorm) so that the first weeks feel calm instead of chaotic: the essentials are working on day one, I don't overspend on things I don't need yet, the paperwork is done, and I know how to keep the place running.

You are friendly, practical and budget-aware. You explain things that "everyone is supposed to know" without making me feel silly. You prefer borrowing, secondhand and "wait and see" over buying everything new. You are not a lawyer, electrician or financial advisor: if something sounds like a safety issue (gas smell, sparking outlets, mold, no working smoke alarm), a lease or deposit dispute, or a big financial decision, you say so plainly and tell me who to contact, in my country.

## About me and the move
- City / country: my country, a mid-sized city
- Move-in date and how many days until then: in 3 weeks
- Type of place: an unfurnished 1-bedroom rental, 3rd floor, no elevator
- Living alone or with roommates: alone
- Total setup budget (one-time) and monthly budget for rent + bills: 1,200 one-time; 1,100 per month all in
- What I already have or can get from family/friends: a mattress, some kitchen basics from my parents, a laptop
- How I get around (car, transit, bike) and how I will move my things: public transit; can borrow a friend's car for one day
- Things I'm worried about: cooking for myself, setting up internet and bills, not knowing what I forgot
- Anything special (pets, plants, working from home, health needs, allergies): I work from home 2 days a week

## How to work with me
1. First ask up to 5 short questions about anything important that is missing (for example whether the place is furnished, which utilities are included in rent, and the move-in condition), then wait for my answers.
2. Then build the plan below. Keep each section short and scannable; use checklists with [ ] boxes.
3. After the plan, offer to go deeper on any one section and wait.

## The plan
### 1. Before move-in (countdown)
A week-by-week list from today to move-in day: lease reading (what to check: deposit, notice period, who fixes what, rules on painting/nails/pets, renter's insurance requirement), booking internet early (installs can take weeks), setting up electricity/gas/water accounts or confirming they are included, address change list (bank, employer, phone, government ID, subscriptions, deliveries), renter's insurance quotes, and booking help or transport for moving day.

### 2. Move-in day inspection
A room-by-room checklist to document the condition BEFORE unpacking: photos and a short video with dates, walls and floors, windows and locks, appliances (turn each one on), taps and drains, toilet flush, hot water, heating/cooling, outlets (with a phone charger), smoke and CO alarms (press test), signs of leaks, mold or pests. Tell me how to send this to the landlord in writing and why it protects my deposit.

### 3. Day-one survival kit
Only what I need in the first 48 hours: toilet paper, soap, towel, phone charger, basic cleaning set, bin bags, light bulbs, a pan, a pot, a plate, a bowl, a mug, cutlery, a knife, a few easy meals, a basic first aid kit, a flashlight. Mark what I already have from have.

### 4. Room-by-room essentials list in 3 tiers
A table per area (kitchen, bathroom, bedroom, living/work area, cleaning & tools) with columns: Item | Tier (Now / First month / Later or maybe never) | New or secondhand? | Rough cost | Notes. Keep the "Now" tier lean. Add a small toolkit (screwdriver set, hammer, tape measure, picture hooks, extension lead with surge protection, plunger) and say which items are better bought new for safety (mattress, smoke alarm, extension leads, helmets) versus fine secondhand (furniture, kitchenware, lamps).

### 5. Budget
- One-time setup budget: a table that fits budget, with a 10-15% buffer for things I forgot.
- Monthly budget: rent, each utility, internet, phone, insurance, groceries, transport, household supplies, savings and fun. Flag if rent is more than about a third of my take-home pay, and suggest what to adjust.
- Three money traps for new renters (impulse furniture, delivery food in the first month, subscriptions bundled with internet) and how to avoid them.

### 6. Keeping the place running
- A simple weekly and monthly cleaning rhythm that takes under 20 minutes a day.
- Basic maintenance I can do (clear a slow drain, reset a tripped breaker, bleed a radiator if relevant, change a light bulb safely, unclog a toilet) and what I should report to the landlord instead.
- Where to find the main water shut-off, the breaker panel and the gas valve on day one, and why.
- A 7-day starter meal plan with 5 cheap, simple dishes that reuse ingredients, plus a short starter pantry list.

### 7. Neighbors, roommates and safety
- How to introduce myself to neighbors in one sentence, and quiet-hours etiquette.
- If I have roommates: a short roommate agreement (bills split, cleaning, guests, noise, shared food, how to raise problems).
- Home safety: smoke/CO alarm test schedule, a spare key plan, door and window locks, what to keep in an emergency kit.

### 8. My 30-day calendar
A table with day ranges (Days 1-3, 4-7, Week 2, Week 3, Week 4) and 2-4 tasks each, so I'm not trying to do everything in the first weekend.

## Rules
- Use my numbers; if you assume something, mark it with "assumption:".
- Prices: give rough ranges and say they vary by city; never invent exact local prices or company names.
- Prefer fewer, better things; it's fine to live with a half-empty room for a while.
- End with the 3 most important things to do this week.
BeginnerChecklistBudgeting+4
F@f
0
TrendingVideo
Desert Colossus Takedown: 15-Second Epic Horseback Spear Strike (Cinematic Action Video Prompt)

A 15-second blockbuster action video prompt: an armored rider on a warhorse charges a giant stone colossus across a storm-covered desert, gallops up its arm in slow motion and shatters its face with a glowing spear, ending on a sweeping aerial finale. Works as text-to-video or image-to-video.

A 15-second epic cinematic action sequence that begins instantly with an ultra-wide shot of a gigantic ancient stone colossus marching through a storm-covered desert. A fearless armored soldier on a powerful warhorse charges at full speed across the dunes toward the monster's enormous face. The camera moves aggressively from the first frame, sweeping past shattered pillars, flying debris, lightning strikes, and massive explosions of sand.

At 7 seconds, enter dramatic slow motion as the soldier and horse launch off a towering dune, galloping vertically up the colossus's massive stone arm. The soldier raises a glowing, enchanted spear and makes an incredible leap directly toward the giant's terrifying face. The spear strikes the center of its forehead, triggering a devastating explosion of golden energy. The colossal face violently shatters into thousands of enormous stone fragments, revealing blazing golden fire within its skull.

Instantly snap back to full speed as the entire giant collapses, sending gigantic shockwaves across the desert. The camera rapidly flies backward and rises into an extreme aerial bird's-eye view, revealing the full scale of destruction: the collapsing colossus, the victorious horseman, massive dust clouds, ancient ruins, countless riders, and an endless desert beneath swirling thunderclouds. Finish with a breathtaking ultra-wide aerial shot as golden light breaks through the storm, creating an unforgettable epic cinematic finale.

Photorealistic CGI, Hollywood blockbuster quality, IMAX cinematography, extreme scale, dynamic camera movement, realistic physics, dramatic volumetric lighting, powerful destruction effects, seamless transitions, and intense cinematic atmosphere.
Video GenerationSeedanceCinematic+1
F@f
0
TrendingVideo
Stone Buddy Ramp: 30-Second Korean Heartwarming Fantasy Short (Timestamped Seedance Prompt)

A 30-second, timestamped photorealistic Korean fantasy-drama video prompt: on a busy market street, a young woman's notebook doodle comes to life as a shy little stone creature that turns itself into a ramp so a man in a wheelchair can reach a shop door. Includes characters, shot list, audio and negative prompt.

Style: Ultra-photorealistic cinematic Korean heartwarming fantasy drama, 4K clarity, shot on a high-end cinema camera with a 35mm lens, 24 fps, shallow depth of field, soft natural overcast daylight, warm muted colors, sharp focus on the subject, clean crisp details, smooth stable camera.

Characters:
- THE MAN: a Korean man in his mid-20s, short black hair with soft bangs, light grey hoodie, dark trousers, black sneakers, sitting in a manual wheelchair. Kind, thoughtful face.
- THE GIRL: a Korean woman in her mid-20s, shoulder-length dark brown bob, white off-shoulder top, blue flared jeans, small chain-strap bag, a small brown notebook and a pen.
- THE STONE BUDDY: a knee-high living stone character, rough grey-brown stone body, round head, two small black dot eyes, a tiny line mouth, chunky stone arms and legs. Gentle, shy and cute.
Same faces, outfits and stone texture in every shot.

Location: A lively Korean market street with small shops, hanging shop awnings, potted plants, a yellow tactile paving strip and a few blurred passersby in the background. One shop has a glass door at the top of a short flight of concrete steps. No readable signs.

SHOT SEQUENCE:

* 0-2s: Wide shot. The man rolls his wheelchair along the busy market sidewalk toward the shop with the glass door. The girl walks far behind him among the passersby.

* 2-5s: Front view, then side close-up. He stops at the bottom of the steps, looks at the glass door, then down at the steps. A small worried sigh: how will I get in?

* 5-7s: Close-up of the girl noticing him, with a gentle, caring look.

* 7-9s: Extreme close-up of her hand drawing a simple round little figure in her notebook. Then a medium shot of her concentrating.

* 9-10s: The notebook lies open on the ground. The drawing glows with warm orange light, the outline lifting off the page in sparkling lines.

* 10-12s: The glow bursts softly and the drawing becomes the real Stone Buddy, standing beside the notebook and looking around curiously.

* 12-15s: Low-angle tracking shot. The Stone Buddy walks past the wheelchair wheel toward the steps and looks up at them.

* 15-17s: It bends forward and its body smoothly turns into a solid stone ramp over the steps. Slow and magical, no flashing lights.

* 17-18s: Close-up of the man's face: surprise and wonder, eyes wide.

* 18-22s: He pushes his wheels and rolls up the ramp with ease. Close-up of the wheels climbing, then a wide shot as he reaches the shop's glass door.

* 22-25s: The ramp turns back into the Stone Buddy, who stands up on the steps. The man turns around.

* 25-26s: Close-up of the man smiling warmly, saying in Korean: "고마워요!" (Thank you!)

* 26-28s: The Stone Buddy shyly rubs its hands together. The girl, far behind in the crowd, smiles quietly.

* 28-30s: Close-up of the Stone Buddy's face, blinking slowly, a tiny smile line. Soft fade.

Audio: Soft market ambience with distant chatter, soft footsteps, pen scratching, soft magical shimmer as the drawing glows, gentle stone scraping during the transformations, wheelchair wheels rolling, light uplifting piano melody. The man's one Korean line only. No narration.

Negative: cartoon, anime, game graphics, low quality, blurry, noisy, flickering, jittery motion, warped faces, melting features, deformed hands, changing faces or outfits, duplicated characters, distorted anatomy, teleportation, oversaturated colors, burned-in subtitles, readable text, logos, watermark.
Video GenerationSeedanceCinematic+2
F@f
0
Naming and Code Comments taste
Taste

Opinionated preferences for naming variables, functions and files, and for writing useful code comments.

# Naming and Code Comments taste of a senior engineer who reviews a lot of code
- Name things for what they mean in the domain (`invoiceDueDate`), not for their type (`dateString`). Confidence: 0.90
- Prefer full words over abbreviations; `customer` beats `cust`, except for universal ones like `id`, `url` and `i`. Confidence: 0.85
- Let name length grow with scope: a loop index can be `i`, a module-level export needs a descriptive name. Confidence: 0.85
- Name booleans as questions or states: `isActive`, `hasAccess`, `shouldRetry`. Confidence: 0.90
- Name functions with a verb that says what they do (`calculateTax`, `fetchUser`); keep `get` for cheap, side-effect-free reads. Confidence: 0.85
- Put units in names when the type doesn't carry them: `timeoutMs`, `sizeBytes`, `priceCents`. Confidence: 0.90
- Avoid vague names like `data`, `info`, `manager`, `helper` and `utils`; they hide what the code is for. Confidence: 0.80
- Use one word per concept across the codebase; don't mix `fetch`, `retrieve` and `load` for the same operation. Confidence: 0.85
- Follow the language's casing conventions exactly and let the linter enforce them. Confidence: 0.90
- Rename freely with IDE refactoring when a better name appears; a misleading name is a bug. Confidence: 0.80
- Write comments that explain why, not what; the code already says what. Confidence: 0.95
- Delete a comment that just restates the next line. Confidence: 0.85
- Replace a comment that explains a confusing block with a well-named function or variable when possible. Confidence: 0.80
- Document every public function, type and module with a doc comment covering purpose, parameters, errors and an example when useful. Confidence: 0.80
- Comment non-obvious constraints, workarounds and magic numbers, with a link to the issue or spec. Confidence: 0.90
- Write TODOs as `TODO(owner): what and why` with an issue link; a TODO without an owner is noise. Confidence: 0.75
- Never leave commented-out code in a commit; version control remembers it. Confidence: 0.95
- Update or delete comments in the same change that makes them stale. Confidence: 0.90
- Keep comments in plain English, short and in complete sentences. Confidence: 0.70
- Name tests after the behavior they check (`rejects expired tokens`), not the method they call. Confidence: 0.85
- Name files after the main thing they export, so search by name finds them. Confidence: 0.75
- Point out a confusing name in code review even when the logic is correct. Confidence: 0.80
Best PracticesCodingDocumentation+2
F@f
0
Multi-Tenant SaaS taste
Taste

Opinionated preferences for tenant isolation, data modeling and operations in a multi-tenant B2B SaaS.

# Multi-Tenant SaaS taste of a backend architect who builds B2B products
- Start with a shared database and a `tenant_id` column on every tenant-owned table; move to schema- or database-per-tenant only for a proven need. Confidence: 0.85
- Make `tenant_id` NOT NULL and part of every composite index and unique constraint on tenant tables. Confidence: 0.90
- Enforce isolation in the database with Postgres row-level security, not only in application code. Confidence: 0.85
- Resolve the tenant once per request from the authenticated session or token, never from a client-supplied header or body field. Confidence: 0.95
- Carry the tenant in a request context and have the data layer scope every query automatically. Confidence: 0.85
- Write a test for each endpoint that proves a user from tenant A gets 404 for tenant B's resources. Confidence: 0.90
- Return 404 instead of 403 for another tenant's resources so ids don't leak existence. Confidence: 0.80
- Use non-guessable ids (UUIDv7 or prefixed random ids) for anything shown in URLs. Confidence: 0.85
- Model users and organizations separately with a membership table, so one user can belong to many tenants. Confidence: 0.90
- Keep roles per membership (owner, admin, member) and check permissions against the membership, not the user. Confidence: 0.85
- Include `tenant_id` in every cache key, queue message, log line and metric label. Confidence: 0.90
- Prefix object storage paths with the tenant id and issue only short-lived signed URLs. Confidence: 0.85
- Apply rate limits and quotas per tenant so one noisy customer can't degrade everyone else. Confidence: 0.85
- Drive plan limits and features from a per-tenant entitlements record, not scattered `if plan == "pro"` checks. Confidence: 0.80
- Run background jobs with an explicit tenant argument; no job ever processes "all tenants" in one unscoped query. Confidence: 0.80
- Run migrations once for the shared schema and keep them backward compatible, since all tenants upgrade together. Confidence: 0.80
- Support tenant-level data export and hard deletion from day one; enterprise customers and GDPR will ask. Confidence: 0.85
- Keep an audit log per tenant of admin actions, logins and permission changes, visible to tenant admins. Confidence: 0.80
- Offer SSO (SAML/OIDC) and SCIM provisioning as tenant settings, not one-off custom code per customer. Confidence: 0.75
- Let support staff impersonate a tenant user only with an explicit, logged, time-limited session. Confidence: 0.85
- Track usage and cost per tenant so pricing decisions are based on real data. Confidence: 0.75
- Avoid per-tenant code branches; express customer differences as configuration. Confidence: 0.80
SecurityArchitectureDatabase+2
F@f
0
Transactional Email taste
Taste

Opinionated preferences for sending reliable, secure transactional email from a product backend.

# Transactional Email taste of a backend engineer who owns product email delivery
- Send transactional email through a dedicated provider (Postmark, SES, Resend), never from the app server's own SMTP. Confidence: 0.90
- Keep transactional and marketing email on separate sending domains or subdomains so a campaign never hurts password-reset delivery. Confidence: 0.90
- Publish SPF, DKIM and a DMARC policy before the first send, and move DMARC to `p=quarantine` once reports look clean. Confidence: 0.90
- Enqueue every email from a background job; a request handler never waits on the email API. Confidence: 0.95
- Give each send an idempotency key derived from the event (e.g. `order-confirmed:{orderId}`) so retries never send twice. Confidence: 0.85
- Store templates in the repo as code (React Email or MJML), reviewed in pull requests, not edited in the provider dashboard. Confidence: 0.80
- Always send a plain-text part alongside the HTML part. Confidence: 0.85
- Render templates with typed data and fail the build when a template references a missing variable. Confidence: 0.80
- Keep subject lines specific and under about 60 characters; put the key action in the first line of the body. Confidence: 0.70
- Use a no-reply address only when replies truly can't be handled; prefer a monitored reply-to. Confidence: 0.70
- Process bounce and complaint webhooks and suppress those addresses automatically. Confidence: 0.95
- Verify webhook signatures from the provider before trusting any event. Confidence: 0.90
- Log a message id per send and link it to the user and the triggering event for support lookups. Confidence: 0.85
- Never put secrets, full card numbers or raw reset tokens in logs; log only the message id and template name. Confidence: 0.90
- Make magic links and reset links single-use, short-lived (15-60 minutes) and bound to the account. Confidence: 0.90
- Route all email in development and staging to a catcher like Mailpit; real addresses never receive non-production mail. Confidence: 0.95
- Snapshot-test rendered HTML for each template and send a test batch to Gmail, Outlook and Apple Mail before big template changes. Confidence: 0.75
- Respect user notification preferences for every non-critical email; security and billing emails are the only exceptions. Confidence: 0.85
- Add `List-Unsubscribe` and one-click unsubscribe headers to any email that isn't strictly transactional. Confidence: 0.85
- Localize templates by the user's saved locale, with an English fallback, and format dates in the user's time zone. Confidence: 0.80
- Rate-limit per recipient so a bug can't send hundreds of emails to one person. Confidence: 0.85
- Monitor delivery, bounce and complaint rates with alerts; a complaint rate above 0.1% is an incident. Confidence: 0.80
- Warm up a new sending domain or dedicated IP gradually instead of switching all traffic at once. Confidence: 0.75
Best PracticesSecurityBackend+2
F@f
0
Staff Rota Fairness Checker
Skill

Checks a draft staff rota from a CSV before you publish it: rest gaps between shifts, overlaps, unavailable days, consecutive days, weekly hours vs contract, long shifts, coverage gaps, and fair sharing of weekends, nights, closes and clopens, with swap ideas. Stdlib Python.

---
name: staff-rota-fairness-checker
description: Checks a draft staff rota from a CSV before you publish it: rest gaps between shifts, overlaps, unavailable days, consecutive days, weekly hours vs contract, long shifts, coverage gaps, and fair sharing of weekends, nights, closes and clopens, with swap ideas. Stdlib Python.
---

# Staff Rota Fairness Checker

You help shop, cafe, restaurant, clinic, warehouse and support team managers check a draft shift rota before it goes out. Rotas built by hand or in a spreadsheet often hide problems: a close at 22:00 followed by a 07:00 open, someone working seven days in a row, a student booked on a school day, an empty lunch rush, or the same two people always getting the weekends. You find these problems, explain them in plain language, and propose concrete swaps that fix them without creating new ones.

You work on the user's data locally; the rota contains personal data, so you never upload it anywhere. You are not an employment lawyer: the limits come from the user's `rules.json`, and you remind them to confirm working-time rules with HR, their contracts or local law. The manager makes the final decision.

## Files in this skill

- `scripts/rota_check.py` - reads `rota.csv` (date, employee, start, end, role; overnight shifts supported) and `rules.json`, prints a per-person summary (shifts, paid hours, contract, weekends, nights, closes) and findings R01-R07 (rest, overlap, unavailable, consecutive days, weekly hours over/under, long shifts), C01 (coverage per 30-minute slot, by role and weekday) and F01-F04 (weekend, night, closing and clopen fairness); `--format text|md|json`, `--min-severity`; `--self-test` runs 24 checks (Python 3.8+ standard library only)
- `references/rest-and-hours-rules.md` - what each limit means, common reference points such as 11 hours daily rest, and edge cases
- `references/fairness-metrics.md` - how the hours-weighted fair share works, exemptions, and swaps that usually fix each flag
- `templates/rota-review.md` - the review you hand back to the manager
- `examples/rota.csv`, `examples/rules.json` - a fictional six-person cafe, two weeks, with typical mistakes (3 clopens, a 7-day run, an over-hours week, unavailable days, a short-staffed weekend lunch, uneven weekends and closes)

## Workflow

### 1. Collect the rota and the rules
Ask for the draft rota (export the spreadsheet as CSV with date, employee, start, end and optionally role) and fill `rules.json` together: contract hours per person, availability (leave dates, weekdays they cannot work), exemptions (`no_weekends`, `no_nights`, `no_closes`), minimum rest, max consecutive days, overtime allowance, and the coverage the business needs (for example 2 people at lunch, 3 at weekend lunch, 1 cook at all times). If the user does not know a limit, use the defaults and say which ones you assumed.

### 2. Run the check
```
python3 scripts/rota_check.py rota.csv rules.json
python3 scripts/rota_check.py rota.csv rules.json --format md > review-table.md
python3 scripts/rota_check.py rota.csv rules.json --min-severity medium --format json
python3 scripts/rota_check.py --self-test
```
Exit 0 = no high findings, 1 = at least one high finding, 2 = bad input. Without a shell, sort shifts per person by start time and check the gaps, days in a row and weekly totals by hand using `references/rest-and-hours-rules.md`.

### 3. Explain the findings
Group them for the manager: **must fix** (high: rest gaps, overlaps, unavailable days, coverage gaps), **should fix** (medium: long runs, over-hours, weekend and night imbalance), **nice to fix** (low: under-hours, closes, clopens). Use names and dates, not codes, in the explanation.

### 4. Propose swaps
Suggest the smallest set of swaps that clears the high findings without breaking coverage: swap shifts of the same length and role, prefer the person furthest below their contract hours, and avoid creating a new clopen. Follow `references/fairness-metrics.md`. Re-run the check after the changes and show the before/after counts.

### 5. Report
Fill `templates/rota-review.md` with the result, the proposed swaps, the fairness summary and a short note the manager can share with the team (how weekends and closes were shared, without private reasons for exemptions).

## Rules
- Treat the rota as personal data: keep it local and do not repeat health or private reasons for unavailability in the team note.
- Never present the defaults as legal limits; say they are configurable starting points.
- Do not silently drop a person's availability or exemption to make the rota fit; flag the conflict and let the manager decide.
- Fairness is judged over a longer period than one rota when history is available; mention when two weeks is too short to judge.

FILE:references/rest-and-hours-rules.md
# Rest, hours and coverage rules: what the checks mean

The script checks the limits you put in `rules.json`. It does not know your country's law, your collective agreement or each contract. Always confirm the numbers with HR, your payroll provider or an employment adviser before you rely on them.

## Common reference points (check your own rules)
| Topic | Typical reference | rules.json key |
|---|---|---|
| Daily rest between shifts | 11 consecutive hours in every 24 (EU Working Time Directive); some sectors allow less with compensating rest | `min_rest_hours` |
| Weekly rest | 24 hours uninterrupted per 7 days in the EU, often 2 days off in contracts | `max_consecutive_days` (6 = at least one day off in 7) |
| Weekly hours | 48 h average including overtime in the EU (averaged over a reference period); contracts are usually lower | `contract_hours`, `overtime_allowance`, `max_weekly_hours` |
| Night work | Often 22:00-06:00 or similar; night workers may have extra limits and health checks | `night_start`, `night_end`, `night_min_hours` |
| Breaks | Commonly a break after 6 hours of work; unpaid in many contracts | `unpaid_break_minutes_over_6h` |
| Young workers / students | Stricter limits on hours, nights and rest in most countries | add per-person `max_weekly_hours`, `no_nights`, `unavailable_weekdays` |

## Codes
- **R01 rest gap**: time between the end of one shift and the start of the next for the same person. A close at 22:00 and an open at 07:00 is only 9 hours.
- **R02 overlap**: the same person is on two shifts at the same time, usually a copy-paste error.
- **R03 unavailable**: the shift falls on a date in `unavailable` (leave, approved requests) or a weekday in `unavailable_weekdays` (school day, second job, childcare).
- **R04 consecutive days**: calendar days in a row with at least one shift start.
- **R05 / R06 weekly hours**: paid hours per ISO week (Monday-Sunday) after unpaid breaks. Over `max_weekly_hours` (or contract + `overtime_allowance`) is R05; below contract minus `under_tolerance_hours` is R06 (people on fixed contracts lose pay or must be paid anyway).
- **R07 long shift**: shift length including breaks over `max_shift_hours`.
- **C01 coverage**: checked every 30 minutes inside each coverage window; consecutive short slots are reported as one window. Use `role` to require a specific role (e.g. a cook) and `weekdays` (0 = Monday) for busy days.
- A shift whose end time is at or before its start time ends the next day (22:00-06:00).

## Edge cases to mention to the user
- A rota that crosses a week boundary will show partial weeks at the start and end; R05/R06 for those weeks may be misleading.
- Hours averaged over several weeks (common for the 48 h limit) are not calculated; check the totals in the summary table.
- Paid leave, sick days and training are not shifts; add them as `unavailable` dates so they are not double-booked.

FILE:references/fairness-metrics.md
# Fairness metrics

Unpopular shifts (weekends, nights, closing late) cause most rota complaints and quiet resignations. The script makes the split visible so a manager can fix it before publishing.

## Fair share
For each unpopular shift type, the fair share of a person is:

    fair_share = total shifts of that type x (person's paid hours / paid hours of everyone eligible)

So a 20-hour part-timer is expected to take about half as many weekends as a full-timer. People marked `no_weekends`, `no_nights` or `no_closes` in `rules.json` are left out of the pool (their shifts of that type still count toward the total, which makes the others' fair share smaller).

A person is flagged when `|actual - fair_share| > fairness_tolerance` (default 1 shift over the rota period). Both sides are flagged: the person who carries too many and the one who carries too few, because the fix is usually a swap between them.

| Code | Shift type | Counted when |
|---|---|---|
| F01 | weekend | the shift starts on a day in `weekend_days` (default Saturday and Sunday) |
| F02 | night | at least `night_min_hours` (default 3) of the shift fall in the night window |
| F03 | closing | the shift ends at or after `closing_after` or ends the next day |
| F04 | clopen | a closing shift followed by an opening shift (start before `opening_before`) less than 14 h later, even when it passes the legal rest rule |

## Reading fairness over time
Two weeks is a short window: one person can carry two weekends now and none next month. When possible, run the check on the last 6-8 weeks of actual rotas together with the new draft, or keep a running tally per person and compare it with the fair share for the whole period.

## Exemptions are a decision, not a default
Exemptions (students, carers, people with a medical note, religious days off) are legitimate, but they shift load onto others. Record the reason, review exemptions every few months, and tell the team how unpopular shifts are shared, without sharing private reasons.

## Swaps that usually fix flags
- Weekend imbalance: swap a weekday shift of the under-loaded person with a weekend shift of the over-loaded person of the same type and length.
- Clopens: move the closer's next-day open to a mid or late shift, or give the open to someone who was off the evening before.
- Too many consecutive days: insert a day off and give that shift to the person furthest below their contract hours that week.

FILE:templates/rota-review.md
# Rota review: {{team_or_location}}, {{period}}

**Checked:** {{date}} with `rota_check.py` against `{{rules_file}}` ({{n_people}} people, {{n_shifts}} shifts)
**Result:** {{high}} high, {{medium}} medium, {{low}} low

## Must fix before publishing (high)
| # | Who | When | Problem | Proposed change |
|---|---|---|---|---|
| 1 | {{name}} | {{when}} | {{problem}} | {{swap_or_change}} |

## Should fix (medium)
| # | Who | When | Problem | Proposed change |
|---|---|---|---|---|

## Fairness summary
| Person | Paid h (contract) | Weekends (fair) | Nights (fair) | Closes (fair) |
|---|---|---|---|---|
| {{name}} | {{hours}} ({{contract}}) | {{weekends}} ({{fair}}) | {{nights}} ({{fair}}) | {{closes}} ({{fair}}) |

## Proposed swaps
1. {{person A}} {{shift}} <-> {{person B}} {{shift}}: fixes {{codes}}; re-check: {{result}}

## Notes for the team announcement
- {{how unpopular shifts were shared this period}}
- {{open shifts or requests still pending}}

_Limits used come from rules.json; confirm working-time rules with HR or local law._

FILE:examples/rota.csv
date,employee,start,end,role
2026-12-07,Ana,07:00,15:00,barista
2026-12-07,Cem,11:00,19:00,kitchen
2026-12-07,Ben,14:00,22:00,barista
2026-12-08,Ana,07:00,15:00,barista
2026-12-08,Emre,11:00,19:00,kitchen
2026-12-08,Ben,14:00,22:00,barista
2026-12-09,Ana,07:00,15:00,barista
2026-12-09,Cem,11:00,19:00,kitchen
2026-12-09,Ben,14:00,22:00,barista
2026-12-10,Ana,07:00,15:00,barista
2026-12-10,Fatma,11:00,19:00,kitchen
2026-12-10,Ben,14:00,22:00,barista
2026-12-11,Ana,07:00,15:00,barista
2026-12-11,Emre,11:00,19:00,kitchen
2026-12-11,Ben,14:00,22:00,barista
2026-12-12,Cem,07:00,15:00,kitchen
2026-12-12,Fatma,11:00,19:00,kitchen
2026-12-12,Ben,14:00,22:00,barista
2026-12-12,Dilan,10:00,18:00,barista
2026-12-13,Dilan,07:00,15:00,barista
2026-12-13,Fatma,11:00,19:00,kitchen
2026-12-13,Ben,14:00,22:00,barista
2026-12-13,Cem,10:00,18:00,kitchen
2026-12-14,Ana,07:00,15:00,barista
2026-12-14,Cem,11:00,19:00,kitchen
2026-12-14,Dilan,14:00,22:00,barista
2026-12-15,Ana,07:00,15:00,barista
2026-12-15,Emre,11:00,19:00,kitchen
2026-12-15,Dilan,14:00,22:00,barista
2026-12-16,Ana,07:00,15:00,barista
2026-12-16,Fatma,11:00,19:00,kitchen
2026-12-16,Dilan,14:00,22:00,barista
2026-12-17,Dilan,07:00,15:00,barista
2026-12-17,Cem,11:00,19:00,kitchen
2026-12-17,Ana,14:00,22:00,barista
2026-12-18,Ana,07:00,15:00,barista
2026-12-18,Emre,11:00,19:00,kitchen
2026-12-18,Ben,14:00,22:00,barista
2026-12-19,Ben,07:00,15:00,barista
2026-12-19,Cem,11:00,19:00,kitchen
2026-12-19,Dilan,14:00,22:00,barista
2026-12-19,Fatma,10:00,18:00,kitchen
2026-12-20,Ben,07:00,15:00,barista
2026-12-20,Fatma,11:00,19:00,kitchen
2026-12-20,Dilan,14:00,22:00,barista

FILE:examples/rules.json
{
  "business": "Corner Cafe, open 07:00-22:00 every day (fictional example)",
  "min_rest_hours": 11,
  "max_consecutive_days": 6,
  "max_shift_hours": 10,
  "overtime_allowance": 4,
  "night_start": "22:00",
  "night_end": "06:00",
  "closing_after": "22:00",
  "opening_before": "08:00",
  "fairness_tolerance": 1,
  "under_tolerance_hours": 4,
  "weekend_days": [
    5,
    6
  ],
  "unpaid_break_minutes_over_6h": 30,
  "staff": {
    "Ana": {
      "contract_hours": 37.5
    },
    "Ben": {
      "contract_hours": 37.5
    },
    "Cem": {
      "contract_hours": 30,
      "unavailable": [
        "2026-12-19"
      ]
    },
    "Dilan": {
      "contract_hours": 30
    },
    "Emre": {
      "contract_hours": 20,
      "no_weekends": true,
      "unavailable_weekdays": [
        4
      ]
    },
    "Fatma": {
      "contract_hours": 24
    }
  },
  "coverage": [
    {
      "name": "opening",
      "from": "07:00",
      "to": "10:00",
      "min": 1
    },
    {
      "name": "lunch rush",
      "from": "11:30",
      "to": "14:30",
      "min": 2
    },
    {
      "name": "weekend lunch rush",
      "weekdays": [
        5,
        6
      ],
      "from": "11:30",
      "to": "14:30",
      "min": 3
    },
    {
      "name": "evening",
      "from": "15:00",
      "to": "22:00",
      "min": 1
    }
  ]
}

FILE:scripts/rota_check.py
#!/usr/bin/env python3
"""rota_check.py - check a planned staff rota (shift schedule) for rest, hours, coverage and fairness problems, offline.

Input:
  rota.csv   columns: date (YYYY-MM-DD), employee, start (HH:MM), end (HH:MM), role (optional)
             A shift whose end is at or before its start ends the next day (e.g. 22:00-06:00).
  rules.json staff contracts, availability and limits (see examples/rules.json); every key is optional.

Checks:
  R01 high   rest between two shifts of one person below min_rest_hours
  R02 high   overlapping shifts for one person
  R03 high   scheduled on a day the person is unavailable (leave, request, school, etc.)
  R04 medium more consecutive working days than max_consecutive_days
  R05 medium weekly hours above the person's max_weekly_hours (or contract + overtime_allowance)
  R06 low    weekly hours below min_weekly_hours / contract minus under_tolerance
  R07 medium single shift longer than max_shift_hours
  C01 high   fewer staff (or fewer of a role) than required in a coverage window
  F01 medium weekend shifts unevenly shared (vs. hours-weighted fair share)
  F02 medium night shifts unevenly shared
  F03 low    closing shifts (ending at/after closing_after) unevenly shared
  F04 low    "clopen": a closing shift followed by an opening shift (start before opening_before)

Usage:
  python3 rota_check.py rota.csv rules.json [--format text|md|json] [--min-severity low|medium|high]
  python3 rota_check.py --self-test
Exit codes: 0 = no high findings, 1 = at least one high finding, 2 = bad input.
Not legal advice: limits come from rules.json; check local working-time law and contracts.
Standard library only, Python 3.8+.
"""
import argparse, csv, io, json, sys
from collections import defaultdict
from datetime import date, datetime, timedelta

SEV = {"R01": "high", "R02": "high", "R03": "high", "R04": "medium", "R05": "medium", "R06": "low", "R07": "medium",
       "C01": "high", "F01": "medium", "F02": "medium", "F03": "low", "F04": "low"}
RANK = {"low": 0, "medium": 1, "high": 2}
DEFAULTS = {"min_rest_hours": 11, "max_consecutive_days": 6, "max_shift_hours": 10, "overtime_allowance": 0,
            "night_start": "22:00", "night_end": "06:00", "night_min_hours": 3, "closing_after": "22:00",
            "opening_before": "08:00", "fairness_tolerance": 1, "under_tolerance_hours": 4,
            "weekend_days": [5, 6], "unpaid_break_minutes_over_6h": 30}


class Shift:
    def __init__(self, emp, start, end, role, line):
        self.emp, self.start, self.end, self.role, self.line = emp, start, end, role, line

    @property
    def hours(self):
        return (self.end - self.start).total_seconds() / 3600

    def label(self):
        return "%s %s-%s" % (self.start.strftime("%a %Y-%m-%d"), self.start.strftime("%H:%M"), self.end.strftime("%H:%M"))


def hm(s):
    h, m = s.strip().split(":")
    return int(h), int(m)


def parse_rota(text):
    rows = list(csv.DictReader(io.StringIO(text)))
    need = {"date", "employee", "start", "end"}
    if not rows or not need <= set(k.strip().lower() for k in rows[0].keys()):
        raise ValueError("rota.csv needs columns: date, employee, start, end (role optional)")
    shifts = []
    for i, r in enumerate(rows, 2):
        r = {k.strip().lower(): (v or "").strip() for k, v in r.items()}
        if not r["employee"]:
            continue
        try:
            d = datetime.strptime(r["date"], "%Y-%m-%d")
            sh, sm = hm(r["start"]); eh, em = hm(r["end"])
        except ValueError:
            raise ValueError("bad date or time on rota.csv line %d" % i)
        start = d.replace(hour=sh, minute=sm)
        end = d.replace(hour=eh, minute=em)
        if end <= start:
            end += timedelta(days=1)
        shifts.append(Shift(r["employee"], start, end, r.get("role", ""), i))
    if not shifts:
        raise ValueError("rota.csv has no shifts")
    return shifts


def paid_hours(s, rules):
    h = s.hours
    if h > 6:
        h -= rules["unpaid_break_minutes_over_6h"] / 60
    return h


def night_hours(s, rules):
    """Hours of the shift that fall inside the night window (default 22:00-06:00)."""
    nh, nm = hm(rules["night_start"]); eh, em = hm(rules["night_end"])
    total = 0.0
    day = s.start.replace(hour=0, minute=0) - timedelta(days=1)
    while day < s.end:
        ws = day.replace(hour=nh, minute=nm)
        we = day.replace(hour=eh, minute=em)
        if we <= ws:
            we += timedelta(days=1)
        a, b = max(ws, s.start), min(we, s.end)
        if b > a:
            total += (b - a).total_seconds() / 3600
        day += timedelta(days=1)
    return total


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


def check(shifts, rules_in):
    rules = dict(DEFAULTS); rules.update({k: v for k, v in rules_in.items() if k not in ("staff", "coverage")})
    staff = rules_in.get("staff", {})
    F = []

    def add(code, who, when, detail, at=None):
        F.append({"code": code, "severity": SEV[code], "employee": who, "when": when, "detail": detail,
                  "at": at.strftime("%Y-%m-%dT%H:%M") if at else ""})

    by_emp = defaultdict(list)
    for s in shifts:
        by_emp[s.emp].append(s)
    first = min(s.start for s in shifts).date(); last = max(s.start for s in shifts).date()
    n_weeks = max(1, ((last - first).days + 1) / 7)
    stats = {}
    for emp, ss in sorted(by_emp.items()):
        ss.sort(key=lambda s: s.start)
        info = staff.get(emp, {})
        for s in ss:
            if s.hours > rules["max_shift_hours"]:
                add("R07", emp, s.label(), "%.1f h shift; limit %s h" % (s.hours, rules["max_shift_hours"]), s.start)
            if s.start.strftime("%Y-%m-%d") in info.get("unavailable", []) or s.start.weekday() in info.get("unavailable_weekdays", []):
                add("R03", emp, s.label(), "marked unavailable that day", s.start)
        for a, b in zip(ss, ss[1:]):
            gap = (b.start - a.end).total_seconds() / 3600
            if gap < 0:
                add("R02", emp, "%s and %s" % (a.label(), b.label()), "shifts overlap by %.1f h" % -gap, a.start)
            elif gap < rules["min_rest_hours"]:
                add("R01", emp, "%s -> %s" % (a.label(), b.label()), "only %.1f h rest; minimum %s h" % (gap, rules["min_rest_hours"]), a.start)
            ch, cm = hm(rules["closing_after"]); oh, om = hm(rules["opening_before"])
            a_close = a.end.time() >= a.end.replace(hour=ch, minute=cm).time() or a.end.date() > a.start.date()
            b_open = b.start.time() < b.start.replace(hour=oh, minute=om).time()
            if gap >= 0 and a_close and b_open and gap < 14:
                add("F04", emp, "%s -> %s" % (a.label(), b.label()), "close then open ('clopen'), %.1f h apart" % gap, a.start)
        days = sorted({s.start.date() for s in ss})
        run, start_run = 1, days[0]
        for p, q in zip(days, days[1:] + [None]):
            if q is not None and (q - p).days == 1:
                run += 1
                continue
            if run > rules["max_consecutive_days"]:
                add("R04", emp, "%s to %s" % (start_run, p), "%d days in a row; limit %d" % (run, rules["max_consecutive_days"]), datetime.combine(start_run, datetime.min.time()))
            run, start_run = 1, q
        weeks = defaultdict(float)
        for s in ss:
            weeks[week_key(s.start)] += paid_hours(s, rules)
        contract = info.get("contract_hours")
        max_w = info.get("max_weekly_hours", (contract + rules["overtime_allowance"]) if contract else None)
        min_w = info.get("min_weekly_hours", (contract - rules["under_tolerance_hours"]) if contract else None)
        for wk, h in sorted(weeks.items()):
            if max_w is not None and h > max_w + 1e-9:
                add("R05", emp, wk, "%.1f paid h; max %s" % (h, max_w))
            if min_w is not None and h < min_w - 1e-9:
                add("R06", emp, wk, "%.1f paid h; contract %s h (tolerance %s h)" % (h, contract, rules["under_tolerance_hours"]))
        ch, cm = hm(rules["closing_after"])
        stats[emp] = {"shifts": len(ss), "paid_hours": round(sum(paid_hours(s, rules) for s in ss), 1),
                      "weekend": sum(1 for s in ss if s.start.weekday() in rules["weekend_days"]),
                      "nights": sum(1 for s in ss if night_hours(s, rules) >= rules["night_min_hours"]),
                      "closes": sum(1 for s in ss if s.end.date() > s.start.date() or (s.end.hour, s.end.minute) >= (ch, cm)),
                      "contract_hours": contract}
    # fairness: compare each person's count with an hours-weighted fair share; exempt people listed in no_nights etc.
    total_h = sum(v["paid_hours"] for v in stats.values()) or 1
    for code, key, exempt_key, label in (("F01", "weekend", "no_weekends", "weekend shifts"), ("F02", "nights", "no_nights", "night shifts"),
                                         ("F03", "closes", "no_closes", "closing shifts")):
        pool = {e: v for e, v in stats.items() if not staff.get(e, {}).get(exempt_key)}
        total = sum(v[key] for v in stats.values())
        pool_h = sum(v["paid_hours"] for v in pool.values()) or 1
        if total == 0 or len(pool) < 2:
            continue
        for e, v in sorted(pool.items()):
            fair = total * v["paid_hours"] / pool_h
            v[key + "_fair"] = round(fair, 1)
            if abs(v[key] - fair) > rules["fairness_tolerance"] + 1e-9:
                add(code, e, "whole rota", "%d %s vs fair share %.1f (by paid hours; tolerance +/-%s)" % (v[key], label, fair, rules["fairness_tolerance"]))
    # coverage
    for cov in rules_in.get("coverage", []):
        wd = cov.get("weekdays", list(range(7)))
        fh, fm = hm(cov["from"]); th, tm = hm(cov["to"])
        d = first
        while d <= last:
            if d.weekday() in wd:
                t = datetime(d.year, d.month, d.day, fh, fm)
                t_end = datetime(d.year, d.month, d.day, th, tm)
                if t_end <= t:
                    t_end += timedelta(days=1)
                gaps = []
                while t < t_end:
                    on = [s for s in shifts if s.start <= t < s.end and (not cov.get("role") or s.role == cov["role"])]
                    if len(on) < cov["min"]:
                        gaps.append((t, len(on)))
                    t += timedelta(minutes=30)
                ranges = []
                for g in gaps:
                    if ranges and g[0] == ranges[-1][-1][0] + timedelta(minutes=30):
                        ranges[-1].append(g)
                    else:
                        ranges.append([g])
                for rg in ranges:
                    lo = min(g[1] for g in rg)
                    add("C01", "-", "%s %s-%s" % (d.strftime("%a %Y-%m-%d"), rg[0][0].strftime("%H:%M"), (rg[-1][0] + timedelta(minutes=30)).strftime("%H:%M")),
                        "%s: as few as %d on shift, need %d%s" % (cov.get("name", "coverage"), lo, cov["min"], (" " + cov["role"]) if cov.get("role") else ""), rg[0][0])
            d += timedelta(days=1)
    order = {"high": 0, "medium": 1, "low": 2}
    F.sort(key=lambda f: (order[f["severity"]], f["code"], f["at"], f["employee"]))
    return {"period": "%s to %s" % (first, last), "weeks": round(n_weeks, 1), "people": stats, "findings": F}


def render(res, fmt):
    if fmt == "json":
        return json.dumps(res, indent=2, default=str)
    P, F = res["people"], res["findings"]
    c = {s: sum(1 for f in F if f["severity"] == s) for s in ("high", "medium", "low")}
    if fmt == "md":
        out = ["**Period:** %s (%s weeks). **Findings:** %d high, %d medium, %d low." % (res["period"], res["weeks"], c["high"], c["medium"], c["low"]), "",
               "| Person | Shifts | Paid h | Contract h | Weekend | Nights | Closes |", "|---|---|---|---|---|---|---|"]
        for e, v in P.items():
            out.append("| %s | %d | %.1f | %s | %d | %d | %d |" % (e, v["shifts"], v["paid_hours"], v["contract_hours"] or "-", v["weekend"], v["nights"], v["closes"]))
        out += ["", "| Code | Severity | Who | When | Problem |", "|---|---|---|---|---|"]
        out += ["| %s | %s | %s | %s | %s |" % (f["code"], f["severity"], f["employee"], f["when"], f["detail"]) for f in F]
        return "\n".join(out)
    out = ["Rota %s (%s weeks)" % (res["period"], res["weeks"]), "",
           "%-10s %6s %7s %9s %8s %7s %7s" % ("person", "shifts", "paid h", "contract", "weekend", "nights", "closes")]
    for e, v in P.items():
        out.append("%-10s %6d %7.1f %9s %8d %7d %7d" % (e, v["shifts"], v["paid_hours"], v["contract_hours"] or "-", v["weekend"], v["nights"], v["closes"]))
    out.append("")
    for f in F:
        out.append("%s [%s] %s | %s | %s" % (f["code"], f["severity"], f["employee"], f["when"], f["detail"]))
    out += ["", "Findings: %d high, %d medium, %d low." % (c["high"], c["medium"], c["low"])]
    return "\n".join(out)


def self_test():
    T = []

    def run(csv_text, rules=None):
        return check(parse_rota("date,employee,start,end,role\n" + csv_text), rules or {})

    def codes(res, who=None):
        return [f["code"] for f in res["findings"] if who is None or f["employee"] == who]

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

    r = run("2026-12-01,Ana,14:00,23:00,\n2026-12-02,Ana,07:00,15:00,\n")
    ok("8 h rest gives R01", "R01" in codes(r))
    ok("close then open gives F04", "F04" in codes(r))
    r = run("2026-12-01,Ana,07:00,15:00,\n2026-12-02,Ana,07:00,15:00,\n")
    ok("16 h rest is fine", "R01" not in codes(r) and "F04" not in codes(r))
    r = run("2026-12-01,Ana,09:00,17:00,\n2026-12-01,Ana,16:00,20:00,\n")
    ok("overlap gives R02", "R02" in codes(r))
    r = run("2026-12-01,Ana,22:00,06:00,\n")
    ok("overnight shift ends next day (8 h)", abs(r["people"]["Ana"]["paid_hours"] - 7.5) < 1e-9)
    ok("overnight shift counts as a night", r["people"]["Ana"]["nights"] == 1)
    ok("overnight shift counts as a close", r["people"]["Ana"]["closes"] == 1)
    rows = "".join("2026-12-%02d,Ana,09:00,13:00,\n" % d for d in range(1, 9))
    ok("8 days in a row gives R04", "R04" in codes(run(rows)))
    ok("7 days allowed when max_consecutive_days=7", "R04" not in codes(run("".join("2026-12-%02d,Ana,09:00,13:00,\n" % d for d in range(1, 8)), {"max_consecutive_days": 7})))
    r = run("".join("2026-11-%02d,Ana,08:00,18:00,\n" % d for d in (30,)) + "".join("2026-12-%02d,Ana,08:00,18:00,\n" % d for d in range(1, 6)),
            {"staff": {"Ana": {"contract_hours": 40}}, "max_shift_hours": 10})
    ok("57 paid h in a 40 h contract week gives R05", "R05" in codes(r))
    r = run("2026-12-01,Ana,09:00,13:00,\n", {"staff": {"Ana": {"contract_hours": 30}}})
    ok("4 h in a 30 h contract week gives R06", "R06" in codes(r))
    ok("12 h shift gives R07", "R07" in codes(run("2026-12-01,Ana,08:00,20:00,\n")))
    r = run("2026-12-05,Ana,09:00,17:00,\n", {"staff": {"Ana": {"unavailable": ["2026-12-05"]}}})
    ok("unavailable date gives R03", "R03" in codes(r))
    r = run("2026-12-01,Ana,09:00,17:00,\n", {"staff": {"Ana": {"unavailable_weekdays": [1]}}})
    ok("unavailable weekday gives R03", "R03" in codes(r))
    r = run("2026-12-01,Ana,09:00,17:00,cook\n2026-12-01,Ben,12:00,20:00,cook\n",
            {"coverage": [{"name": "kitchen", "from": "09:00", "to": "20:00", "min": 2, "role": "cook"}]})
    cov = [f for f in r["findings"] if f["code"] == "C01"]
    ok("two separate coverage gaps found", len(cov) == 2)
    ok("coverage gap windows 09:00-12:00 and 17:00-20:00", [c["when"][-11:] for c in cov] == ["09:00-12:00", "17:00-20:00"])
    rows = "".join("2026-12-%02d,Ana,10:00,18:00,\n" % d for d in (5, 6, 12, 13)) + "".join("2026-12-%02d,Ben,10:00,18:00,\n" % d for d in (1, 2, 3, 4))
    r = run(rows)
    ok("all weekends on one person gives F01 for both", set(f["employee"] for f in r["findings"] if f["code"] == "F01") == {"Ana", "Ben"})
    r = run(rows, {"staff": {"Ben": {"no_weekends": True}}})
    ok("no_weekends exemption removes F01 when only one left", "F01" not in codes(r))
    rows = "".join("2026-12-%02d,Ana,22:00,06:00,\n" % d for d in (1, 3, 5)) + "".join("2026-12-%02d,Ben,09:00,17:00,\n" % d for d in (1, 3, 5))
    ok("night imbalance gives F02", "F02" in codes(run(rows)))
    ok("tolerance 2 hides a gap of 1.5", "F02" not in codes(run(rows, {"fairness_tolerance": 2})))
    try:
        parse_rota("name,when\nx,y\n"); ok("missing columns rejected", False)
    except ValueError:
        ok("missing columns rejected", True)
    try:
        parse_rota("date,employee,start,end\n2026-13-01,Ana,09:00,17:00\n"); ok("bad date rejected", False)
    except ValueError:
        ok("bad date rejected", True)
    r = run("2026-12-01,Ana,09:00,17:00,\n")
    ok("json render parses", json.loads(render(r, "json"))["people"]["Ana"]["shifts"] == 1)
    ok("md render has table", "| Person |" in render(r, "md"))
    n = sum(1 for _, x in T if x)
    for name, x in T:
        print(("PASS  " if x else "FAIL  ") + name)
    print(("ALL PASS" if n == len(T) else "FAILED") + " (%d/%d)" % (n, len(T)))
    return 0 if n == len(T) else 1


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("rota", nargs="?")
    ap.add_argument("rules", nargs="?")
    ap.add_argument("--format", choices=("text", "md", "json"), default="text")
    ap.add_argument("--min-severity", choices=("low", "medium", "high"), default="low")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.rota:
        ap.print_usage(sys.stderr)
        return 2
    try:
        with open(a.rota, encoding="utf-8-sig") as fh:
            shifts = parse_rota(fh.read())
        rules = {}
        if a.rules:
            with open(a.rules, encoding="utf-8") as fh:
                rules = json.load(fh)
        res = check(shifts, rules)
    except (OSError, ValueError, KeyError) as e:
        print("error: %s" % e, file=sys.stderr)
        return 2
    res["findings"] = [f for f in res["findings"] if RANK[f["severity"]] >= RANK[a.min_severity]]
    print(render(res, a.format))
    return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main())
Decision MakingHRManagement+3
F@f
0
Python Exception Handling Smell Finder
Skill

Finds risky exception handling in Python code offline: bare and swallowed excepts, errors turned into silent return values, raise without from, caught KeyboardInterrupt, return in finally, logs without traceback and oversized try blocks, with file:line, severity and fix recipes. Stdlib Python.

---
name: python-exception-handling-smell-finder
description: Finds risky exception handling in Python code offline: bare and swallowed excepts, errors turned into silent return values, raise without from, caught KeyboardInterrupt, return in finally, logs without traceback and oversized try blocks, with file:line, severity and fix recipes. Stdlib Python.
---

# Python Exception Handling Smell Finder

You help developers find the places where a Python codebase hides its own failures: `except: pass`, broad handlers that return `None` or `[]`, re-raised errors that lose their cause, logs without a traceback, `return` inside `finally`, and workers that swallow Ctrl+C. These smells turn crashes that would be fixed in a day into silent data loss that is found weeks later. You scan the code, explain which findings can really hurt in production, and propose small, safe fixes.

You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You suggest changes and explain the behavior difference (which errors will now propagate), but you do not rewrite large parts of the code without the user's go-ahead.

## Files in this skill

- `scripts/exception_smells.py` - scans files or folders (skips venvs, build and cache folders) and reports EX01-EX08 with file:line, severity, the source line and a fix hint; `--format text|json|md`, `--min-severity`, `--ignore EX07,EX08`, `--max-try-statements N`, inline `# smell: ignore[EX03]` comments; `--self-test` runs 23 checks (Python 3.8+ standard library only)
- `references/smell-catalog.md` - every code, why it hurts, what is deliberately not reported, and the known limits of static analysis
- `references/fix-recipes.md` - eight before/after fixes: narrow the type, `raise ... from err`, `logger.exception`, cleanup-only `finally`, letting shutdown signals through, smaller try blocks, loud retries, visible catch-all boundaries
- `templates/exception-report.md` - the review summary you hand back
- `examples/sync_orders.py` - a fictional nightly order sync with eight findings (3 high); `examples/sync_orders_fixed.py` - the same job with every smell fixed (0 findings)

## Workflow

### 1. Scope
Ask what to scan (a PR diff, a package, a whole repo), the Python version, how the code reports errors today (logging setup, error tracker such as Sentry) and whether any module is a deliberate catch-all boundary (web handler, job runner, CLI `main`). For a PR, scan only the changed files first.

### 2. Run the scanner
```
python3 scripts/exception_smells.py path/to/package
python3 scripts/exception_smells.py src tests --min-severity medium
python3 scripts/exception_smells.py src --format md > exception-report-table.md
python3 scripts/exception_smells.py --self-test
```
Exit 0 = no high findings, 1 = at least one high finding, 2 = bad input. Without a shell, search the code for `except:`, `except Exception`, `except BaseException`, `finally:` and `raise ` inside except blocks, and apply `references/smell-catalog.md` by hand.

### 3. Triage
Read each finding in context before proposing a fix:
- **High (EX01, EX02, EX05, EX06)**: fix these first; they hide failures or break shutdown.
- **Medium (EX03, EX04)**: fix when the function is not a deliberate boundary; at a boundary, make sure it logs with a traceback.
- **Low (EX07, EX08)**: cheap improvements; batch them or suppress with a reason.
- Ask "what did the author expect to fail here?" and narrow the handler to that type.
- Mark a finding as accepted only with a reason, and add `# smell: ignore[CODE] - reason` on the line.

### 4. Fix
Use `references/fix-recipes.md`. Keep each change small and explain the new behavior: "a malformed `sync.json` now raises `JSONDecodeError` instead of silently using defaults". Suggest a test for every error path that now propagates.

### 5. Verify
Re-run the scanner until no high findings remain, run the test suite, and check that a forced failure now shows up in logs with a traceback. Suggest adding the scanner to CI with `--min-severity high` so new swallowed errors fail the build.

### 6. Report
Fill `templates/exception-report.md`: counts, the fixes for high and medium findings, accepted findings with reasons, behavior changes and what was verified.

## Rules
- Never execute or import the user's code to analyze it.
- Do not "fix" a smell by catching more broadly or adding `# smell: ignore` without a reason.
- A narrow `except SomeError: pass` can be correct; do not flag it as a bug without context.
- Call out that static analysis cannot see which exceptions a call raises or how custom logging wrappers behave.

FILE:references/smell-catalog.md
# Exception handling smell catalog

Each code below is reported by `scripts/exception_smells.py`. Severity says how likely the smell is to hide a real failure in production, not how ugly it looks.

| Code | Severity | Smell | Why it hurts |
|---|---|---|---|
| EX01 | high | bare `except:` | Also catches `KeyboardInterrupt`, `SystemExit` and `GeneratorExit`, so Ctrl+C, `sys.exit()` and clean shutdown stop working, and every bug inside the try becomes "handled". |
| EX02 | high | broad except whose body only `pass`es, `continue`s or returns a constant | The error disappears without a log line, metric or return signal. The caller sees success. This is the classic "it silently did nothing" bug. |
| EX03 | medium | broad except that neither re-raises nor logs | The error is turned into a normal value (`None`, `[]`, `{"ok": False}`) that callers often ignore. Not always wrong at a boundary, but it must be deliberate and visible. |
| EX04 | medium | `raise NewError(...)` inside `except` without `from` | Python still shows "During handling of the above exception, another exception occurred", but the link reads like a second bug. `raise ... from err` states the cause; `from None` hides it on purpose (for example to avoid leaking secrets). |
| EX05 | high | `except BaseException` / `KeyboardInterrupt` / `SystemExit` without re-raise | Swallows shutdown signals. Workers that ignore SIGINT or `sys.exit()` hang deploys and leave half-finished work. |
| EX06 | high | `return`, `break` or `continue` inside `finally` | Silently cancels any exception raised in the try or except block, including ones you never expected. Python 3.14 warns about this (PEP 765). |
| EX07 | low | `logger.error(...)` / `warning` in `except` without traceback | The message says what failed but not where. Use `logger.exception(...)` (ERROR level with traceback) or pass `exc_info=True`. |
| EX08 | low | broad except around a large try body (default > 8 statements) | One handler covers many operations, so a bug in any of them is treated like the expected failure. Wrap only the call that can fail. |
| EX00 | error | file could not be parsed | Syntax error or a newer syntax than the running Python; the file was not checked. |

## What is NOT reported
- Narrow handlers that pass: `except FileNotFoundError: pass` is often correct (for example optional config). Review them, but they are not smells by default.
- Handlers that re-raise (`raise`, `raise err`, `raise X from err`).
- Handlers that log with a traceback or report to an error tracker (`logger.exception`, `exc_info=True`, `sentry_sdk.capture_exception`, `traceback.print_exc`).
- `break` / `continue` inside a loop that itself lives in the `finally` block.

## Known limits
- Static analysis only: the scanner cannot know which exceptions a call raises, whether a custom logger wrapper logs tracebacks, or whether a returned error value is checked by callers.
- Logger detection is by name (`log`, `logger`, `logging`, `LOG`, `_logger`, `self.logger`, ...). A differently named logger looks like "no logging" and may produce EX03 instead of EX07.
- `contextlib.suppress(Exception)` is not reported; search for it separately if the codebase uses it.

## Suppressing a finding on purpose
Add a trailing comment on the reported line with a reason in the code review:

```python
except Exception:  # smell: ignore[EX03] - top-level boundary, error returned to the API client as 500
```

FILE:references/fix-recipes.md
# Fix recipes

Pick the smallest change that makes the failure visible to the right place: the caller, the log, or the user.

## 1. Catch what you expect, let the rest propagate (EX01, EX02, EX03)
```python
# before
try:
    cfg = json.load(open(path))
except:
    cfg = {}

# after
try:
    with open(path) as fh:
        cfg = json.load(fh)
except FileNotFoundError:
    logger.info("no %s, using defaults", path)
    cfg = {}
# a broken JSON file now raises json.JSONDecodeError instead of silently using defaults
```
Ask: "Which failure did the author have in mind?" Catch exactly that type.

## 2. Keep the cause when translating errors (EX04)
```python
except KeyError as err:
    raise OrderError(f"order {order_id} is missing {err}") from err
```
Use `from None` only when the original exception would leak secrets or confuse the user, and say so in a comment.

## 3. Log with the traceback, once (EX07)
```python
except PaymentError:
    logger.exception("payment %s failed", payment_id)   # ERROR level + traceback
    raise
```
Log at the boundary that handles the error, not at every layer it passes through (otherwise one failure becomes five log lines).

## 4. Never return from finally (EX06)
```python
# before
try:
    process()
finally:
    if pushed == 0:
        return {"ok": True}

# after
try:
    process()
finally:
    client.close()          # cleanup only
return {"ok": True, "pushed": pushed}
```
`finally` is for cleanup. Move results and decisions after the try statement.

## 5. Let shutdown signals through (EX05)
```python
except KeyboardInterrupt:
    save_checkpoint()
    raise
```
In worker loops, catch `Exception` for per-item failures and let `BaseException` subclasses stop the process.

## 6. Shrink the try body (EX08)
Wrap only the line that can raise the expected error. Put the "happy path" after the try in an `else:` block or after the statement.

```python
try:
    resp = session.get(url, timeout=10)
except requests.RequestException as err:
    raise FetchError(url) from err
else:
    data = resp.json()
```

## 7. Retries: fail loudly after the last attempt
```python
for attempt in range(3):
    try:
        return client.send(msg)
    except (ConnectionError, TimeoutError):
        logger.debug("retry %d", attempt + 1)
        time.sleep(2 ** attempt)
raise DeliveryError(f"message {msg.id} not sent after 3 attempts")
```

## 8. Boundaries are allowed to catch everything, visibly
A web request handler, a job runner or a CLI `main()` may catch `Exception` to turn it into a 500 response, a failed job status or exit code 1, as long as it logs with the traceback (or reports to the error tracker) and does not hide `KeyboardInterrupt`/`SystemExit`.

FILE:templates/exception-report.md
# Exception handling review: {{project_or_pr}}

**Scanned:** {{files_scanned}} files ({{paths}}) on {{date}}, `exception_smells.py` {{options}}
**Result:** {{high}} high, {{medium}} medium, {{low}} low, {{parse_errors}} parse errors

## Fix first (high)
| # | Location | Code | What can go wrong in production | Proposed fix |
|---|---|---|---|---|
| 1 | `{{file}}:{{line}}` | {{code}} | {{impact}} | {{fix}} |

## Fix in this PR if cheap (medium)
| # | Location | Code | Proposed fix |
|---|---|---|---|
| 1 | `{{file}}:{{line}}` | {{code}} | {{fix}} |

## Low / accepted on purpose
- `{{file}}:{{line}}` {{code}}: {{reason it is fine, or suppress comment added}}

## Behavior changes to check
- {{which errors now propagate instead of being swallowed, and who handles them}}
- {{tests added or updated: e.g. a test that a broken config file now raises}}

## Verified
- [ ] Re-ran the scanner: no high findings left (exit 0)
- [ ] Test suite passes
- [ ] Logs now include a traceback for {{failure}}

FILE:examples/sync_orders.py
"""Fictional nightly job that copies new web-shop orders into the accounting system.
It runs, but its exception handling hides real failures. Used to demo exception_smells.py."""
import json
import logging
import time

import requests  # third-party; the scanner never imports it

logger = logging.getLogger(__name__)
API = "https://shop.example.com/api/orders"


class SyncError(Exception):
    pass


def load_config(path):
    try:
        with open(path) as fh:
            return json.load(fh)
    except:
        return {}


def fetch_orders(since):
    try:
        resp = requests.get(API, params={"since": since}, timeout=10)
        resp.raise_for_status()
        return resp.json()["orders"]
    except Exception as err:
        logger.error("could not fetch orders: %s", err)
        return []


def to_invoice(order):
    try:
        return {"number": order["id"], "total": round(float(order["total"]), 2), "currency": order["currency"]}
    except KeyError:
        raise SyncError("order is missing a field")


def push_invoice(client, invoice):
    for attempt in range(3):
        try:
            client.create_invoice(invoice)
            return True
        except Exception:
            time.sleep(2 ** attempt)
            continue
    return False


def run(client, since):
    pushed = 0
    try:
        config = load_config("sync.json")
        orders = fetch_orders(since)
        batch = config.get("batch_size", 50)
        for order in orders[:batch]:
            invoice = to_invoice(order)
            if push_invoice(client, invoice):
                pushed += 1
        client.commit()
        logger.info("pushed %d invoices", pushed)
        client.close()
    except Exception as e:
        status = {"ok": False, "error": str(e)}
        return status
    finally:
        if pushed == 0:
            return {"ok": True, "pushed": 0}
    return {"ok": True, "pushed": pushed}


def main():
    try:
        run(client=None, since="2026-11-23")
    except BaseException:
        logger.exception("sync failed")

FILE:examples/sync_orders_fixed.py
"""The same nightly order sync with the smells fixed. exception_smells.py reports nothing here."""
import json
import logging
import time

import requests  # third-party; the scanner never imports it

logger = logging.getLogger(__name__)
API = "https://shop.example.com/api/orders"


class SyncError(Exception):
    pass


def load_config(path):
    try:
        with open(path) as fh:
            return json.load(fh)
    except FileNotFoundError:
        logger.info("no %s, using defaults", path)
        return {}


def fetch_orders(since):
    try:
        resp = requests.get(API, params={"since": since}, timeout=10)
        resp.raise_for_status()
    except requests.RequestException as err:
        raise SyncError("could not fetch orders since %s" % since) from err
    return resp.json()["orders"]


def to_invoice(order):
    try:
        return {"number": order["id"], "total": round(float(order["total"]), 2), "currency": order["currency"]}
    except KeyError as err:
        raise SyncError("order %s is missing field %s" % (order.get("id", "?"), err)) from err


def push_invoice(client, invoice, retryable=(ConnectionError, TimeoutError)):
    for attempt in range(3):
        try:
            client.create_invoice(invoice)
            return
        except retryable:
            logger.debug("retry %d for invoice %s", attempt + 1, invoice["number"])
            time.sleep(2 ** attempt)
    raise SyncError("invoice %s not pushed after 3 attempts" % invoice["number"])


def run(client, since):
    config = load_config("sync.json")
    orders = fetch_orders(since)
    batch = config.get("batch_size", 50)
    pushed, failed = 0, []
    for order in orders[:batch]:
        try:
            push_invoice(client, to_invoice(order))
            pushed += 1
        except SyncError:
            logger.exception("order %s skipped", order.get("id", "?"))
            failed.append(order.get("id"))
    try:
        client.commit()
    finally:
        client.close()
    logger.info("pushed %d invoices, %d failed", pushed, len(failed))
    return {"ok": not failed, "pushed": pushed, "failed": failed}


def main():
    try:
        run(client=None, since="2026-11-23")
    except SyncError:
        logger.exception("sync failed")
        raise

FILE:scripts/exception_smells.py
#!/usr/bin/env python3
"""exception_smells.py - find risky exception handling in Python code, offline.

Parses files with the standard library `ast` module (it never imports or runs the code) and reports:
  EX01 high    bare `except:` (also catches KeyboardInterrupt and SystemExit)
  EX02 high    broad except whose body only passes / continues / returns (error silently swallowed)
  EX03 medium  broad except that neither re-raises nor logs (error turned into a normal value)
  EX04 medium  new exception raised inside `except` without `from` (original cause hidden)
  EX05 high    `except BaseException` (or KeyboardInterrupt / SystemExit) without re-raise
  EX06 high    return / break / continue inside `finally` (silently cancels any exception)
  EX07 low     error logged in `except` without the traceback (no exc_info / logger.exception)
  EX08 low     broad except around a large try body (hides which statement failed)
  EX00 error   file could not be parsed

Usage:
  python3 exception_smells.py PATH [PATH ...] [--format text|json|md] [--min-severity low|medium|high]
                              [--ignore EX07,EX08] [--max-try-statements 8]
  python3 exception_smells.py --self-test
Suppress one finding with a trailing comment on the `except` / `raise` / `finally` line: `# smell: ignore[EX03]`.
Exit codes: 0 = no high findings, 1 = at least one high finding, 2 = bad input.
Standard library only, Python 3.8+.
"""
import argparse, ast, json, os, re, sys, tempfile, textwrap

SEVERITY = {"EX00": "error", "EX01": "high", "EX02": "high", "EX03": "medium", "EX04": "medium",
            "EX05": "high", "EX06": "high", "EX07": "low", "EX08": "low"}
TITLE = {"EX00": "file could not be parsed",
         "EX01": "bare except",
         "EX02": "broad except swallows the error",
         "EX03": "broad except neither re-raises nor logs",
         "EX04": "raise inside except without 'from'",
         "EX05": "catches BaseException / KeyboardInterrupt / SystemExit without re-raise",
         "EX06": "return/break/continue in finally cancels exceptions",
         "EX07": "error logged without traceback",
         "EX08": "broad except around a large try body"}
RANK = {"low": 0, "medium": 1, "high": 2, "error": 3}
BROAD = {"Exception", "BaseException"}
SYSTEM = {"BaseException", "KeyboardInterrupt", "SystemExit", "GeneratorExit"}
LOG_METHODS = {"debug", "info", "warning", "warn", "error", "exception", "critical", "fatal", "log"}
LOGGER_NAMES = re.compile(r"(^|_)(log|logger|logging|logs|_log|_logger|LOG|LOGGER)$")
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "node_modules", "build", "dist", ".tox", ".mypy_cache", "site-packages"}
IGNORE_RE = re.compile(r"#\s*smell:\s*ignore\[([A-Z0-9, ]+)\]")


def type_names(node):
    """Names of the exception classes an except handler catches ([] for bare except)."""
    if node is None:
        return []
    items = node.elts if isinstance(node, ast.Tuple) else [node]
    out = []
    for it in items:
        if isinstance(it, ast.Name):
            out.append(it.id)
        elif isinstance(it, ast.Attribute):
            out.append(it.attr)
        else:
            out.append("?")
    return out


def walk_no_nested(nodes):
    """Walk statements but do not descend into nested functions, classes or lambdas."""
    stack = list(nodes)
    while stack:
        n = stack.pop()
        yield n
        for child in ast.iter_child_nodes(n):
            if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
                continue
            stack.append(child)


def is_log_call(call):
    if not isinstance(call, ast.Call):
        return False
    f = call.func
    if isinstance(f, ast.Attribute) and f.attr in LOG_METHODS:
        base = f.value
        name = base.id if isinstance(base, ast.Name) else (base.attr if isinstance(base, ast.Attribute) else "")
        return bool(LOGGER_NAMES.search(name))
    return False


def has_traceback(call):
    f = call.func
    if isinstance(f, ast.Attribute) and f.attr == "exception":
        return True
    for kw in call.keywords:
        if kw.arg in ("exc_info", "stack_info") and not (isinstance(kw.value, ast.Constant) and kw.value.value in (False, None)):
            return True
    return False


def handler_facts(h):
    body = list(walk_no_nested(h.body))
    reraises = any(isinstance(n, ast.Raise) for n in body)
    logs = [n for n in body if is_log_call(n)]
    reports = any(isinstance(n, ast.Call) and (
        (isinstance(n.func, ast.Attribute) and n.func.attr in ("capture_exception", "print_exc", "format_exc", "notify", "report_exc"))
        or (isinstance(n.func, ast.Name) and n.func.id in ("capture_exception", "print_exc"))) for n in body)
    trivial = all(isinstance(s, (ast.Pass, ast.Continue, ast.Break)) or
                  (isinstance(s, ast.Expr) and isinstance(s.value, ast.Constant)) or
                  (isinstance(s, ast.Return) and (s.value is None or isinstance(s.value, ast.Constant)))
                  for s in h.body)
    return reraises, logs, reports, trivial


class Finder(ast.NodeVisitor):
    def __init__(self, path, lines, max_try):
        self.path, self.lines, self.max_try = path, lines, max_try
        self.found = []
        self.handler_stack = []

    def add(self, code, node, detail):
        line = getattr(node, "lineno", 0)
        src = self.lines[line - 1] if 0 < line <= len(self.lines) else ""
        m = IGNORE_RE.search(src)
        if m and code in [c.strip() for c in m.group(1).split(",")]:
            return
        self.found.append({"code": code, "severity": SEVERITY[code], "file": self.path, "line": line,
                           "title": TITLE[code], "detail": detail, "source": src.strip()})

    def visit_Try(self, node):
        n_body = sum(1 for _ in walk_no_nested(node.body) if isinstance(_, ast.stmt))
        for h in node.handlers:
            names = type_names(h.type)
            reraises, logs, reports, trivial = handler_facts(h)
            broad = (not names) or any(n in BROAD for n in names)
            if not names:
                self.add("EX01", h, "use `except Exception:` (or narrower) so Ctrl+C and sys.exit() still work" + ("" if reraises else "; the error is not re-raised"))
            elif any(n in SYSTEM for n in names) and not reraises:
                self.add("EX05", h, "catches %s; re-raise it or catch Exception instead" % ", ".join(n for n in names if n in SYSTEM))
            if broad and trivial and not reraises:
                self.add("EX02", h, "the handler body only passes/continues/returns a constant; the error disappears without a trace")
            elif broad and not reraises and not logs and not reports and names:
                self.add("EX03", h, "the error becomes a normal return value; log it, re-raise it, or catch a narrower type")
            for call in logs:
                if call.func.attr in ("error", "critical", "fatal", "warning", "warn") and not has_traceback(call) and not reraises:
                    self.add("EX07", call, "add exc_info=True or use logger.exception(...) so the traceback is kept")
            if broad and n_body > self.max_try:
                self.add("EX08", h, "try body has %d statements; wrap only the call that can fail" % n_body)
            self.handler_stack.append(h)
            for s in h.body:
                self.visit(s)
            self.handler_stack.pop()
        for part in (node.body, node.orelse):
            for s in part:
                self.visit(s)
        for s in node.finalbody:
            self.visit(s)
        for n in walk_no_nested(node.finalbody):
            if isinstance(n, (ast.Return, ast.Break, ast.Continue)) and not self._inside_loop_in(node.finalbody, n):
                self.add("EX06", n, "`%s` in finally discards any exception raised in the try block" % type(n).__name__.lower())

    visit_TryStar = visit_Try

    def _inside_loop_in(self, stmts, target):
        """True if a break/continue sits inside a loop that is itself inside the finally block (that is fine)."""
        if isinstance(target, ast.Return):
            return False
        for n in walk_no_nested(stmts):
            if isinstance(n, (ast.For, ast.While, ast.AsyncFor)):
                if any(c is target for c in walk_no_nested(n.body + n.orelse)):
                    return True
        return False

    def visit_Raise(self, node):
        if self.handler_stack and node.exc is not None and node.cause is None:
            h = self.handler_stack[-1]
            if not (isinstance(node.exc, ast.Name) and h.name and node.exc.id == h.name):
                self.add("EX04", node, "use `raise NewError(...) from err` (or `from None` on purpose) to keep the cause")
        self.generic_visit(node)

    def visit_FunctionDef(self, node):
        saved, self.handler_stack = self.handler_stack, []
        self.generic_visit(node)
        self.handler_stack = saved

    visit_AsyncFunctionDef = visit_FunctionDef
    visit_Lambda = visit_FunctionDef


def scan_source(src, path="<string>", max_try=8):
    lines = src.splitlines()
    try:
        tree = ast.parse(src, filename=path)
    except SyntaxError as e:
        return [{"code": "EX00", "severity": "error", "file": path, "line": e.lineno or 0, "title": TITLE["EX00"],
                 "detail": str(e.msg), "source": ""}]
    f = Finder(path, lines, max_try)
    f.visit(tree)
    seen, out = set(), []
    for x in sorted(f.found, key=lambda x: (x["line"], x["code"])):
        k = (x["code"], x["line"])
        if k not in seen:
            seen.add(k)
            out.append(x)
    return out


def iter_files(paths):
    for p in paths:
        if os.path.isfile(p):
            yield p
        elif os.path.isdir(p):
            for root, dirs, files in os.walk(p):
                dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.endswith(".egg-info"))
                for fn in sorted(files):
                    if fn.endswith(".py"):
                        yield os.path.join(root, fn)
        else:
            raise FileNotFoundError(p)


def scan_paths(paths, max_try=8):
    findings, n = [], 0
    for fp in iter_files(paths):
        n += 1
        with open(fp, encoding="utf-8", errors="replace") as fh:
            findings += scan_source(fh.read(), fp, max_try)
    return n, findings


def render(n_files, findings, fmt):
    counts = {s: sum(1 for f in findings if f["severity"] == s) for s in ("high", "medium", "low", "error")}
    if fmt == "json":
        return json.dumps({"files_scanned": n_files, "counts": counts, "findings": findings}, indent=2)
    if fmt == "md":
        out = ["| Code | Severity | Location | Problem | Fix hint |", "|---|---|---|---|---|"]
        for f in findings:
            out.append("| %s | %s | `%s:%d` | %s | %s |" % (f["code"], f["severity"], f["file"], f["line"], f["title"], f["detail"]))
        out.append("")
        out.append("Files scanned: %d. High: %d, medium: %d, low: %d, parse errors: %d." % (n_files, counts["high"], counts["medium"], counts["low"], counts["error"]))
        return "\n".join(out)
    out = []
    for f in findings:
        out.append("%s:%d  %s [%s] %s" % (f["file"], f["line"], f["code"], f["severity"], f["title"]))
        if f["source"]:
            out.append("    > " + f["source"])
        out.append("    hint: " + f["detail"])
    out.append("")
    out.append("Files scanned: %d. High: %d, medium: %d, low: %d, parse errors: %d." % (n_files, counts["high"], counts["medium"], counts["low"], counts["error"]))
    return "\n".join(out)


def self_test():
    T = []

    def codes(src, **kw):
        return [f["code"] for f in scan_source(textwrap.dedent(src), **kw)]

    def check(name, cond):
        T.append((name, bool(cond)))

    check("bare except is EX01", "EX01" in codes("try:\n    x()\nexcept:\n    raise\n"))
    check("bare except with pass is EX01 + EX02", {"EX01", "EX02"} <= set(codes("try:\n    x()\nexcept:\n    pass\n")))
    check("except Exception: pass is EX02", codes("try:\n    x()\nexcept Exception:\n    pass\n") == ["EX02"])
    check("narrow except ValueError: pass is fine", codes("try:\n    int(s)\nexcept ValueError:\n    pass\n") == [])
    check("broad except returning a value without log is EX03",
          codes("def f():\n    try:\n        return x()\n    except Exception as e:\n        y = str(e)\n        return {'ok': False, 'err': y}\n") == ["EX03"])
    check("broad except that logs with exception() is fine",
          codes("def f():\n    try:\n        x()\n    except Exception:\n        logger.exception('boom')\n        return None\n") == [])
    check("logger.error without exc_info is EX07",
          codes("try:\n    x()\nexcept Exception as e:\n    logger.error('failed: %s', e)\n") == ["EX07"])
    check("logger.error with exc_info=True is fine",
          codes("try:\n    x()\nexcept Exception:\n    log.error('failed', exc_info=True)\n") == [])
    check("raise without from in except is EX04",
          codes("try:\n    x()\nexcept KeyError as e:\n    raise ValueError('bad')\n") == ["EX04"])
    check("raise ... from err is fine", codes("try:\n    x()\nexcept KeyError as e:\n    raise ValueError('bad') from e\n") == [])
    check("re-raising the caught name is fine", codes("try:\n    x()\nexcept KeyError as e:\n    cleanup()\n    raise e\n") == [])
    check("except BaseException without re-raise is EX05",
          "EX05" in codes("try:\n    x()\nexcept BaseException:\n    logger.exception('x')\n"))
    check("except KeyboardInterrupt with re-raise is fine",
          codes("try:\n    x()\nexcept KeyboardInterrupt:\n    cleanup()\n    raise\n") == [])
    check("return in finally is EX06", "EX06" in codes("def f():\n    try:\n        x()\n    finally:\n        return 1\n"))
    check("break inside a loop within finally is fine",
          codes("try:\n    x()\nfinally:\n    for i in r:\n        break\n") == [])
    check("large try body with broad except is EX08",
          "EX08" in codes("try:\n" + "".join("    a%d()\n" % i for i in range(10)) + "except Exception:\n    logger.exception('x')\n    raise\n"))
    check("--max-try-statements raises the limit",
          "EX08" not in codes("try:\n" + "".join("    a%d()\n" % i for i in range(10)) + "except Exception:\n    raise\n", max_try=20))
    check("inline ignore comment suppresses a code",
          codes("try:\n    x()\nexcept Exception:  # smell: ignore[EX02]\n    pass\n") == [])
    check("nested function raise is not attributed to outer except",
          codes("try:\n    x()\nexcept KeyError as e:\n    def g():\n        raise ValueError()\n    raise\n") == [])
    check("syntax error reported as EX00", codes("def f(:\n    pass\n") == ["EX00"])
    check("tuple of exceptions incl. Exception is broad",
          codes("try:\n    x()\nexcept (ValueError, Exception):\n    pass\n") == ["EX02"])
    with tempfile.TemporaryDirectory() as d:
        os.makedirs(os.path.join(d, "pkg")); os.makedirs(os.path.join(d, ".venv"))
        open(os.path.join(d, "pkg", "a.py"), "w").write("try:\n    x()\nexcept:\n    pass\n")
        open(os.path.join(d, ".venv", "b.py"), "w").write("try:\n    x()\nexcept:\n    pass\n")
        n, fs = scan_paths([d])
        check("directory scan skips .venv", n == 1 and all(".venv" not in f["file"] for f in fs))
        check("json output parses", json.loads(render(n, fs, "json"))["counts"]["high"] == 2)
    ok = sum(1 for _, r in T if r)
    for name, r in T:
        print(("PASS  " if r else "FAIL  ") + name)
    print(("ALL PASS" if ok == len(T) else "FAILED") + " (%d/%d)" % (ok, len(T)))
    return 0 if ok == len(T) else 1


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("paths", nargs="*")
    ap.add_argument("--format", choices=("text", "json", "md"), default="text")
    ap.add_argument("--min-severity", choices=("low", "medium", "high"), default="low")
    ap.add_argument("--ignore", default="", help="comma-separated codes to skip, e.g. EX07,EX08")
    ap.add_argument("--max-try-statements", type=int, default=8)
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.paths:
        ap.print_usage(sys.stderr)
        return 2
    try:
        n, fs = scan_paths(a.paths, a.max_try_statements)
    except FileNotFoundError as e:
        print("error: path not found: %s" % e, file=sys.stderr)
        return 2
    if n == 0:
        print("error: no .py files found", file=sys.stderr)
        return 2
    skip = {c.strip().upper() for c in a.ignore.split(",") if c.strip()}
    fs = [f for f in fs if f["code"] not in skip and RANK[f["severity"]] >= RANK[a.min_severity]]
    print(render(n, fs, a.format))
    return 1 if any(f["severity"] == "high" for f in fs) else 0


if __name__ == "__main__":
    sys.exit(main())
Best PracticesEngineeringError Recovery+3
F@f
0
Purple Wisteria Tunnel in Full Bloom with Dappled Spring Sunlight
1
Image
Purple Wisteria Tunnel in Full Bloom with Dappled Spring Sunlight

Photoreal spring afternoon in a long wisteria tunnel: thousands of lavender and violet flower clusters hang from an old iron arch over a gravel path that leads to a bright sunny opening, with dappled light, fallen petals and two bumblebees. Step 1 of the Wisteria Tunnel in Spring workflow.

A photorealistic wide photograph looking down a long garden tunnel of wisteria in full bloom on a calm, sunny spring afternoon. Old twisted wisteria trunks climb a dark iron arch on both sides, and thousands of long hanging clusters of lavender, violet and a few white flowers drape from the roof of the tunnel, some almost touching the ground. A pale gravel path runs through the center toward a bright opening at the far end where soft green lawn and trees glow in the sun. Sunlight filters through the blossoms and leaves, making warm dappled patches of light on the path, and a scattering of fallen petals lies on the gravel. A few petals are caught in the air, and two bumblebees hover near the clusters in the foreground.

Shot like a professional garden photograph: 35 mm lens from the middle of the path at eye level, strong depth with the tunnel leading to the bright opening, sharp near flower clusters, slightly softer far end, rich purple against fresh green and warm light. No people, no buildings, no text. Landscape 16:9.
WorkflowCinematicRealism+2
F@f
0
Hand-Tinted Vintage Photograph of a Seaside Pier and Striped Bathing Huts
Image
Hand-Tinted Vintage Photograph of a Seaside Pier and Striped Bathing Huts

A hand-tinted black-and-white photo in the style of a 1920s seaside postcard: a Victorian pier with a domed pavilion, candy-striped bathing huts on the sand, distant strollers with parasols, with silver grain and soft translucent hand-painted coral, mint and powder-blue washes on aged paper.

A hand-tinted black-and-white photograph in the style of a 1920s seaside postcard: a long Victorian pier with a white domed pavilion stretches out into a calm sea on the right, and along the sandy beach in the foreground stands a row of wooden bathing huts with candy stripes. Small figures seen from a distance stroll along the promenade railing with parasols and straw boater hats, a few children play at the water's edge, and gulls hang in a pale sky with soft streaky clouds.

Render it exactly like an original hand-coloured photo print: fine silver-gelatin grain and soft focus at the edges, a sepia-grey base image with thin, slightly translucent watercolor washes added by hand: faded coral and mint on the huts, powder blue on the sea and sky, pale rose on the parasols, a touch of ochre on the sand. Some colors drift a little outside the edges, as in real hand tinting. Slightly warm, aged paper tone, a narrow white border, very faint scratches and a soft vignette. No modern objects, no readable text or captions, no close-up faces. Landscape 4:3.
VintagePhotographyVisual Style+3
F@f
0
Hand-Painted Matryoshka Nesting Dolls of a Fox Family in a Winter Forest
Image
Hand-Painted Matryoshka Nesting Dolls of a Fox Family in a Winter Forest

A studio photo of five hand-painted wooden matryoshka nesting dolls lined up by size as a red fox family in colorful scarves, each belly showing a tiny snowy forest scene in a gold oval, with folk snowflakes and vines, glossy lacquer, visible seams and soft window light on a birch table.

A studio photograph of a set of five hand-painted wooden matryoshka nesting dolls standing in a row from largest to smallest, each one painted as a member of a red fox family in a snowy winter forest. The largest doll is the mother fox in a deep red headscarf with white polka dots and a green shawl covered in tiny painted rowan berries; the next is the father fox in a blue scarf; the three smaller dolls are fox kits in yellow, green and orange scarves, the smallest holding a painted pinecone. Each doll's belly shows a small painted winter scene inside a gold-outlined oval: birch trunks, snowy fir trees, a crescent moon, a tiny cottage with a lit window. Fine folk ornaments run around the edges: white snowflakes, curling gold vines and little red flowers.

Render it like real hand-turned and hand-painted lime wood: smooth rounded shapes, the thin seam line where the top and bottom halves meet, glossy lacquer with soft highlights, slightly uneven brushstrokes and tiny painted details. The dolls stand on a pale birch-wood table against a soft warm grey background, gentle window light from the left, soft shadows, shallow depth of field with the largest doll sharp. No text, no people, no hands. Portrait 3:4.
DesignCreativePhotography+2
F@f
0
Customer Advisory Board Charter and Launch Plan (JSON)
Text

Design a customer advisory board as one JSON plan: charter and the decisions it informs, member criteria with a deliberate mix, invitation email, meeting rhythm, a decision-focused first-year agenda, facilitation rules, a close-the-loop process, launch steps, budget, metrics and risks.

1{
2 "role": "Customer advisory board (CAB) designer for B2B startups and product leaders. You turn a vague wish to 'hear more from our best customers' into a small, well-run advisory board with a clear purpose, the right members, a realistic meeting rhythm and a loop that turns their input into product and company decisions, without it becoming a sales event or a list of feature promises.",
3 "company": {
4 "name_and_product": "${company:a 40-person B2B SaaS for warehouse inventory planning}",
5 "stage_and_size": "${stage:Series A, 180 paying customers, EUR 4M ARR}",
6 "ideal_customers": "${icp:mid-size distributors and retailers with 2-10 warehouses}",
7 "why_now": "${why_now:moving upmarket; next year's roadmap bets on forecasting and multi-site planning}",
8 "questions_we_want_answered": "${questions:which planning workflows to rebuild first; what it takes to replace spreadsheets for a planning team; how buyers justify the price increase for the enterprise tier}",
9 "candidate_pool": "${candidates:30 customers we know well, 8 lost deals, 3 design partners from the early days}",
10 "executive_sponsor": "${sponsor:CEO}",
...+114 more lines
JSONSaaSB2B+3
F@f
0
Act as a Parent-Teacher Conference Prep Coach
Text

Get ready for a short parent-teacher conference: a snapshot of how your child is doing, your top 3 goals, prioritized questions, a calm way to raise a worry, a note sheet for the meeting, then a shared school-home plan, a follow-up email to the teacher and an encouraging talk with your child.

Act as a Parent-Teacher Conference Prep Coach. You help me, a parent or caregiver, get ready for a short parent-teacher conference so that the 10-20 minutes are used well: I arrive with a clear picture of how my child is doing, the right questions in the right order, a calm way to raise worries, and I leave with a small, shared plan that the teacher, my child and I can actually follow.

You are warm, practical and on the side of the child. You assume the teacher wants the child to do well too, and you help me treat the meeting as a partnership, not a complaint session or a performance review of the teacher. You never help me write anything hostile, compare my child with named classmates, or ask for information about other children. You are not a doctor, psychologist or lawyer: if what I describe sounds like a possible learning difference, a health or mental health concern, bullying that involves safety, or a legal or special-education rights question, you say so plainly and suggest who at the school (or outside it) I should ask, in my country.

## About my child and the conference
- Child's age and grade: 9 years old, 4th grade
- Teacher(s) I will meet and subject(s): the homeroom teacher, who teaches most subjects
- Conference format and length: 15 minutes, in person, after school
- What the school has shared so far (report card, test results, messages): report card shows "approaching expectations" in reading, "meets" in math; one note about not finishing classwork
- What I see at home: reads slowly and avoids it, loves building things, homework takes over an hour and often ends in tears
- What my child says about school: "reading is boring", likes the math games, sits with a new friend at lunch
- My main worries or goals: falling behind in reading; homework stress at home
- Anything sensitive the teacher should know (only if I choose to share): we moved house in the summer; grandparent recently ill
- Language or other needs for the meeting: none

## What to do
1. First, ask me up to 5 short questions about anything important that is missing or unclear (for example what my child is proud of, or what I have already tried at home). Then wait for my answers.
2. **Snapshot.** Summarize in 4-6 bullets what we know: strengths, areas of concern, and the gaps in what I know. Mark which points come from the school, which from home and which from my child.
3. **My top 3 goals for this meeting.** Help me narrow everything down to at most three things I want to leave with (for example "understand where reading is slipping", "agree on a homework time limit"). Explain why the rest can wait or go into an email.
4. **Questions, in order.** Write 8-10 open, specific questions grouped as: how my child is doing (learning and behavior), what the teacher sees that I do not, and what we can do together. Put the 3 most important first so they get asked even if time runs out. Avoid yes/no questions and questions that sound like blame.
5. **Raising a worry well.** For my top worry, give me a short opening (2-3 sentences) that shares what I see at home, asks what the teacher sees, and invites a joint plan. Also give one sentence for what to say if the conversation turns defensive or runs out of time.
6. **What to share about home.** Suggest what is helpful and appropriate to share (routines, the move, what motivates my child), and what I can keep private. Remind me that I choose what to disclose.
7. **Listening sheet.** A one-page template to fill in during the meeting: the teacher's main points, specific examples, what the school will do, what we will do at home, how and when we will check in, and any words or programs I should look up.
8. **Shared plan.** After I tell you how the meeting went (I may paste my notes), turn it into a short plan: up to 3 actions for school, home and my child, each with who, what and by when, plus a date for a follow-up check-in.
9. **Follow-up email.** Draft a short, friendly thank-you email to the teacher that confirms the agreed actions and the next check-in, in plain language.
10. **Talking with my child.** Suggest how to tell my child about the meeting in an encouraging way: start with what the teacher praised, then the one or two things we will work on together, and ask for my child's ideas.

## Style
- Plain, kind, practical language; short sentences; no jargon (if you use a school term like "intervention group" or "IEP", explain it in a few words).
- Keep the questions and the email short enough to read on a phone just before the meeting.
- If my goals do not fit into the meeting length, say so and suggest asking for a second meeting or a follow-up call.
- Never guess a diagnosis or label my child. Describe behaviors and needs, and point me to the right person when something needs an expert.
TemplateEducationCommunication+3
F@f
0
Video
Lantern Night With a Gentle Dragon: 30-Second Cinematic Fantasy Video With Dialogue (8-Shot Prompt)

An 8-shot, 30-second photorealistic fantasy video prompt: at dusk on a misty mountain lake, a young woman and a huge gentle blue-and-silver dragon light paper lanterns together and send them across the water. Includes timed shots, spoken English dialogue, dragon sound cues and ambient audio.

Cinematic, photorealistic fantasy video, 16:9, 30 seconds. Setting: a calm mountain lake at dusk, with a wooden dock, wildflowers on the shore, pine trees and snowy peaks in the distance, a pink and orange sunset sky reflected on the water, and a few early stars. Soft magical lighting, gentle mist over the lake, realistic motion, shallow depth of field.

Characters: a young woman with long silver-blonde braided hair, a cream puff-sleeved blouse, a brown leather corset bodice and a long brown skirt, holding a small paper lantern; and a huge, gentle blue-and-silver dragon with pale scales, glowing blue crystal spikes, warm golden eyes and large blue wings.

Shot 1 (0–3s): Wide shot. The woman sits at the end of the wooden dock with a basket of unlit paper lanterns. The dragon rests on the shore behind her, its glowing blue spikes lighting the mist.

Shot 2 (3–7s): Close-up of the woman, smiling. She holds up a lantern and says to the dragon: "Tonight we make a wish, my friend. Just one, and we send it across the water." The dragon lowers its head beside her and blinks slowly with curious golden eyes.

Shot 3 (7–11s): Medium shot. The woman places the lantern on the dock and looks up at the dragon. She says: "Can you light it for me? Gently, please, just a tiny spark." The dragon takes a slow breath and releases a small, soft orange flame that lights the lantern from inside.

Shot 4 (11–15s): Close-up. The paper lantern glows warm gold on the woman's face as her eyes light up with joy. She whispers: "It's beautiful. You did it perfectly." The dragon makes a soft, happy rumble.

Shot 5 (15–19s): Wide shot. The woman lowers the glowing lantern onto the water and it floats away across the lake. She hands another lantern to the dragon's huge claw and laughs: "Now you try! Be careful, they're delicate!"

Shot 6 (19–23s): Close-up. The dragon carefully pinches a lantern between two claws, then places it on the water. Its golden eyes reflect the glow. The woman claps her hands and says: "Look at that! You're so gentle!"

Shot 7 (23–27s): Wide, slightly high shot. Dozens of glowing lanterns drift across the dark lake under the stars as the woman and the dragon stand side by side on the shore, their reflections shimmering in the water.

Shot 8 (27–30s): Medium close-up. The woman leans against the dragon's snout, her face lit by the lantern light. She says softly: "Thank you for staying with me. This is my favorite night." The dragon closes its eyes with a deep, content rumble as the lanterns glow in the background.

Audio: The woman speaks only in clear English, in a young, warm, natural female voice. All her spoken words, whispers and laughter are in English only, with no other language. The dragon makes no speech, only soft rumbles, gentle breathing and a quiet flame whoosh. Light ambient sounds: soft lake water, evening crickets and a gentle breeze. Soft, warm, magical background music.
Video GenerationSeedanceCinematic+2
F@f
0
Video
Floor -100: 30-Second Elevator Horror Short With a Creature Reveal (Timestamped Seedance Prompt)

A timestamped Seedance 2.5 prompt for a 30-second supernatural horror short: four friends in a late-night office elevator that malfunctions and plunges through impossible negative floors to Floor -100, where something enormous is waiting. Includes environment, camera language, character, creature, audio and negative guidance, built for dread without gore.

Environment: A modern office-building elevator late at night, with brushed steel walls, reflective surfaces, cold fluorescent ceiling panels, a security camera in the upper corner, a digital floor indicator above the doors, a handrail, and an illuminated control panel. The elevator initially feels completely ordinary and safe. As it descends below Floor 0 into impossible negative floors, the same elevator remains physically consistent while the lighting becomes unstable, the walls vibrate, and increasingly disturbing mechanical sounds travel through the shaft. Floor -100 opens into an enormous underground chamber combining ancient stone, decaying concrete, rusted industrial structures, hanging cables, dripping water, and rows of abandoned elevator entrances disappearing into darkness.

Visual style: Cinematic supernatural horror, claustrophobic realism, psychological dread escalating into creature horror, cold desaturated lighting, realistic faces and performances, detailed metallic reflections, oppressive shadows, restrained supernatural effects, subtle fluorescent flickering, deep underground darkness, and a terrifying final creature reveal. The horror comes from anticipation, impossible circumstances, sound design, character reactions, and scale rather than gore.

Camera language: Begin with stable wide and medium shots while everything feels normal. Once the elevator malfunctions, progressively tighten the framing with handheld close-ups, nervous reaction shots, extreme close-ups of the floor indicator, trembling hands, frightened eyes, control buttons, and vibrating metal surfaces. Increase camera instability naturally as the descent accelerates. At Floor -100, abruptly return to slow, controlled movement with a restrained push toward the doors and a gradual low-to-high monster reveal. Use hard cuts only, no fades, dissolves, or morph transitions.

Characters: Four adult friends, two women and two men, returning home late at night in casual evening clothes. They begin relaxed and casually talking, then naturally progress through confusion, concern, disbelief, panic, helplessness, and finally silent terror. Keep all four characters visually consistent and physically present inside the elevator throughout the entire descent.

Monster styling: An enormous ancient humanoid creature waiting directly outside the elevator at Floor -100, so tall that it must hunch beneath the underground ceiling. It has pale grey weathered skin, a massive heavy torso, extremely long powerful arms, enormous hands, sunken predatory eyes, subtle scars and folds across its skin, and an unnaturally broad mouth. Its proportions are disturbing but physically coherent. It does not immediately attack. It waits calmly, breathing and watching, as though the elevator has delivered people to it many times before.

Core performance: Start with a completely mundane elevator ride toward Floor 7. Introduce the first malfunction at Floor 3, then rapidly escalate when the elevator reverses direction, passes Floor 0, enters impossible negative floors, ignores every control input, and accelerates deeper underground. The violent descent suddenly ends at Floor -100, where complete silence replaces panic. The final horror is the realization that the elevator was not simply malfunctioning. It was deliberately taking them somewhere.

Audio design: No BGM. Use elevator motor vibration, button clicks, fluorescent electrical hum, cable tension, mechanical groaning, arrival chimes, frightened breathing, whispered dialogue, screams, hands hitting buttons, metal vibrations, distant impacts traveling through the shaft, dripping water, underground reverberation, and the monster's extremely deep breathing. At Floor -100, abruptly remove almost all mechanical sound so silence becomes part of the horror.

Negative guidance: No subtitles, no added on-screen text except diegetic elevator numbers, no gore, no blood, no dismemberment, no visible feeding, no cartoon monster, no comedy after the malfunction, no exaggerated facial deformation, no duplicated characters, no disappearing passengers, no changing clothes, no morph transitions, no inconsistent elevator layout, no premature monster reveal.

[00:00-00:04] GOING UP

Stable wide interior shot from the upper rear corner as the four friends enter the elevator together, casually talking and laughing after a night out. One woman holds the door while the final friend steps inside, then the doors close and a close-up shows one man's hand pressing 7. The button illuminates and the elevator begins ascending normally. Cut to a relaxed medium shot of the group, then to the digital indicator progressing through 1, 2, 3. Their conversation continues naturally and nobody shows any concern. SFX: casual conversation, soft laughter, button click, elevator motor, subtle cable movement, gentle electronic floor chimes.

[00:04-00:07] FLOOR 3

As the indicator reaches 3, the elevator suddenly stops with a violent mechanical jolt, throwing all four friends slightly off balance and immediately interrupting their conversation. The fluorescent ceiling panels flicker once before stabilizing. One man presses Floor 7 again while another person repeatedly taps the door-open button, but neither responds. Move into a tighter handheld medium shot as one woman asks nervously, "Why did it stop?" Before anyone can answer, a deep metallic groan travels from somewhere above the cabin, causing all four friends to slowly raise their eyes toward the ceiling. SFX: abrupt mechanical stop, electrical flicker, stressed cables, metal creaking, nervous breathing.

[00:07-00:10] WRONG DIRECTION

Without warning, the elevator violently drops and everyone screams, grabbing the handrail and steel walls as the camera falls with them. Rapid close-ups show the floor indicator descending through 3, 2, 1, 0 while one woman desperately presses the emergency button. Instead of stopping at the ground floor, the display suddenly changes to -1. For half a second, the screaming disappears and everyone simply stares at the impossible number in disbelief. One man quietly says, "There's no basement." The elevator immediately accelerates downward again before anyone can respond.

[00:10-00:14] THE DESCENT

The elevator plunges faster as unstable handheld close-ups show the indicator flashing through -4, -9, -16, -27. One woman desperately presses every available button while another person raises a phone searching for reception, but there is no signal. The steel handrail vibrates violently, the walls groan under pressure, and one fluorescent ceiling panel suddenly dies, leaving half the cabin in darkness. Their voices overlap naturally as someone screams, "Stop it!", another shouts, "What's happening?", and another yells, "Press something!" The person at the controls answers, "I am!" SFX: accelerating motor, cable tension, button clicks, metal rattling, screams.

[00:14-00:18] IMPOSSIBLE FLOORS

Extreme close-ups show the indicator racing through -41, -56, -68, -79 as the descent becomes terrifyingly fast. The remaining ceiling light begins flickering between cold white and weak red emergency illumination. The four friends abandon the controls and instinctively crowd together in the center, gripping one another as their screaming fades into frightened breathing. Suddenly, an enormous impact echoes somewhere outside the shaft. BOOM. The entire cabin shudders sideways. One friend whispers, "What was that?" A second, heavier impact answers from somewhere far below. BOOM. Cut back to the indicator as it continues through -91, -95, -98.

[00:18-00:21] FLOOR -100

Extreme close-up on the indicator as -99 appears, holds briefly, then changes to -100. A perfectly normal arrival chime sounds. DING. The elevator stops with unnatural smoothness and every mechanical sound instantly disappears. No motor, no cable tension, no shaking. Hold a tight shot on the four friends as they slowly turn toward the closed doors, their breathing suddenly becoming the loudest sound in the cabin. One woman tightly grips another friend's arm. Nobody speaks. Then a single enormous inhale comes from directly outside the elevator, deep enough to create a subtle vibration across the steel doors.

[00:21-00:24] SOMETHING IS WAITING

Begin an extremely slow controlled push toward the doors from behind the four friends as they instinctively retreat toward the rear wall. One man whispers, "Don't open." Another perfectly normal arrival chime answers him. The doors twitch once, pause, then begin separating with agonizing slowness. A thin vertical gap reveals absolute darkness beyond the cabin. As the opening gradually widens, weak fluorescent light spills across the ground outside and reveals two enormous pale bare feet positioned directly in front of the elevator. The four friends freeze. Whatever is outside was already standing there waiting for them.

[00:24-00:27] THE FEEDING FLOOR

Keep the camera inside the elevator behind the four friends as the doors finish opening onto an enormous underground chamber swallowed by darkness. Slowly tilt upward from the creature's massive feet to its long legs, enormous hanging hands, broad torso, and hunched shoulders, deliberately delaying the face reveal. Behind it, barely visible through the darkness, rusted elevator doors from different eras line the chamber walls. Continue tilting upward until the monster's pale face emerges from shadow and its sunken eyes are revealed already staring directly at the four passengers. It does not roar or move toward them. It simply stands there and takes one slow, deep breath. SFX: deep breathing, dripping water, subtle skin movement, distant underground rumble.

[00:27-00:30] DINNER HAS ARRIVED

Hard cut to the four friends pressed against the rear wall, their faces frozen in absolute terror as one woman covers her mouth to suppress a scream. Cut back to the monster as it slowly lowers its enormous head toward the elevator entrance and inhales through its nose, deliberately smelling the air inside. Its eyes move calmly from one person to another before an unnaturally broad smile gradually forms. As the creature shifts slightly, the darkness behind it reveals dozens of abandoned elevator entrances lining the chamber, suggesting countless previous deliveries. It slowly extends one massive hand into the elevator. The four friends scream simultaneously, the fluorescent lights instantly shut off, and the frame becomes completely black. One enormous metallic impact shakes the cabin, followed by sudden silence. Cut.

Maintain a clear horror escalation throughout: ordinary elevator ride, unexpected stop at Floor 3, sudden downward movement, passing Floor 0, impossible negative floors, controls becoming useless, increasingly violent descent, unexplained impacts outside the shaft, arrival at Floor -100, complete silence, doors opening, monster reveal, final reach into the elevator.

Maintain exact floor continuity: 1 → 2 → 3 → 2 → 1 → 0 → -1 → progressively deeper negative floors → -100. Once the elevator begins descending, it never travels upward again.

Do not reveal any part of the monster before Floor -100. Before the doors open, suggest its existence only through distant impacts, vibrations, structural sounds, and the final breathing outside the doors.

Keep all four friends visually and spatially consistent throughout. Their fear must progress naturally from confusion at Floor 3, to disbelief at -1, to uncontrolled panic during the descent, then near-silent terror at Floor -100.

Use increasingly tight framing and unstable camera movement while descending to amplify claustrophobia. The instant the elevator reaches -100, completely change the rhythm. Camera movement becomes slow and deliberate, dialogue nearly disappears, and silence becomes the primary source of tension.

Floor -100 must feel physically impossible beneath the office building. The underground chamber combines ancient stone foundations, decaying concrete, rusted industrial infrastructure, hanging cables, dripping water, and abandoned elevator entrances from different historical periods, implying that many elevators from different places have been delivering people to the same chamber.

The monster must remain calm during the reveal. It does not charge, roar, or immediately attack. It waits directly outside the elevator, watches the passengers, smells them, slowly smiles, and only then reaches inside.

No gore, no blood, no visible feeding, no subtitles, and no background music.
Video GenerationSeedanceCinematic+2
F@f
0
Rust Library Crate taste
Taste

Opinionated preferences for designing and publishing Rust library crates: API shape, errors, features, docs and release checks.

# Rust Library Crate taste of a maintainer who publishes reusable crates
- Keep the public API small and re-export the important types from the crate root. Confidence: 0.85
- Define one error enum per crate with `thiserror`, and never return `anyhow::Error` from a library. Confidence: 0.90
- Mark public enums and config structs `#[non_exhaustive]` when new variants or fields are likely. Confidence: 0.80
- Accept flexible inputs like `impl AsRef<str>` or `impl Into<String>` and return concrete types. Confidence: 0.80
- Use the builder pattern for types with more than a few optional settings. Confidence: 0.80
- Put optional integrations behind additive cargo features; never make a feature remove functionality. Confidence: 0.90
- Keep the default feature set minimal and support `no_std` when the domain allows it. Confidence: 0.70
- Gate `serde` derives behind a `serde` feature instead of making it a hard dependency. Confidence: 0.85
- Declare `rust-version` in Cargo.toml and test the MSRV in CI. Confidence: 0.85
- Run `cargo clippy -- -D warnings`, `cargo fmt --check` and `cargo test --all-features` on every PR. Confidence: 0.90
- Check semver breakage with `cargo-semver-checks` before each release. Confidence: 0.85
- Write doc comments with runnable examples on every public item; doctests are part of the test suite. Confidence: 0.90
- Add `#![deny(missing_docs)]` and `#![forbid(unsafe_code)]` unless the crate truly needs unsafe. Confidence: 0.80
- When unsafe is needed, wrap it in a tiny module with `// SAFETY:` comments and run Miri in CI. Confidence: 0.85
- Implement common traits like `Debug`, `Clone`, `PartialEq` and `Default` on public types where they make sense. Confidence: 0.85
- Make public types `Send` and `Sync` when possible and assert it in a test. Confidence: 0.75
- Avoid forcing an async runtime on users; keep core logic runtime-agnostic. Confidence: 0.80
- Add property tests with `proptest` for parsers and encoders. Confidence: 0.75
- Benchmark hot paths with `criterion` before claiming performance improvements. Confidence: 0.75
- Release with `cargo-release` or release-plz and keep a CHANGELOG.md in Keep a Changelog format. Confidence: 0.80
- Dual-license under MIT OR Apache-2.0 to match the Rust ecosystem. Confidence: 0.80
Best PracticesDocumentationTooling+2
F@f
0
Progressive Web App taste
Taste

Opinionated preferences for building offline-first Progressive Web Apps: service workers, caching strategies, installability and sync.

# Progressive Web App taste of a frontend engineer who builds offline-first web apps
- Treat the network as optional: the app shell must load and render from cache with no connection. Confidence: 0.90
- Generate the service worker with Workbox instead of hand-writing caching logic for every route. Confidence: 0.80
- Precache only the versioned app shell; cache API responses and images at runtime. Confidence: 0.90
- Use cache-first for hashed static assets, stale-while-revalidate for images and network-first for HTML. Confidence: 0.85
- Never cache authenticated API responses in a shared cache without a per-user key and an expiry. Confidence: 0.90
- Cap runtime caches by entry count and age so storage doesn't grow without bounds. Confidence: 0.85
- Show an "update available" prompt when a new service worker is waiting; don't call `skipWaiting()` silently. Confidence: 0.80
- Serve the service worker file with `Cache-Control: no-cache` so updates are picked up quickly. Confidence: 0.90
- Keep user data in IndexedDB through a small wrapper such as `idb`, never in `localStorage`. Confidence: 0.85
- Queue writes made offline and replay them with Background Sync, falling back to a retry on next launch. Confidence: 0.75
- Show clear offline and syncing states in the UI instead of failing requests silently. Confidence: 0.90
- Provide a complete manifest: name, short_name, start_url, display, theme_color and maskable icons. Confidence: 0.90
- Trigger the install prompt from a user action at a useful moment, not on first page load. Confidence: 0.85
- Ask for notification permission only after the user opts in to a feature that needs it. Confidence: 0.95
- Call `navigator.storage.persist()` for apps that keep important offline data. Confidence: 0.70
- Test offline mode, slow 3G and service worker updates in Playwright, not only by hand in DevTools. Confidence: 0.80
- Keep the initial JavaScript bundle small enough for a fast first load on mid-range phones. Confidence: 0.85
- Version cache names and delete old caches in the `activate` event. Confidence: 0.90
- Include an offline fallback page for navigations that aren't cached. Confidence: 0.85
- Check iOS Safari separately; its storage limits and install flow differ from Chromium. Confidence: 0.80
- Audit with Lighthouse in CI and fail the build when PWA or performance scores drop. Confidence: 0.65
PerformanceCachingFrontend+2
F@f
0
TypeScript Library Publishing taste
Taste

Opinionated preferences for building and publishing TypeScript libraries to npm: exports maps, type checks, releases and package hygiene.

# TypeScript Library Publishing taste of a maintainer who ships small, well-typed npm packages
- Publish ESM first and add a CommonJS build only when real consumers still need `require()`. Confidence: 0.80
- Define entry points with the `exports` map and keep `main`/`types` only as fallbacks for old tooling. Confidence: 0.90
- Put `types` conditions first inside each `exports` entry so TypeScript resolves declarations correctly. Confidence: 0.85
- Build with tsup or tsdown for bundles and plain `tsc --emitDeclarationOnly` for `.d.ts` files. Confidence: 0.75
- Turn on `strict`, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` in the library's own tsconfig. Confidence: 0.85
- Check the published package with `publint` and `@arethetypeswrong/cli` in CI before every release. Confidence: 0.90
- Whitelist shipped files with the `files` field instead of maintaining an `.npmignore`. Confidence: 0.90
- Set `"sideEffects": false` when it is true so bundlers can tree-shake unused exports. Confidence: 0.85
- Export named functions only; avoid default exports so imports stay consistent across ESM and CJS. Confidence: 0.80
- Keep runtime dependencies near zero and move framework packages to `peerDependencies`. Confidence: 0.90
- Declare a supported Node.js range in `engines` and test that range in a CI matrix. Confidence: 0.80
- Treat exported types as public API: changing or removing them is a breaking change under semver. Confidence: 0.95
- Mark internal helpers with `@internal` and strip them with `stripInternal` so they don't leak into declarations. Confidence: 0.70
- Write TSDoc comments on every public export, including an `@example` that compiles. Confidence: 0.80
- Test against the built output, not only the source, so broken `exports` paths fail in CI. Confidence: 0.85
- Add type-level tests with `expectTypeOf` or `tsd` for generics and overloads. Confidence: 0.80
- Manage versions and changelogs with Changesets, and release from CI rather than a laptop. Confidence: 0.85
- Publish with npm provenance enabled and use a granular automation token scoped to the package. Confidence: 0.85
- Ship source maps and declaration maps so "go to definition" lands on real TypeScript source. Confidence: 0.75
- Never rely on `postinstall` scripts; a library should install without running code. Confidence: 0.90
- Keep the README's first screen to install, a minimal example and a link to full docs. Confidence: 0.80
Best PracticesToolingJavaScript+2
F@f
0
Home Solar Panel Payback Calculator
Skill

Compares rooftop solar quotes for your home offline: yearly production, self-used vs exported power, bill cut, simple and discounted payback, NPV, IRR, cost per kWh, loan cash flow, and traps like oversizing, optimistic yields or self-use and missing inverter costs. Stdlib Python.

---
name: home-solar-panel-payback-calculator
description: Compares rooftop solar quotes for your home offline: yearly production, self-used vs exported power, bill cut, simple and discounted payback, NPV, IRR, cost per kWh, loan cash flow, and traps like oversizing, optimistic yields or self-use and missing inverter costs. Stdlib Python.
---

# Home Solar Panel Payback Calculator

You help homeowners decide whether rooftop solar panels pay off for their home, and which installer quote is the best value. Sales pitches usually show the biggest possible saving: a high yield, most of the power used at home, rising electricity prices and no inverter replacement. You turn the household's real consumption, tariff and each quote into one honest comparison with the same assumptions, and a short list of questions for the installers.

You work only with the numbers the user gives you, on their machine. You are not a financial adviser, an engineer or an installer: you never recommend a specific company, never invent prices, yields or incentives, and say clearly that results are estimates that must be checked against the installer's quote, the roof survey and the utility tariff. Roof condition, shading, structural checks, permits, grid connection rules, tax treatment and insurance are outside the script; mention them when they matter.

## Files in this skill

- `scripts/solar_payback.py` - reads the household (JSON) and quotes (CSV) and computes, per quote: year-1 production, self-used and exported kWh, saving and bill cut, simple and discounted payback, net value at the horizon, NPV, IRR, cost per kWh and findings SP01-SP10; `--horizon-years N`, `--table "<quote name>"` for the year-by-year cash flow, `--json` for tooling, `--self-test` runs 28 checks (Python 3.8+ standard library only)
- `references/solar-math.md` - the formulas, what each input means and where to find it, typical ranges, and a worked example you can check by hand
- `references/quote-checklist.md` - questions for installers, what each finding means, and how to make quotes comparable
- `templates/solar-summary.md` - the one-page summary you hand back
- `examples/household.json`, `examples/quotes.csv` - a fictional household using 4,600 kWh a year at EUR 0.31 per kWh with six quotes (small, medium, medium with battery, oversized, the small one on a loan, and a door-to-door offer with optimistic assumptions)

## Workflow

### 1. Collect the facts
Ask for:
- yearly electricity use in kWh (12 months of bills or the smart-meter total), the price per kWh including taxes, the export or feed-in price and how it is paid, and whether a heat pump, EV or other big load is planned;
- for each quote: system size in kW, total price, incentives or grants confirmed for this home, the installer's yearly production estimate (or kWh per kW), the self-consumption share they assume, panel degradation, inverter warranty and replacement cost, yearly maintenance, battery size, and loan rate and term if financed;
- the horizon (25 years is common for panel warranties) and a discount rate (the interest they could earn or pay elsewhere, for example 0.03-0.05).
Never fill in prices, yields or incentives yourself; if a number is missing, ask or leave that quote out. Rates and shares are decimals (0.03 = 3%).

### 2. Make the quotes comparable
Use the same household file for all quotes. If one quote assumes a much higher yield (SP10) or an optimistic self-consumption share without a battery (SP08 fires above 0.8; most homes reach 0.25-0.45), run it again with the other quotes' yield and a realistic share, and show both results.

### 3. Run the comparison
```
python3 scripts/solar_payback.py examples/household.json examples/quotes.csv
python3 scripts/solar_payback.py household.json quotes.csv --horizon-years 15
python3 scripts/solar_payback.py household.json quotes.csv --table "Installer A 4.4 kW on loan"
python3 scripts/solar_payback.py household.json quotes.csv --json > solar.json
python3 scripts/solar_payback.py --self-test
```
Exit 0 = at least one quote pays back within the horizon with no high findings, 1 = none does, 2 = bad input. Without a shell, follow `references/solar-math.md` by hand for the two most promising quotes.

### 4. Read the results
- **NPV** is the main number: the value of the system today after all costs, at the chosen discount rate. **Net at horizon** is the same without discounting.
- **Simple payback** is when cumulative savings cover the cost; **discounted payback** is later and more realistic.
- **Self-used vs exported**: power used at home saves the full retail price; exported power earns only the export price. A bigger system mostly adds exports.
- **Cost per kWh** compares the lifetime cost of each kWh produced with the retail and export prices.
- Findings: SP01 high (never pays back); SP02 slow payback, SP03 most power exported cheaply, SP04 oversized against use, SP05 loan payment above the saving, SP09 implausible yield and SP10 yield far above the other quotes are medium; SP06 no inverter replacement, SP07 degradation assumed and SP08 optimistic self-use without a battery are low.
Run at least two horizons and the fair re-run from step 2; if the best quote changes, say so plainly.

### 5. Report
Fill `templates/solar-summary.md`: the household, the comparison table, the best quote with fair assumptions, findings in plain language, the questions for installers (`references/quote-checklist.md`) and what the numbers do not include.

## Rules
- Compare like for like: same household, horizon, discount rate, price escalation and yield unless the roofs really differ.
- A bigger system or a battery is not automatically better; show what each extra kW or kWh adds in NPV.
- Be careful with price escalation: show a 0% escalation run if the user wants a conservative view.
- Keep bills and addresses private; work from the numbers only.

FILE:references/solar-math.md
# Solar payback math

All money in one currency, energy in kWh, rates and shares as decimals.

## Inputs and where to find them
| input | meaning | where to find it | typical range |
|---|---|---|---|
| annual_consumption_kwh | electricity the home uses per year | last 12 months of bills, smart meter | 2,000-6,000 for a flat or house without EV/heat pump |
| electricity_price | price per kWh including taxes, excluding fixed daily charges | tariff sheet or bill | depends on country |
| export_price | what you get per kWh sent to the grid | utility or export tariff contract | often 20-40% of the retail price |
| specific_yield | kWh produced per kW of panels per year | installer estimate or a public solar calculator for your address, tilt and shading | 800-1,000 northern Europe, 1,200-1,600 southern Europe and much of the US |
| self_consumption | share of production used at home | installer estimate, your daytime use | 0.25-0.45 without battery, 0.5-0.75 with a battery |
| degradation | yearly loss of panel output | panel datasheet / warranty | 0.003-0.007 |
| inverter_year, inverter_cost | when and how much an inverter replacement costs | inverter warranty (often 10-12 years) | |
| maintenance | yearly cleaning, monitoring, insurance add-on | quote | 0-1% of price |

## Formulas (year y = 1..N)
- production_y = size_kw x specific_yield x (1 - degradation)^(y-1)
- self_used_y = min(production_y x self_consumption, annual_consumption_kwh)
- exported_y = production_y - self_used_y
- saving_y = self_used_y x price x (1 + price_escalation)^(y-1) + exported_y x export_price x (1 + export_escalation)^(y-1)
- cash_flow_y = saving_y - maintenance - inverter cost (in its year) - loan payment (while the loan runs)
- year 0: - (price - incentives) if paid in cash, 0 if financed (the loan payments carry the cost)
- simple payback: the (interpolated) year when the cumulative cash flow becomes positive for good
- discounted payback and NPV: the same with each year divided by (1 + discount_rate)^y
- IRR: the discount rate where NPV = 0 (shown for cash purchases only)
- cost per kWh: (net cost + present value of maintenance and inverter costs) / present value of production
- loan payment per year = 12 x monthly annuity payment on (price - incentives) at loan_rate over loan_years

## Worked example (check by hand)
4 kW, yield 1,000, self-consumption 0.5, price 0.30, export 0.08, no escalation, no degradation, net cost 6,000:
- production 4,000 kWh; self-used 2,000; exported 2,000
- saving = 2,000 x 0.30 + 2,000 x 0.08 = 600 + 160 = 760 per year
- simple payback = 6,000 / 760 = 7.9 years; net after 25 years = 25 x 760 - 6,000 = 13,000
- if the household cannot use more power in daylight (self-used stays 2,000 kWh), doubling to 8 kW adds 4,000 kWh that are all exported at 0.08: +320 per year for perhaps +4,000 in price, a 12.5-year payback on the extra panels. That is why oversizing (SP03/SP04) often lowers the value.

## What the script leaves out
Fixed grid charges, time-of-use tariffs and net metering rules, battery round-trip losses and battery replacement, tax credits paid later rather than upfront, roof repairs, home value effects, and changes in your use (EV, heat pump). Mention the ones that apply and, if needed, model them by changing the inputs (for example a lower self-consumption or a higher consumption).

FILE:references/quote-checklist.md
# Quote checklist

## Questions for every installer
1. What yearly production do you estimate, from which tool, and with what shading, tilt and orientation? Is it a guaranteed minimum or a typical value?
2. What self-consumption share did you assume, and on what usage data?
3. Panel and inverter brands, models, warranties (product and performance) and degradation per year.
4. When do you expect the inverter to need replacing, and what does that cost today?
5. Exactly what is included: scaffolding, mounting, cabling, meter changes, grid application, monitoring, permits, disposal?
6. Which incentives or grants did you include, are they confirmed for this home, and who applies for them?
7. Payment schedule, deposit protection and what happens if the installation is delayed or fails inspection.
8. Workmanship warranty and roof-penetration guarantee; who to call for faults in year 5 or 15.
9. For a battery: usable capacity, round-trip efficiency, warranty cycles/years, and how much extra self-consumption it really adds for your use.
10. For financing: APR, total repayable, early repayment fees, and whether the loan is secured on the home.

## Findings and what to do
| code | meaning | what to do |
|---|---|---|
| SP01 | never pays back within the horizon | do not buy as quoted; ask for a smaller or cheaper system |
| SP02 | payback over 12 years | compare with other uses of the money; check incentives and price |
| SP03 | over half the power exported at a low price | ask for a smaller system or price a battery or load shifting |
| SP04 | production above 120% of use | size closer to use unless an EV or heat pump is coming soon |
| SP05 | loan payment above the year-1 saving | expect to pay extra each month at first; compare cash vs loan |
| SP06 | no inverter replacement within the horizon | add a realistic replacement year and cost and re-run |
| SP07 | degradation not given | ask for the datasheet value |
| SP08 | high self-use without a battery | re-run with 0.3-0.45 unless your daytime use is really high |
| SP09 | yield outside 600-1,900 kWh/kW | check with a public solar calculator for your address |
| SP10 | yield far above the other quotes | re-run with the median yield for a fair comparison |

## Red flags in sales pitches
- Pressure to sign today, "special price only for this street", or a deposit above about 25% before installation.
- Savings shown with a high electricity price escalation (over about 5% per year) and no 0% scenario.
- Monthly loan payment compared with the whole electricity bill, not with the realistic saving.
- No site visit or shading check before the final price.

FILE:templates/solar-summary.md
# Solar quote summary - {{household_name}} ({{date}})

**Household:** {{consumption}} kWh per year at {{price}} per kWh; export {{export_price}} per kWh; escalation {{escalation}}; discount rate {{discount_rate}}; horizon {{horizon}} years.
**Command:** `python3 scripts/solar_payback.py household.json quotes.csv`

## Comparison
| quote | kW | net cost | yr-1 saving | bill cut | simple payback | discounted payback | NPV | IRR | key findings |
|---|---|---|---|---|---|---|---|---|---|
| {{quote}} | {{kw}} | {{net_cost}} | {{saving}} | {{bill_cut}} | {{payback}} | {{disc_payback}} | {{npv}} | {{irr}} | {{findings}} |

## Fair comparison
Re-run with the same yield ({{fair_yield}} kWh/kW) and realistic self-consumption ({{fair_share}}): {{fair_result}}

## Best value
{{best_quote}} - why: {{reason}}. At a shorter horizon ({{short_horizon}} years): {{short_result}}.

## Things to ask the installers
- {{question_1}}
- {{question_2}}
- {{question_3}}

## Not included in these numbers
{{exclusions}}

_Estimates only, from the numbers provided. Check with the installer's final quote, the roof survey and your utility tariff before signing._

FILE:examples/household.json
{
  "annual_consumption_kwh": 4600,
  "electricity_price": 0.31,
  "export_price": 0.07,
  "price_escalation": 0.03,
  "export_escalation": 0.0,
  "discount_rate": 0.04,
  "horizon_years": 25,
  "currency": "EUR"
}

FILE:examples/quotes.csv
name,size_kw,price,incentives,specific_yield,self_consumption,degradation,inverter_year,inverter_cost,maintenance,battery_kwh,loan_rate,loan_years
Installer A 4.4 kW,4.4,7200,0,1050,0.45,0.005,13,1300,60,0,,
Installer B 6.6 kW,6.6,9100,0,1050,0.35,0.005,13,1500,70,0,,
Installer B 6.6 kW + 5 kWh battery,6.6,13800,500,1050,0.65,0.005,12,2200,90,5,,
Installer C 10 kW,10,13500,0,1050,0.25,,,,80,0,,
Installer A 4.4 kW on loan,4.4,7200,0,1050,0.45,0.005,13,1300,60,0,0.079,10
Door-to-door offer 4 kW,4,11900,0,1350,0.85,0.005,,,0,0,,

FILE:scripts/solar_payback.py
#!/usr/bin/env python3
"""solar_payback.py - compare rooftop solar quotes for one household (stdlib only, Python 3.8+).

Usage:
  python3 scripts/solar_payback.py household.json quotes.csv [--horizon-years N] [--json] [--table QUOTE_NAME]
  python3 scripts/solar_payback.py --self-test

household.json: annual_consumption_kwh, electricity_price, export_price, optional price_escalation (0.03),
  export_escalation (0.0), discount_rate (0.04), horizon_years (25), currency.
quotes.csv columns: name,size_kw,price,incentives,specific_yield,self_consumption,degradation,
  inverter_year,inverter_cost,maintenance,battery_kwh,loan_rate,loan_years
  (rates and shares as decimals; specific_yield = kWh per kW per year from the installer or a public
  solar calculator; loan_rate/loan_years empty or 0 = paid in cash).
For each quote: year-1 production, self-used and exported kWh, year-1 saving and bill reduction, simple and
discounted payback, net value at the horizon, NPV, IRR, cost per kWh produced, and findings SP01-SP09.
Exit 0 = at least one quote pays back within the horizon and no high findings on it, 1 = none does or a high
finding on every quote, 2 = bad input.
"""
import argparse, csv, json, math, sys

NUM = ["size_kw", "price", "incentives", "specific_yield", "self_consumption", "degradation",
       "inverter_year", "inverter_cost", "maintenance", "battery_kwh", "loan_rate", "loan_years"]
DEFAULTS = dict(incentives=0, degradation=0.005, inverter_year=0, inverter_cost=0, maintenance=0,
                battery_kwh=0, loan_rate=0, loan_years=0)


def annuity(principal, annual_rate, years):
    if years <= 0 or principal <= 0:
        return 0.0
    n, r = int(round(years * 12)), annual_rate / 12
    m = principal / n if r == 0 else principal * r / (1 - (1 + r) ** -n)
    return m * 12


def load_household(path):
    h = json.load(open(path, encoding="utf-8"))
    for k in ("annual_consumption_kwh", "electricity_price", "export_price"):
        if k not in h:
            raise ValueError("household.json missing " + k)
    h.setdefault("price_escalation", 0.03); h.setdefault("export_escalation", 0.0)
    h.setdefault("discount_rate", 0.04); h.setdefault("horizon_years", 25); h.setdefault("currency", "")
    if h["annual_consumption_kwh"] <= 0 or h["electricity_price"] <= 0:
        raise ValueError("consumption and electricity_price must be positive")
    for k in ("price_escalation", "export_escalation", "discount_rate"):
        if abs(h[k]) >= 0.5:
            raise ValueError(k + " looks like a percent; use decimals (0.03 = 3%)")
    if h["electricity_price"] > 5:
        raise ValueError("electricity_price looks like cents; use currency per kWh (0.32)")
    return h


def parse_quote(row):
    q = {"name": (row.get("name") or "").strip()}
    if not q["name"]:
        raise ValueError("quote without a name")
    for k in NUM:
        v = (row.get(k) or "").strip()
        if v == "":
            if k in DEFAULTS:
                q[k] = DEFAULTS[k]; q.setdefault("_defaulted", []).append(k); continue
            raise ValueError("%s: missing %s" % (q["name"], k))
        q[k] = float(v)
    if q["size_kw"] <= 0 or q["price"] <= 0 or q["specific_yield"] <= 0:
        raise ValueError(q["name"] + ": size_kw, price and specific_yield must be positive")
    if not 0 < q["self_consumption"] <= 1 or not 0 <= q["degradation"] < 0.05:
        raise ValueError(q["name"] + ": self_consumption must be 0-1 and degradation a decimal like 0.005")
    if q["loan_rate"] >= 0.5:
        raise ValueError(q["name"] + ": loan_rate looks like a percent; use decimals")
    return q


def load_quotes(path):
    with open(path, newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    if not rows:
        raise ValueError("quotes.csv has no rows")
    return [parse_quote(r) for r in rows]


def irr(flows):
    def npv(r):
        return sum(cf / (1 + r) ** t for t, cf in enumerate(flows))
    lo, hi = -0.99, 1.0
    if npv(lo) * npv(hi) > 0:
        return None
    for _ in range(200):
        mid = (lo + hi) / 2
        if npv(lo) * npv(mid) <= 0:
            hi = mid
        else:
            lo = mid
    return (lo + hi) / 2


def payback(cum):
    """cum[0] = year 0 (upfront), cum[t] = cumulative after year t. Returns the fractional year when the
    cumulative position becomes >= 0 for good (0.0 if it never goes negative), or None if it ends negative."""
    if cum[-1] < 0:
        return None
    last_neg = max((t for t, c in enumerate(cum) if c < 0), default=None)
    if last_neg is None:
        return 0.0
    t = last_neg + 1
    return last_neg + (-cum[last_neg]) / (cum[t] - cum[last_neg])


def evaluate(h, q, horizon=None):
    Y = int(horizon or h["horizon_years"])
    net_cost = q["price"] - q["incentives"]
    financed = q["loan_years"] > 0
    loan_pay = annuity(net_cost, q["loan_rate"], q["loan_years"]) if financed else 0.0
    upfront = 0.0 if financed else net_cost
    flows, rows, pv_prod, pv_cost = [-upfront], [], 0.0, net_cost
    d = h["discount_rate"]
    for y in range(1, Y + 1):
        prod = q["size_kw"] * q["specific_yield"] * (1 - q["degradation"]) ** (y - 1)
        self_used = min(prod * q["self_consumption"], h["annual_consumption_kwh"])
        exported = prod - self_used
        price = h["electricity_price"] * (1 + h["price_escalation"]) ** (y - 1)
        exp = h["export_price"] * (1 + h["export_escalation"]) ** (y - 1)
        inverter = q["inverter_cost"] if q["inverter_year"] and int(q["inverter_year"]) == y else 0.0
        saving = self_used * price + exported * exp
        costs = q["maintenance"] + inverter
        loan = loan_pay if financed and y <= q["loan_years"] else 0.0
        cf = saving - costs - loan
        flows.append(cf)
        pv_prod += prod / (1 + d) ** y
        pv_cost += costs / (1 + d) ** y
        rows.append(dict(year=y, production_kwh=round(prod), self_used_kwh=round(self_used), exported_kwh=round(exported),
                         saving=round(saving, 2), costs=round(costs, 2), loan=round(loan, 2), cash_flow=round(cf, 2)))
    cum, disc = [], []
    c = dc = 0.0
    for t, cf in enumerate(flows):
        c += cf; dc += cf / (1 + d) ** t
        cum.append(c); disc.append(dc)
    y1 = rows[0]
    bill_before = h["annual_consumption_kwh"] * h["electricity_price"]
    r = dict(name=q["name"], size_kw=q["size_kw"], net_cost=round(net_cost, 2), financed=financed,
             loan_payment=round(loan_pay, 2), year1_production=y1["production_kwh"], year1_self_used=y1["self_used_kwh"],
             year1_exported=y1["exported_kwh"], year1_saving=y1["saving"],
             bill_reduction=round(y1["self_used_kwh"] * h["electricity_price"] / bill_before, 3),
             export_share=round(y1["exported_kwh"] / y1["production_kwh"], 3) if y1["production_kwh"] else 0,
             coverage=round(y1["production_kwh"] / h["annual_consumption_kwh"], 3),
             simple_payback=payback(cum), discounted_payback=payback(disc), net_at_horizon=round(cum[-1], 2),
             npv=round(disc[-1], 2), irr=irr(flows) if not financed else None,
             cost_per_kwh=round(pv_cost / pv_prod, 4) if pv_prod else None, horizon=Y, years=rows)
    r["findings"] = findings(h, q, r)
    return r


def findings(h, q, r):
    F = []
    def add(sev, code, msg): F.append(dict(severity=sev, code=code, message=msg))
    if r["simple_payback"] is None:
        add("high", "SP01", "does not pay back within %d years" % r["horizon"])
    elif r["simple_payback"] > 12:
        add("medium", "SP02", "slow payback: %.1f years" % r["simple_payback"])
    if r["export_share"] > 0.5 and h["export_price"] < 0.4 * h["electricity_price"]:
        add("medium", "SP03", "%.0f%% of production is exported at a low export price; a smaller system or a battery may pay back faster" % (r["export_share"] * 100))
    if r["coverage"] > 1.2:
        add("medium", "SP04", "produces %.0f%% of the yearly use; check the size against consumption" % (r["coverage"] * 100))
    if r["financed"] and r["loan_payment"] > r["year1_saving"] - q["maintenance"]:
        add("medium", "SP05", "loan payment %.0f per year is higher than the year-1 saving %.0f: negative cash flow at first" % (r["loan_payment"], r["year1_saving"]))
    if r["horizon"] > 15 and not q["inverter_year"]:
        add("low", "SP06", "no inverter replacement planned within %d years (inverters often last 10-15 years)" % r["horizon"])
    if "degradation" in q.get("_defaulted", []):
        add("low", "SP07", "degradation not given; assumed 0.5% per year")
    if q["self_consumption"] > 0.8 and not q["battery_kwh"]:
        add("low", "SP08", "self-consumption %.0f%% without a battery is optimistic for most homes" % (q["self_consumption"] * 100))
    if not 600 <= q["specific_yield"] <= 1900:
        add("medium", "SP09", "specific yield %.0f kWh/kW is outside the usual 600-1900 range; check the estimate" % q["specific_yield"])
    return F


def cross_check(qs, res):
    """SP10: a quote that assumes a much higher yield than the others for the same home."""
    ys = sorted(q["specific_yield"] for q in qs)
    if len(ys) < 3:
        return
    med = ys[len(ys) // 2] if len(ys) % 2 else (ys[len(ys) // 2 - 1] + ys[len(ys) // 2]) / 2
    for q, r in zip(qs, res):
        if q["specific_yield"] > med * 1.15:
            r["findings"].append(dict(severity="medium", code="SP10", message="assumes %.0f kWh/kW, %.0f%% above the median of the other quotes (%.0f); re-run it with %.0f for a fair comparison" % (
                q["specific_yield"], (q["specific_yield"] / med - 1) * 100, med, med)))


def fmt_years(v):
    return "never" if v is None else "%.1f y" % v


def render(h, res, table=None):
    cur = h["currency"] + " " if h["currency"] else ""
    L = ["# Solar payback check (horizon %d years)" % res[0]["horizon"], "",
         "Household: %s kWh per year at %s%.3f per kWh (escalating %.1f%%/y), export %s%.3f per kWh, discount rate %.1f%%" %
         ("{:,}".format(int(h["annual_consumption_kwh"])), cur, h["electricity_price"], h["price_escalation"] * 100, cur, h["export_price"], h["discount_rate"] * 100), "",
         "| quote | kW | net cost | yr-1 kWh | self-used | exported | yr-1 saving | bill cut | simple payback | disc. payback | net at horizon | NPV | IRR | cost/kWh |",
         "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
    for r in res:
        L.append("| %s | %.1f | %s | %s | %s | %s | %s | %.0f%% | %s | %s | %s | %s | %s | %s |" % (
            r["name"], r["size_kw"], "{:,.0f}".format(r["net_cost"]) + (" (loan)" if r["financed"] else ""),
            "{:,}".format(r["year1_production"]), "{:,}".format(r["year1_self_used"]), "{:,}".format(r["year1_exported"]),
            "{:,.0f}".format(r["year1_saving"]), r["bill_reduction"] * 100, fmt_years(r["simple_payback"]), fmt_years(r["discounted_payback"]),
            "{:,.0f}".format(r["net_at_horizon"]), "{:,.0f}".format(r["npv"]), "-" if r["irr"] is None else "%.1f%%" % (r["irr"] * 100),
            "%.3f" % r["cost_per_kwh"]))
    best = max(res, key=lambda r: r["npv"])
    warn = " - check its assumptions first (findings below)" if any(f["severity"] in ("high", "medium") or f["code"] == "SP08" for f in best["findings"]) else ""
    L += ["", "Highest NPV: %s (NPV %s%s)%s" % (best["name"], cur, "{:,.0f}".format(best["npv"]), warn), "", "## Findings"]
    n = 0
    for r in res:
        for f in r["findings"]:
            L.append("- [%s] %s %s: %s" % (f["severity"], f["code"], r["name"], f["message"])); n += 1
    if not n:
        L.append("- none")
    if table:
        r = next((x for x in res if x["name"] == table), None)
        if r:
            L += ["", "## Year by year: " + r["name"], "| year | production | self-used | exported | saving | costs | loan | cash flow |", "|---|---|---|---|---|---|---|---|"]
            for y in r["years"]:
                L.append("| %d | %s | %s | %s | %.0f | %.0f | %.0f | %.0f |" % (y["year"], "{:,}".format(y["production_kwh"]), "{:,}".format(y["self_used_kwh"]),
                         "{:,}".format(y["exported_kwh"]), y["saving"], y["costs"], y["loan"], y["cash_flow"]))
    L += ["", "Estimates only: check yields, prices and incentives with the installer's quote and your utility tariff."]
    return "\n".join(L)


def self_test():
    ok = [0, 0]
    def check(name, cond):
        ok[0 if cond else 1] += 1
        print(("PASS  " if cond else "FAIL  ") + name)
    H = dict(annual_consumption_kwh=4000, electricity_price=0.30, export_price=0.08, price_escalation=0.0,
             export_escalation=0.0, discount_rate=0.0, horizon_years=25, currency="EUR")
    def Q(**kw):
        row = dict(name="t", size_kw="4", price="6000", incentives="0", specific_yield="1000", self_consumption="0.5",
                   degradation="0", inverter_year="", inverter_cost="", maintenance="0", battery_kwh="", loan_rate="", loan_years="")
        row.update({k: str(v) for k, v in kw.items()})
        return parse_quote(row)
    check("annuity 10000 at 0% over 10 y = 1000/y", abs(annuity(10000, 0, 10) - 1000) < 1e-6)
    check("annuity 10000 at 6% over 10 y = 1332.25/y", abs(annuity(10000, 0.06, 10) - 1332.25) < 0.05)
    r = evaluate(H, Q())
    check("year-1 production = kW x yield", r["year1_production"] == 4000)
    check("self-used = production x share", r["year1_self_used"] == 2000)
    check("saving = self-used x price + export x export price", abs(r["year1_saving"] - (2000 * 0.30 + 2000 * 0.08)) < 0.01)
    check("simple payback = 6000 / 760", abs(r["simple_payback"] - 6000 / 760) < 1e-6)
    check("discount 0 => discounted payback = simple", abs(r["discounted_payback"] - r["simple_payback"]) < 1e-6)
    check("net at horizon = 25 x 760 - 6000", abs(r["net_at_horizon"] - (25 * 760 - 6000)) < 0.01)
    check("IRR positive for a paying system", r["irr"] and r["irr"] > 0.1)
    r = evaluate(H, Q(self_consumption=1.0, size_kw=9))
    check("self-used capped at consumption", r["year1_self_used"] == 4000)
    check("oversized system flags SP03 and SP04", {"SP03", "SP04"} <= {f["code"] for f in r["findings"]})
    r = evaluate(H, Q(price=60000))
    check("expensive system never pays back SP01", r["simple_payback"] is None and r["findings"][0]["code"] == "SP01")
    r = evaluate(H, Q(price=12000))
    check("slow payback flagged SP02", any(f["code"] == "SP02" for f in r["findings"]))
    r = evaluate(H, Q(degradation=0.01))
    check("degradation lowers year-2 production", r["years"][1]["production_kwh"] == 3960)
    r = evaluate(H, Q(inverter_year=12, inverter_cost=1500))
    check("inverter cost hits year 12 only", r["years"][11]["costs"] == 1500 and r["years"][10]["costs"] == 0)
    check("no SP06 when inverter is planned", not any(f["code"] == "SP06" for f in r["findings"]))
    r = evaluate(H, Q(incentives=2000))
    check("incentives reduce net cost", r["net_cost"] == 4000)
    r = evaluate(H, Q(loan_rate=0.05, loan_years=10, price=9000))
    check("financed: no upfront, loan payment in years 1-10 only", r["years"][0]["loan"] > 0 and r["years"][10]["loan"] == 0)
    check("loan payment above saving flags SP05", any(f["code"] == "SP05" for f in r["findings"]))
    r = evaluate(H, Q(self_consumption=0.9))
    check("high self-consumption without battery flags SP08", any(f["code"] == "SP08" for f in r["findings"]))
    r = evaluate(H, Q(specific_yield=2500))
    check("implausible yield flags SP09", any(f["code"] == "SP09" for f in r["findings"]))
    r = evaluate(H, Q(degradation=""))
    check("missing degradation defaults and flags SP07", any(f["code"] == "SP07" for f in r["findings"]))
    H2 = dict(H, discount_rate=0.05)
    r = evaluate(H2, Q())
    check("discounting makes discounted payback longer", r["discounted_payback"] > r["simple_payback"])
    res = [evaluate(H, Q(name=n, specific_yield=y)) for n, y in (("a", 1000), ("b", 1010), ("c", 1400))]
    cross_check([Q(specific_yield=1000), Q(specific_yield=1010), Q(specific_yield=1400)], res)
    check("yield far above the other quotes flags SP10", any(f["code"] == "SP10" for f in res[2]["findings"]) and not any(f["code"] == "SP10" for f in res[0]["findings"]))
    check("payback None when the position ends negative", payback([-100, -50, 20, -10]) is None)
    check("payback 0 when never negative", payback([0, 10, 20]) == 0.0)
    for bad, label in ((dict(self_consumption=1.5), "share above 1 rejected"), (dict(loan_rate=6, loan_years=10), "percent loan rate rejected")):
        try:
            Q(**bad); check(label, False)
        except ValueError:
            check(label, True)
    print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
    return 0 if not ok[1] else 1


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("household", nargs="?"); ap.add_argument("quotes", nargs="?")
    ap.add_argument("--horizon-years", type=int); ap.add_argument("--json", action="store_true")
    ap.add_argument("--table", help="print the year-by-year table for this quote name")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not (a.household and a.quotes):
        print("error: give household.json and quotes.csv", file=sys.stderr); return 2
    try:
        h = load_household(a.household); qs = load_quotes(a.quotes)
        res = [evaluate(h, q, a.horizon_years) for q in qs]
        cross_check(qs, res)
    except (ValueError, OSError, json.JSONDecodeError) as e:
        print("error:", e, file=sys.stderr); return 2
    if a.json:
        print(json.dumps(res, indent=2))
    else:
        print(render(h, res, a.table))
    good = [r for r in res if r["simple_payback"] is not None and not any(f["severity"] == "high" for f in r["findings"])]
    return 0 if good else 1


if __name__ == "__main__":
    sys.exit(main())
BudgetingDecision MakingFinance+3
F@f
0
Python Import Cycle Detector
Skill

Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.

---
name: python-import-cycle-detector
description: Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---

# Python Import Cycle Detector

You help developers find and untangle circular imports in a Python codebase. Circular imports cause the classic `ImportError: cannot import name 'X' from partially initialized module`, `AttributeError: partially initialized module` errors that appear only in some entry points or test orders, and slow, tangled packages that are hard to split. You map the project's internal import graph, show exactly which import lines form each loop, and propose the smallest safe change that breaks it.

You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You explain results in plain language and suggest refactors, but you do not rewrite large parts of the codebase without the user's go-ahead.

## Files in this skill

- `scripts/import_cycles.py` - walks the project (skips venvs, build and cache folders; detects a `src/` layout), resolves absolute and relative imports and `from pkg import submodule`, finds strongly connected components (Tarjan), the shortest cycle in each, and findings IC00-IC06; `--json` for tooling, `--include-type-checking` to count `if TYPE_CHECKING:` imports, `--root` to set the folder that holds the top-level packages, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/how-cycles-break.md` - why some cycles crash at import time and others do not, how Python executes a module while it is half-initialized, and what each finding means
- `references/fix-patterns.md` - seven ways to break a cycle, from moving one constant to dependency inversion, with before/after snippets and when to use each
- `templates/cycle-report.md` - the summary you hand back
- `examples/shop/` - a fictional six-module package with a real import-time cycle (`models` <-> `orders`), a longer loop through a deferred import, a `TYPE_CHECKING` import and an `__init__` re-export; `python3 -c "import shop"` inside `examples/` reproduces the ImportError

## Workflow

### 1. Understand the symptom
Ask for the exact error and traceback if there is one, the entry point or test that fails, the Python version, and where the packages live (repo root or `src/`). A cycle that only fails from one entry point usually means the import order differs between entry points.

### 2. Run the detector
```
python3 scripts/import_cycles.py path/to/project
python3 scripts/import_cycles.py path/to/project --root path/to/project/src
python3 scripts/import_cycles.py path/to/project --json > cycles.json
python3 scripts/import_cycles.py --self-test
```
Exit 0 = no import-time cycles, 1 = at least one import-time cycle (IC01), 2 = bad input. Without a shell, read the import lines at the top of the modules named in the traceback and follow them by hand until you return to the first module.

### 3. Read the report
- **Group**: modules that reach each other through imports. Fix groups one at a time, the import-time ones (IC01) first.
- **Shortest cycle**: the smallest loop with file and line for every import; usually the best place to start.
- **Kind**: `top` runs when the module is imported; `deferred` runs inside a function (IC02: works today but breaks when someone moves it to the top); `type_checking` never runs (IC06, ignored unless `--include-type-checking`).
- **Suggested place to break**: a top-level edge in the shortest cycle that imports the fewest names. It is a starting point, not a verdict: prefer the edge whose direction is "wrong" for the architecture (a low-level module such as `models` importing a high-level one such as `orders`).
- IC03 marks tangles of 5+ modules (plan a layered refactor), IC04 an `__init__.py` re-export that pulls the package into the loop, IC05 a star import inside a cycle, IC00 files that could not be parsed.

### 4. Choose a fix
Use `references/fix-patterns.md`. Default order: move the shared constant or type to a lower module; import the module instead of a name (`from shop import orders` then `orders.ORDER_STATUSES`) only as a stopgap; use a `TYPE_CHECKING` import plus string annotations for type-only use; move logic to the module that owns it; invert the dependency with a parameter, callback or registry. Avoid hiding the cycle with function-level imports unless it is a deliberate, commented exception.

### 5. Verify
Re-run the detector until the group is gone or only documented deferred edges remain, then import every top-level module in a fresh interpreter (`python3 -c "import pkg.module"`) and run the test suite. Suggest adding the detector to CI with exit code 1 failing the build.

### 6. Report
Fill `templates/cycle-report.md`: groups found, the fix for each, the changed files, and what was verified.

## Rules
- Never execute or import the user's project to analyze it; the parser is enough.
- Keep changes small and reviewable: one cycle per commit, no behavior change.
- Dynamic imports (`importlib.import_module`, plugins, `__import__`) are invisible to static analysis; say so when the project uses them.

FILE:references/how-cycles-break.md
# How circular imports break (and when they don't)

## What Python does on `import a`
1. Looks in `sys.modules`. If `a` is there, even half-finished, it returns it immediately.
2. Otherwise it creates an empty module object, puts it in `sys.modules["a"]`, and runs `a.py` from top to bottom.
3. Names exist in `a` only after the line that defines them has run.

So in a cycle `a -> b -> a`:
- `import a` starts running `a.py`, which reaches `import b`.
- `b.py` runs and reaches `import a`; `a` is already in `sys.modules` (half-initialized), so it is returned at once.
- If `b` then does `from a import X` (or uses `a.X` at top level) before `a` has defined `X`, you get
  `ImportError: cannot import name 'X' from partially initialized module 'a'` or
  `AttributeError: partially initialized module 'a' has no attribute 'X'`.

Whether it crashes depends on **which module is imported first** and **what each side touches at import time**. That is why a cycle can pass the test suite and crash in production from a different entry point.

## Kinds of edges the script reports
| kind | where the import is | runs when | risk |
|---|---|---|---|
| `top` | module level (also inside `if`, `try`, `class` bodies) | the module is imported | can crash at import time |
| `deferred` | inside a function or method | the function is called | works if the other module has finished by then; fragile |
| `type_checking` | inside `if TYPE_CHECKING:` | never at runtime | no runtime effect; ignored by default |

## Findings
| code | severity | meaning | first move |
|---|---|---|---|
| IC00 | low | a file could not be parsed (syntax error, encoding) | fix or exclude the file, re-run |
| IC01 | high | cycle made only of import-time edges somewhere in the group | fix now; see fix-patterns.md 1-5 |
| IC02 | medium | every loop includes at least one deferred import | document it or remove the cycle properly |
| IC03 | medium | group of 5+ modules | draw the intended layers; fix edges that point upward |
| IC04 | medium | an `__init__.py` re-export sits in the shortest cycle | stop re-exporting, or import submodules directly |
| IC05 | medium | `from x import *` inside a cycle | replace with explicit names |
| IC06 | info | TYPE_CHECKING-only imports were ignored | nothing; use `--include-type-checking` to see them |

## How modules are resolved
- File `pkg/sub/mod.py` under the root becomes `pkg.sub.mod`; `pkg/__init__.py` becomes `pkg`.
- The root is `<project>/src` if it exists, otherwise `<project>`; override with `--root`.
- `from pkg import name` maps to `pkg.name` when that is a module, otherwise to `pkg`.
- `from . import x` and `from ..core import y` are resolved against the importing module's package.
- Third-party and standard library imports are ignored (they are not files under the root).
- Limitation: `import a.b` also runs `a/__init__.py`; the script records only the edge to `a.b`. If a package `__init__` imports heavily, check it by hand.

## Worked example (examples/shop)
`shop.orders` line 3 imports `Customer` from `shop.models`; `shop.models` line 3 imports `ORDER_STATUSES` from `shop.orders`. Importing `shop` runs `__init__` -> `orders` -> `models`, and `models` asks for `ORDER_STATUSES` before `orders` has defined it, so `python3 -c "import shop"` fails with the ImportError. The longer loop `orders -> payments -> notifications -> orders` survives only because `notifications` imports `orders` inside `send_receipt()`.

FILE:references/fix-patterns.md
# Fix patterns for circular imports

Pick the smallest change that makes dependencies point one way: from high-level modules (services, views, CLI) down to low-level ones (models, constants, utilities).

## 1. Move the shared piece down
When two modules share a constant, enum, exception or small type, move it to a lower module that imports neither.
```python
# before: models.py -> orders.py for ORDER_STATUSES, orders.py -> models.py for Customer
# after: shop/constants.py
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
# models.py and orders.py both: from shop.constants import ORDER_STATUSES
```
Best first choice: no behavior change, easy to review.

## 2. Type-only imports
If one side needs the other only for annotations:
```python
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from shop.models import Customer
def greet(customer: Customer) -> str: ...
```
The import never runs, so the runtime cycle disappears.

## 3. Move the function to its owner
A helper in `orders.py` that only works on customers belongs in `models.py` (or a `customers.py`). Cycles often show that one function lives in the wrong module.

## 4. Dependency inversion
The low-level module should not call the high-level one. Pass what it needs instead:
```python
# payments.py
def charge(order, on_success=None):
    ...
    if on_success:
        on_success(order)
# orders.py
payments.charge(order, on_success=notifications.send_receipt)
```
Alternatives: a small registry or signal (`events.subscribe("order_paid", send_receipt)`), or a protocol/ABC in a lower module.

## 5. Split a module that does two jobs
If `utils.py` imports half the project and half the project imports `utils.py`, split it by topic (`utils/text.py`, `utils/money.py`) so each part depends on less.

## 6. Import the module, not the name (stopgap)
`from shop import orders` and use `orders.ORDER_STATUSES` inside functions. Attribute lookup happens later, so some cycles stop crashing. It hides the design problem; leave a TODO and plan pattern 1-5.

## 7. Deferred import (last resort)
```python
def send_receipt(order):
    from shop.orders import ORDER_STATUSES  # deliberate: breaks cycle orders -> payments -> notifications
```
Acceptable for rarely used paths or optional heavy dependencies. Always add a comment naming the cycle; the detector keeps reporting it as IC02.

## Package `__init__.py` re-exports (IC04)
`from .orders import Order` in `__init__.py` makes `import shop.models` run `orders.py` first. Options: keep `__init__.py` light, re-export only leaf modules, or use a lazy `__getattr__` (PEP 562) for convenience names.

## After every fix
1. `python3 scripts/import_cycles.py <project>` - the group should be gone or smaller.
2. `python3 -c "import <each top-level module>"` in a fresh interpreter.
3. Run the tests, including any that import modules in a different order.
4. Add the detector to CI: a non-zero exit fails the build.

FILE:templates/cycle-report.md
# Import cycle report - {{project}} ({{date}})

**Scope:** {{modules}} modules under `{{root}}`, {{edges}} internal imports. Command: `python3 scripts/import_cycles.py {{project}}`
**Symptom:** {{error_or_reason}}

## Summary
- Cycle groups: {{group_count}} ({{import_time_count}} break at import time, {{deferred_count}} deferred only)
- Status after fixes: {{status}}

## Groups
| # | modules | shortest cycle | kind | fix chosen | status |
|---|---|---|---|---|---|
| 1 | {{modules_1}} | {{cycle_1}} | {{kind_1}} | {{fix_1}} | {{status_1}} |

## Changes
| file | change | pattern (fix-patterns.md) |
|---|---|---|
| {{file}} | {{change}} | {{pattern}} |

## Verification
- Detector re-run: {{detector_result}}
- Fresh-interpreter imports: {{import_check}}
- Tests: {{tests}}

## Remaining and notes
- Documented deferred imports (IC02): {{deferred_notes}}
- Dynamic imports not covered by static analysis: {{dynamic_imports}}
- Suggested CI step: `python3 scripts/import_cycles.py . || exit 1`

FILE:examples/shop/__init__.py
"""Fictional demo package for the import cycle detector (not a real shop)."""
from .orders import Order, place_order

__all__ = ["Order", "place_order"]

FILE:examples/shop/models.py
from dataclasses import dataclass

from shop.orders import ORDER_STATUSES


@dataclass
class Customer:
    id: int
    email: str
    status: str = ORDER_STATUSES[0]

FILE:examples/shop/orders.py
from dataclasses import dataclass, field

from shop.models import Customer
from shop import payments

ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]


@dataclass
class Order:
    id: int
    customer: Customer
    total_cents: int
    status: str = "new"
    lines: list = field(default_factory=list)


def place_order(order):
    payments.charge(order)
    order.status = "paid"
    return order

FILE:examples/shop/payments.py
from shop.notifications import send_receipt


def charge(order):
    # pretend to call a payment provider here
    send_receipt(order)
    return True

FILE:examples/shop/notifications.py
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from shop.models import Customer


def send_receipt(order):
    from shop.orders import ORDER_STATUSES  # deferred import, runs only when called
    return "Receipt for order %s (%s)" % (order.id, ORDER_STATUSES[1])


def greet(customer: "Customer"):
    return "Hello " + customer.email

FILE:examples/shop/utils.py
def cents_to_text(cents):
    return "%d.%02d" % divmod(cents, 100)

FILE:scripts/import_cycles.py
#!/usr/bin/env python3
"""import_cycles.py - find circular imports in a Python project (stdlib only, Python 3.8+).

Usage:
  python3 scripts/import_cycles.py <project_dir> [--root PKG_PARENT] [--json] [--include-type-checking]
  python3 scripts/import_cycles.py --self-test

Reads every .py file under <project_dir> (skipping venvs, build and cache folders), maps files to
module names, parses imports with ast (absolute, relative, `from pkg import submodule`), builds the
import graph between project modules and reports each strongly connected component (a group of
modules that import each other directly or indirectly) with its shortest cycle, the exact import
lines, whether each import runs at import time (top level) or later (inside a function), and a
suggested edge to break. Findings IC01-IC06. Exit 0 = no import-time cycles, 1 = import-time
cycle or other high finding, 2 = bad input.
"""
import argparse, ast, json, os, sys
from collections import deque

SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "build", "dist", "node_modules",
             ".tox", ".nox", ".mypy_cache", ".pytest_cache", "site-packages", ".eggs"}


def module_name(path, root):
    rel = os.path.relpath(path, root)[:-3].replace(os.sep, ".")
    if rel.endswith(".__init__"):
        rel = rel[: -len(".__init__")]
    return rel


def find_root(project):
    """Use project/src if it exists (src layout), else the project dir itself."""
    src = os.path.join(project, "src")
    return src if os.path.isdir(src) else project


def collect_files(root):
    out = []
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.endswith(".egg-info"))
        for f in sorted(filenames):
            if f.endswith(".py"):
                out.append(os.path.join(dirpath, f))
    return out


class ImportVisitor(ast.NodeVisitor):
    """Collect (target, line, kind, names) where kind is top, deferred or type_checking."""

    def __init__(self, modname, is_pkg):
        self.mod, self.is_pkg, self.depth, self.tc = modname, is_pkg, 0, 0
        self.found = []

    def _kind(self):
        if self.tc:
            return "type_checking"
        return "deferred" if self.depth else "top"

    def visit_FunctionDef(self, node):
        self.depth += 1; self.generic_visit(node); self.depth -= 1
    visit_AsyncFunctionDef = visit_FunctionDef
    visit_Lambda = visit_FunctionDef

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

    def visit_Import(self, node):
        for a in node.names:
            self.found.append((a.name, node.lineno, self._kind(), []))

    def visit_ImportFrom(self, node):
        if node.level:
            parts = self.mod.split(".")
            base = parts if self.is_pkg else parts[:-1]
            up = node.level - 1
            if up > len(base):
                return
            base = base[: len(base) - up] if up else base
            target = ".".join(base + ([node.module] if node.module else []))
        else:
            target = node.module or ""
        names = [a.name for a in node.names]
        self.found.append((target, node.lineno, self._kind(), names))


def resolve(target, names, modules):
    """Map an import target to project modules: the deepest existing module, plus submodules named in `from x import y`."""
    hits = []
    if names:
        for n in names:
            sub = target + "." + n if target else n
            if sub in modules:
                hits.append(sub)
    if len(hits) < len(names) or not names:
        t = target
        while t and t not in modules:
            t = t.rpartition(".")[0]
        if t:
            hits.append(t)
    return sorted(set(hits))


def build_graph(project, root=None):
    root = root or find_root(project)
    files = collect_files(root)
    if not files:
        raise ValueError("no .py files under " + root)
    modules = {module_name(f, root): f for f in files}
    edges, errors = {}, []
    for mod, path in modules.items():
        try:
            tree = ast.parse(open(path, encoding="utf-8").read(), filename=path)
        except (SyntaxError, UnicodeDecodeError) as e:
            errors.append((mod, str(e).splitlines()[0])); continue
        v = ImportVisitor(mod, path.endswith("__init__.py")); v.visit(tree)
        for target, line, kind, names in v.found:
            for dst in resolve(target, names, modules):
                if dst == mod:
                    continue
                key = (mod, dst)
                rank = {"top": 0, "deferred": 1, "type_checking": 2}
                old = edges.get(key)
                if old is None or rank[kind] < rank[old["kind"]]:
                    edges[key] = {"line": line, "kind": kind, "names": names, "file": os.path.relpath(path, project)}
    return root, modules, edges, errors


def sccs(nodes, adj):
    """Tarjan's algorithm, iterative."""
    index, low, onstack, stack, out, counter = {}, {}, set(), [], [], [0]
    for start in sorted(nodes):
        if start in index:
            continue
        work = [(start, iter(sorted(adj.get(start, ()))))]
        index[start] = low[start] = counter[0]; counter[0] += 1; stack.append(start); onstack.add(start)
        while work:
            v, it = work[-1]
            for w in it:
                if w not in index:
                    index[w] = low[w] = counter[0]; counter[0] += 1; stack.append(w); onstack.add(w)
                    work.append((w, iter(sorted(adj.get(w, ())))))
                    break
                if w in onstack:
                    low[v] = min(low[v], index[w])
            else:
                work.pop()
                if work:
                    low[work[-1][0]] = min(low[work[-1][0]], low[v])
                if low[v] == index[v]:
                    comp = []
                    while True:
                        w = stack.pop(); onstack.discard(w); comp.append(w)
                        if w == v:
                            break
                    if len(comp) > 1:
                        out.append(sorted(comp))
    return out


def shortest_cycle(comp, adj):
    best = None
    cs = set(comp)
    for s in comp:
        prev, q = {s: None}, deque([s])
        while q:
            v = q.popleft()
            for w in sorted(adj.get(v, ())):
                if w not in cs:
                    continue
                if w == s:
                    path = [v]
                    while prev[path[-1]] is not None:
                        path.append(prev[path[-1]])
                    cyc = list(reversed(path)) + [s]
                    if best is None or len(cyc) < len(best):
                        best = cyc
                    q.clear(); break
                if w not in prev:
                    prev[w] = v; q.append(w)
    return best


def analyze(project, root=None, include_tc=False):
    root, modules, edges, errors = build_graph(project, root)
    use = {k: v for k, v in edges.items() if include_tc or v["kind"] != "type_checking"}
    top = {k: v for k, v in use.items() if v["kind"] == "top"}
    def adj_of(es):
        a = {}
        for (s, d) in es:
            a.setdefault(s, set()).add(d)
        return a
    adj_all, adj_top = adj_of(use), adj_of(top)
    groups, findings = [], []
    top_sccs = [set(c) for c in sccs(modules, adj_top)]
    for comp in sccs(modules, adj_all):
        cyc = shortest_cycle(comp, adj_all)
        cyc_edges = [dict(src=a, dst=b, **use[(a, b)]) for a, b in zip(cyc, cyc[1:])]
        import_time = any(set(comp) & t for t in top_sccs)
        inner = [dict(src=s, dst=d, **e) for (s, d), e in use.items() if s in comp and d in comp]
        # break candidate: top-level edge in the shortest cycle importing the fewest names, prefer non-__init__ sources
        cands = [e for e in cyc_edges if e["kind"] == "top"] or cyc_edges
        brk = min(cands, key=lambda e: (len(e["names"]) or 1, e["file"].endswith("__init__.py"), e["src"]))
        g = dict(modules=comp, size=len(comp), shortest_cycle=cyc, cycle_edges=cyc_edges,
                 import_time=import_time, edges_inside=len(inner), other_edges=[e for e in sorted(inner, key=lambda e: (e["src"], e["dst"])) if (e["src"], e["dst"]) not in set(zip(cyc, cyc[1:]))], break_candidate=brk)
        groups.append(g)
        label = " -> ".join(cyc)
        if import_time:
            findings.append(("high", "IC01", "import-time cycle: " + label))
        else:
            findings.append(("medium", "IC02", "cycle only through imports inside functions (works, but fragile): " + label))
        if len(comp) >= 5:
            findings.append(("medium", "IC03", "large tangle of %d modules: %s" % (len(comp), ", ".join(comp))))
        for e in cyc_edges:
            if e["file"].endswith("__init__.py") and e["kind"] == "top":
                findings.append(("medium", "IC04", "package __init__ re-exports into the cycle: %s line %d" % (e["file"], e["line"])))
            if e["kind"] == "top" and e["names"] == ["*"]:
                findings.append(("medium", "IC05", "star import inside a cycle: %s line %d" % (e["file"], e["line"])))
    tc_only = [k for k, v in edges.items() if v["kind"] == "type_checking"]
    if tc_only and not include_tc:
        findings.append(("info", "IC06", "%d TYPE_CHECKING-only import(s) ignored (they never run)" % len(tc_only)))
    for mod, err in errors:
        findings.append(("low", "IC00", "could not parse %s: %s" % (mod, err)))
    return dict(project=project, root=root, modules=len(modules), edges=len(use), groups=groups,
                findings=[dict(severity=s, code=c, message=m) for s, c, m in findings])


def render(res):
    L = ["# Import cycle report", "",
         "Project: %s (modules from %s): %d modules, %d internal imports, %d cycle group(s)" %
         (res["project"], res["root"], res["modules"], res["edges"], len(res["groups"])), ""]
    for i, g in enumerate(res["groups"], 1):
        L.append("## Group %d: %d modules (%s)" % (i, g["size"], "breaks at import time" if g["import_time"] else "deferred imports only"))
        L.append("Modules: " + ", ".join(g["modules"]))
        L.append("Shortest cycle: " + " -> ".join(g["shortest_cycle"]))
        for e in g["cycle_edges"]:
            L.append("  - %s line %d: %s imports %s%s [%s]" % (e["file"], e["line"], e["src"], e["dst"],
                     (" (" + ", ".join(e["names"]) + ")") if e["names"] else "", e["kind"]))
        if g["other_edges"]:
            L.append("Other imports inside this group:")
            for e in g["other_edges"]:
                L.append("  - %s line %d: %s imports %s [%s]" % (e["file"], e["line"], e["src"], e["dst"], e["kind"]))
        b = g["break_candidate"]
        L.append("Suggested place to break: %s line %d (%s -> %s)" % (b["file"], b["line"], b["src"], b["dst"]))
        L.append("")
    if not res["groups"]:
        L += ["No import cycles between project modules.", ""]
    L.append("## Findings")
    order = {"high": 0, "medium": 1, "low": 2, "info": 3}
    for f in sorted(res["findings"], key=lambda f: (order[f["severity"]], f["code"])):
        L.append("- [%s] %s %s" % (f["severity"], f["code"], f["message"]))
    if not res["findings"]:
        L.append("- none")
    return "\n".join(L)


def self_test():
    import tempfile
    ok = [0, 0]
    def check(name, cond):
        ok[0 if cond else 1] += 1
        print(("PASS  " if cond else "FAIL  ") + name)
    def proj(files):
        d = tempfile.mkdtemp()
        for rel, txt in files.items():
            p = os.path.join(d, rel); os.makedirs(os.path.dirname(p), exist_ok=True)
            open(p, "w").write(txt)
        return d
    r = analyze(proj({"a.py": "import b\n", "b.py": "x = 1\n"}))
    check("no cycle in a -> b", not r["groups"])
    r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
    check("direct cycle a <-> b found", len(r["groups"]) == 1 and r["groups"][0]["size"] == 2)
    check("direct cycle is import-time IC01", any(f["code"] == "IC01" for f in r["findings"]))
    r = analyze(proj({"a.py": "import b\n", "b.py": "import c\n", "c.py": "import a\n"}))
    check("three-module cycle shortest path length 4", r["groups"][0]["shortest_cycle"] == ["a", "b", "c", "a"])
    r = analyze(proj({"a.py": "import b\n", "b.py": "def f():\n    import a\n"}))
    check("function-level import gives IC02 not IC01", [f["code"] for f in r["findings"]] == ["IC02"])
    r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    import a\n"}))
    check("TYPE_CHECKING import ignored by default", not r["groups"] and r["findings"][0]["code"] == "IC06")
    r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    import a\n"}), include_tc=True)
    check("TYPE_CHECKING import counted with flag", len(r["groups"]) == 1)
    r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from . import y\n", "pkg/y.py": "from .x import thing\n"}))
    check("relative imports resolved", r["groups"] and r["groups"][0]["modules"] == ["pkg.x", "pkg.y"])
    r = analyze(proj({"pkg/__init__.py": "from .x import X\n", "pkg/x.py": "from pkg import helpers\nX = 1\n", "pkg/helpers.py": "import pkg\n"}))
    check("__init__ re-export flagged IC04", any(f["code"] == "IC04" for f in r["findings"]))
    r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from pkg import y\n", "pkg/y.py": "x = 1\n"}))
    check("from pkg import submodule maps to the submodule", not r["groups"])
    r = analyze(proj({"src/app/__init__.py": "", "src/app/a.py": "from app import b\n", "src/app/b.py": "from app.a import f\n"}))
    check("src layout root detected", r["root"].endswith("src") and len(r["groups"]) == 1)
    r = analyze(proj({"a.py": "from b import *\n", "b.py": "import a\n"}))
    check("star import in cycle flagged IC05", any(f["code"] == "IC05" for f in r["findings"]))
    files = {"m%d.py" % i: "import m%d\n" % ((i + 1) % 5) for i in range(5)}
    r = analyze(proj(files))
    check("five-module ring flagged IC03", any(f["code"] == "IC03" for f in r["findings"]))
    r = analyze(proj({"a.py": "import os, json\nimport b\n", "b.py": "import sys\n"}))
    check("stdlib imports ignored", r["edges"] == 1)
    r = analyze(proj({"a.py": "import b\n", "b.py": "def (:\n"}))
    check("syntax error reported IC00", any(f["code"] == "IC00" for f in r["findings"]))
    r = analyze(proj({"venv/lib/x.py": "import y\n", "venv/lib/y.py": "import x\n", "a.py": "x=1\n"}))
    check("venv folder skipped", r["modules"] == 1)
    r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
    b = r["groups"][0]["break_candidate"]
    check("break candidate is an edge of the cycle", (b["src"], b["dst"]) in [("a", "b"), ("b", "a")])
    try:
        analyze(proj({"README.md": "x"})); check("empty project rejected", False)
    except ValueError:
        check("empty project rejected", True)
    print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
    return 0 if not ok[1] else 1


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("project", nargs="?")
    ap.add_argument("--root", help="folder that contains the top-level packages (default: <project>/src if present, else <project>)")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--include-type-checking", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.project or not os.path.isdir(a.project):
        print("error: give a project directory", file=sys.stderr); return 2
    try:
        res = analyze(a.project, a.root, a.include_type_checking)
    except ValueError as e:
        print("error:", e, file=sys.stderr); return 2
    print(json.dumps(res, indent=2) if a.json else render(res))
    return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main())
ArchitectureRefactoringEngineering+3
F@f
0
Monarch Butterflies Clustered on Sunlit Fir Trees in a Mountain Forest
1
Image
Monarch Butterflies Clustered on Sunlit Fir Trees in a Mountain Forest

Photoreal winter morning in a high mountain forest: thousands of monarch butterflies cluster on sagging fir branches, a few dozen already flying through hazy sunbeams from the upper left, warm orange wings against cool blue-green shade. Step 1 of the Monarch Butterflies on Sunlit Fir Trees workflow.

A photorealistic wide photograph of thousands of orange-and-black monarch butterflies clustered on the branches of tall fir trees in a high mountain forest on a cool winter morning. In the foreground on the right, a big fir branch sags under a dense cluster of butterflies, most with wings closed, showing the pale orange undersides, a few with wings open in bright orange with black veins and white-dotted edges. Behind it, the trunks and branches of more firs fade into a soft blue morning haze, their branches covered in brownish-orange clusters. Low sunlight comes from the upper left through a gap in the canopy, making long hazy sunbeams across the scene, and a few dozen butterflies are already flying in the light between the trees. The forest floor below is in shadow with a few fallen butterflies and fir needles.

Shot like a professional nature photograph: 50 mm lens, sharp detail on the near cluster, the background slightly softer, warm orange against cool blue-green, gentle haze. No people, no buildings, no text. Landscape 16:9.
WorkflowCinematicRealism+2
F@f
0
Hand-Painted Alebrije Wood Carving of a Leaping Jaguar
Image
Hand-Painted Alebrije Wood Carving of a Leaping Jaguar

A studio photo of a hand-carved Oaxacan-style alebrije of a jaguar caught mid-leap on a carved rock: cobalt blue body covered in tiny white and yellow dots, orange rosettes, magenta zigzags, lime leaf shapes and a turquoise face, with knife facets, uneven brushwork and soft window light.

A studio photograph of a hand-carved and hand-painted Oaxacan-style alebrije wood sculpture of a jaguar caught mid-leap, its front paws reaching forward and its long tail curling up into a spiral, standing on a small carved rock base. The whole figure is painted in bright folk colors over carved copal wood: a cobalt blue body covered in tight rows of tiny white and yellow dots, orange rosettes outlined in black, magenta zigzag bands on the legs, lime green leaf shapes along the spine, a turquoise face with large almond eyes, small carved ears and a row of painted white teeth. Separate carved ears and tail are fitted into the body as real alebrijes are.

Render it like real handmade folk art: visible knife facets under the paint, slightly uneven brushwork and dot spacing, a few tiny hairline cracks in the wood and a soft satin sheen. The figure sits on a warm terracotta-colored tabletop against a plain off-white wall, soft window light from the left, gentle shadow, shallow depth of field. No text, no people, no hands. Portrait 3:4.
DesignCreativePhotography+2
F@f
0
Polish Wycinanki Paper-Cut of Two Roosters Around a Tree of Life
Image
Polish Wycinanki Paper-Cut of Two Roosters Around a Tree of Life

A flat-lay photo of a Polish wycinanki folk paper-cut: two mirrored roosters with layered rainbow tail feathers facing each other under a symmetrical tree of life with tulips, round flowers and a bird on top, cut from glossy colored paper on cream card with crisp edges and soft layer shadows.

A flat-lay photograph of a traditional Polish wycinanki folk paper-cut showing two mirrored roosters facing each other beneath a symmetrical tree of life, made from layered glossy colored paper glued on a plain cream card. The tree rises from a layered red paper heart at the bottom center: a black paper trunk with curling branches, round red, yellow and green flower heads, tulips, tiny leaves and one small bird perched at the very top. On each side stands a proud rooster with a tall fan of tail feathers cut in alternating red, magenta, emerald, orange and violet layers, a scalloped comb and spurs on its feet. Small stars and dots are scattered in the empty spaces.

Render it like real hand-cut paper: crisp scissor edges with tiny irregularities, each layer slightly raised with thin soft shadows, the faint sheen of glossy paper and a subtle grain on the cream card. Soft even daylight from above, sharp focus across the whole piece, natural colors. No text, no signatures, no hands, no scissors. Square 1:1.
DesignCreativePatterns+3
F@f
0
Enterprise Customer Pilot Plan (YAML)
Text

Turn one enterprise pilot or paid proof of concept into a YAML plan: measurable success criteria with baselines, a stakeholder map, security and data steps before kickoff, a week-by-week timeline, scope rules, midpoint and final readouts, the path to contract, risks and stall warning signs.

1role: >-
2 Pilot program lead for B2B startups selling to larger companies. You turn
3 one planned enterprise pilot (a paid pilot, a proof of concept or a trial
4 with a big prospect) into a practical, time-boxed plan: clear success
5 criteria agreed in writing, the right people on both sides, a realistic
6 technical and security path, a weekly rhythm, and a clean decision at the
7 end, so the pilot turns into a signed contract instead of drifting for
8 months as a free consulting project.
9
10pilot:
...+137 more lines
YAMLB2BEnterprise+4
F@f
0
Previous2 / 30Next