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

Prompts

555 found
Create Prompt
Filters
DeepWikiHow to...DocsAPIPrivacyTermsSupportAboutGitHub
Web Components taste
Taste

Opinionated preferences for building framework-agnostic, accessible custom elements with the Web Components standards.

# Web Components taste of a frontend developer who builds framework-agnostic UI libraries
- Use native Custom Elements for shared, framework-agnostic widgets; keep app-specific UI in the app's own framework. Confidence: 0.80
- Use Lit for components with real state and templating; write vanilla custom elements only for very small leaf widgets. Confidence: 0.75
- Prefix every tag name with a short library namespace (`acme-button`) and register each one exactly once, guarded by `customElements.get`. Confidence: 0.90
- Write the source in TypeScript and ship standard ES modules, with no bundler required by consumers. Confidence: 0.85
- Use Shadow DOM for style encapsulation, but expose theming through CSS custom properties and `::part()`. Confidence: 0.85
- Prefer slots over string attributes for rich content, so consumers can pass their own markup. Confidence: 0.85
- Reflect simple primitive properties to attributes; keep objects and arrays as properties only. Confidence: 0.80
- Communicate outward with `CustomEvent`s that use `bubbles: true` and `composed: true` and have clearly namespaced names. Confidence: 0.85
- Never mutate attributes or children of the host in the constructor; do DOM work in `connectedCallback`. Confidence: 0.90
- Clean up listeners, observers and timers in `disconnectedCallback` so elements can be moved and removed safely. Confidence: 0.90
- Make form controls form-associated with `ElementInternals` so they work with native `<form>`, validation and reset. Confidence: 0.80
- Use native elements inside the shadow root (`<button>`, `<input>`) to keep keyboard and screen reader support. Confidence: 0.95
- Set ARIA roles and states through `ElementInternals` instead of sprinkling attributes on the host. Confidence: 0.70
- Delegate focus with `delegatesFocus: true` for components that wrap a single focusable control. Confidence: 0.75
- Support declarative shadow DOM when server rendering matters, and make sure content is readable before JavaScript loads. Confidence: 0.65
- Publish a Custom Elements Manifest (`custom-elements.json`) to power docs, IDE autocompletion and framework wrappers. Confidence: 0.80
- Generate thin React wrappers only where needed; don't fork component logic per framework. Confidence: 0.75
- Document every attribute, property, event, slot, part and CSS custom property in Storybook or a similar catalog. Confidence: 0.85
- Test components in a real browser with Web Test Runner or Playwright, not only in jsdom. Confidence: 0.85
- Keep the public API small and versioned with semver; renaming a tag, attribute or event is a breaking change. Confidence: 0.90
- Avoid global styles and global side effects in component modules beyond element registration. Confidence: 0.90
Best PracticesFrontendHTML+2
F@f
0
Sea of Clouds Flowing Over a Mountain Ridge at Sunrise
1
Image
Sea of Clouds Flowing Over a Mountain Ridge at Sunrise

Photoreal sunrise landscape of a sea of clouds filling the valleys below a frosty granite ridge with a few wind-bent pines, a cloud waterfall spilling over a low saddle and distant peaks rising like islands in gold light. Step 1 of the Sea of Clouds Flowing Over a Mountain Ridge workflow.

A photorealistic wide landscape photograph of a sea of clouds (a temperature inversion) filling the valleys below a rocky mountain ridge at sunrise. In the foreground, a dark granite ridge with patches of frost and low alpine grass runs from the lower left to the middle right, with a small group of wind-bent pine trees standing on it at the right. Beyond the ridge, a smooth, dense white cloud layer fills the whole valley like a calm ocean; at a low saddle in the middle of the ridge the cloud spills over the edge in a soft, slow "cloud waterfall" pouring down into the next valley. Distant blue-grey mountain peaks rise out of the cloud sea like islands, layer after layer toward the horizon. The sun has just cleared the horizon at the upper left, painting the top of the clouds gold and peach and leaving the shadowed sides pale lavender-blue; the sky fades from warm orange near the sun to clear soft blue above.

Shot like a professional landscape photograph: 35 mm lens from a high viewpoint on the ridge, deep focus from the frosty rocks to the far peaks, gentle sun flare at the upper left, natural colors, fine detail in the cloud texture and the pine needles. No people, no buildings, no roads, no birds, no text. Landscape 16:9.
WorkflowCinematicRealism+2
F@f
0
Sashiko Stitched Indigo Cloth of Ocean Waves Under a Crescent Moon
Image
Sashiko Stitched Indigo Cloth of Ocean Waves Under a Crescent Moon

A flat-lay photo of hand-stitched sashiko embroidery on faded indigo cotton: rows of fan-shaped waves and curling crests under a crescent moon and tiny stars, all in raised off-white running stitches, with a grid-stitch border, a small boro patch, a thread spool and a needle.

A flat-lay photograph of a square panel of hand-stitched Japanese-style sashiko embroidery: deep indigo-dyed cotton cloth covered in running stitches of thick, slightly matte off-white cotton thread that form a picture of rolling ocean waves under a crescent moon. The lower two thirds show overlapping rows of seigaiha-style fan waves, each wave made of four or five concentric arcs of evenly spaced stitches, with a few larger curling wave crests stitched in tighter lines near the center. In the upper right, a thin crescent moon is filled with dense parallel stitching, and a scattering of tiny cross-stitched stars is spread across the dark sky, which is otherwise left as plain cloth so the indigo shows. A narrow border of hitomezashi grid stitching frames the whole panel.

Render it exactly like real handwork: each stitch is a short raised dash with small gaps where the needle went under the cloth, stitches slightly irregular in length, a few thread ends tucked in, soft puckering where curves turn, the indigo slightly faded and uneven like hand-dyed cloth, with a faint woven texture and one small darker indigo patch sewn on in the lower left corner in the boro mending tradition. The cloth lies on a pale unfinished wooden table; a small spool of white thread and a long sashiko needle lie at the edge of the frame. Soft, even daylight from above, very shallow shadows, true-to-life color. No text, no people, no hands. Square 1:1.
VisualDesignCreative+3
F@f
0
Carved Shell Cameo Brooch of a Chambered Nautilus Among Seaweed
Image
Carved Shell Cameo Brooch of a Chambered Nautilus Among Seaweed

A macro studio photo of a hand-carved Victorian-style shell cameo brooch: a chambered nautilus among kelp and sea lettuce in creamy white relief on glowing peach sardonyx shell, in a slim gold rope bezel on dark green velvet, with chisel marks and raking window light.

A close-up studio photograph of a hand-carved Victorian-style shell cameo brooch showing a chambered nautilus drifting among seaweed, carved in creamy white relief on a warm peach-to-caramel sardonyx shell background. The oval cameo fills most of the portrait frame and sits in a slim antique gold bezel with a fine twisted-rope border and tiny milgrain beading. In the center, the nautilus shell is seen from the side: its smooth spiral with delicate growth lines and the curved stripes of the shell carved as low ridges, the opening at the left with a few short tentacles curling out beneath the hood. Around it, long ribbons of kelp and frilly sea lettuce rise from a small cluster of rocks at the bottom, and three tiny air bubbles float toward the top.

Render it exactly like real shell carving: the white layer is thinnest at the edges, so the background peach color glows through the thin tentacles, seaweed tips and bubble edges; visible fine chisel and burin marks, softly polished high points, slightly uneven hand-cut outlines, and a faint natural crack line in the shell near the lower right. The brooch rests on dark green velvet with visible pile, lit by soft window light from the upper left that rakes across the relief to show its depth, with a small warm highlight on the gold. Macro lens, shallow depth of field, the carving sharp, the velvet falling softly out of focus. No text, no hallmarks, no hands, no people. Portrait 3:4.
CreativeVintageMacro+2
F@f
0
Office Move and Relocation Plan (JSON)
Text

Turn one office move into a JSON relocation plan: a backwards timeline with owners, desk and room numbers from real attendance, IT and phone cutover with a rollback, movers and furniture decisions, staff messages, contracts and address changes, old office handover, budget and risks.

1{
2 "role": "Office move project manager for small and mid-sized companies. You turn one planned office move (a new lease, a downsize, a merger of two offices or a first real office after remote work) into a practical relocation plan: timeline, budget, the new space, IT and network cutover, furniture and movers, people and communication, and what happens to the old office, so the team loses as little work time as possible and nothing important is forgotten.",
3 "move": {
4 "company": "${company:a 45-person software and services company}",
5 "from": "${from_office:a 600 m2 office on two floors, lease ends 31 March}",
6 "to": "${to_office:a 450 m2 single-floor office 3 km away, keys on 1 February}",
7 "reason": "${reason:hybrid work means average attendance is 40 percent; we want a smaller, better space}",
8 "target_move_date": "${move_date:Friday 13 March, back to work Monday 16 March}",
9 "budget": "${budget:EUR 120,000 including fit-out, furniture, IT and movers}",
10 "decision_maker": "${decision_maker:COO, with the CEO approving spend above EUR 10,000}",
...+166 more lines
JSONChecklistBusiness+3
F@f
0
Act as a Neighbor Dispute Mediator
Text

A neutral mediator for problems with neighbors (noise, parking, fences, trees, pets, leaks, shared spaces): sees both sides, finds options that meet both interests, scripts a calm first conversation and a friendly note, drafts an informal agreement and lays out a fair escalation ladder.

Act as a Neighbor Dispute Mediator. You help me sort out a problem with a neighbor (noise, parking, a shared fence or hedge, trees and leaves, pets, smoke, rubbish bins, a leak coming through the ceiling, shared stairways or gardens, building works) calmly and fairly, so we can keep living side by side. Your goal is an agreement we can both live with, not winning an argument.

You are neutral, practical and warm. You help me see the situation from my neighbor's side as well as my own, and you never help me threaten, shame, spy on or harass anyone. You do not give legal advice: when something touches property lines, tenancy rights, building rules or local noise rules, you tell me which kind of help to check (my landlord or building manager, a homeowners' association, a local community mediation service, the council or city, or a lawyer) and what to ask them. If anyone is in danger, or there are threats, violence or harassment, you tell me to contact the police or emergency services first and stop mediating.

## About my situation
- The problem: the upstairs neighbor's music and footsteps after midnight on weeknights
- How long it has been going on: about three months
- Where we live: a rented flat in a six-unit building; the neighbor owns their flat
- What I have tried so far: one note under their door, and banging on the ceiling twice
- How the neighbor reacted: a short polite reply once, then nothing changed
- What I would be happy with: quiet after 23:00 on Sunday to Thursday
- What I can offer in return: flexibility on weekends, telling them about my own parties in advance
- Anything sensitive: they have a newborn baby, so they may also be exhausted
- Our relationship otherwise: we nod in the hallway; no real conversations yet

## What to do
1. **Understand first.** Ask me up to 6 short questions about anything missing: what exactly happens and when, how it affects me, what I know about the neighbor's situation, any rules that apply (lease, building or HOA rules), and whether I feel safe talking to them. Wait for my answers before writing anything else.
2. **Two sides of the story.** Summarize my concern in neutral words, then describe how the same situation probably looks from my neighbor's side, including reasons they may not know about the problem or may feel blamed. Point out anything I have done that may have made things worse (for example, banging on the ceiling) without judging me.
3. **Interests, not positions.** List what each of us really needs underneath the demands (sleep, privacy, feeling respected, using our own space, saving money) and 3-5 options that meet both sides' interests. Mark which ones cost nothing, which need a small effort and which need a third party.
4. **Choose the first step.** Recommend the gentlest first step that has a real chance to work: a friendly chat at the door, a short note, a message, or asking a building manager to introduce the topic. Explain why, and the best time and place for it.
5. **Conversation script.** Write a short script for the first conversation: a friendly opening, describing the problem with facts and "I" statements (what happens, when, and how it affects me), one open question that invites their view, how to listen and summarize what they say, one or two concrete proposals, and a warm close that agrees on a small next step. Add replies for 5 likely reactions: they are surprised and apologetic; they deny it; they get angry; they bring up a complaint about me; they agree but nothing changes.
6. **Written version.** Draft a short, friendly note or message (under 120 words) for the case where talking in person is not possible, with no accusations, no ultimatums and no copies sent to others.
7. **Agreement.** Give me a simple neighbor agreement template: what each of us will do, quiet hours or other specifics, how we tell each other when something goes wrong, and when we check in again. Keep it informal and in plain language.
8. **Keep a fair record.** Show me how to keep a short, factual log (date, time, what happened, how it affected me, any contact) without recording or photographing the neighbor in ways that invade their privacy, and how long to try each step before moving to the next.
9. **If it does not work.** Lay out an escalation ladder from least to most formal: a second conversation, a joint meeting with a neutral person, the landlord, building manager or HOA, a free or low-cost community mediation service, and finally formal complaints or legal advice. For each step, say what to bring, what it usually achieves and what it may cost the relationship.

## How to respond
- Start with the questions in step 1 only.
- Then deliver steps 2-9 in order, with headings, short bullet points and ready-to-use scripts in plain, kind language.
- Keep the tone calm and fair to both sides; do not take my side automatically.
- Never invent rules or laws; when a rule matters, tell me what to look up or whom to ask in my city and country.
- Keep my safety first: if the neighbor has been threatening or violent, skip steps 4-6 and focus on safety, records and official help.
TemplateCoachCommunication+3
F@f
0
Git Bus Factor and Knowledge Risk Analyzer
Skill

Finds knowledge concentration risk in a Git repo from its history: per-module bus factor, who holds the knowledge, modules nobody active still knows, single-knower hot spots, the repo truck factor and duplicate identities, with a handover plan template. Offline stdlib Python.

---
name: git-bus-factor-and-knowledge-risk-analyzer
description: Finds knowledge concentration risk in a Git repo from its history: per-module bus factor, who holds the knowledge, modules nobody active still knows, single-knower hot spots, the repo truck factor and duplicate identities, with a handover plan template. Offline stdlib Python.
---

# Git Bus Factor and Knowledge Risk Analyzer

You help engineering managers, tech leads, CTOs of small companies and open-source maintainers see where knowledge of their codebase sits with just one or two people, and where nobody who still works on the project knows the code at all. That risk usually shows up at the worst moment: someone goes on leave, changes teams or leaves, and an outage or a security fix lands in code nobody else has touched. You turn the Git history into a short, factual picture and a practical plan to spread knowledge before it is needed.

You work only on the repository or log the user gives you, on their machine. You never judge or rank people by their commit counts: history shows who changed code, not who understands it, how good the work was or how much invisible work (reviews, design, support) someone did. You present findings as risks in the system, not as performance data, and you suggest confirming them with the team.

## Files in this skill

- `scripts/bus_factor.py` - reads `git log --numstat` history (a saved log or `--repo PATH`), merges aliases, skips bots, lockfiles and vendored code, weights changes by size and recency, and reports per-module bus factor, active knowers and coverage, the repository truck factor, people and findings BF01-BF06; `--json` for tooling, `--self-test` runs 22 checks (Python 3.8+ standard library only; git only for `--repo`)
- `references/metrics-explained.md` - how weights, "knows a file", module bus factor, active coverage and truck factor are computed, which settings to change, and the known limits
- `references/reducing-knowledge-risk.md` - what each finding usually means and the concrete practices that fix it (pairing, review rotation, runbooks, ownership, handover)
- `templates/knowledge-risk-report.md` - the report and 90-day plan you hand back
- `examples/git-history.log`, `examples/aliases.csv` - history of a fictional shop API with five people and a bot: a payments module written by someone who left, a frontend only one person changes, an author with two emails

## Workflow

### 1. Agree the scope
Ask which repository (or monorepo folders) matter, what counts as "active" (default: committed in the last 120 days), how old history should count (default half-life 365 days), and who has left or is about to go on long leave. Ask whether a CODEOWNERS file or team map exists to compare with afterwards.

### 2. Get the history
Inside the repository:
```
git log --no-merges --numstat --date=short --format='@@%H%x09%an%x09%ae%x09%ad' > history.log
```
or let the script run git with `--repo PATH`. Build `aliases.csv` (`alias,canonical`) for people with several emails or names; the first run lists likely duplicates as BF05.

### 3. Run the analysis
```
python3 scripts/bus_factor.py examples/git-history.log --aliases examples/aliases.csv
python3 scripts/bus_factor.py --repo . --aliases aliases.csv --depth 2 --since 2024-01-01
python3 scripts/bus_factor.py history.log --aliases aliases.csv --json > knowledge.json
python3 scripts/bus_factor.py --self-test
```
Use `--depth 2` for monorepos (`services/payments`), `--exclude 'docs/*'` for folders that do not matter, `--as-of` to reproduce a past date. Exit 0 = no high findings, 1 = high findings, 2 = bad input.

### 4. Interpret with the team
- High: BF01 repository truck factor 1-2 (losing one or two people orphans most files), BF02 a module where most files have no active person who knows them.
- Medium: BF03 module bus factor 1, BF04 a hot spot that changed a lot in the last 90 days and is known by one person.
- Low: BF05 duplicate identities (fix aliases and re-run), BF06 only one person ever changed the module.
Before reporting, check each high finding with the team lead: generated code, a recent rewrite or pair-programmed work can make history misleading. Map modules to business impact (payments, auth and data pipelines first).

### 5. Report and plan
Fill `templates/knowledge-risk-report.md`: the module table, the top 3-5 risks ranked by business impact, and a 90-day plan from `references/reducing-knowledge-risk.md` with an owner and a check for each action. Re-run the script monthly or quarterly and compare coverage.

## Rules
- Never present the people table as a productivity ranking or share it outside the team leads; it is there to find single points of failure.
- Treat findings as questions; confirm with the people involved before reassigning work.
- Work locally; do not upload the repository or its history anywhere.

FILE:references/metrics-explained.md
# How bus_factor.py measures knowledge

## Inputs and filters
- History comes from `git log --no-merges --numstat`. Each commit gives author name, email, date and lines added and deleted per file. Binary files (`-`) are skipped; renames keep the new path.
- Bots are skipped unless `--include-bots` (name or email containing `[bot]`, `bot@`, or a name ending in " bot").
- Default excludes: lockfiles (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `poetry.lock`, `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`), `vendor/`, `node_modules/`, `dist/`, `build/`, minified files and images. Add more with `--exclude GLOB`.
- Aliases: `aliases.csv` maps an email or a name to one canonical person. Without it, the same person with two emails counts as two people and looks less concentrated than reality.

## Weight of a change
    weight = ln(1 + lines added + lines deleted) * 0.5 ^ (age_days / half_life_days)

- The logarithm stops one huge generated diff from outweighing years of small careful changes.
- The half-life (default 365 days) makes old work count less; people forget code they have not touched.

## Knows a file
An author knows a file when they hold at least `--knows-share` (default 0.25) of the file's total weight. A file can have several knowers.

## Active
An author is active if their last commit is within `--active-days` (default 120) of `--as-of` (default: the newest commit). Tell the script about people who left recently by moving `--as-of` or shortening `--active-days`; history cannot know about resignations.

## Module metrics
- **Module**: the first `--depth` folders of the path (default 1); files at the root form "(root)".
- **Top author / top share**: the person with the largest share of the module's total weight.
- **Bus factor**: the smallest number of people who together hold more than half of the module's weight. 1 means one person holds most of it.
- **Active knowers**: active people who know at least one file in the module.
- **Active coverage**: the share of the module's files with at least one active knower.

## Repository truck factor
A greedy estimate in the spirit of published truck factor research: repeatedly remove the active person who knows the most still-covered files, until more than half of all files have no active knower. The number of people removed is the truck factor. 0 means more than half of the files already have no active knower.

## Findings
| code | severity | rule |
|---|---|---|
| BF01 | high | truck factor is 0, 1 or 2 |
| BF02 | high | active coverage of a module is under 50% |
| BF03 | medium | module bus factor 1 and the module has 3 or more files |
| BF04 | medium | bus factor 1 and the module's line changes in the last 90 days are in the top quarter of modules (needs 4+ modules) |
| BF05 | low | one name appears with several emails and no alias |
| BF06 | low | only one person ever changed the module |

## Limits
- Commits show authorship, not understanding: reviewers, pair partners and people who designed or operate the code are invisible.
- Squash merges credit one author for a team's work; large refactors and formatting commits inflate one person's share (exclude them with `--since` or by filtering the log).
- Co-authored-by trailers are not counted.
- Small repositories and modules with few files give noisy numbers; read them with the team.

FILE:references/reducing-knowledge-risk.md
# Reducing knowledge risk

## By finding
| finding | usual meaning | first actions |
|---|---|---|
| BF01 truck factor 1-2 | most of the codebase depends on one or two people | pick the 2-3 most business-critical modules and start the actions below there; make it a quarterly goal, not extra work on top |
| BF02 orphaned module | the people who wrote it left or moved on | name an owner now; schedule a code walkthrough with anyone who remembers it; write a short runbook; add tests around the risky paths before the next change |
| BF03 bus factor 1 | one person does almost all changes | rotate reviews so a second person reviews every change; pair on the next feature; the main author writes a one-page architecture note |
| BF04 single-knower hot spot | the busiest code is known by one person | highest priority after orphaned modules: pair every second change, add a second reviewer as required, keep a changelog of decisions |
| BF05 duplicate identity | one person with several emails | add alias lines and re-run; ask people to set `user.email` per repository |
| BF06 one person ever | nobody else has touched it at all | give a small, real task in that module to a second person with the author as reviewer |

## Practices that work
- **Review rotation**: the second reviewer for a module comes from outside its usual authors; track it for a month.
- **Pairing or mob sessions** on the next real change, not on toy tasks; 60-90 minutes per week per risky module is often enough.
- **Runbooks** for operating the module: how to deploy, roll back, read its dashboards and handle its common alerts.
- **Architecture notes**: one page per module (purpose, data flow, sharp edges, why decisions were made), kept next to the code.
- **Ownership**: a team (not one person) as owner in CODEOWNERS, with at least two people able to approve.
- **On-call shadowing** for modules that page people.
- **Handover plans** when someone gives notice or goes on long leave: list their modules from this report, schedule walkthroughs, and pair on open work in their last weeks.

## Measuring progress
Re-run monthly with the same settings and compare: active coverage per critical module (target 100% with at least two active knowers), module bus factor (target 2+), and the repository truck factor (target 3+ for a small team).

FILE:templates/knowledge-risk-report.md
# Knowledge risk report: {{repository}} - {{date}}

Settings: active = committed in the last {{active_days}} days; half-life {{half_life_days}} days; knows-share {{knows_share}}; module depth {{depth}}. History since {{since}}.

## Summary
- Repository truck factor: {{truck_factor}} ({{people}})
- Modules with low active coverage: {{bf02_modules}}
- Single-knower modules: {{bf03_modules}}
- Hot spots known by one person: {{bf04_modules}}

## Module table
(paste the module table from bus_factor.py)

## Top risks (ranked by business impact)
| # | module | why it matters | finding | confirmed with |
|---|---|---|---|---|
| 1 | {{module}} | {{impact, e.g. checkout payments}} | {{code}} | {{lead}} |

## 90-day plan
| action | module | owner | by | done when |
|---|---|---|---|---|
| {{e.g. pair on next two changes}} | {{module}} | {{name}} | {{date}} | {{second person merged a change alone}} |

## Caveats
- History shows who changed code, not who understands it; reviewers, pair partners and operators are not counted.
- {{anything specific: squash merges, a big refactor, generated code}}

## Next check
{{date}} with the same settings.

FILE:examples/git-history.log
@@58f5d4cce18a5ce4e3f9aa12d9767dcfd74b25ee	Ben Okafor	ben@shop.example	2026-11-14

5	0	web/src/api.ts
32	0	web/src/checkout.tsx
@@4cbab3078c9e5e9fac0a6d3627c6e022739f96e1	Eli Novak	eli@shop.example	2026-11-12

12	0	core/config.py
40	0	core/db.py
@@a0d3945429639f6c562a88444476839744d9453e	Ana Silva	ana.silva@shop.example	2026-11-10

10	0	core/db.py
29	0	orders/api.py
@@faa0aacf2cd46c8e74c9bd98cf5921fb50dd6c6b	Ana Silva	ana.silva@shop.example	2026-10-20

15	0	payments/webhooks.py
@@b579089fdf73b4d2bc6598a4ee680b3839743088	Ben Okafor	ben@shop.example	2026-10-11

9	0	web/src/cart.tsx
6	0	web/src/checkout.tsx
@@50b03245d12d83ddb1e9ae1c66a2d45178051021	Eli Novak	eli@shop.example	2026-10-10

15	0	core/config.py
11	0	search/query.py
@@7214f7c5b6154585c695eaf02e978b3464b8dc02	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2026-10-01

150	0	web/package-lock.json
150	0	web/package.json
@@16652d4b388444019ca413263b86cbfd87baed7a	Ana Silva	ana.silva@shop.example	2026-09-24

37	0	orders/api.py
7	0	orders/service.py
@@8290901896c8e9f9611cff8466cf7966b25eb76d	Ben Okafor	ben@shop.example	2026-09-15

5	0	README.md
@@fffb9688a48be4a6e95b08b16cba70e17e9f4b9b	Eli Novak	eli@shop.example	2026-09-07

15	0	orders/api.py
31	0	search/query.py
@@e841c7d0bbed56f4725d681b6587a1808123c893	Ben Okafor	ben@shop.example	2026-09-07

24	0	web/src/api.ts
25	0	web/src/cart.tsx
@@88ccae50a361536da22fe6b5e96cc008385ccccb	Ana Silva	ana.silva@shop.example	2026-08-09

25	0	orders/models.py
14	0	orders/service.py
@@000ed52a381b54ba901092d2050c6165b8441de8	Eli Novak	eli@shop.example	2026-08-06

37	0	core/db.py
27	0	orders/api.py
@@c548efcb90ebc04644b4f9d761bb0a96bc9be56d	Ben Okafor	ben@shop.example	2026-08-04

4	0	web/src/api.ts
13	0	web/src/checkout.tsx
@@b9a4d1e4e28cda2113d8ac51cdff3389910dc14e	Eli Novak	eli@shop.example	2026-07-04

32	0	core/config.py
15	0	core/db.py
@@a003bffd397e386e00c745b4393ca3c509859e35	Ben O.	ben.okafor@gmail.example	2026-07-01

3	0	web/src/cart.tsx
9	0	web/src/checkout.tsx
@@10e0e7b09f2d37b0c7055c4a7a17af09dc945e91	Ana Silva	ana.silva@shop.example	2026-06-24

18	0	core/db.py
28	0	orders/models.py
@@d0076f938d1899cc368d2cc627220682762e6516	Eli Novak	eli@shop.example	2026-06-02

35	0	core/config.py
15	0	search/query.py
@@b70911cb2b187c324a78b2af770bff9c354ed222	Ben Okafor	ben@shop.example	2026-05-29

28	0	web/src/api.ts
6	0	web/src/cart.tsx
@@c77843f7c87f8d6ad35d107e4ad625e4559cf306	Chen Wei	chen@shop.example	2026-05-15

30	0	core/config.py
9	0	search/query.py
@@faeb60ed9f9ec1faaf33e8393463027d45666e4a	Ana Silva	ana.silva@shop.example	2026-05-09

25	0	core/db.py
31	0	orders/api.py
@@09c4044f954ffd84dc15713518cc1532a6c5cc6f	Ben Okafor	ben@shop.example	2026-04-25

8	0	web/src/api.ts
8	0	web/src/checkout.tsx
@@efcdcc32cc592412a5a7dd1796fa0149aff7094a	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2026-04-01

150	0	web/package-lock.json
150	0	web/package.json
@@ae3fc07a50e237c4a8b98c1df55da1f5e8155aa6	Ana Silva	ana.silva@shop.example	2026-03-24

30	0	orders/api.py
36	0	orders/service.py
@@eb7130d2a61f5f297762462e5ea807f5c601b827	Ben Okafor	ben@shop.example	2026-03-22

36	0	web/src/cart.tsx
30	0	web/src/checkout.tsx
@@bdadf66c0528166414b20facd6e0bc6490dc50c4	Chen Wei	chen@shop.example	2026-03-14

38	0	search/index.py
37	0	search/query.py
@@9dd045964286f69e2630aa8d2492d9cb8b126f45	Ben Okafor	ben@shop.example	2026-02-16

22	0	web/src/api.ts
39	0	web/src/cart.tsx
@@e5b16b9f4a0600bb1303545da56d8ec5b775a71d	Ana Silva	ana.silva@shop.example	2026-02-06

40	0	orders/models.py
4	0	orders/service.py
@@9f3ce69e27b7d9c169f07879450c79faffb917e9	Ben Okafor	ben@shop.example	2026-01-14

28	0	web/src/api.ts
26	0	web/src/checkout.tsx
@@87c36c4896129acc5b4dacb88498e10394a0dfaf	Chen Wei	chen@shop.example	2026-01-11

22	0	core/config.py
39	0	search/index.py
@@8ef82e501b1097d202e79c324d4a6118e855f852	Ana Silva	ana.silva@shop.example	2025-12-22

28	0	core/db.py
14	0	orders/models.py
@@3433f75f61d9493c5cb9d48d7a5fb86ef241bea0	Ben Okafor	ben@shop.example	2025-12-11

36	0	web/src/cart.tsx
29	0	web/src/checkout.tsx
@@304e9fd851a7b0cdd05780fe452310a5d3d86abc	Chen Wei	chen@shop.example	2025-11-11

21	0	core/config.py
35	0	search/query.py
@@98d8c4bbb5f3b6604cfd38bc5dda9f08736c64ed	Ben Okafor	ben@shop.example	2025-11-07

29	0	web/src/api.ts
19	0	web/src/cart.tsx
@@03290d9ed4de0c842c7b378220f9a385b4135a4d	Ana Silva	ana@personal.example	2025-11-06

5	0	core/db.py
37	0	orders/api.py
@@f1e157a039fbe041730b8f1137c684027f0e7c32	Ben Okafor	ben@shop.example	2025-10-04

24	0	web/src/api.ts
6	0	web/src/checkout.tsx
@@5622224adaa507aa5490d234b1840d20477c3575	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2025-09-30

150	0	web/package-lock.json
150	0	web/package.json
@@f658dbaddfcc5963b8e27a6f36a1903d4b3db6e6	Ana Silva	ana.silva@shop.example	2025-09-21

30	0	orders/api.py
14	0	orders/service.py
@@bac00f633bef75ed05866ccc8d6d31fb9e071e3e	Chen Wei	chen@shop.example	2025-09-10

20	0	search/index.py
20	0	search/query.py
@@c460c69d03be963f77b2524616dfde637254e72f	Ben Okafor	ben@shop.example	2025-09-01

35	0	web/src/cart.tsx
12	0	web/src/checkout.tsx
@@65153a48d22bf9b981f3680e6f9917b64a43ec35	Ana Silva	ana.silva@shop.example	2025-08-06

28	0	orders/models.py
22	0	orders/service.py
@@bc8cbd6bf9daee0d05449afbbaccb64f56bfb29a	Chen Wei	chen@shop.example	2025-07-11

19	0	core/config.py
14	0	search/index.py
@@6a34d862b912eb393cf7f8ca55c028b9010173be	Ana Silva	ana.silva@shop.example	2025-06-21

23	0	core/db.py
24	0	orders/models.py
@@6059e786b3ab3482031920657fecf929a4a58bd4	Dana Kim	dana@shop.example	2025-05-20

6	0	payments/stripe_client.py
39	0	payments/webhooks.py
@@e7cb62d4ed5198d9ce0a3fe0b1c938113a67ad97	Chen Wei	chen@shop.example	2025-05-10

36	0	core/config.py
40	0	search/query.py
@@9fd0749dd73e35beb76f65b7e3657463d44c7e54	Ana Silva	ana.silva@shop.example	2025-05-06

10	0	core/db.py
14	0	orders/api.py
@@a0c736ff9075a594896ca5bf024440a12c35c115	Dana Kim	dana@shop.example	2025-05-03

29	0	payments/refunds.py
15	0	payments/webhooks.py
@@1e40d5f4b152a88dbd317ede961bf06ae2a0a742	Dana Kim	dana@shop.example	2025-04-17

22	0	payments/refunds.py
19	0	payments/stripe_client.py
@@ab3f7a3a2d1bea59b43fc959a0b3e1116dcf247f	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2025-04-01

150	0	web/package-lock.json
150	0	web/package.json
@@fb0a311f7267f495367425518ef25dbf365f5ae1	Dana Kim	dana@shop.example	2025-03-31

40	0	payments/stripe_client.py
4	0	payments/webhooks.py
@@cd493d2263836828dcb0be8e4c4140125c965850	Ana Silva	ana.silva@shop.example	2025-03-21

39	0	orders/api.py
6	0	orders/service.py
@@3c743484d0dd4bca3905f9686bba1f48b22de580	Dana Kim	dana@shop.example	2025-03-15

38	0	payments/refunds.py
30	0	payments/webhooks.py
@@981e4f06309729c1da359503aed2ba7acd1a8e8b	Chen Wei	chen@shop.example	2025-03-10

23	0	search/index.py
14	0	search/query.py
@@c9168c14828d2c382e334aa604064471d5d0cd63	Dana Kim	dana@shop.example	2025-02-26

6	0	payments/refunds.py
20	0	payments/stripe_client.py
@@4e20074f7f1b7bddfda1949cc23b0852c36ec61a	Dana Kim	dana@shop.example	2025-02-10

17	0	payments/stripe_client.py
8	0	payments/webhooks.py
@@d53da3ddd6680b9335a63352e7b365c79f62c028	Ana Silva	ana.silva@shop.example	2025-02-03

10	0	orders/models.py
25	0	orders/service.py
@@3e657197ddd176ccb02ab859abd3f8416459b665	Dana Kim	dana@shop.example	2025-01-24

31	0	payments/refunds.py
14	0	payments/webhooks.py
@@8590bef42bccc66937a1dcbc79275ed93099cef7	Dana Kim	dana@shop.example	2025-01-08

4	0	payments/refunds.py
18	0	payments/stripe_client.py
@@f67141a910fd0594c02e23adbc41e740d373506c	Ana Silva	ana.silva@shop.example	2025-01-06

11	0	README.md

FILE:examples/aliases.csv
alias,canonical
ben.okafor@gmail.example,Ben Okafor
Ben O.,Ben Okafor

FILE:scripts/bus_factor.py
#!/usr/bin/env python3
"""bus_factor.py - find knowledge concentration ("bus factor") risk in a Git repository from its history.

Reads `git log --numstat` history (from a saved log file or by running git on a repo), merges author
aliases, skips bots, lockfiles and vendored code, and weights each change by lines touched and how
recent it is. Per module (top-level folder by default) it reports who holds the knowledge, the module
bus factor (fewest people holding more than half of it), whether any active person still knows it,
and the repository truck factor (how many people would have to leave before more than half of the
files have no active person who knows them). Standard library only.

Usage:
  python3 bus_factor.py LOGFILE [options]
  python3 bus_factor.py --repo PATH [options]          (runs git log for you)
  python3 bus_factor.py --self-test
Make LOGFILE with:
  git log --no-merges --numstat --date=short --format='@@%H%x09%an%x09%ae%x09%ad' > history.log
Options:
  --aliases FILE       CSV alias,canonical  (alias = an email or a name; canonical = the person's name)
  --depth N            module = first N folders of the path (default 1; root files = "(root)")
  --since YYYY-MM-DD   ignore older commits
  --as-of YYYY-MM-DD   reference date (default: newest commit in the log)
  --active-days N      an author is active if they committed within N days of --as-of (default 120)
  --half-life-days N   a change loses half its weight after N days (default 365)
  --knows-share X      an author "knows" a file when they hold at least X of its weight (default 0.25)
  --exclude GLOB       extra path pattern to skip (repeatable); defaults skip lockfiles, vendor, dist, minified
  --include-bots       keep authors whose name or email contains [bot] or "bot@"
  --json               machine-readable output
Exit codes: 0 no high findings, 1 high findings, 2 bad input.
"""
import csv, datetime as dt, fnmatch, json, math, os, subprocess, sys
from collections import defaultdict

DEFAULT_EXCLUDES = ["*package-lock.json", "*yarn.lock", "*pnpm-lock.yaml", "*poetry.lock", "*Cargo.lock", "*go.sum",
                    "*composer.lock", "*Gemfile.lock", "vendor/*", "*/vendor/*", "node_modules/*", "dist/*",
                    "build/*", "*.min.js", "*.min.css", "*.svg", "*.png", "*.jpg", "*.pdf"]
SEV = {"BF01": "high", "BF02": "high", "BF03": "medium", "BF04": "medium", "BF05": "low", "BF06": "low"}
NAMES = {"BF01": "repository truck factor is 1 or 2",
         "BF02": "orphaned module: most files have no active person who knows them",
         "BF03": "module bus factor 1: one person holds most of the knowledge",
         "BF04": "hot spot with a single knower (busy recently, one person)",
         "BF05": "possible duplicate identity (same name, different emails)",
         "BF06": "only one person has ever changed this module"}


class InputError(Exception):
    pass


def parse_date(s, what):
    try:
        return dt.date.fromisoformat(s.strip()[:10])
    except (ValueError, AttributeError):
        raise InputError("bad %s date: %r" % (what, s))


def parse_log(lines):
    """Return list of commits: dict(sha, name, email, date, files=[(path, added, deleted)])."""
    commits, cur = [], None
    for n, raw in enumerate(lines, 1):
        line = raw.rstrip("\n")
        if line.startswith("@@"):
            parts = line[2:].split("\t")
            if len(parts) < 4:
                raise InputError("line %d: header needs sha, name, email, date separated by tabs" % n)
            cur = {"sha": parts[0], "name": parts[1].strip(), "email": parts[2].strip().lower(),
                   "date": parse_date(parts[3], "commit"), "files": []}
            commits.append(cur)
        elif line.strip():
            if cur is None:
                raise InputError("line %d: numstat line before any @@ commit header (wrong --format?)" % n)
            parts = line.split("\t")
            if len(parts) != 3:
                raise InputError("line %d: expected 'added<TAB>deleted<TAB>path'" % n)
            a, d, path = parts
            if a == "-" or d == "-":      # binary file
                continue
            path = path.strip()
            if " => " in path:            # rename: keep the new path
                if "{" in path:
                    pre, rest = path.split("{", 1)
                    mid, post = rest.split("}", 1)
                    path = (pre + mid.split(" => ")[1] + post).replace("//", "/")
                else:
                    path = path.split(" => ")[1]
            try:
                cur["files"].append((path, int(a), int(d)))
            except ValueError:
                raise InputError("line %d: added/deleted must be numbers" % n)
    if not commits:
        raise InputError("no commits found (expected lines starting with @@)")
    return commits


def git_log(repo, since=None):
    cmd = ["git", "-C", repo, "log", "--no-merges", "--numstat", "--date=short", "--format=@@%H%x09%an%x09%ae%x09%ad"]
    if since:
        cmd.append("--since=" + since)
    try:
        out = subprocess.run(cmd, capture_output=True, text=True, check=True).stdout
    except (OSError, subprocess.CalledProcessError) as e:
        raise InputError("git log failed: %s" % (getattr(e, "stderr", "") or e))
    return out.splitlines()


def load_aliases(path):
    m = {}
    if not path:
        return m
    try:
        for row in csv.DictReader(open(path, encoding="utf-8", newline="")):
            a, c = (row.get("alias") or "").strip(), (row.get("canonical") or "").strip()
            if a and c:
                m[a.lower()] = c
    except OSError as e:
        raise InputError("cannot read aliases: %s" % e)
    return m


def module_of(path, depth):
    parts = path.split("/")
    if len(parts) == 1:
        return "(root)"
    return "/".join(parts[:min(depth, len(parts) - 1)])


def analyse(commits, aliases=None, depth=1, since=None, as_of=None, active_days=120, half_life=365,
            knows_share=0.25, excludes=None, include_bots=False):
    aliases = aliases or {}
    pats = DEFAULT_EXCLUDES + list(excludes or [])
    since_d = parse_date(since, "--since") if since else None
    as_of_d = parse_date(as_of, "--as-of") if as_of else max(c["date"] for c in commits)
    emails_by_name = defaultdict(set)
    last_seen = {}
    fw = defaultdict(lambda: defaultdict(float))       # file -> author -> weight
    f_last = {}
    f_recent = defaultdict(float)                       # lines in last 90 days
    commits_per_module = defaultdict(set)
    authors_ever = defaultdict(set)                     # module -> authors (unweighted)
    used = 0
    for c in commits:
        if since_d and c["date"] < since_d:
            continue
        if c["date"] > as_of_d:
            continue
        if not include_bots and ("[bot]" in c["name"].lower() or "bot@" in c["email"] or c["name"].lower().endswith(" bot")):
            continue
        who = aliases.get(c["email"]) or aliases.get(c["name"].lower()) or c["name"]
        if who == c["name"] and not aliases.get(c["email"]):
            emails_by_name[c["name"]].add(c["email"])
        last_seen[who] = max(last_seen.get(who, c["date"]), c["date"])
        age = (as_of_d - c["date"]).days
        w = 0.5 ** (age / float(half_life)) if half_life > 0 else 1.0
        touched = False
        for path, a, d in c["files"]:
            if any(fnmatch.fnmatch(path, p) for p in pats):
                continue
            lines = a + d
            if lines == 0:
                continue
            touched = True
            fw[path][who] += math.log1p(lines) * w     # log damps huge generated diffs
            f_last[path] = max(f_last.get(path, c["date"]), c["date"])
            if age <= 90:
                f_recent[path] += lines
            mod = module_of(path, depth)
            commits_per_module[mod].add(c["sha"])
            authors_ever[mod].add(who)
        used += touched
    if not fw:
        raise InputError("no usable file changes after filters")
    active = {a for a, d in last_seen.items() if (as_of_d - d).days <= active_days}

    def knowers(path):
        tot = sum(fw[path].values())
        return {a for a, v in fw[path].items() if v / tot >= knows_share}

    files = sorted(fw)
    mods = defaultdict(list)
    for p in files:
        mods[module_of(p, depth)].append(p)
    recent_by_mod = {m: sum(f_recent[p] for p in ps) for m, ps in mods.items()}
    hot_cut = sorted(recent_by_mod.values())[int(len(recent_by_mod) * 0.75)] if recent_by_mod else 0
    out_mods, findings = [], []
    for m in sorted(mods):
        ps = mods[m]
        aw = defaultdict(float)
        for p in ps:
            for a, v in fw[p].items():
                aw[a] += v
        tot = sum(aw.values())
        ranked = sorted(aw.items(), key=lambda x: -x[1])
        acc, bf = 0.0, 0
        for a, v in ranked:
            acc += v; bf += 1
            if acc > tot / 2:
                break
        kn = set().union(*(knowers(p) for p in ps))
        act_kn = sorted(kn & active)
        covered = sum(1 for p in ps if knowers(p) & active)
        top, share = ranked[0][0], ranked[0][1] / tot
        row = {"module": m, "files": len(ps), "commits": len(commits_per_module[m]), "authors": len(aw),
               "top_author": top, "top_share": round(share, 3), "bus_factor": bf,
               "active_knowers": act_kn, "active_coverage": round(covered / len(ps), 3),
               "last_change": max(f_last[p] for p in ps).isoformat(), "recent_lines_90d": int(recent_by_mod[m]),
               "top_author_active": top in active, "findings": []}
        if covered / len(ps) < 0.5:
            row["findings"].append("BF02")
        if bf == 1 and len(ps) >= 3:
            row["findings"].append("BF03")
        if bf == 1 and recent_by_mod[m] > 0 and recent_by_mod[m] >= hot_cut and len(mods) >= 4:
            row["findings"].append("BF04")
        if len(authors_ever[m]) == 1:
            row["findings"].append("BF06")
        out_mods.append(row)
    # repository truck factor: greedily remove the author who knows most still-covered files
    file_kn = {p: knowers(p) & active for p in files}
    removed, tf = [], 0
    remaining = {p: set(k) for p, k in file_kn.items()}
    def orphaned():
        return sum(1 for k in remaining.values() if not k)
    if orphaned() > len(files) / 2:
        tf = 0
    else:
        while orphaned() <= len(files) / 2:
            cnt = defaultdict(int)
            for k in remaining.values():
                for a in k:
                    cnt[a] += 1
            if not cnt:
                break
            a = sorted(cnt.items(), key=lambda x: (-x[1], x[0]))[0][0]
            removed.append(a); tf += 1
            for k in remaining.values():
                k.discard(a)
    if tf <= 2:
        findings.append({"code": "BF01", "detail": "truck factor %d (%s)" % (tf, ", ".join(removed) or "already orphaned")})
    for name, em in sorted(emails_by_name.items()):
        if len(em) > 1:
            findings.append({"code": "BF05", "detail": "%s uses %s; add an alias line" % (name, ", ".join(sorted(em)))})
    for r in out_mods:
        for code in r["findings"]:
            findings.append({"code": code, "module": r["module"], "detail": "top %s %.0f%%, active knowers: %s" % (
                r["top_author"], r["top_share"] * 100, ", ".join(r["active_knowers"]) or "none")})
    people = sorted(({"author": a, "last_commit": d.isoformat(), "active": a in active,
                      "files_known": sum(1 for p in files if a in knowers(p))} for a, d in last_seen.items()),
                    key=lambda x: -x["files_known"])
    return {"as_of": as_of_d.isoformat(), "commits_used": used, "files": len(files), "modules": out_mods,
            "truck_factor": tf, "truck_factor_people": removed, "people": people,
            "settings": {"depth": depth, "active_days": active_days, "half_life_days": half_life, "knows_share": knows_share},
            "findings": findings}


def render(a):
    L = ["# Knowledge risk report (as of %s)" % a["as_of"], "",
         "Commits used: %d | files: %d | repository truck factor: %d (%s)" % (
             a["commits_used"], a["files"], a["truck_factor"], ", ".join(a["truck_factor_people"]) or "-"), "",
         "| module | files | commits | authors | top author | top share | bus factor | active knowers | active coverage | last change |",
         "|---|---|---|---|---|---|---|---|---|---|"]
    for r in a["modules"]:
        L.append("| %s | %d | %d | %d | %s%s | %.0f%% | %d | %s | %.0f%% | %s |" % (
            r["module"], r["files"], r["commits"], r["authors"], r["top_author"], "" if r["top_author_active"] else " (inactive)",
            r["top_share"] * 100, r["bus_factor"], ", ".join(r["active_knowers"]) or "none", r["active_coverage"] * 100,
            r["last_change"]))
    L += ["", "## People", "", "| author | last commit | active | files known |", "|---|---|---|---|"]
    for p in a["people"]:
        L.append("| %s | %s | %s | %d |" % (p["author"], p["last_commit"], "yes" if p["active"] else "no", p["files_known"]))
    L += ["", "## Findings"]
    order = {"high": 0, "medium": 1, "low": 2}
    for f in sorted(a["findings"], key=lambda f: (order[SEV[f["code"]]], f["code"], f.get("module", ""))):
        L.append("- [%s] %s %s%s: %s" % (SEV[f["code"]], f["code"], NAMES[f["code"]],
                                         (" - " + f["module"]) if f.get("module") else "", f["detail"]))
    if not a["findings"]:
        L.append("- none")
    L += ["", "History shows who changed code, not who understands it; confirm with the team before acting."]
    return "\n".join(L)


def self_test():
    T = []
    def check(name, cond):
        T.append((name, bool(cond)))
    log = """@@a1\tAna\tana@x.io\t2026-01-10
10\t2\tapi/orders.py
5\t0\tapi/users.py
@@a2\tBen\tben@x.io\t2026-03-01
20\t5\tweb/app.js
3\t1\tapi/orders.py
@@a3\tAna\tana@home.io\t2026-06-01
4\t4\tapi/users.py
-\t-\tweb/logo.png
@@a4\tdependabot[bot]\t49699333+dependabot[bot]@users.noreply.github.com\t2026-06-02
200\t180\tpackage-lock.json
1\t1\tweb/package.json
@@a5\tCara\tcara@x.io\t2025-01-05
50\t0\tbilling/{old => new}/invoice.py
@@a6\tBen\tben@x.io\t2026-06-10
2\t2\tREADME.md
""".splitlines()
    c = parse_log(log)
    check("parses 6 commits", len(c) == 6)
    check("binary numstat rows skipped", all(f[0] != "web/logo.png" for x in c for f in x["files"]))
    check("brace rename resolved to new path", c[4]["files"][0][0] == "billing/new/invoice.py")
    check("module of root file is (root)", module_of("README.md", 1) == "(root)")
    check("module depth 2", module_of("src/api/x/y.py", 2) == "src/api")
    a = analyse(c, as_of="2026-06-10")
    mods = {m["module"]: m for m in a["modules"]}
    check("bot commits skipped", "web" in mods and mods["web"]["authors"] == 1)
    check("lockfile excluded", all(m["module"] != "(root)" or m["files"] == 1 for m in a["modules"]))
    check("duplicate identity flagged BF05", any(f["code"] == "BF05" and "Ana" in f["detail"] for f in a["findings"]))
    a2 = analyse(c, aliases={"ana@home.io": "Ana"}, as_of="2026-06-10")
    check("alias removes BF05", not any(f["code"] == "BF05" for f in a2["findings"]))
    check("inactive author makes billing orphaned BF02", "BF02" in mods["billing"]["findings"])
    check("single-author module flagged BF06", "BF06" in mods["web"]["findings"])
    check("api bus factor is 1 (Ana holds most)", mods["api"]["bus_factor"] == 1 and mods["api"]["top_author"] == "Ana")
    check("truck factor small -> BF01", any(f["code"] == "BF01" for f in a["findings"]))
    a3 = analyse(c, as_of="2026-06-10", since="2026-02-01")
    check("--since drops older commits", a3["commits_used"] == 3)
    a4 = analyse(c, as_of="2026-06-10", active_days=600)
    check("long active window: billing has an active knower", "BF02" not in {m["module"]: m for m in a4["modules"]}["billing"]["findings"])
    check("BF02 uses active coverage under 50%", all(("BF02" in m["findings"]) == (m["active_coverage"] < 0.5) for m in a["modules"]))
    check("recency weight halves after half-life", abs(0.5 ** (365 / 365.0) - 0.5) < 1e-9)
    for bad, label in [(["10\t2\tx.py"], "numstat before header rejected"), (["@@x\tA\ta@b\tnot-a-date"], "bad date rejected"),
                       (["@@x\tA\ta@b\t2026-01-01", "ten\t2\tx.py"], "non-numeric counts rejected"), ([], "empty log rejected")]:
        try:
            parse_log(bad); check(label, False)
        except InputError:
            check(label, True)
    try:
        analyse(parse_log(["@@x\tA\ta@b\t2026-01-01", "3\t1\tyarn.lock"])); check("only excluded files rejected", False)
    except InputError:
        check("only excluded files rejected", True)
    for name, ok in T:
        print(("PASS  " if ok else "FAIL  ") + name)
    good = all(ok for _, ok in T)
    print("ALL PASS" if good else "SOME FAILED", "(%d/%d)" % (sum(ok for _, ok in T), len(T)))
    return 0 if good else 1


def main(argv):
    if "--self-test" in argv:
        return self_test()
    opts = {"aliases": None, "depth": "1", "since": None, "as-of": None, "active-days": "120", "half-life-days": "365",
            "knows-share": "0.25", "repo": None}
    excludes, pos, i = [], [], 0
    while i < len(argv):
        x = argv[i]
        if x in ("--json", "--include-bots"):
            i += 1; continue
        if x.startswith("--"):
            k = x[2:]
            if i + 1 >= len(argv) or (k not in opts and k != "exclude"):
                print("error: unknown or incomplete option %s" % x, file=sys.stderr); return 2
            if k == "exclude":
                excludes.append(argv[i + 1])
            else:
                opts[k] = argv[i + 1]
            i += 2; continue
        pos.append(x); i += 1
    try:
        if opts["repo"]:
            lines = git_log(opts["repo"], opts["since"])
        elif len(pos) == 1:
            try:
                lines = open(pos[0], encoding="utf-8", errors="replace").read().splitlines()
            except OSError as e:
                raise InputError("cannot read %s: %s" % (pos[0], e))
        else:
            print(__doc__, file=sys.stderr); return 2
        try:
            depth, ad, hl, ks = int(opts["depth"]), int(opts["active-days"]), int(opts["half-life-days"]), float(opts["knows-share"])
        except ValueError:
            raise InputError("--depth, --active-days and --half-life-days need whole numbers, --knows-share a decimal")
        if depth < 1 or not 0 < ks <= 1:
            raise InputError("--depth must be >= 1 and --knows-share between 0 and 1")
        a = analyse(parse_log(lines), load_aliases(opts["aliases"]), depth, opts["since"], opts["as-of"], ad, hl, ks,
                    excludes, "--include-bots" in argv)
    except InputError as e:
        print("error: %s" % e, file=sys.stderr); return 2
    print(json.dumps(a, indent=2) if "--json" in argv else render(a))
    return 1 if any(SEV[f["code"]] == "high" for f in a["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
RiskEngineeringGit+3
F@f
0
Mortgage Refinance Break-Even Calculator
Skill

Compares mortgage refinance offers with your current loan: new payment, monthly saving, simple and true break-even month, net benefit over the years you expect to stay, interest to payoff, points payback, and traps like term resets, rolled-in costs and cash-out. Offline stdlib Python.

---
name: mortgage-refinance-break-even-calculator
description: Compares mortgage refinance offers with your current loan: new payment, monthly saving, simple and true break-even month, net benefit over the years you expect to stay, interest to payoff, points payback, and traps like term resets, rolled-in costs and cash-out. Offline stdlib Python.
---

# Mortgage Refinance Break-Even Calculator

You help homeowners decide whether a mortgage refinance is worth it, and which offer is best for how long they expect to keep the loan. Lenders and brokers usually quote the lower monthly payment; that number alone hides the closing costs, the points, a 30-year term that starts again from zero, and costs rolled into the new balance. You turn the current loan and a few offers into one honest comparison and a short list of things to ask the lender.

You work only with the numbers the user gives you, on their machine. You are not a financial adviser or a lender: you never recommend a specific lender, you never guess rates or fees, and you say clearly that results are estimates of principal and interest that must be checked against the lender's official loan estimate. Taxes, insurance, escrow, mortgage insurance, adjustable-rate resets and local fees are outside the script; you mention them when they matter.

## Files in this skill

- `scripts/refi_breakeven.py` - reads the current loan (JSON) and offers (CSV), computes payments, simple and true break-even, net benefit at the horizon, total interest, points payback and findings RF01-RF09; `--horizon-months N` to try other stay lengths, `--json` for tooling, `--self-test` runs 23 checks (Python 3.8+ standard library only)
- `references/refinance-math.md` - the formulas, what "true break-even" means and why it differs from costs divided by savings, and a worked example you can check by hand
- `references/decision-checklist.md` - questions to answer before choosing, what each finding means, and what to ask the lender
- `templates/refinance-summary.md` - the one-page summary you hand back
- `examples/current_loan.json`, `examples/offers.csv` - a fictional 312,000 loan at 7.25% with seven offers (30-year with and without points, a matching-term offer, a no-cost offer, a 15-year, rolled costs and a cash-out)

## Workflow

### 1. Collect the facts
Ask for, from the latest mortgage statement and each lender's loan estimate:
- current balance, interest rate, months left and the principal-and-interest payment (not the total with escrow); any prepayment penalty;
- for each offer: rate, term in months, total closing costs (lender, title, appraisal, recording fees), points as a share of the loan, any cash-out, and whether costs are paid at closing or rolled into the loan;
- how long they expect to keep the home or the loan (the horizon). If unsure, run 3, 5, 7 and 10 years.
Never fill in a rate or fee yourself; if a number is missing, ask or leave that offer out.

### 2. Prepare the files
- `current_loan.json`: `balance`, `annual_rate` (decimal, 0.0725), `remaining_months`, optional `monthly_payment`, `prepayment_penalty`, `currency`, `horizon_months`.
- `offers.csv`: `name,annual_rate,term_months,closing_costs,points_pct,cash_out,roll_costs` with rates and points as decimals (`0.01` = 1 point) and `roll_costs` yes/no.

### 3. Run the comparison
```
python3 scripts/refi_breakeven.py examples/current_loan.json examples/offers.csv
python3 scripts/refi_breakeven.py current_loan.json offers.csv --horizon-months 60
python3 scripts/refi_breakeven.py current_loan.json offers.csv --json > refi.json
python3 scripts/refi_breakeven.py --self-test
```
Exit 0 = at least one offer pays off within the horizon and no high findings, 1 = none pays off or a high finding is present, 2 = bad input. Without a shell, follow `references/refinance-math.md` by hand for the two most promising offers.

### 4. Read the results
- **Net at horizon** is the main number: what the offer saves (or costs) by the end of the horizon, counting payments, the remaining balance and the cash paid at closing.
- **True break-even** is the first month the refinance is ahead. It can be earlier than the simple break-even (shorter terms pay the balance down faster) or later (rolled-in costs, longer terms).
- **Interest to payoff** shows the long-run cost if they keep the loan to the end.
- Findings: RF01 high (does not pay off within the horizon) and RF05 high (higher payment without a shorter term); RF02 term reset, RF03 more lifetime interest, RF04 rolled-in costs and RF07 points that do not pay back are medium; RF06 cash-out, RF08 small rate drop and RF09 higher payment on a shorter term are low.
Run at least two horizons; if the best offer changes, say so plainly.

### 5. Report
Fill `templates/refinance-summary.md`: the current loan, the comparison table, the best offer at each horizon, findings in plain language, the questions for the lender (`references/decision-checklist.md`) and what the numbers do not include.

## Rules
- Compare like for like: a cash-out offer adds new debt, so compare it with other ways to borrow that cash, not only with the current mortgage.
- A lower payment on a new 30-year term is not automatically a saving; always show the payoff date and the interest to payoff next to it.
- Keep personal financial documents private; work from the numbers, never upload statements.

FILE:references/refinance-math.md
# Refinance math used by refi_breakeven.py

## Monthly payment (principal and interest)
For a loan amount `P`, monthly rate `r = annual_rate / 12` and `n` months:

    payment = P * r / (1 - (1 + r)^-n)        (payment = P / n when r = 0)

Example: 200,000 at 6% for 360 months -> 1,199.10 per month.

## Upfront costs
    upfront = closing_costs + points_pct * new_loan + prepayment_penalty

- Points are a share of the new loan: 1 point = 1% of the loan.
- When `roll_costs` is yes, upfront costs are added to the new loan (you pay no cash at closing but pay interest on the costs for the life of the loan). The script solves this iteratively because points depend on the loan amount.
- Cash-out is added to the new loan; the cash you receive counts in your favor in the net position.

## Simple break-even
    simple_break_even = ceil(upfront / (old_payment - new_payment))

Shown as "never" when the payment does not go down or the result is longer than the new term. This is the number most calculators show, and it ignores how fast each loan pays down its balance.

## True break-even (the one to use)
Month by month, the script runs both amortization schedules side by side and tracks:

    net(m) = sum of (old payment - new payment) up to month m
           + (old balance at m - new balance at m)
           - cash paid at closing
           + cash received (cash-out)

The true break-even is the first month where `net(m) >= 0`. `net(horizon)` is the "net at horizon" column: the money you are ahead (or behind) if you sell or refinance again at that point, before taxes and selling costs.

Why they differ:
- A shorter or matching term pays principal down faster, so the true break-even comes before the simple one, even when the payment rises (a 15-year offer can break even in about 16 months while the "saving" is negative).
- A new 30-year term on a loan that had 27 years left lowers the payment partly by stretching it; the slower balance paydown pushes the true break-even later.
- Rolled-in costs show up as a higher new balance, not as cash.

## Points payback
The script assumes the common rule of thumb that 1 point buys about 0.25 percentage points. Points payback = points cost / (payment at rate + 0.25 pp per point - payment at the quoted rate). If the lender quotes the same loan with and without points, compare those two rows directly instead; that is more accurate than the rule of thumb.

## Worked check (from the examples)
Current: 312,000 at 7.25% with 324 months left -> payment 2,197.09.
"Bank A 30y no points": 6.25% for 360 months -> payment 1,921.04, saving 276.05 per month, upfront 5,800, simple break-even ceil(5,800 / 276.05) = 22 months. The true break-even is month 23, slightly later, because the new 30-year schedule pays down principal more slowly than the old one with 27 years left.

## Not modeled
Property tax, insurance and escrow; mortgage insurance; adjustable-rate resets; tax deductibility of interest; inflation and the return you could earn on the closing cost cash; selling costs. Mention them when they could change the decision.

FILE:references/decision-checklist.md
# Refinance decision checklist

## Before choosing
1. How long will you keep the home or this loan? Run the script for at least two horizons (for example 3 and 7 years).
2. Is the new payment comfortable even if income drops? A shorter term saves the most interest but raises the payment (RF09).
3. Are you resetting the clock? A new 30-year loan after paying for years moves the payoff date later (RF02); you can keep the old payoff date by paying extra each month.
4. Are closing costs paid in cash or rolled into the loan (RF04)? Rolling them in feels free but costs interest for years.
5. Are you taking cash out (RF06)? Compare that new debt with other options and with not borrowing it at all.
6. Do the points pay back before you expect to move (RF07)?
7. Is the rate drop large enough (RF08)? Under about 0.5 percentage points, costs often eat the savings unless the offer is genuinely no-cost.

## What each finding means
| code | severity | meaning | what to do |
|---|---|---|---|
| RF01 | high | the offer is still behind at the horizon | skip it, or negotiate costs down and re-run |
| RF02 | medium | payoff date moves later | compare interest to payoff; consider paying extra monthly |
| RF03 | medium | more interest to payoff than the current loan | fine only if you will move or refinance well before payoff |
| RF04 | medium | costs rolled into the balance | ask the price to pay them in cash; compare both |
| RF05 | high | payment rises without a shorter term | usually a bad deal; check for cash-out or fees |
| RF06 | low | cash-out adds debt | compare with a home equity loan or saving up |
| RF07 | medium | points do not pay back within the horizon | ask for the same loan without points |
| RF08 | low | small rate drop | refinance only if costs are very low |
| RF09 | low | shorter term with a higher payment | check the budget and emergency savings |

## Questions for the lender
- Please send the official loan estimate for each option, including the same loan with zero points.
- Which fees are lender fees, and which are third-party (title, appraisal, recording)? Which can be waived or shopped?
- Is the rate locked, until when, and what does extending the lock cost?
- Is there a prepayment penalty on the new loan?
- If costs are rolled in, what is the exact new loan amount?

## Red flags
- Pressure to sign before you receive the loan estimate.
- A "no-cost" offer whose rate is much higher than others (you pay through the rate instead).
- Fees that appear for the first time at closing.

FILE:templates/refinance-summary.md
# Refinance check: {{property_or_household}} - {{date}}

Numbers from: {{statement_date}} statement and loan estimates from {{lenders}}. Estimates of principal and interest only.

## Current loan
- Balance {{balance}} at {{rate}}, {{months_left}} months left, payment {{payment}} (P&I)
- Interest to payoff if nothing changes: {{interest_to_payoff}}

## Comparison (horizon {{horizon_years}} years)
(paste the table from refi_breakeven.py)

## Best option
- At {{horizon_1}} years: {{best_1}} (net {{net_1}})
- At {{horizon_2}} years: {{best_2}} (net {{net_2}})
- Why: {{one or two plain sentences}}

## Watch out
- {{finding code, offer, plain-language meaning}}

## Ask the lender
- {{question}}

## Not included
- Taxes, insurance, escrow, mortgage insurance, rate resets, selling costs, the return on cash you keep.

## Next step
- {{for example: request the zero-point version of offer B and re-run; lock the rate by date}}

FILE:examples/current_loan.json
{
  "balance": 312000,
  "annual_rate": 0.0725,
  "remaining_months": 324,
  "prepayment_penalty": 0,
  "currency": "USD",
  "horizon_months": 84,
  "note": "fictional example: 30-year loan taken 3 years ago, owners expect to stay about 7 more years"
}

FILE:examples/offers.csv
name,annual_rate,term_months,closing_costs,points_pct,cash_out,roll_costs
Bank A 30y no points,0.0625,360,5800,0,0,no
Bank A 30y 1 point,0.0600,360,5800,0.01,0,no
Credit union 27y match,0.0630,324,4200,0,0,no
Online lender no-cost,0.0675,360,0,0,0,no
Broker 15y,0.0575,180,6500,0,0,no
Bank B rolled costs,0.0625,360,6200,0,0,yes
Bank B cash-out 30y,0.0650,360,6200,0,35000,no

FILE:scripts/refi_breakeven.py
#!/usr/bin/env python3
"""refi_breakeven.py - compare refinance offers against your current mortgage and find the real break-even month.

For each offer it works out the new monthly payment (principal and interest), the monthly saving,
the simple break-even (upfront costs / monthly saving) and the true break-even month, where the
cumulative payment savings plus the difference in remaining balance first cover what you paid up
front. It also compares total cost over the time you expect to keep the loan, total interest to
payoff, and flags common traps (term reset, costs rolled into the balance, cash-out, points that
never pay back, a prepayment penalty). Standard library only.

Usage:
  python3 refi_breakeven.py CURRENT.json OFFERS.csv [--horizon-months N] [--json]
  python3 refi_breakeven.py --self-test

CURRENT.json keys: balance, annual_rate (decimal, 0.065 = 6.5%), remaining_months,
  optional: monthly_payment (P&I; computed if missing), prepayment_penalty (amount), currency,
  horizon_months (how long you expect to keep the loan; default 84).
OFFERS.csv columns: name,annual_rate,term_months,closing_costs,points_pct[,cash_out][,roll_costs]
  annual_rate decimal; points_pct as a decimal share of the new loan (0.01 = 1 point);
  cash_out extra cash taken (default 0); roll_costs yes/no (costs added to the new loan, default no).
Exit codes: 0 at least one offer breaks even within the horizon and no high findings,
            1 no offer pays off within the horizon or high findings present, 2 bad input.
Estimates only: taxes, insurance, escrow, adjustable-rate resets and fees not listed are ignored.
"""
import csv, json, math, sys

SEV = {"RF01": "high", "RF02": "medium", "RF03": "medium", "RF04": "medium", "RF05": "high",
       "RF06": "low", "RF07": "medium", "RF08": "low", "RF09": "low"}
NAMES = {"RF01": "does not break even within the horizon",
         "RF02": "term reset: payoff date moves later",
         "RF03": "more total interest to payoff than keeping the current loan",
         "RF04": "costs rolled into the loan (you pay interest on them)",
         "RF05": "monthly payment goes up with no shorter term",
         "RF06": "cash-out increases the debt (compare like for like)",
         "RF07": "points take longer to pay back than the horizon",
         "RF08": "rate drop under 0.5 percentage points",
         "RF09": "shorter term with a higher payment: check it fits your budget"}
POINT_RATE_CUT = 0.0025  # rule of thumb: 1 point (1% of the loan) buys about 0.25 percentage points


class InputError(Exception):
    pass


def payment(principal, annual_rate, months):
    if months <= 0:
        raise InputError("months must be positive")
    r = annual_rate / 12.0
    if r == 0:
        return principal / months
    return principal * r / (1 - (1 + r) ** -months)


def schedule(principal, annual_rate, months, pay):
    """Yield (month, interest, principal_paid, balance) until paid off or months reached."""
    r = annual_rate / 12.0
    bal = principal
    for m in range(1, months + 1):
        interest = bal * r
        princ = min(pay - interest, bal)
        bal = bal - princ
        if bal < 0.005:
            bal = 0.0
        yield m, interest, princ, bal
        if bal == 0.0:
            break


def balance_after(principal, annual_rate, pay, m):
    b = principal
    for mm, _, _, bal in schedule(principal, annual_rate, 10 ** 6, pay):
        b = bal
        if mm >= m or bal == 0:
            break
    return b if m > 0 else principal


def total_interest(principal, annual_rate, months, pay):
    return sum(i for _, i, _, _ in schedule(principal, annual_rate, months, pay))


def to_float(row, key, default=None, lo=None, hi=None):
    v = row.get(key)
    if v is None or str(v).strip() == "":
        if default is None:
            raise InputError("missing %s" % key)
        return default
    try:
        f = float(str(v).replace(",", "").strip())
    except ValueError:
        raise InputError("%s is not a number: %r" % (key, v))
    if lo is not None and f < lo or hi is not None and f > hi:
        raise InputError("%s out of range: %r" % (key, v))
    return f


def load_current(path):
    try:
        d = json.load(open(path, encoding="utf-8"))
    except (OSError, ValueError) as e:
        raise InputError("cannot read %s: %s" % (path, e))
    cur = {"balance": to_float(d, "balance", lo=1),
           "annual_rate": to_float(d, "annual_rate", lo=0, hi=0.5),
           "remaining_months": int(to_float(d, "remaining_months", lo=1, hi=600)),
           "prepayment_penalty": to_float(d, "prepayment_penalty", 0.0, lo=0),
           "currency": d.get("currency", ""),
           "horizon_months": int(to_float(d, "horizon_months", 84, lo=1, hi=600))}
    if cur["annual_rate"] > 0.3:
        raise InputError("annual_rate looks like a percent; use a decimal such as 0.065")
    calc = payment(cur["balance"], cur["annual_rate"], cur["remaining_months"])
    cur["monthly_payment"] = to_float(d, "monthly_payment", calc, lo=0.01)
    if cur["monthly_payment"] <= cur["balance"] * cur["annual_rate"] / 12:
        raise InputError("monthly_payment does not cover the interest")
    return cur


def load_offers(path):
    try:
        rows = list(csv.DictReader(open(path, encoding="utf-8", newline="")))
    except OSError as e:
        raise InputError("cannot read %s: %s" % (path, e))
    if not rows:
        raise InputError("no offers in %s" % path)
    out = []
    for n, r in enumerate(rows, 2):
        try:
            rate = to_float(r, "annual_rate", lo=0, hi=0.5)
            if rate > 0.3:
                raise InputError("annual_rate looks like a percent; use a decimal")
            pts = to_float(r, "points_pct", 0.0, lo=0, hi=0.1)
            out.append({"name": (r.get("name") or "offer %d" % (n - 1)).strip(), "annual_rate": rate,
                        "term_months": int(to_float(r, "term_months", lo=12, hi=600)),
                        "closing_costs": to_float(r, "closing_costs", 0.0, lo=0), "points_pct": pts,
                        "cash_out": to_float(r, "cash_out", 0.0, lo=0),
                        "roll_costs": (r.get("roll_costs") or "no").strip().lower() in ("yes", "y", "true", "1")})
        except InputError as e:
            raise InputError("offers line %d: %s" % (n, e))
    return out


def analyse(cur, offers, horizon=None):
    H = horizon or cur["horizon_months"]
    bal, rate, rem, pay = cur["balance"], cur["annual_rate"], cur["remaining_months"], cur["monthly_payment"]
    cur_interest = total_interest(bal, rate, 10 ** 6, pay)
    cur_months = sum(1 for _ in schedule(bal, rate, 10 ** 6, pay))
    cur_cost_h = pay * min(H, cur_months) + balance_after(bal, rate, pay, H)
    results = []
    for o in offers:
        base = bal + o["cash_out"]
        # points are charged on the new loan amount; solve iteratively when costs are rolled in
        loan = base
        for _ in range(20):
            upfront = o["closing_costs"] + o["points_pct"] * loan + cur["prepayment_penalty"]
            new_loan = base + (upfront if o["roll_costs"] else 0.0)
            if abs(new_loan - loan) < 0.01:
                break
            loan = new_loan
        loan = new_loan
        cash_paid = 0.0 if o["roll_costs"] else upfront
        npay = payment(loan, o["annual_rate"], o["term_months"])
        saving = pay - npay
        simple = math.ceil(upfront / saving) if saving > 0 else None
        if simple is not None and simple > o["term_months"]:
            simple = None
        # true break-even: cumulative (old - new payments) + (old balance - new balance) - cash paid - cash_out adj >= 0
        true_be = None
        horizon_net = None
        cum = 0.0
        ob, nb = bal, loan
        oi = schedule(bal, rate, 10 ** 6, pay)
        ni = schedule(loan, o["annual_rate"], o["term_months"], npay)
        for m in range(1, max(cur_months, o["term_months"]) + 1):
            op = np_ = 0.0
            try:
                _, i1, p1, ob = next(oi); op = i1 + p1
            except StopIteration:
                pass
            try:
                _, i2, p2, nb = next(ni); np_ = i2 + p2
            except StopIteration:
                pass
            cum += op - np_
            net = cum + (ob - nb) - cash_paid + o["cash_out"]
            if m == H:
                horizon_net = net
            if true_be is None and net >= 0 and m >= 1:
                true_be = m
        if horizon_net is None:
            horizon_net = net
        new_interest = total_interest(loan, o["annual_rate"], o["term_months"], npay)
        r = {"name": o["name"], "new_loan": round(loan, 2), "annual_rate": o["annual_rate"], "term_months": o["term_months"],
             "upfront_costs": round(upfront, 2), "cash_paid_at_closing": round(cash_paid, 2), "new_payment": round(npay, 2),
             "monthly_saving": round(saving, 2), "simple_break_even_months": simple, "true_break_even_month": true_be,
             "net_benefit_at_horizon": round(horizon_net, 2), "total_interest_new": round(new_interest, 2),
             "total_interest_current": round(cur_interest, 2), "payoff_shift_months": o["term_months"] - cur_months,
             "findings": []}
        f = r["findings"]
        if true_be is None or true_be > H:
            f.append("RF01")
        if o["term_months"] > cur_months + 6:
            f.append("RF02")
        if new_interest > cur_interest:
            f.append("RF03")
        if o["roll_costs"] and upfront > 0:
            f.append("RF04")
        if saving < 0 and o["term_months"] >= cur_months:
            f.append("RF05")
        if o["cash_out"] > 0:
            f.append("RF06")
        pts_payback = None
        if o["points_pct"] > 0:
            pts_cost = o["points_pct"] * loan
            no_pts_rate = o["annual_rate"] + o["points_pct"] / 0.01 * POINT_RATE_CUT
            pts_saving = payment(loan, no_pts_rate, o["term_months"]) - npay
            pts_payback = math.ceil(pts_cost / pts_saving) if pts_saving > 0 else None
            if pts_payback is None or pts_payback > H:
                f.append("RF07")
        r["points_payback_months"] = pts_payback
        if saving < 0 and o["term_months"] < cur_months:
            f.append("RF09")
        if 0 <= rate - o["annual_rate"] < 0.005:
            f.append("RF08")
        results.append(r)
    best = max(results, key=lambda x: x["net_benefit_at_horizon"])
    return {"current": {"balance": bal, "annual_rate": rate, "remaining_months": rem, "monthly_payment": round(pay, 2),
                        "months_to_payoff": cur_months, "total_interest_to_payoff": round(cur_interest, 2),
                        "cost_over_horizon_incl_balance": round(cur_cost_h, 2)},
            "horizon_months": H, "currency": cur["currency"], "offers": results,
            "best_at_horizon": best["name"] if best["net_benefit_at_horizon"] > 0 else None}


def money(x, cur=""):
    return ("%s%s" % (cur + " " if cur else "", "{:,.2f}".format(x)))


def render(a):
    c, cur = a["current"], a["currency"]
    L = ["# Refinance check (horizon %d months = %.1f years)" % (a["horizon_months"], a["horizon_months"] / 12), "",
         "Current loan: balance %s at %.3f%%, %d months left, payment %s (P&I), interest to payoff %s" % (
             money(c["balance"], cur), c["annual_rate"] * 100, c["months_to_payoff"], money(c["monthly_payment"], cur),
             money(c["total_interest_to_payoff"], cur)), "",
         "| offer | rate | term | new loan | upfront | new payment | saving/mo | simple BE | true BE | net at horizon | interest to payoff |",
         "|---|---|---|---|---|---|---|---|---|---|---|"]
    for r in a["offers"]:
        L.append("| %s | %.3f%% | %d | %s | %s | %s | %s | %s | %s | %s | %s |" % (
            r["name"], r["annual_rate"] * 100, r["term_months"], money(r["new_loan"]), money(r["upfront_costs"]),
            money(r["new_payment"]), money(r["monthly_saving"]),
            ("%d mo" % r["simple_break_even_months"]) if r["simple_break_even_months"] is not None else "never",
            ("%d mo" % r["true_break_even_month"]) if r["true_break_even_month"] is not None else "never",
            money(r["net_benefit_at_horizon"]), money(r["total_interest_new"])))
    L += ["", "Best at the horizon: %s" % (a["best_at_horizon"] or "none - keeping the current loan costs least"), "", "## Findings"]
    n = 0
    for r in a["offers"]:
        for code in r["findings"]:
            n += 1
            L.append("- [%s] %s %s: %s" % (SEV[code], code, r["name"], NAMES[code]))
    if not n:
        L.append("- none")
    L += ["", "Estimates of principal and interest only; confirm with the lender's official loan estimate."]
    return "\n".join(L)


def exit_code(a):
    high = any(SEV[c] == "high" for r in a["offers"] for c in r["findings"])
    ok = any(r["true_break_even_month"] is not None and r["true_break_even_month"] <= a["horizon_months"] for r in a["offers"])
    return 0 if ok and not high else 1


def self_test():
    T = []
    def check(name, cond):
        T.append((name, bool(cond)))
    check("payment 200k 6% 360m = 1199.10", abs(payment(200000, 0.06, 360) - 1199.10) < 0.01)
    check("zero-rate payment = principal / months", payment(12000, 0, 120) == 100)
    check("schedule pays off to zero", list(schedule(10000, 0.05, 60, payment(10000, 0.05, 60)))[-1][3] == 0)
    check("balance after 0 months = principal", balance_after(1000, 0.05, 100, 0) == 1000)
    cur = {"balance": 300000, "annual_rate": 0.07, "remaining_months": 300, "prepayment_penalty": 0, "currency": "",
           "horizon_months": 84}
    cur["monthly_payment"] = payment(300000, 0.07, 300)
    same = analyse(cur, [{"name": "same", "annual_rate": 0.07, "term_months": 300, "closing_costs": 0, "points_pct": 0,
                          "cash_out": 0, "roll_costs": False}])["offers"][0]
    check("identical free offer saves nothing", abs(same["monthly_saving"]) < 0.01 and abs(same["net_benefit_at_horizon"]) < 0.5)
    o = {"name": "cut", "annual_rate": 0.055, "term_months": 300, "closing_costs": 6000, "points_pct": 0, "cash_out": 0,
         "roll_costs": False}
    r = analyse(cur, [o])["offers"][0]
    check("lower rate same term saves money each month", r["monthly_saving"] > 0)
    check("simple break-even = ceil(costs / saving)", r["simple_break_even_months"] == math.ceil(6000 / r["monthly_saving"]))
    check("true break-even exists and <= simple", r["true_break_even_month"] and r["true_break_even_month"] <= r["simple_break_even_months"])
    check("no term reset finding at same term", "RF02" not in r["findings"])
    o2 = dict(o, name="reset", term_months=360)
    r2 = analyse(cur, [o2])["offers"][0]
    check("30-year reset flagged RF02", "RF02" in r2["findings"])
    o3 = dict(o, name="tiny", annual_rate=0.068, closing_costs=8000)
    r3 = analyse(cur, [o3])["offers"][0]
    check("tiny rate drop flagged RF08", "RF08" in r3["findings"])
    check("tiny drop with big costs flagged RF01", "RF01" in r3["findings"])
    o4 = dict(o, name="rolled", roll_costs=True)
    r4 = analyse(cur, [o4])["offers"][0]
    check("rolled costs raise the loan by the costs", abs(r4["new_loan"] - 306000) < 0.01)
    check("rolled costs flagged RF04 and no cash at closing", "RF04" in r4["findings"] and r4["cash_paid_at_closing"] == 0)
    o5 = dict(o, name="points", points_pct=0.01)
    r5 = analyse(cur, [o5])["offers"][0]
    check("1 point adds 1% of the loan to upfront", abs(r5["upfront_costs"] - 9000) < 0.01)
    o6 = dict(o, name="cash", cash_out=40000)
    r6 = analyse(cur, [o6])["offers"][0]
    check("cash-out flagged RF06 and loan includes it", "RF06" in r6["findings"] and abs(r6["new_loan"] - 340000) < 0.01)
    o7 = dict(o, name="higher", annual_rate=0.08)
    check("higher payment, same term flagged RF05", "RF05" in analyse(cur, [o7])["offers"][0]["findings"])
    o8 = dict(o, name="15y", annual_rate=0.052, term_months=180, closing_costs=5000)
    r8 = analyse(cur, [o8])["offers"][0]
    check("15-year offer cuts total interest", r8["total_interest_new"] < r8["total_interest_current"])
    check("15-year higher payment flagged RF09, not RF05", "RF09" in r8["findings"] and "RF05" not in r8["findings"])
    check("points payback uses 0.25 pp per point", r5["points_payback_months"] and r5["points_payback_months"] > 0)
    o9 = dict(o, name="free", closing_costs=0)
    r9 = analyse(cur, [o9])["offers"][0]
    check("no-cost offer: simple break-even 0 months", r9["simple_break_even_months"] == 0 and r9["true_break_even_month"] == 1)
    for bad, label in [({"balance": 0, "annual_rate": 0.05, "remaining_months": 100}, "zero balance rejected"),
                       ({"balance": 1000, "annual_rate": 6.5, "remaining_months": 100}, "percent rate rejected")]:
        try:
            to_float(bad, "balance", lo=1); r_ = to_float(bad, "annual_rate", lo=0, hi=0.5)
            check(label, False)
        except InputError:
            check(label, True)
    for name, ok in T:
        print(("PASS  " if ok else "FAIL  ") + name)
    good = all(ok for _, ok in T)
    print("ALL PASS" if good else "SOME FAILED", "(%d/%d)" % (sum(ok for _, ok in T), len(T)))
    return 0 if good else 1


def main(argv):
    if "--self-test" in argv:
        return self_test()
    args = [a for a in argv if not a.startswith("--")]
    horizon = None
    if "--horizon-months" in argv:
        try:
            horizon = int(argv[argv.index("--horizon-months") + 1])
            args.remove(str(horizon))
        except (IndexError, ValueError):
            print("error: --horizon-months needs a whole number", file=sys.stderr); return 2
    if len(args) != 2:
        print(__doc__, file=sys.stderr); return 2
    try:
        a = analyse(load_current(args[0]), load_offers(args[1]), horizon)
    except InputError as e:
        print("error: %s" % e, file=sys.stderr); return 2
    print(json.dumps(a, indent=2) if "--json" in argv else render(a))
    return exit_code(a)


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
BudgetingDecision MakingFinance+2
F@f
0
Employee Timesheet and Overtime Checker
Skill

Checks a small team's timesheets pre-payroll: splits each week into regular, overtime and double-time hours under your daily and weekly rules, estimates pay, and flags missing punches, overlaps, duplicates, short breaks, short rest, over-max weeks and too many days in a row. Offline stdlib Python.

---
name: employee-timesheet-and-overtime-checker
description: Checks a small team's timesheets pre-payroll: splits each week into regular, overtime and double-time hours under your daily and weekly rules, estimates pay, and flags missing punches, overlaps, duplicates, short breaks, short rest, over-max weeks and too many days in a row. Offline stdlib Python.
---

# Employee Timesheet and Overtime Checker

You help small business owners, shop and restaurant managers, office managers and payroll admins check a week or two of timesheets before they run payroll. Timesheet mistakes are expensive in both directions: a missing clock-out or a duplicate row pays the wrong amount, overtime that is not paid becomes a wage claim, and short breaks or short rest between a closing and an opening shift can break working-time rules. You turn the raw export into a clear hours-and-pay table and a short list of things to fix or confirm.

You work only on the files the user gives you, on their machine. You never decide what the law is where they are: you apply the rules they confirm, say clearly that the bundled defaults are only an example, and suggest checking local labour rules, the employment contracts or a payroll provider for anything unclear. You do not judge employees; findings are data questions to check with the person and their manager.

## Files in this skill

- `scripts/timesheet_check.py` - reads a timesheet CSV (and optional employees and rules files), splits hours per employee and week into regular, overtime and double time with daily and weekly thresholds, estimates gross pay, and reports findings TS01-TS11 by severity; `--json` for tooling, `--self-test` runs 20 checks (Python 3.8+ standard library only)
- `references/overtime-and-working-time-rules.md` - how the hours are split, what each rule key means, examples of rule sets people commonly configure, and what the script does not handle
- `references/fixing-timesheet-problems.md` - what each finding usually means, how to confirm and correct it, and how to prevent it next time
- `templates/payroll-check-report.md` - the summary you hand back before payroll
- `examples/timesheet.csv`, `examples/employees.csv`, `examples/rules.json` - a fictional shop week with five people and planted problems (missing clock-out, duplicate row, overlap, short break, closing-then-opening, a 49-hour week)

## Workflow

### 1. Confirm the rules first
Before running anything, ask which rules apply and fill `rules.json`:
- week start day and pay period;
- overtime thresholds (daily and/or weekly hours), multipliers and any double-time threshold;
- break rules (break required after how many hours, minimum minutes, paid or unpaid);
- minimum rest between shifts, maximum weekly hours and maximum days in a row;
- which employees are not eligible for overtime (salaried or exempt) and their hourly rates.
If the user does not know, run with the defaults but label every result "example rules" and list the questions in the report.

### 2. Prepare the files
- `timesheet.csv`: `employee,date,start,end,break_minutes[,note]`, date `YYYY-MM-DD`, times `HH:MM` 24 h. An end time earlier than the start means an overnight shift counted on the start date. Most clock systems can export this; rename columns if needed.
- `employees.csv` (optional): `employee,hourly_rate[,overtime_eligible]`.
- Names must match exactly between files.

### 3. Run the check
```
python3 scripts/timesheet_check.py examples/timesheet.csv --rules examples/rules.json --employees examples/employees.csv
python3 scripts/timesheet_check.py timesheet.csv --rules rules.json --employees employees.csv --json > check.json
python3 scripts/timesheet_check.py --self-test
```
Exit 0 = no high findings, 1 = high findings to fix before payroll, 2 = bad input. Without a shell, follow `references/overtime-and-working-time-rules.md` by hand for each employee and week.

### 4. Triage the findings
- High (fix before payroll): TS01 missing or unreadable time (the row was skipped, so pay is too low), TS02 overlapping shifts (double counting or a wrong date), TS08 over the weekly maximum.
- Medium (confirm with the manager): TS04 duplicate row (counted once), TS05 very long shift, TS06 missing or short break, TS07 short rest between shifts, TS09 too many days in a row.
- Low (information): TS10 no pay rate, TS11 overnight shift.
Use `references/fixing-timesheet-problems.md` for the likely cause and the fix. Never "correct" a time yourself: list the question for the employee or manager, then re-run after they confirm.

### 5. Report
Fill `templates/payroll-check-report.md`: rules used, hours and pay table, overtime total and cost, findings with the exact question to ask, and anything the script does not cover (shift premiums, holiday pay, tips, on-call, travel time, local rounding rules).

## Rules
- Overtime is never counted twice: hours already paid as daily overtime or double time do not count toward the weekly regular threshold.
- Pay estimates are gross base pay only, before taxes, premiums, allowances and deductions.
- Keep personal data private: do not upload timesheets, and share only the report with people who need it.

FILE:references/overtime-and-working-time-rules.md
# How timesheet_check.py splits hours and applies rules

## Worked time
worked hours = (end - start) - break. An end at or before the start is an overnight shift (end + 24 h), counted on the start date. Rows with a missing or unreadable time are skipped and reported as TS01, so the employee's total is too low until fixed.

## Splitting a week (no double counting)
For each employee and week (week_start in rules), day by day in date order:
1. Double time = hours above daily_dt_after (if set).
2. Daily overtime = remaining hours above daily_ot_after (if set).
3. The rest is regular, until the week's regular hours reach weekly_ot_after; regular hours beyond that move to overtime.
Employees with overtime_eligible = no get all hours as regular.
Pay estimate = rate x (regular + overtime x ot_multiplier + double time x dt_multiplier).

Example (daily 8 / weekly 40): Mon 8, Tue 8, Wed 10, Thu 8, Fri 9, Sat 5 = 48 h. Daily overtime 2 + 1 = 3 h; regular would be 45, so 5 more hours move to overtime: 40 regular, 8 overtime.

## Rule keys
| key | meaning | default |
|---|---|---|
| week_start | first day of the work week | monday |
| daily_ot_after | overtime after this many hours in a day (null = no daily overtime) | null |
| daily_dt_after | double time after this many hours in a day (null = none) | null |
| weekly_ot_after | overtime after this many regular hours in a week (null = none) | 40 |
| ot_multiplier / dt_multiplier | pay multipliers | 1.5 / 2.0 |
| break_required_after_hours / min_break_minutes | a break of at least N minutes for shifts longer than H hours | 6 / 30 |
| min_rest_hours | minimum rest between two shifts on different days | 11 |
| max_weekly_hours | flag weeks above this total | 48 |
| max_shift_hours | flag a start-to-end span above this (often a typo) | 14 |
| max_days_in_a_row | flag runs of consecutive working days above this | 6 |

## Rule sets people commonly configure (check your own law and contracts)
- Weekly-only overtime: weekly_ot_after 40, daily keys null (a common US federal-style setup).
- Daily and weekly overtime with double time: daily_ot_after 8, daily_dt_after 12, weekly_ot_after 40 (used in some US states).
- Working-time limits without statutory overtime pay: weekly_ot_after null or per contract, min_rest_hours 11, max_weekly_hours 48 (European working-time style; the 48 h is often an average over several months, which this weekly check does not average).
These are examples to start a conversation, not legal advice.

## Not handled
Averaging periods, seventh-day rules, shift or night premiums, holiday and sick pay, on-call and travel time, split-shift premiums, tips, minimum wage checks, time rounding policies, and multi-rate employees. Mention any that apply and handle them separately.

FILE:references/fixing-timesheet-problems.md
# Findings: likely causes and fixes

| code | finding | likely cause | how to confirm and fix | prevent next time |
|---|---|---|---|---|
| TS01 | missing or unreadable time | forgot to clock out, app crash, manual edit | ask the employee and manager for the real time; add it and re-run | clock-out reminders; manager reviews open punches daily |
| TS02 | overlapping shifts | wrong date on an overnight shift, double entry, two locations | compare with the rota and the till/door logs; fix the date or delete the duplicate | one clock-in at a time per person |
| TS03 | break longer than the shift | break entered in hours or the wrong column | confirm the real break and correct it | validate break fields in the export |
| TS04 | duplicate row | double import or edit | the script counts it once; delete it at the source | import each period once |
| TS05 | very long shift | typo in the end time or a missing clock-out the next day | confirm with the employee; if real, check rest and maximum rules | alert on shifts over the limit |
| TS06 | break missing or short | busy shift, break not recorded | ask whether a break was taken; some places owe a penalty for missed breaks | schedule breaks on the rota |
| TS07 | short rest between shifts | closing then opening ("clopening") | confirm; adjust the rota; check whether local rules require a premium | rota checks before publishing |
| TS08 | over the weekly maximum | extra cover, missing staff | confirm the hours are real and any opt-out or averaging agreement | plan cover earlier |
| TS09 | too many days in a row | cover for absence | confirm a day off is scheduled | rota checks |
| TS10 | no pay rate | new hire, name spelled differently | add the employee or fix the name | one employee list as the source of names |
| TS11 | overnight shift | night work | confirm the start date is right | none needed |

When you report a finding, give the exact question to ask, for example: "Priya, on Wed 18 Nov you clocked in at 09:00 but there is no clock-out. What time did you finish?"

FILE:templates/payroll-check-report.md
# Payroll check: {{business}} - pay period {{period}}

Prepared {{date}}. Rules used: {{rules_summary}} ({{confirmed_or_example}} rules).

## Summary
- Employees: {{employee_count}} | shifts: {{shift_count}}
- Overtime and double-time hours: {{ot_hours}} (estimated cost {{ot_cost}})
- Estimated gross base pay: {{gross_pay}}
- Fix before payroll: {{high_count}} high findings | confirm: {{medium_count}} medium

## Hours and pay
(paste the table from timesheet_check.py)

## Fix before payroll
| employee | date | finding | question to ask | owner |
|---|---|---|---|---|
| {{employee}} | {{date}} | {{code and issue}} | {{exact question}} | {{manager}} |

## Confirm with managers
- {{finding and question}}

## Not covered by this check
- {{premiums, holiday pay, tips, averaging periods, local rounding rules}}

## Rota suggestions
- {{for example: avoid closing-then-opening shifts; schedule breaks on 8 h shifts}}

FILE:examples/timesheet.csv
employee,date,start,end,break_minutes,note
Maya Torres,2026-11-16,07:00,15:30,30,
Maya Torres,2026-11-17,07:00,15:30,30,
Maya Torres,2026-11-18,07:00,17:30,30,stock delivery
Maya Torres,2026-11-19,07:00,15:30,30,
Maya Torres,2026-11-20,07:00,16:30,30,
Maya Torres,2026-11-21,08:00,13:00,0,Saturday cover
Jonah Reed,2026-11-16,12:00,20:30,30,
Jonah Reed,2026-11-17,12:00,23:00,30,closing
Jonah Reed,2026-11-18,07:00,15:00,30,opening after closing
Jonah Reed,2026-11-19,12:00,20:30,15,
Jonah Reed,2026-11-20,12:00,20:30,30,
Jonah Reed,2026-11-20,12:00,20:30,30,
Priya Nair,2026-11-16,09:00,17:00,45,
Priya Nair,2026-11-17,09:00,17:00,45,
Priya Nair,2026-11-18,09:00,,45,forgot to clock out
Priya Nair,2026-11-19,09:00,19:00,45,
Priya Nair,2026-11-20,09:00,17:00,45,
Sam Okafor,2026-11-17,22:00,06:30,30,night stock count
Sam Okafor,2026-11-18,06:00,10:00,0,
Sam Okafor,2026-11-19,18:00,23:00,0,
Lena Fischer,2026-11-16,08:00,16:00,30,
Lena Fischer,2026-11-17,08:00,18:00,60,
Lena Fischer,2026-11-18,08:00,18:00,60,
Lena Fischer,2026-11-19,08:00,18:00,60,
Lena Fischer,2026-11-20,08:00,18:00,60,
Lena Fischer,2026-11-21,08:00,14:00,30,

FILE:examples/employees.csv
employee,hourly_rate,overtime_eligible
Maya Torres,19.50,yes
Jonah Reed,17.00,yes
Priya Nair,24.00,yes
Sam Okafor,18.25,yes
Lena Fischer,32.00,no

FILE:examples/rules.json
{
  "name": "Example shop rules (illustrative only, set yours from local law and contracts)",
  "week_start": "monday",
  "daily_ot_after": 8,
  "daily_dt_after": 12,
  "weekly_ot_after": 40,
  "ot_multiplier": 1.5,
  "dt_multiplier": 2.0,
  "break_required_after_hours": 6,
  "min_break_minutes": 30,
  "min_rest_hours": 11,
  "max_weekly_hours": 48,
  "max_shift_hours": 14,
  "max_days_in_a_row": 6
}

FILE:scripts/timesheet_check.py
#!/usr/bin/env python3
"""timesheet_check.py - check a team's timesheets and work out regular, overtime and double-time hours.

Reads shift rows, applies your overtime and working-time rules (daily and weekly
thresholds, multipliers, breaks, rest between shifts, weekly maximum, days in a
row), estimates pay per employee and week, and flags data errors and rule
breaches before payroll. Standard library only.

Usage:
  python3 timesheet_check.py TIMESHEET.csv [--rules RULES.json] [--employees EMPLOYEES.csv] [--json]
  python3 timesheet_check.py --self-test

TIMESHEET.csv columns: employee,date,start,end,break_minutes[,note]
  date YYYY-MM-DD, start/end HH:MM (24 h). An end earlier than the start is an overnight shift
  (counted on the start date).
EMPLOYEES.csv columns: employee,hourly_rate[,overtime_eligible]  (overtime_eligible: yes/no, default yes)
RULES.json keys (all optional, defaults in DEFAULT_RULES): week_start (monday..sunday),
  daily_ot_after, daily_dt_after, weekly_ot_after (hours or null), ot_multiplier, dt_multiplier,
  break_required_after_hours, min_break_minutes, min_rest_hours, max_weekly_hours,
  max_shift_hours, max_days_in_a_row.
Exit codes: 0 no high findings, 1 high findings, 2 bad input.
The default rules are an example, not the law where you are: set them from your local labour rules and contracts.
"""
import csv, datetime as dt, json, sys
from collections import defaultdict

DEFAULT_RULES = {
    "week_start": "monday",
    "daily_ot_after": None,          # e.g. 8 where daily overtime applies
    "daily_dt_after": None,          # e.g. 12 where daily double time applies
    "weekly_ot_after": 40,
    "ot_multiplier": 1.5,
    "dt_multiplier": 2.0,
    "break_required_after_hours": 6,
    "min_break_minutes": 30,
    "min_rest_hours": 11,
    "max_weekly_hours": 48,
    "max_shift_hours": 14,
    "max_days_in_a_row": 6,
}
DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
SEV = {"TS01": "high", "TS02": "high", "TS03": "high", "TS04": "medium", "TS05": "medium", "TS06": "medium",
       "TS07": "medium", "TS08": "high", "TS09": "medium", "TS10": "low", "TS11": "low"}
NAMES = {"TS01": "missing or unreadable time", "TS02": "overlapping shifts", "TS03": "break longer than the shift",
         "TS04": "duplicate row", "TS05": "very long shift (typo?)", "TS06": "required break missing or short",
         "TS07": "short rest between shifts", "TS08": "over the weekly maximum", "TS09": "too many days in a row",
         "TS10": "no pay rate", "TS11": "overnight shift (check the date)"}


class InputError(Exception):
    pass


def parse_time(s):
    try:
        h, m = s.strip().split(":")
        h, m = int(h), int(m)
        if not (0 <= h <= 24 and 0 <= m < 60) or (h == 24 and m):
            raise ValueError
        return h * 60 + m
    except (ValueError, AttributeError):
        return None


def load_rules(path):
    rules = dict(DEFAULT_RULES)
    if path:
        with open(path, encoding="utf-8") as f:
            user = json.load(f)
        unknown = set(user) - set(DEFAULT_RULES) - {"name", "notes"}
        if unknown:
            raise InputError("unknown rule keys: " + ", ".join(sorted(unknown)))
        rules.update({k: v for k, v in user.items() if k in DEFAULT_RULES})
    if str(rules["week_start"]).lower() not in DAYS:
        raise InputError("week_start must be a weekday name")
    for k in ("ot_multiplier", "dt_multiplier"):
        if not isinstance(rules[k], (int, float)) or rules[k] < 1:
            raise InputError(k + " must be a number >= 1")
    return rules


def load_employees(path):
    emp = {}
    if not path:
        return emp
    with open(path, newline="", encoding="utf-8") as f:
        for i, row in enumerate(csv.DictReader(f), start=2):
            row = {k.strip(): (v or "").strip() for k, v in row.items()}
            try:
                rate = float(row.get("hourly_rate", ""))
            except ValueError:
                raise InputError("employees line %d: hourly_rate must be a number" % i)
            emp[row["employee"]] = {"rate": rate, "ot": row.get("overtime_eligible", "yes").lower() not in ("no", "n", "false", "0")}
    return emp


def load_shifts(path):
    shifts, findings = [], []
    with open(path, newline="", encoding="utf-8") as f:
        r = csv.DictReader(f)
        need = {"employee", "date", "start", "end", "break_minutes"}
        if not r.fieldnames or not need.issubset({h.strip() for h in r.fieldnames}):
            raise InputError("timesheet needs columns employee,date,start,end,break_minutes")
        seen = set()
        for i, row in enumerate(r, start=2):
            row = {k.strip(): (v or "").strip() for k, v in row.items() if k}
            if not any(row.values()):
                continue
            e = row["employee"]
            key = (e, row["date"], row["start"], row["end"])
            if key in seen:
                findings.append(("TS04", e, row["date"], "line %d repeats an earlier row; counted once" % i))
                continue
            seen.add(key)
            try:
                day = dt.date.fromisoformat(row["date"])
            except ValueError:
                findings.append(("TS01", e, row["date"], "line %d: date is not YYYY-MM-DD; row skipped" % i)); continue
            s, en = parse_time(row["start"]), parse_time(row["end"])
            if s is None or en is None:
                findings.append(("TS01", e, row["date"], "line %d: start or end missing/unreadable (%r-%r); row skipped" % (i, row["start"], row["end"]))); continue
            try:
                brk = int(row["break_minutes"] or 0)
            except ValueError:
                findings.append(("TS01", e, row["date"], "line %d: break_minutes is not a whole number; treated as 0" % i)); brk = 0
            overnight = en <= s
            if overnight:
                en += 24 * 60
                findings.append(("TS11", e, row["date"], "line %d: %s-%s crosses midnight; counted on %s" % (i, row["start"], row["end"], row["date"])))
            start = dt.datetime.combine(day, dt.time()) + dt.timedelta(minutes=s)
            end = dt.datetime.combine(day, dt.time()) + dt.timedelta(minutes=en)
            span = (en - s)
            if brk > span:
                findings.append(("TS03", e, row["date"], "line %d: break %d min is longer than the %d-min shift; worked time set to 0" % (i, brk, span)))
                brk = span
            shifts.append({"employee": e, "date": day, "start": start, "end": end, "break": brk,
                           "hours": (span - brk) / 60.0, "span_h": span / 60.0, "line": i, "note": row.get("note", "")})
    return shifts, findings


def week_of(day, week_start):
    offset = (day.weekday() - DAYS.index(week_start)) % 7
    return day - dt.timedelta(days=offset)


def analyse(shifts, rules, employees, findings):
    ws = rules["week_start"].lower()
    by_emp = defaultdict(list)
    for s in shifts:
        by_emp[s["employee"]].append(s)
    weeks = []
    for e, ss in sorted(by_emp.items()):
        ss.sort(key=lambda x: x["start"])
        for a, b in zip(ss, ss[1:]):
            if b["start"] < a["end"]:
                findings.append(("TS02", e, b["date"].isoformat(), "lines %d and %d overlap (%s-%s and %s-%s)" % (
                    a["line"], b["line"], a["start"].strftime("%a %H:%M"), a["end"].strftime("%H:%M"), b["start"].strftime("%a %H:%M"), b["end"].strftime("%H:%M"))))
            else:
                rest = (b["start"] - a["end"]).total_seconds() / 3600
                if rules["min_rest_hours"] and rest < rules["min_rest_hours"] and b["date"] != a["date"]:
                    findings.append(("TS07", e, b["date"].isoformat(), "only %.1f h rest between line %d and line %d (minimum %s h)" % (rest, a["line"], b["line"], rules["min_rest_hours"])))
        for s in ss:
            if rules["max_shift_hours"] and s["span_h"] > rules["max_shift_hours"]:
                findings.append(("TS05", e, s["date"].isoformat(), "line %d: %.1f h from start to end (limit %s h); check for a typo" % (s["line"], s["span_h"], rules["max_shift_hours"])))
            if rules["break_required_after_hours"] and s["span_h"] > rules["break_required_after_hours"] and s["break"] < rules["min_break_minutes"]:
                findings.append(("TS06", e, s["date"].isoformat(), "line %d: %.1f h shift with %d min break (needs %d min after %s h)" % (s["line"], s["span_h"], s["break"], rules["min_break_minutes"], rules["break_required_after_hours"])))
        days = sorted({s["date"] for s in ss if s["hours"] > 0})
        run, best, best_end = 1, 1, days[0] if days else None
        for a, b in zip(days, days[1:]):
            run = run + 1 if (b - a).days == 1 else 1
            if run > best:
                best, best_end = run, b
        if rules["max_days_in_a_row"] and best > rules["max_days_in_a_row"]:
            findings.append(("TS09", e, best_end.isoformat(), "%d days in a row without a day off (limit %d)" % (best, rules["max_days_in_a_row"])))
        info = employees.get(e)
        if employees and info is None:
            findings.append(("TS10", e, "", "not in the employees file; pay not estimated"))
        ot_ok = True if info is None else info["ot"]
        by_week = defaultdict(lambda: defaultdict(float))
        for s in ss:
            by_week[week_of(s["date"], ws)][s["date"]] += s["hours"]
        for wk, daymap in sorted(by_week.items()):
            reg = ot = dtm = 0.0
            for day in sorted(daymap):
                h = daymap[day]
                d_dt = max(0.0, h - rules["daily_dt_after"]) if rules["daily_dt_after"] else 0.0
                d_ot = max(0.0, h - d_dt - rules["daily_ot_after"]) if rules["daily_ot_after"] else 0.0
                d_reg = h - d_dt - d_ot
                if rules["weekly_ot_after"] is not None and reg + d_reg > rules["weekly_ot_after"]:
                    over = reg + d_reg - rules["weekly_ot_after"]
                    moved = min(over, d_reg)
                    d_reg -= moved; d_ot += moved
                reg += d_reg; ot += d_ot; dtm += d_dt
            total = reg + ot + dtm
            if not ot_ok:
                reg, ot, dtm = total, 0.0, 0.0
            if rules["max_weekly_hours"] and total > rules["max_weekly_hours"]:
                findings.append(("TS08", e, wk.isoformat(), "%.2f h in the week starting %s (maximum %s h)" % (total, wk.isoformat(), rules["max_weekly_hours"])))
            pay = None
            if info:
                pay = info["rate"] * (reg + ot * rules["ot_multiplier"] + dtm * rules["dt_multiplier"])
            weeks.append({"employee": e, "week_start": wk.isoformat(), "days": len(daymap), "total": round(total, 2),
                          "regular": round(reg, 2), "overtime": round(ot, 2), "double_time": round(dtm, 2),
                          "overtime_eligible": ot_ok, "rate": info["rate"] if info else None,
                          "pay_estimate": round(pay, 2) if pay is not None else None})
    return weeks


def run(ts_path, rules_path=None, emp_path=None):
    rules = load_rules(rules_path)
    employees = load_employees(emp_path)
    shifts, findings = load_shifts(ts_path)
    if not shifts:
        raise InputError("no usable shifts in the timesheet")
    weeks = analyse(shifts, rules, employees, findings)
    findings = [{"code": c, "severity": SEV[c], "issue": NAMES[c], "employee": e, "date": d, "detail": t} for c, e, d, t in findings]
    order = {"high": 0, "medium": 1, "low": 2}
    findings.sort(key=lambda f: (order[f["severity"]], f["code"], f["employee"], f["date"]))
    return {"rules": rules, "weeks": weeks, "findings": findings, "shift_count": len(shifts)}


def report(res):
    r = res["rules"]
    L = ["# Timesheet and overtime check", ""]
    L.append("Rules used: week starts %s; overtime after %s h/day and %s h/week at x%s; double time after %s h/day at x%s; break %s min after %s h; rest %s h; max %s h/week; max %s days in a row." % (
        r["week_start"], r["daily_ot_after"] or "-", r["weekly_ot_after"] if r["weekly_ot_after"] is not None else "-", r["ot_multiplier"],
        r["daily_dt_after"] or "-", r["dt_multiplier"], r["min_break_minutes"], r["break_required_after_hours"], r["min_rest_hours"], r["max_weekly_hours"], r["max_days_in_a_row"]))
    L.append("%d shifts read." % res["shift_count"])
    L.append("")
    L.append("## Hours and pay by employee and week")
    L.append("| employee | week starting | days | total h | regular | overtime | double time | rate | pay estimate |")
    L.append("|---|---|---:|---:|---:|---:|---:|---:|---:|")
    for w in res["weeks"]:
        L.append("| %s | %s | %d | %.2f | %.2f | %.2f | %.2f | %s | %s |" % (w["employee"] + ("" if w["overtime_eligible"] else " (no OT)"), w["week_start"], w["days"],
                 w["total"], w["regular"], w["overtime"], w["double_time"], "%.2f" % w["rate"] if w["rate"] is not None else "-",
                 "{:,.2f}".format(w["pay_estimate"]) if w["pay_estimate"] is not None else "-"))
    tot_pay = sum(w["pay_estimate"] or 0 for w in res["weeks"])
    tot_ot = sum(w["overtime"] + w["double_time"] for w in res["weeks"])
    L.append("")
    L.append("Totals: %.2f overtime/double-time hours; estimated gross pay %s (before taxes, premiums and allowances)." % (tot_ot, "{:,.2f}".format(tot_pay)))
    L.append("")
    L.append("## Findings (%d)" % len(res["findings"]))
    if not res["findings"]:
        L.append("- none")
    for f in res["findings"]:
        L.append("- [%s] %s %s - %s%s: %s" % (f["severity"].upper(), f["code"], f["issue"], f["employee"], (" " + f["date"]) if f["date"] else "", f["detail"]))
    L.append("")
    L.append("Check every high finding with the employee or manager before payroll. Your local labour law and contracts decide the real rules.")
    return "\n".join(L)


def self_test():
    import os, tempfile
    ok = True
    def check(name, cond):
        nonlocal ok
        print(("PASS  " if cond else "FAIL  ") + name); ok = ok and cond
    tmp = tempfile.mkdtemp()
    def write(name, text):
        p = os.path.join(tmp, name); open(p, "w", encoding="utf-8").write(text); return p
    emp = write("e.csv", "employee,hourly_rate,overtime_eligible\nAna,20,yes\nBo,30,no\n")
    week = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,08:00,17:00,30\n" % d for d in (16, 17, 18, 19, 20))
    res = run(write("a.csv", week), None, emp)
    w = res["weeks"][0]
    check("5 x 8.5 h = 42.5 h total", abs(w["total"] - 42.5) < 1e-9)
    check("weekly OT after 40 h = 2.5 h", abs(w["overtime"] - 2.5) < 1e-9 and abs(w["regular"] - 40) < 1e-9)
    check("pay = 40x20 + 2.5x30", abs(w["pay_estimate"] - 875) < 1e-6)
    rules = write("r.json", json.dumps({"daily_ot_after": 8, "daily_dt_after": 12, "weekly_ot_after": 40}))
    res = run(write("b.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,06:00,20:00,30\n"), rules, emp)
    w = res["weeks"][0]
    check("13.5 h day with daily rules: 8 reg, 4 OT, 1.5 DT", (w["regular"], w["overtime"], w["double_time"]) == (8.0, 4.0, 1.5))
    res = run(write("c.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,22:00,06:00,30\n"))
    check("overnight shift counted 7.5 h", abs(res["weeks"][0]["total"] - 7.5) < 1e-9)
    check("overnight shift flagged TS11", any(f["code"] == "TS11" for f in res["findings"]))
    res = run(write("d.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-16,15:00,18:00,0\n"))
    check("overlap TS02", any(f["code"] == "TS02" for f in res["findings"]))
    res = run(write("e2.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-16,08:00,16:00,30\n"))
    check("duplicate TS04 counted once", any(f["code"] == "TS04" for f in res["findings"]) and abs(res["weeks"][0]["total"] - 7.5) < 1e-9)
    res = run(write("f.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:30,10\n"))
    check("missing break TS06", any(f["code"] == "TS06" for f in res["findings"]))
    res = run(write("g.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,14:00,23:00,30\nAna,2026-11-17,06:00,14:00,30\n"))
    check("7 h rest TS07", any(f["code"] == "TS07" for f in res["findings"]))
    res = run(write("h.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,,30\nAna,2026-11-17,08:00,16:00,30\n"))
    check("missing end TS01 and row skipped", any(f["code"] == "TS01" for f in res["findings"]) and res["shift_count"] == 1)
    rows = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,07:00,18:00,30\n" % d for d in range(16, 21))
    res = run(write("i.csv", rows))
    check("52.5 h week TS08", any(f["code"] == "TS08" for f in res["findings"]))
    rows = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,09:00,13:00,0\n" % d for d in range(10, 18))
    res = run(write("j.csv", rows))
    check("8 days in a row TS09", any(f["code"] == "TS09" for f in res["findings"]))
    res = run(write("k.csv", week.replace("Ana", "Bo")), None, emp)
    check("not OT eligible: all regular", res["weeks"][0]["overtime"] == 0 and abs(res["weeks"][0]["regular"] - 42.5) < 1e-9)
    res = run(write("l.csv", week.replace("Ana", "Cy")), None, emp)
    check("unknown employee TS10, no pay", any(f["code"] == "TS10" for f in res["findings"]) and res["weeks"][0]["pay_estimate"] is None)
    res = run(write("m.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,09:00,90\n"))
    check("break longer than shift TS03", any(f["code"] == "TS03" for f in res["findings"]) and res["weeks"][0]["total"] == 0)
    res = run(write("n.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-22,08:00,16:00,30\nAna,2026-11-23,08:00,16:00,30\n"))
    check("sunday belongs to the monday week, next monday starts a new week", [w["week_start"] for w in res["weeks"]] == ["2026-11-16", "2026-11-23"])
    rules2 = write("r2.json", json.dumps({"week_start": "sunday"}))
    res = run(write("o.csv", "employee,date,start,end,break_minutes\nAna,2026-11-22,08:00,16:00,30\n"), rules2)
    check("week_start sunday", res["weeks"][0]["week_start"] == "2026-11-22")
    try:
        run(write("p.csv", "employee,date,start\nAna,2026-11-16,08:00\n")); check("missing columns rejected", False)
    except InputError:
        check("missing columns rejected", True)
    try:
        run(write("q.csv", week), write("bad.json", json.dumps({"weekly_overtime": 40}))); check("unknown rule key rejected", False)
    except InputError:
        check("unknown rule key rejected", True)
    print("ALL PASS" if ok else "SOME TESTS FAILED")
    return 0 if ok else 1


def main(argv):
    if "--self-test" in argv:
        return self_test()
    args, opts, i = [], {}, 0
    while i < len(argv):
        a = argv[i]
        if a in ("--rules", "--employees"):
            if i + 1 >= len(argv):
                print(a + " needs a file", file=sys.stderr); return 2
            opts[a] = argv[i + 1]; i += 2; continue
        if a != "--json":
            args.append(a)
        i += 1
    if len(args) != 1:
        print(__doc__, file=sys.stderr); return 2
    try:
        res = run(args[0], opts.get("--rules"), opts.get("--employees"))
    except (InputError, OSError, json.JSONDecodeError) as e:
        print("input error: %s" % e, file=sys.stderr); return 2
    print(json.dumps(res, indent=2, default=str) if "--json" in argv else report(res))
    return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
ComplianceBusinessData Analysis+3
F@f
0
Hand-Colored Magic Lantern Slide of a Great Comet over a Snowy Village
Image
Hand-Colored Magic Lantern Slide of a Great Comet over a Snowy Village

A glowing hand-painted Victorian magic lantern glass slide: a great comet with a long sweeping tail over a snowy village with a church spire, amber windows and a frozen pond, in translucent Prussian blue and amber washes inside a round black mask, with bubbles, dust and hairline scratches.

A hand-colored Victorian magic lantern glass slide showing a great comet over a snowy village at night, photographed straight-on against a soft backlight so the glass glows. The picture sits inside a round opening of a black paper mask, with a narrow dark binding-tape border around the square glass. Inside the circle: a deep translucent Prussian-blue night sky filled with tiny pin-prick stars; a large bright comet in the upper left with a pale yellow-white head and a long sweeping tail that fans across the sky toward the right; below, a small village of steep snow-covered roofs, a church with a slender spire in the center, bare trees, a frozen pond reflecting the comet, and windows glowing warm amber; a few tiny dark figures on the lane look up at the sky.

Render it exactly like an 1880s transparent hand-painted slide: thin, luminous aniline and varnish colors laid over a fine black line image, slightly uneven washes that stop a little short of the outlines, soft brush streaks in the sky, glowing light where the paint is thinnest, tiny air bubbles and dust specks in the glass, faint hairline scratches, gentle vignetting toward the edge of the round mask and a slight chromatic halo at the comet's head. Warm, glowing, nostalgic and magical. No text, no labels, no modern objects. Square 1:1.
DesignCreativeVintage+2
F@f
0
Silverpoint Drawing of a Wren on a Bramble Branch with Blackberries
Image
Silverpoint Drawing of a Wren on a Bramble Branch with Blackberries

A Renaissance-style silverpoint drawing on warm ivory-pink prepared paper: a wren with a cocked tail on an arching bramble branch with blackberries, thorns and serrated leaves, built only from fine tarnished hatching lines with white chalk highlights and faint construction lines.

A Renaissance-style silverpoint drawing of a small wren perched on an arching bramble branch with ripe and unripe blackberries, drawn on paper coated with a pale warm ivory-pink prepared ground. The wren sits in the upper middle of the sheet facing left, tail cocked upright, its round body built from hundreds of fine parallel hatching lines and soft cross-hatching that describe the barred wing and tail feathers, a bright tiny eye and a thin slightly curved beak. The bramble enters from the lower right and curves up under the bird: thorny stems, three serrated leaves with clear veins, two clusters of blackberries with each round drupelet modeled by tiny curved strokes, a few hard green berries and one small five-petal flower.

Render it exactly like a real metalpoint drawing: only thin, even, delicate grey lines that have aged to a soft warm brown-grey tarnish, no smudging, no thick or black strokes, no solid fills; tone is built only by layered hatching that follows the forms. Add a few faint exploratory construction lines and one lightly corrected wing outline, small white chalk highlights on the eye, the berries and the leaf edges, and plenty of empty toned paper around the subject. Slight fibre texture and a soft foxing spot near one corner. Even, flat museum lighting, straight-on view of the whole sheet. No text, no signature, no frame. Portrait 3:4.
VisualCreativeVintage+2
F@f
0
Holiday Code Freeze and Peak Traffic Readiness Plan (YAML)
Text

Turn one peak season (holiday sales, a launch, a ticket drop) into a YAML code freeze and readiness plan: soft and hard freeze rules, capacity targets and load tests, a dependency fallback matrix, kill switches, alerts, a holiday-aware on-call rota, rollback steps and a day-of runbook.

1role: >-
2 Site reliability and release planner for small and mid-sized engineering
3 teams. You turn one upcoming peak season (holiday sales, a big launch, a
4 ticket drop, tax deadline week) into a practical code freeze and peak
5 traffic readiness plan: what gets frozen and when, what is still allowed,
6 how capacity and dependencies are checked, who is on call, and how the
7 team rolls back fast if something breaks while traffic is highest.
8
9event:
10 name: "${event_name:Black Friday to Cyber Monday sales weekend}"
...+134 more lines
YAMLMonitoringDeployment+4
F@f
0
Act as a Skip-Level Meeting Coach
Text

A coach for directors and managers of managers: prepares your direct reports first, writes the invitation, a question bank and run sheets for 1:1 and group skip-levels, scripts for tricky moments, a notes and themes template, and you-said-we-did follow-up messages.

Act as a Skip-Level Meeting Coach. You help a manager of managers (a director, head of department or senior manager) prepare, run and follow up on skip-level meetings with people who report to their direct reports, so they hear what is really happening on the ground without undermining the managers in between or turning the meeting into a complaint session or a performance review.

You are practical and people-aware. You never encourage going around a manager, collecting gossip, or promising things the leader cannot deliver. If something raised in a skip-level points to harassment, discrimination, safety or a legal issue, you tell me to follow my company's HR or reporting process instead of handling it alone.

## About my situation
- My role: Director of Engineering with 4 engineering managers and about 30 engineers
- Who I am meeting: engineers in two teams I rarely talk to directly
- Format: 1:1 skip-levels of 30 minutes, or small groups of 4-5 people
- How often: each person once per quarter
- Why now: a reorg two months ago, rising attrition in one team, and an upcoming planning cycle
- What I already know or suspect: on-call load feels unfair; one manager is new and stretched
- My worry: people will be polite and tell me nothing, or their managers will feel I am checking up on them

## What to do
1. **Clarify the goal.** Ask me up to 5 short questions about my goals, the teams, the managers in between and any recent events (reorg, layoffs, launches, departures). Wait for my answers before writing anything.
2. **Prepare the managers first.** Draft a short, honest message I can send to my direct reports before the skip-levels start: why I am doing them, what I will and will not do with what I hear (no surprise decisions about their teams, themes shared back with them, no performance judgments), and an invitation to tell me what they would like me to listen for.
3. **Invitation to attendees.** Write a friendly invitation for the attendees that explains the purpose, says the meeting is not a performance review, explains how confidentiality works (I share themes, not names, unless they ask me to), and offers 2-3 topics they can think about in advance. Keep it under 120 words.
4. **Question bank.** Give me 12-15 open questions grouped by theme, with a note on when to use each:
   - Work and priorities (what is getting in the way, what they would stop doing)
   - Team and collaboration (how decisions get made, where handoffs break)
   - Growth (what they want to learn, what support they get)
   - Company direction (what is unclear about strategy or recent changes)
   - Me as a leader (what I should know but probably do not)
   Avoid leading or yes/no questions, and avoid any question that asks people to rate or criticise their own manager directly.
5. **Run sheet.** Produce a minute-by-minute plan for one 30-minute 1:1 and one 45-minute group session: opening words, how to build trust in the first five minutes, which questions to start with, how to dig deeper ("Can you give me an example?", "What would good look like?"), how to handle silence, and how to close with a clear promise about follow-up.
6. **Tricky moments.** Tell me exactly what to say when: someone complains about their manager; someone asks me to keep something secret that I cannot keep; someone asks about layoffs, promotions or pay; the group goes quiet; one person dominates; I hear a strong claim I cannot verify.
7. **Notes and themes.** Give me a simple notes template (date, attendee or group, themes, quotes without names, ideas, my follow-ups), and a way to group notes across sessions into 3-5 themes with how often each came up.
8. **Close the loop.** Draft: a short theme summary to discuss with each direct report first, a "you said, we did" message to attendees two to four weeks later, and a list of what I will change, what I will not change and why. Make sure every promise I made in the meetings is tracked.

## How to respond
- Start with the questions in step 1 only.
- Then deliver steps 2-8 in order, with headings, short bullet points and ready-to-send drafts in plain language.
- Keep my direct reports in the loop at every step: nothing in the plan should surprise them.
- If my goal looks like checking up on a specific manager or employee, say so plainly and suggest a better route (coaching that manager, a direct conversation, or HR).
- Never invent facts about my company, teams or people; ask when you need information.
ChecklistCoachCommunication+3
F@f
0
Performance Marketer for Blockchain Internet Cafe
Text

نسخه‌ی مخصوص دفتر خدمات اینترنتی بلاکچین لنگرود از پرامپت بازاریاب عملکردی — ۱۰ زاویه‌ی تبلیغاتی برای خدمات دفتر با مخاطب محلی، با هوک و CTA برای مراجعه‌ی حضوری.

Act as a performance marketer for Blockchain Internet Cafe, an internet services office in Langarud, Iran. Our services: online government registrations, vehicle plate appointments, utility bills, insurance, judicial services, commercial tax/VAT/ledger accounting, dormant bank account recovery with identity verification, online buying/selling and consulting. Our customers are local residents and small business owners in Langarud who need paperwork done quickly and correctly, in person at the shop.

Give me 10 different ad angles for our services aimed at local customers who have never heard of us: pain point, desired outcome, objection, comparison, customer proof, curiosity, behind the scenes, how-to, identity ("for people who…") and a time-sensitive angle (only if I have a real deadline). For each, give a headline, one line of ad text and why it might work. Write the ads in Persian. Every ad must have a scroll-stopping hook and a clear call to action to visit the shop in person (Langarud, Kofsh-e Melli alley, opposite Babak passage).

Follow-up: Pick the 3 angles most likely to work with people who have never heard of me and write full ads for them.
AdvertisingCopywritingMarketing
B@bigshaah
0
TrendingVideo
Modest Fashion Unboxing-to-Street Promo Video With Hijab Outfit Showcase (40s)

A six-scene cinematic modest-fashion commercial: package reveal at home, outfit try-on, multi-angle showcase, golden-hour shopping street walk and fabric close-ups, with strict character and outfit consistency.

Create a 40-second realistic cinematic fashion promotional video featuring a beautiful young Muslim woman wearing a beige hijab and elegant modest clothing.

Scene 1: She sits behind a table in a cozy, beautifully decorated living room, smiling and presenting an online-store shopping package to the camera.

Scene 2: She opens the package and reveals a beautiful dusty-rose pink modest outfit, showing the fabric and details.

Scene 3: Transition smoothly to her wearing the complete outfit: a dusty-rose pink long-sleeve blouse with elegant gathered cuffs and matching wide-leg floral-patterned trousers. She wears a beige hijab and carries a small cream-colored crossbody handbag.

Scene 4: Show her full outfit from different angles. She gently walks, turns, smiles, and poses naturally while showcasing the blouse, sleeves, trousers, and handbag.

Scene 5: Transition to an elegant outdoor shopping street with warm cinematic lighting. She walks confidently along the sidewalk, smiles at the camera, and poses naturally.

Scene 6: Finish with beautiful close-up fashion shots highlighting the fabric texture, floral patterns, handbag, and overall outfit.

Visual Style: Ultra-realistic fashion commercial, elegant modest fashion, warm natural lighting, soft cinematic color grading, smooth camera movements, realistic fabric physics, detailed textures, professional fashion photography, 4K quality.

Important: Maintain consistent facial features, hijab color, outfit design, and accessories throughout the video. Natural body movements, realistic proportions, no distorted hands or clothing.
Video GenerationCinematicEcommerce+2
F@f
0
Node.js Backend Service taste
Taste

Opinionated Node.js and TypeScript service conventions for small, observable APIs that start fast and shut down cleanly.

# Node.js Backend Service taste of a TypeScript engineer who wants small, predictable services
- Write services in TypeScript with `strict: true` and native ES modules. Confidence: 0.90
- Pin the Node.js version to an active LTS release in `.nvmrc`, `engines` and the Docker base image. Confidence: 0.90
- Use Fastify or Hono for HTTP, with request and response schemas that also generate the OpenAPI document. Confidence: 0.75
- Validate every incoming body, query and header at the edge and work only with typed data inside. Confidence: 0.95
- Load configuration once at startup from environment variables, validate it with a schema and fail fast if anything is missing. Confidence: 0.90
- Keep handlers thin: they parse input, call a service function and map the result to a response. Confidence: 0.85
- Never block the event loop; move CPU-heavy work to worker threads or a separate job queue. Confidence: 0.90
- Use `async`/`await` everywhere and treat any floating promise as a lint error. Confidence: 0.90
- Log structured JSON with pino, include a request ID on every line and never log secrets or tokens. Confidence: 0.90
- Return errors in one consistent JSON shape with a stable error code, and map unknown errors to 500 without leaking stack traces. Confidence: 0.85
- Handle `SIGTERM` by closing the server, draining in-flight requests and closing database pools before exit. Confidence: 0.90
- Crash on `unhandledRejection` and `uncaughtException` after logging, and let the orchestrator restart the process. Confidence: 0.80
- Expose separate liveness and readiness endpoints; readiness checks real dependencies. Confidence: 0.85
- Set timeouts on every outgoing HTTP and database call, and use `AbortSignal` to cancel them. Confidence: 0.85
- Use a connection pool with a fixed maximum size for the database, tuned to the number of instances. Confidence: 0.80
- Prefer the built-in `fetch`, `node:test` and `node:crypto` before adding a dependency. Confidence: 0.70
- Test HTTP routes with in-process injection instead of starting a real port. Confidence: 0.75
- Add OpenTelemetry tracing early so slow requests can be followed across services. Confidence: 0.75
- Build a small production image with a multi-stage Dockerfile and run it as a non-root user. Confidence: 0.85
- Keep `package-lock.json` committed and install with `npm ci` in CI and Docker builds. Confidence: 0.90
Best PracticesAPIBackend+2
F@f
0
Folk Reverse Glass Painting of Sunflowers in a Cobalt Jug on Gold Leaf
Image
Folk Reverse Glass Painting of Sunflowers in a Cobalt Jug on Gold Leaf

A naive Hinterglasmalerei reverse glass painting: nine chrome-yellow sunflowers in a cobalt-blue jug painted with white daisies, bold black outlines and flat colors behind glossy old glass, a crinkled gold-leaf background, a red-and-white dot border and a dark wooden frame.

A folk-art reverse glass painting (Hinterglasmalerei) of a bouquet of sunflowers in a cobalt-blue jug, painted on the back of an old glass pane and seen from the front, so the colors sit behind a glossy glass surface. Vertical 3:4 composition.

Subject: nine sunflowers with bright chrome-yellow petals and dark brown, finely dotted centers, a few buds and broad green leaves with crisp darker veins, arranged in a round-bellied cobalt-blue jug with white painted daisies around its belly. The jug stands on a simple brick-red tabletop band at the bottom of the picture.

Technique: bold black outlines painted first, then flat opaque layers of color with no blending, the typical naive folk style of reverse glass painting; the background is a sheet of gilded gold-leaf foil behind the glass, crinkled and shimmering, with a few visible seams. A painted border of small red and white dots runs around the edge, framed by a narrow dark wooden frame.

Surface: slight reflections and soft glare on the glass, tiny bubbles and a hairline scratch in the old pane, a little paint flaking at one corner that reveals the gold behind.

Lighting: soft daylight from the upper left, warm glow on the gold, rich saturated colors. No people, no text.
DesignCreativeVintage+2
F@f
0
Gyotaku Ink Fish Print of a Red Sea Bream and Two Mackerel on Washi Paper
Image
Gyotaku Ink Fish Print of a Red Sea Bream and Two Mackerel on Washi Paper

A traditional Japanese gyotaku fish rubbing in sumi ink on fibrous handmade washi: a large red sea bream with a faded vermilion wash above two mackerel, every scale and fin ray pressed in, hand-painted eyes, abstract brush marks and a red seal stamp.

A traditional Japanese gyotaku fish print, made by inking real fish and pressing thin washi paper onto them, photographed flat as a finished artwork. Horizontal 4:3 composition on a sheet of warm off-white handmade washi with visible long kozo fibers, soft deckled edges and a faint crease.

Subject: one red sea bream (madai) printed large across the center, facing left, with two smaller mackerel side by side below it, also facing left. The prints are in deep sumi black ink with the true gyotaku texture: every scale pressed as a fine crescent pattern, fin rays as delicate radiating lines, the gill plate and lateral line clearly embossed, slightly uneven ink density where the paper touched the body more or less firmly, a few dry-brush gaps and soft halos at the edges. The sea bream carries a soft vermilion-red wash over its whole body, fading paler toward the belly; each fish has a small hand-painted eye added with a fine brush, as in classic gyotaku.

Details: a vertical column of brushed Japanese-style calligraphy marks at the right edge is abstract and illegible, with one small red square seal stamp beneath it. Light ink speckles near the fins.

Lighting: even, soft, flat museum reproduction light, true colors, high detail, the paper texture visible across the whole sheet. No frame, no table, no hands, no readable text.
VisualCreativeVintage+2
F@f
0
Churned Customer Win-Back Plan (JSON)
Text

Turn your cancelled-customer export into a JSON win-back plan for a subscription business: reasons grouped with quotes, segments scored for win-back potential, honest offers within budget, up to 3 consent-aware messages per segment, payment recovery, a holdout test and product fixes.

1{
2 "role": "You are a retention and win-back strategist for small subscription businesses (SaaS, apps, memberships, subscription boxes). You help founders understand why customers cancelled and build an honest, low-pressure win-back plan that targets the customers most likely to return.",
3 "task": "Using the business details and the cancelled-customer data I provide, produce a win-back plan as a single valid JSON object that follows the output_schema exactly.",
4 "inputs_i_will_provide": {
5 "business": "What we sell, pricing and plans, billing cycle, typical customer type, and current monthly churn if known.",
6 "cancellations": "A list or export of cancelled customers: plan, monthly value, tenure, cancel date, stated cancellation reason (free text or a picked option), usage before cancelling, and any support tickets.",
7 "changes_since": "Product changes, fixes, new features, or pricing changes shipped since these customers left.",
8 "constraints": "Budget for discounts or credits, team time available, channels we can use (email, in-app, phone), and anything we must never offer.",
9 "goal": "What success looks like, for example: reactivate 5% of last quarter's cancellations within 60 days."
10 },
...+125 more lines
JSONSaaSSubscription+4
F@f
0
SaaS MRR and Churn Metrics Calculator
Skill

Turns a subscription events CSV into a monthly MRR bridge (new, expansion, contraction, churn, reactivation) with logo churn, GRR, NRR, ARPA, quick ratio and cohort retention. Normalizes annual and quarterly billing to MRR and flags data errors, shrinking months, high churn and customer concentration. Offline stdlib Python calculator.

---
name: saas-mrr-and-churn-metrics-calculator
description: Turns a subscription events CSV into a monthly MRR bridge (new, expansion, contraction, churn, reactivation) with logo churn, GRR, NRR, ARPA, quick ratio and cohort retention. Normalizes annual and quarterly billing to MRR and flags data errors (annual typed as monthly, mislabeled upgrades, churn of unknown customers), shrinking months, high churn and customer concentration. Offline stdlib Python calculator.
---

# SaaS MRR and Churn Metrics Calculator

You help founders, finance leads and product managers of subscription businesses get honest recurring-revenue numbers. Spreadsheet MRR usually goes wrong in the same places: an annual contract typed in as a monthly price inflates MRR twelvefold, downgrades get logged as upgrades, churn is counted on customers who already left, and one big account hides the fact that everyone else is leaving. You take a plain events export, rebuild MRR month by month so every movement is explained, and say what the numbers mean for the business.

You do not connect to billing systems, change data or give investment or accounting advice. Work only from the CSV the user provides, show every assumption, and remind them that MRR is a management metric, not recognized revenue.

## Files in this skill

- `scripts/mrr_metrics.py` - reads the events CSV and prints the MRR bridge, retention, cohorts, top customers and findings SM01-SM10; `--from/--to` to pick the reporting window, `--json` for further analysis, `--self-test` runs 17 checks (Python 3.8+ standard library only)
- `references/metric-definitions.md` - exact formulas for every metric and how the script classifies each event
- `references/data-prep-and-pitfalls.md` - how to export events from common billing tools, what counts as MRR, and the classic mistakes
- `templates/metrics-report.md` - the monthly metrics report you hand back
- `examples/subscription_events.csv` - ten months of events for a fictional scheduling SaaS with planted errors

## Workflow

### 1. Get the events
Ask for one row per subscription change: `date` (YYYY-MM-DD), `customer`, `event` (`new`, `upgrade`, `downgrade`, `price_change`, `churn`, `reactivate`), `amount` (the recurring price after the change, per billing period, excluding tax and one-off fees), `billing` (`monthly`, `quarterly`, `annual`) and optional `plan`. Use one currency (convert first). See `references/data-prep-and-pitfalls.md` for exports from Stripe, Paddle, Chargebee or a spreadsheet.

### 2. Run the calculator
```
python3 scripts/mrr_metrics.py examples/subscription_events.csv
python3 scripts/mrr_metrics.py events.csv --from 2026-07 --to 2026-10
python3 scripts/mrr_metrics.py events.csv --json --top-share 0.15 --churn-alert 0.03
python3 scripts/mrr_metrics.py --self-test
```
Pass `--from` to get period retention (NRR and logo retention of the customers active just before the window). Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, build the bridge by hand with `references/metric-definitions.md`; it is just bookkeeping per customer.

### 3. Fix the data, then read the metrics
- Data findings first: SM01 unreadable row, SM02 event that doesn't fit the customer's state (churn of an unknown customer, `new` for an active one), SM03 zero-MRR new customer (free or trial), SM04 monthly amount 8x or more the median (an annual price typed as monthly?), SM05 `upgrade` that lowers MRR or `downgrade` that raises it, SM08 negative amount. Correct the CSV and re-run before drawing conclusions.
- Business findings: SM07 quick ratio below 1 (the business shrank that month, high), SM06 monthly logo churn above the alert level, SM09 period NRR below 100%, SM10 one customer above the concentration threshold.

### 4. Deliver
Fill `templates/metrics-report.md`: headline MRR and growth, the bridge table, retention and cohorts, what changed and why, data fixes made, and three concrete actions (for example: call the customers who downgraded, fix onboarding for the cohort that churns in month 2, diversify away from the largest account). Keep the language plain; define GRR and NRR once.

## Example result
On the sample file, ending MRR in October shows 6,435.40 across 14 paying customers, but 4,788 of it is A09, whose annual Business contract was typed as monthly (SM04); with `billing=annual` it is 399 MRR and the business is about a third of the size it appears. The data also has an "upgrade" from 399 to 149 (SM05), a churn row for unknown customer A99 and a `new` row for already-active A01 (SM02). Business signals: May, June and August lost more MRR than they gained (quick ratio 0.16, 0.75, 0.43), logo churn hit 22% in May and 25% in August, and July to October NRR is 92%. Result: 3 high, 8 medium, 1 low.

## Rules

- Never mix one-off charges, setup fees, usage overages or taxes into MRR unless the user explicitly defines MRR that way; say which definition you used.
- Divide annual and quarterly prices by 12 and 3; do not book the whole contract in the signing month.
- Fix data findings before interpreting trends, and state every correction you made.
- Small numbers lie: with fewer than ~20 customers, one churn moves rates a lot; say so instead of over-reading percentages.
- These are management metrics, not GAAP/IFRS revenue; refer accounting questions to an accountant.

FILE:references/metric-definitions.md
# Metric definitions (as implemented in mrr_metrics.py)

## Normalizing to MRR
`MRR = amount / months in billing period` (monthly 1, quarterly 3, annual 12). The amount is the recurring price after the change, net of recurring discounts, without tax or one-off fees.

## Classifying each event per customer
| Event | Condition | Bridge bucket |
|---|---|---|
| `new` | customer never paid before | New MRR (+ new customer) |
| `new` | customer already active | treated as price change, flagged SM02 |
| `new` / `reactivate` | customer paid before, now at 0 | Reactivation MRR |
| `upgrade` / `downgrade` / `price_change` | active customer | Expansion if MRR rises, Contraction if it falls (label mismatch flagged SM05) |
| change to 0 | active customer | counted as Churn, flagged SM05 |
| `churn` | active customer | Churn MRR = the customer's MRR before churning (+ churned customer) |
| any change / churn | no active subscription | ignored, flagged SM02 |

Bridge identity (checked every month): `start MRR + new + expansion + reactivation - contraction - churn = end MRR`.

## Monthly metrics
- **Net new MRR** = end MRR - start MRR
- **Logo churn rate** = churned customers / paying customers at start of month
- **MRR churn rate (gross)** = (churn + contraction) / start MRR
- **GRR (gross revenue retention)** = (start MRR - churn - contraction) / start MRR, never above 100%
- **NRR (net revenue retention)** = (start MRR - churn - contraction + expansion) / start MRR; reactivation and new are excluded
- **Quick ratio** = (new + expansion + reactivation) / (churn + contraction); above 4 is excellent, 1-2 means growth is fragile, below 1 means shrinking
- **ARPA** = end MRR / paying customers at end of month

## Period and cohort metrics
- **Period NRR** (`--from`): customers paying at the end of the month before the window; their MRR at the end of the window divided by their MRR at the start. New customers acquired in the window are excluded.
- **Logo retention**: share of that base still paying at the end of the window.
- **Cohort retention**: customers grouped by the month of their first paid event; share still paying after 1, 3, 6 and 12 months (reactivated customers count as paying again).
- **Concentration**: largest customer's share of current MRR (default alert above 20%).

## Rules of thumb (context, not targets)
Monthly logo churn for SMB SaaS is often 3-7%, for mid-market 1-2%; annual NRR above 100% means expansion outruns churn. Compare with your own history before comparing with benchmarks.

FILE:references/data-prep-and-pitfalls.md
# Data preparation and pitfalls

## Getting an events file
- **Stripe**: export subscriptions and subscription item changes (or invoice line items for `subscription` items); one row per change with the new recurring price. Use `plan.interval` (month/year) and `interval_count` for `billing`.
- **Paddle / Chargebee / Recurly**: subscription activity or "subscription changes" export; map created -> `new`, plan change -> `upgrade`/`downgrade`, cancelled (effective date, not request date) -> `churn`, reactivated -> `reactivate`.
- **Spreadsheet**: if you only have a monthly list of customers and prices, generate events by comparing each month to the previous one (appeared = new, price up = upgrade, price down = downgrade, disappeared = churn).

## What counts as MRR
- Include: recurring subscription fees after recurring discounts, per-seat fees at the current seat count, committed minimums.
- Exclude: setup and onboarding fees, one-off services, usage overages (track separately or average them explicitly), taxes, refunds and credits, free and trial plans.
- Paused subscriptions: treat as churn when paused and reactivation when resumed, or exclude consistently; say which.
- Use the **effective** date of a cancellation (end of paid period), not the date the customer clicked cancel; otherwise churn shows up a month early.

## Classic mistakes the script catches
1. Annual price typed as monthly (SM04): MRR jumps by the full contract value. Set `billing=annual`.
2. Wrong event labels (SM05): an "upgrade" to a cheaper plan. The script trusts the amounts, not the label, and flags the row.
3. Churn or changes for customers who are not active (SM02): usually duplicate exports or wrong customer ids.
4. Duplicate `new` rows for an active customer (SM02): often a plan change exported as a new subscription.
5. Negative amounts (SM08): refunds or credit notes in the subscription export. Remove them.

## Mistakes the script cannot catch
- Mixed currencies in one file (convert to one currency at a fixed rate first).
- Customer ids that change after a migration (merge them first, or churn + new will be overstated).
- Multiple subscriptions per customer: either sum them per customer before export, or use `customer-subscription` as the id and say that logo metrics count subscriptions.

FILE:templates/metrics-report.md
# Subscription metrics report: [Company], [reporting window]

**Ending MRR:** [x] ([+/- y%] vs previous month, [+/- z%] vs start of window)  **ARR run-rate:** [MRR x 12]
**Paying customers:** [n]  **ARPA:** [x]
**Data status:** [clean / corrected: list of fixes]  (`mrr_metrics.py` output attached)

## MRR bridge
| Month | Start | New | Expansion | Contraction | Churn | Reactivation | End | Logo churn | NRR | Quick ratio |
|---|---|---|---|---|---|---|---|---|---|---|
| [YYYY-MM] | | | | | | | | | | |

## Retention
- Period NRR [x%], GRR trend [..], logo retention [x%] of the [n] customers active on [date]
- Cohorts: [which cohorts hold up, where the drop happens (month 1? month 3?)]

## What changed and why
1. [Biggest movement and its drivers, with customer names if useful]
2. [...]

## Risks
- Concentration: [largest customer share]
- [Churn spike / shrinking months / small-sample caveat]

## Data corrections made
| Row | Problem | Fix |
|---|---|---|
| [line 12, A09] | [annual typed as monthly] | [billing=annual] |

## Recommended actions (next 30 days)
1. [...]
2. [...]
3. [...]

_MRR here is a management metric (recurring subscription value), not recognized revenue._

FILE:examples/subscription_events.csv
date,customer,event,amount,billing,plan
2026-01-06,A01,new,49,monthly,Starter
2026-01-12,A02,new,149,monthly,Team
2026-01-19,A03,new,1430.40,annual,Team
2026-01-27,A04,new,49,monthly,Starter
2026-02-03,A05,new,149,monthly,Team
2026-02-11,A06,new,49,monthly,Starter
2026-02-20,A01,upgrade,149,monthly,Team
2026-03-02,A07,new,399,monthly,Business
2026-03-16,A08,new,49,monthly,Starter
2026-03-30,A04,churn,0,monthly,Starter
2026-04-07,A09,new,4788,monthly,Business
2026-04-15,A10,new,149,monthly,Team
2026-04-22,A06,upgrade,149,monthly,Team
2026-05-05,A11,new,49,monthly,Starter
2026-05-13,A02,downgrade,49,monthly,Starter
2026-05-21,A05,churn,0,monthly,Team
2026-05-28,A08,churn,0,monthly,Starter
2026-06-04,A12,new,149,monthly,Team
2026-06-10,A13,new,470.40,annual,Starter
2026-06-24,A07,upgrade,149,monthly,Team
2026-07-01,A14,new,49,monthly,Starter
2026-07-09,A04,reactivate,149,monthly,Team
2026-07-15,A15,new,0,monthly,Free
2026-07-23,A99,churn,0,monthly,Team
2026-08-04,A16,new,149,monthly,Team
2026-08-12,A10,churn,0,monthly,Team
2026-08-19,A11,churn,0,monthly,Starter
2026-08-26,A12,churn,0,monthly,Team
2026-09-02,A17,new,399,monthly,Business
2026-09-09,A18,new,49,monthly,Starter
2026-09-17,A14,upgrade,149,monthly,Team
2026-10-06,A19,new,149,monthly,Team
2026-10-14,A20,new,49,monthly,Starter
2026-10-20,A06,downgrade,49,monthly,Starter
2026-10-27,A01,new,149,monthly,Team

FILE:scripts/mrr_metrics.py
#!/usr/bin/env python3
"""SaaS MRR and churn metrics calculator (offline, Python 3.8+ standard library only).

Reads a subscription events CSV (date, customer, event, amount, billing, plan), normalizes
annual and quarterly amounts to MRR, builds a month-by-month MRR bridge (new, expansion,
contraction, churn, reactivation), computes logo churn, GRR, NRR, ARPA and quick ratio, and
flags data problems and business warning signs.

Usage:
  mrr_metrics.py events.csv [--from 2026-01] [--to 2026-10] [--json] [--top-share 0.2]
  mrr_metrics.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, csv, json, statistics, sys
from collections import Counter, OrderedDict
from datetime import date

EVENTS = {"new", "upgrade", "downgrade", "churn", "reactivate", "price_change"}
BILLING_MONTHS = {"monthly": 1, "quarterly": 3, "annual": 12, "yearly": 12}
SEV = {"high": 0, "medium": 1, "low": 2}


def month_key(s):
    y, m = int(s[:4]), int(s[5:7])
    if not (1 <= m <= 12):
        raise ValueError("bad month in %r" % s)
    return "%04d-%02d" % (y, m)


def next_month(k):
    y, m = int(k[:4]), int(k[5:7])
    return "%04d-%02d" % (y + (m == 12), 1 if m == 12 else m + 1)


def month_range(a, b):
    out = [a]
    while out[-1] < b:
        out.append(next_month(out[-1]))
    return out


def load(path):
    with open(path, newline="", encoding="utf-8-sig") as fh:
        rows = list(csv.DictReader(fh))
    need = {"date", "customer", "event", "amount"}
    if not rows or not need <= set(k.strip() for k in rows[0].keys()):
        raise ValueError("CSV needs columns: date, customer, event, amount (optional: billing, plan)")
    return [{k.strip(): (v or "").strip() for k, v in r.items()} for r in rows]


def compute(rows, start=None, end=None, top_share=0.2, churn_alert=0.05):
    findings = []
    def add(code, sev, msg, month=None, customer=None):
        findings.append({"code": code, "severity": sev, "month": month, "customer": customer, "message": msg})
    events = []
    for i, r in enumerate(rows, start=2):
        try:
            d = date.fromisoformat(r["date"][:10])
        except ValueError:
            add("SM01", "high", "line %d: bad date %r" % (i, r["date"])); continue
        ev = r["event"].lower()
        if ev not in EVENTS:
            add("SM01", "high", "line %d: unknown event %r (use %s)" % (i, r["event"], ", ".join(sorted(EVENTS)))); continue
        billing = (r.get("billing") or "monthly").lower()
        if billing not in BILLING_MONTHS:
            add("SM01", "high", "line %d: unknown billing %r" % (i, billing)); continue
        try:
            amount = float(r["amount"] or 0)
        except ValueError:
            add("SM01", "high", "line %d: amount %r is not a number" % (i, r["amount"])); continue
        if amount < 0:
            add("SM08", "high", "line %d: negative amount %.2f (refunds and credits are not MRR)" % (i, amount), customer=r["customer"]); continue
        events.append({"line": i, "date": d, "month": d.strftime("%Y-%m"), "customer": r["customer"], "event": ev,
                       "mrr": round(amount / BILLING_MONTHS[billing], 2), "billing": billing, "amount": amount, "plan": r.get("plan", "")})
    if not events:
        raise ValueError("no usable events")
    events.sort(key=lambda e: (e["date"], e["line"]))
    # SM04: monthly-billed amounts that look like annual totals typed as monthly
    monthly_amounts = [e["mrr"] for e in events if e["billing"] == "monthly" and e["mrr"] > 0]
    med = statistics.median(monthly_amounts) if monthly_amounts else 0
    for e in events:
        if med and e["billing"] == "monthly" and e["mrr"] >= 8 * med and e["mrr"] > 0:
            add("SM04", "medium", "line %d: monthly amount %.2f is %.0fx the median monthly price: an annual contract entered as monthly? (set billing=annual)" % (e["line"], e["mrr"], e["mrr"] / med), e["month"], e["customer"])
    first = start or events[0]["month"]
    last = end or events[-1]["month"]
    months = month_range(min(first, events[0]["month"]), last)
    state = {}            # customer -> current MRR (0 = churned)
    ever = set()
    bridge = OrderedDict()
    by_month = {}
    for e in events:
        by_month.setdefault(e["month"], []).append(e)
    cohort_start = {}
    active_by_month = {}
    snaps = {}
    for m in months:
        start_mrr = round(sum(state.values()), 2)
        start_logos = sum(1 for v in state.values() if v > 0)
        b = {"month": m, "start_mrr": start_mrr, "new": 0.0, "expansion": 0.0, "contraction": 0.0, "churn": 0.0, "reactivation": 0.0,
             "start_customers": start_logos, "new_customers": 0, "churned_customers": 0, "reactivated_customers": 0}
        for e in by_month.get(m, []):
            c, ev, new = e["customer"], e["event"], e["mrr"]
            cur = state.get(c)
            if ev == "new":
                if cur is not None and cur > 0:
                    add("SM02", "medium", "line %d: 'new' for a customer who is already active (%.2f MRR); treated as a price change" % (e["line"], cur), m, c)
                    ev = "price_change"
                elif cur is not None and cur == 0 and c in ever:
                    add("SM02", "low", "line %d: 'new' for a returning customer; counted as reactivation" % e["line"], m, c)
                    ev = "reactivate"
            if ev == "new":
                state[c] = new; b["new"] += new
                if new == 0:
                    add("SM03", "low", "line %d: new customer with 0 MRR (free plan or trial?) not counted in paid metrics" % e["line"], m, c)
                else:
                    b["new_customers"] += 1; cohort_start[c] = m; ever.add(c)
            elif ev == "churn":
                if not cur:
                    add("SM02", "medium", "line %d: churn for a customer who is not active; ignored" % e["line"], m, c); continue
                b["churn"] += cur; b["churned_customers"] += 1; state[c] = 0.0
            elif ev == "reactivate":
                if cur:
                    add("SM02", "medium", "line %d: reactivate for an active customer; treated as a price change" % e["line"], m, c)
                    ev = "price_change"
                else:
                    if c not in ever:
                        add("SM02", "low", "line %d: reactivate for an unknown customer; counted as new" % e["line"], m, c)
                        b["new"] += new; b["new_customers"] += 1; ever.add(c); cohort_start[c] = m
                    else:
                        b["reactivation"] += new; b["reactivated_customers"] += 1
                    state[c] = new
            if ev in ("upgrade", "downgrade", "price_change"):
                if cur is None or cur == 0:
                    add("SM02", "medium", "line %d: %s for a customer with no active subscription; ignored" % (e["line"], e["event"]), m, c); continue
                delta = round(new - cur, 2)
                if e["event"] == "upgrade" and delta < 0:
                    add("SM05", "medium", "line %d: 'upgrade' lowers MRR %.2f -> %.2f; check the event type" % (e["line"], cur, new), m, c)
                if e["event"] == "downgrade" and delta > 0:
                    add("SM05", "medium", "line %d: 'downgrade' raises MRR %.2f -> %.2f; check the event type" % (e["line"], cur, new), m, c)
                if new == 0:
                    add("SM05", "medium", "line %d: change to 0 MRR; record it as churn instead" % e["line"], m, c)
                    b["churn"] += cur; b["churned_customers"] += 1; state[c] = 0.0; continue
                if delta > 0: b["expansion"] += delta
                else: b["contraction"] += -delta
                state[c] = new
        end_mrr = round(sum(state.values()), 2)
        for k in ("new", "expansion", "contraction", "churn", "reactivation"):
            b[k] = round(b[k], 2)
        b["end_mrr"] = end_mrr
        b["net_new_mrr"] = round(end_mrr - start_mrr, 2)
        b["end_customers"] = sum(1 for v in state.values() if v > 0)
        b["arpa"] = round(end_mrr / b["end_customers"], 2) if b["end_customers"] else 0.0
        if start_mrr:
            b["grr"] = round((start_mrr - b["churn"] - b["contraction"]) / start_mrr, 4)
            b["nrr"] = round((start_mrr - b["churn"] - b["contraction"] + b["expansion"]) / start_mrr, 4)
            b["mrr_churn_rate"] = round((b["churn"] + b["contraction"]) / start_mrr, 4)
        else:
            b["grr"] = b["nrr"] = b["mrr_churn_rate"] = None
        b["logo_churn_rate"] = round(b["churned_customers"] / start_logos, 4) if start_logos else None
        lost = b["churn"] + b["contraction"]
        b["quick_ratio"] = round((b["new"] + b["expansion"] + b["reactivation"]) / lost, 2) if lost else None
        assert abs(start_mrr + b["new"] + b["expansion"] + b["reactivation"] - b["contraction"] - b["churn"] - end_mrr) < 0.05, m
        active_by_month[m] = {c for c, v in state.items() if v > 0}
        snaps[m] = dict(state)
        bridge[m] = b
    report_months = [m for m in months if m >= first]
    rows_out = [bridge[m] for m in report_months]
    for b in rows_out:
        m = b["month"]
        if b["logo_churn_rate"] is not None and b["logo_churn_rate"] > churn_alert and b["start_customers"] >= 5:
            add("SM06", "medium", "logo churn %.1f%% in %s (alert above %.1f%%)" % (100 * b["logo_churn_rate"], m, 100 * churn_alert), m)
        if b["quick_ratio"] is not None and b["quick_ratio"] < 1:
            add("SM07", "high", "quick ratio %.2f in %s: lost MRR exceeded gained MRR (shrinking)" % (b["quick_ratio"], m), m)
    # trailing NRR over the reported period (cohort of customers active at period start)
    base_month = report_months[0]
    prev = None
    for m in months:
        if m == base_month: break
        prev = m
    period = {}
    if prev and snaps[prev]:
        base = {c: v for c, v in snaps[prev].items() if v > 0}
        now = snaps[report_months[-1]]
        start_sum = sum(base.values()); end_sum = sum(now.get(c, 0) for c in base)
        kept = sum(1 for c in base if now.get(c, 0) > 0)
        period = {"base_month": prev, "base_customers": len(base), "base_mrr": round(start_sum, 2),
                  "same_customers_mrr_now": round(end_sum, 2), "period_nrr": round(end_sum / start_sum, 4) if start_sum else None,
                  "logo_retention": round(kept / len(base), 4) if base else None}
        if period["period_nrr"] is not None and period["period_nrr"] < 1:
            add("SM09", "medium", "net revenue retention over %s..%s is %.1f%% (<100%%): existing customers shrink" % (report_months[0], report_months[-1], 100 * period["period_nrr"]))
    final = {c: v for c, v in state.items() if v > 0}
    total = sum(final.values())
    if total:
        top = sorted(final.items(), key=lambda x: -x[1])[:3]
        if top[0][1] / total > top_share:
            add("SM10", "medium", "largest customer %s is %.0f%% of MRR (threshold %.0f%%): concentration risk" % (top[0][0], 100 * top[0][1] / total, 100 * top_share), customer=top[0][0])
    # cohorts: logo retention by start month
    cohorts = OrderedDict()
    for c, m in sorted(cohort_start.items(), key=lambda x: x[1]):
        cohorts.setdefault(m, []).append(c)
    cohort_table = []
    for m, cs in cohorts.items():
        row = {"cohort": m, "customers": len(cs)}
        k = m
        for i in range(0, 13):
            if k > last: break
            if i in (1, 3, 6, 12):
                row["m%d" % i] = round(sum(1 for c in cs if c in active_by_month[k]) / len(cs), 2)
            k = next_month(k)
        cohort_table.append(row)
    findings.sort(key=lambda f: (SEV[f["severity"]], f["code"], f["month"] or ""))
    s = Counter(f["severity"] for f in findings)
    return {"months": rows_out, "period": period, "cohorts": cohort_table,
            "top_customers": [{"customer": c, "mrr": v, "share": round(v / total, 3)} for c, v in sorted(final.items(), key=lambda x: -x[1])[:5]] if total else [],
            "findings": findings, "summary": {k: s.get(k, 0) for k in ("high", "medium", "low")}}


def pct(x):
    return "   -  " if x is None else "%5.1f%%" % (100 * x)


def print_text(rep):
    print("MRR bridge")
    print("month    start_mrr      new  expans  contr    churn  react   end_mrr  cust  logo_ch   GRR     NRR    QR    ARPA")
    for b in rep["months"]:
        print("%s %10.2f %8.2f %7.2f %6.2f %8.2f %6.2f %9.2f %5d %s %s %s %5s %7.2f" % (
            b["month"], b["start_mrr"], b["new"], b["expansion"], b["contraction"], b["churn"], b["reactivation"],
            b["end_mrr"], b["end_customers"], pct(b["logo_churn_rate"]), pct(b["grr"]), pct(b["nrr"]),
            "-" if b["quick_ratio"] is None else "%.2f" % b["quick_ratio"], b["arpa"]))
    p = rep["period"]
    if p:
        print("\nPeriod retention (customers active at end of %s: %d, %.2f MRR): NRR %s, logo retention %s" % (
            p["base_month"], p["base_customers"], p["base_mrr"], pct(p["period_nrr"]), pct(p["logo_retention"])))
    if rep["cohorts"]:
        print("\nCohort logo retention (share still paying after N months)")
        for c in rep["cohorts"]:
            print("  %s  n=%-3d m1=%s m3=%s m6=%s" % (c["cohort"], c["customers"], c.get("m1", "-"), c.get("m3", "-"), c.get("m6", "-")))
    print("\nTop customers: " + ", ".join("%s %.2f (%.0f%%)" % (t["customer"], t["mrr"], 100 * t["share"]) for t in rep["top_customers"]))
    print("\nFindings: %(high)d high, %(medium)d medium, %(low)d low" % rep["summary"])
    for f in rep["findings"]:
        print("  [%s] %s %s%s: %s" % (f["severity"].upper(), f["code"], f["month"] or "", (" " + f["customer"]) if f["customer"] else "", f["message"]))


def self_test():
    ok = total = 0
    def t(name, cond):
        nonlocal ok, total
        total += 1; ok += bool(cond)
        print(("PASS  " if cond else "FAIL  ") + name)
    def R(*lines):
        return [dict(zip(["date", "customer", "event", "amount", "billing"], l.split(","))) for l in lines]
    r = compute(R("2026-01-05,a,new,100,monthly", "2026-01-09,b,new,1200,annual", "2026-02-03,a,upgrade,150,monthly",
                  "2026-02-10,b,churn,0,annual", "2026-03-01,b,reactivate,50,monthly", "2026-03-15,c,new,200,monthly"))
    m = {b["month"]: b for b in r["months"]}
    t("annual normalized to MRR", m["2026-01"]["end_mrr"] == 200)
    t("expansion counted", m["2026-02"]["expansion"] == 50)
    t("churn counted at prior MRR", m["2026-02"]["churn"] == 100 and m["2026-02"]["churned_customers"] == 1)
    t("reactivation separate from new", m["2026-03"]["reactivation"] == 50 and m["2026-03"]["new"] == 200)
    t("bridge closes", all(abs(b["start_mrr"] + b["new"] + b["expansion"] + b["reactivation"] - b["contraction"] - b["churn"] - b["end_mrr"]) < 0.01 for b in r["months"]))
    t("NRR feb = (200-100+50)/200", m["2026-02"]["nrr"] == 0.75 and m["2026-02"]["grr"] == 0.5)
    t("SM07 quick ratio < 1 in feb", any(f["code"] == "SM07" and f["month"] == "2026-02" for f in r["findings"]))
    r = compute(R("2026-01-01,a,new,50,monthly", "2026-01-01,b,new,50,monthly", "2026-01-01,c,new,55,monthly", "2026-01-02,d,new,1200,monthly"))
    t("SM04 annual typed as monthly", any(f["code"] == "SM04" and f["customer"] == "d" for f in r["findings"]))
    t("SM10 concentration", any(f["code"] == "SM10" for f in r["findings"]))
    r = compute(R("2026-01-01,a,new,50,monthly", "2026-02-01,a,upgrade,40,monthly", "2026-02-02,z,churn,0,monthly", "2026-02-03,a,new,60,monthly"))
    codes = Counter(f["code"] for f in r["findings"])
    t("SM05 upgrade lowering MRR", codes["SM05"] == 1)
    t("SM02 churn of unknown + new for active", codes["SM02"] == 2)
    t("contraction from mislabeled upgrade", r["months"][1]["contraction"] == 10 and r["months"][1]["expansion"] == 20)
    rows = R(*["2026-01-0%d,c%d,new,100,monthly" % (1 + i % 9, i) for i in range(20)] + ["2026-02-05,c%d,churn,0,monthly" % i for i in range(3)])
    r = compute(rows)
    t("SM06 logo churn alert (15%)", any(f["code"] == "SM06" for f in r["findings"]) and r["months"][1]["logo_churn_rate"] == 0.15)
    r = compute(R("2026-01-01,a,new,100,monthly", "2026-01-01,b,new,100,monthly", "2026-02-01,a,downgrade,60,monthly", "2026-03-01,c,new,500,monthly"), start="2026-02")
    t("period NRR for base cohort excludes new logos", r["period"]["period_nrr"] == 0.8 and r["period"]["base_customers"] == 2)
    t("SM09 NRR < 100%", any(f["code"] == "SM09" for f in r["findings"]))
    r = compute(R("2026-01-01,f,new,0,monthly", "2026-02-01,f,new,49,monthly"))
    t("free-to-paid conversion counted as new", r["months"][1]["new"] == 49 and r["months"][1]["new_customers"] == 1 and r["months"][0]["new_customers"] == 0)
    try:
        compute(R("2026-13-01,a,new,1,monthly")); t("bad date reported", False)
    except ValueError:
        t("bad date -> no usable events error", True)
    print("%d/%d passed" % (ok, total))
    return 0 if ok == total else 1


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("file", nargs="?"); ap.add_argument("--from", dest="start"); ap.add_argument("--to", dest="end")
    ap.add_argument("--json", action="store_true"); ap.add_argument("--top-share", type=float, default=0.2)
    ap.add_argument("--churn-alert", type=float, default=0.05); ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.file:
        ap.print_help(); return 2
    try:
        rep = compute(load(a.file), a.start and month_key(a.start), a.end and month_key(a.end), a.top_share, a.churn_alert)
    except (OSError, ValueError) as e:
        print("bad input: %s" % e, file=sys.stderr); return 2
    if a.json:
        print(json.dumps(rep, indent=2))
    else:
        print_text(rep)
    return 1 if rep["summary"]["high"] else 0


if __name__ == "__main__":
    sys.exit(main())
SaaSRevenueData Analysis+3
F@f
0
Utility Meter Reading and Bill Checker
Skill

Checks electricity, gas and water meter readings for a home or small business: fixes typos, rollovers, over-estimates and duplicates, works out usage per period and month, prices it with your tariffs (standing charge, VAT, price changes, gas m3 to kWh), checks bills, flags leaks. Offline Python.

---
name: utility-meter-reading-and-bill-checker
description: Checks electricity, gas and water meter readings for a home or small business: fixes typos, rollovers, over-estimates and duplicates, works out usage per period and month, prices it with your tariffs (standing charge, VAT, price changes, gas m3 to kWh), checks bills, flags leaks. Offline Python.
---

# Utility Meter Reading and Bill Checker

You help households, landlords, flat-sharers and small shop or office owners understand their electricity, gas and water use and check that their bills match their meters. Bills go wrong in predictable ways: the supplier estimates a reading that is far too high, a price change is applied to the whole period, a reading is typed from memory with swapped digits, a five-digit meter wraps from 99999 to 00000, and a running toilet or dripping tap doubles the water use for months before anyone notices. You turn the user's own meter readings into clean usage figures, price them with their tariff and compare each bill with what the readings imply.

You work only from the readings, tariffs and bills the user gives you. You do not contact suppliers, log into accounts or give legal or financial advice. Show every assumption (meter digits, gas calorific value, which reading was dropped) and say when a figure is interpolated.

## Files in this skill

- `scripts/meter_check.py` - reads the readings CSV (plus optional tariffs and bills CSVs) and prints per-meter periods, monthly usage and cost, annual estimate, a bill check and findings UM01-UM11; `--digits meter=N` for rollover, `--spike`, `--tolerance`, `--calorific`, `--max-gap`, `--json`, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/reading-meters-and-units.md` - how to read common meters, units, rollover, estimated vs actual readings, gas m3 to kWh conversion
- `references/tariffs-and-bill-checks.md` - how to enter tariffs, how the bill check works, typical billing errors and what to ask the supplier
- `templates/usage-and-bill-report.md` - the report you hand back
- `examples/meter_readings.csv` - ten months of readings for a fictional flat with planted problems
- `examples/tariffs.csv` - electricity (with a July price rise), gas priced per kWh, water
- `examples/bills.csv` - five bills to check, one based on an over-estimate

## Workflow

### 1. Collect the readings
Ask for one row per reading: `date` (YYYY-MM-DD), `meter` (any name, e.g. `electricity`, `gas`, `water`, `ev-charger`), `reading` (the number on the display, without the red decimal digits on gas and water dials unless used consistently), optional `type` (`actual`, `customer`, `estimate`) and `note`. Readings from bills count: mark supplier estimates as `estimate`. Monthly readings on roughly the same day work best; photos of the meter are the best evidence. See `references/reading-meters-and-units.md`.

### 2. Collect tariffs and bills (optional but needed for costs)
- `tariffs.csv`: `meter,from,meter_unit,tariff_unit,unit_price,standing_per_day,vat_pct`, one row per price change. For gas measured in m3 but priced per kWh, set `meter_unit=m3`, `tariff_unit=kWh`.
- `bills.csv`: `meter,start,end,amount[,units]` with inclusive dates and the amount including tax.
- Ask how many digits the meter display has (before the decimal point) so rollovers are detected.

### 3. Run the checker
```
python3 scripts/meter_check.py examples/meter_readings.csv --tariffs examples/tariffs.csv --bills examples/bills.csv --digits electricity=5
python3 scripts/meter_check.py readings.csv --tariffs tariffs.csv --calorific 38.9 --json > usage.json
python3 scripts/meter_check.py readings.csv --spike 1.4 --tolerance 0.03
python3 scripts/meter_check.py --self-test
```
Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, follow the formulas in `references/tariffs-and-bill-checks.md`: usage = later reading - earlier reading, prorate by days, cost = (units x unit price + days x standing charge) x (1 + VAT).

### 4. Fix the data first
- UM01 unreadable row, UM02 reading lower than the previous one (typo or wrong meter, ignored), UM06 two different readings on the same day (actual beats customer beats estimate), UM09 rollover assumed (check the digit count), UM07 long gap between readings (monthly numbers are interpolated).
- UM03 an estimate that was higher than the next actual reading: the estimate is dropped and the bills based on it overcharged.
- Ask the user to confirm each correction, then re-run.

### 5. Read usage and bills
- UM04 a period whose daily use is well above the recent periods; UM05 high use for the last two periods in a row: on water this is the classic leak signal (running toilet, dripping tap, outdoor pipe), on electricity a new appliance, heater or faulty fridge.
- UM10 a bill more than the tolerance above (high) or below (medium, a catch-up bill will follow) what readings and tariff imply; compare billed units with reading units to see whether the price or the reading is wrong.
- UM08 a bill that ends on an estimated reading; UM11 a bill that cannot be checked (outside the readings or no tariff).
- Seasonal patterns are normal for gas heating: compare with the same months last year if the user has them.

### 6. Deliver
Fill `templates/usage-and-bill-report.md`: usage and cost per meter, the bill check table, data corrections, problems found, money at stake, and next steps (submit an actual reading and ask for a re-bill, do a leak test, check the tariff). Use the user's currency and units; round money to 2 decimals.

## Example result
On the example files the checker uses 8 of 10 electricity readings: the 89650 typed from memory is ignored (UM02, high) and the April supplier estimate of 98650 is dropped because the May actual was 98500 (UM03). The 00050 in October is read as a rollover of the 5-digit display (UM09). The March-April electricity bill charged 760 kWh, 237.62, but the readings imply 305 kWh, 103.85: an overcharge of 133.77 (UM10 high, UM08). The June-July bill correctly splits the 1 July price rise. Gas has two different readings on 4 July; the actual 5085.5 is kept (UM06). Water jumped from about 0.35 to 0.66-0.68 m3/day in the last two months (UM04 twice, UM05 high): a probable leak costing about 0.67 per day (0.32 m3 x 2.10). Result: 3 high, 5 medium, 1 low.

## Rules

- Never invent readings; interpolate only between real readings and say so.
- Prefer actual readings over estimates; recommend submitting a reading before every bill date.
- Explain rollover and digit assumptions before correcting usage by a power of ten.
- Gas conversion uses volume correction 1.02264 and the calorific value from the user's bill (default 39.5 MJ/m3); say which value you used.
- Do not tell the user to stop paying a bill; suggest disputing it with the supplier with the evidence.
- Leak suspicion is a prompt to test (meter reading before and after a no-use period), not a diagnosis.

FILE:references/reading-meters-and-units.md
# Reading meters and units

## Reading the display
- **Digital electricity meters**: press the display button until the cumulative import register appears (often labelled `1.8.0`, `IMP` or `kWh`). Ignore instantaneous kW values. Day/night (two-rate) meters have two registers: use two meter names, e.g. `electricity-day` and `electricity-night`.
- **Smart meters**: readings are sent automatically, but bills can still be estimated when the communication fails; check the bill says "actual" or "smart".
- **Gas meters**: read the black digits from left to right; ignore the red digits after the decimal point (or include them every time, consistently). Older imperial meters show hundreds of cubic feet; multiply by 2.83 to get m3.
- **Water meters**: black digits are m3; red dials are litres. A slowly turning star or triangle with every tap closed is a leak indicator.
- **Dial meters**: read each dial; if a pointer is between two numbers, take the lower one.

## Digits and rollover
A meter with 5 digits before the decimal point goes from 99999 to 00000. If a reading is much lower than the previous one and the previous one was close to the maximum, it is a rollover, not a typo. Pass `--digits meter=5`. Without `--digits`, any backwards reading is treated as an error (UM02).

## Reading types
- `actual`: read by the supplier or a smart meter.
- `customer`: read and submitted by you (as good as actual if it comes with a photo).
- `estimate`: calculated by the supplier. Estimates are often based on last winter or on a national average and can be far off. When a later actual reading is lower, the estimate was too high and every bill since overcharged you (UM03).

## Units
| Meter | Display unit | Usually priced in |
|---|---|---|
| Electricity | kWh | kWh |
| Gas | m3 (or 100 ft3) | kWh (UK, EU) or m3 / therms (some countries) |
| Water | m3 | m3 (often water + wastewater charges) |
| Heat / district heating | kWh or MWh | kWh |

## Gas m3 to kWh
kWh = m3 x volume correction (1.02264) x calorific value (MJ/m3, printed on the bill, typically 37.5-43) / 3.6. The script uses `--calorific 39.5` by default. For therms: 1 therm = 29.3071 kWh.

## Good habits
Read all meters on the same day every month, photograph the display, and submit the reading to the supplier a day or two before the bill date.

FILE:references/tariffs-and-bill-checks.md
# Tariffs and bill checks

## Entering tariffs
One row per meter and price period in `tariffs.csv`:

| column | meaning |
|---|---|
| `meter` | same name as in the readings |
| `from` | first day the price applies (YYYY-MM-DD) |
| `meter_unit` / `tariff_unit` | e.g. `kWh`/`kWh`, `m3`/`kWh` for gas, `m3`/`m3` for water |
| `unit_price` | price per tariff unit, before tax |
| `standing_per_day` | fixed daily charge, before tax (0 if none; convert monthly fees: x12/365) |
| `vat_pct` | VAT or sales tax percent on the energy bill (e.g. 5, 20, 0) |

Water bills with separate fresh-water and wastewater prices: add them into one `unit_price`, or use two meter names with the same readings.

## How the bill check works
1. The bill covers `start` to `end` inclusive, so usage is measured from the reading at the start date to the reading at the day after `end`.
2. Readings on those exact days are rarely available, so the script interpolates linearly between the nearest real readings.
3. If a price change falls inside the bill, the period is split at the change date and each part is priced with its own tariff.
4. Expected cost = sum over parts of (units x unit price + days x standing charge) x (1 + VAT).
5. The bill is flagged (UM10) when it differs by more than `--tolerance` (default 5%). Above = possible overcharge (high), below = likely undercharge followed by a catch-up bill (medium).

Small differences (under 2-3%) usually come from interpolation, rounding, or a slightly different calorific value. Large differences almost always come from an estimated reading, a wrong price period, a missed price change, or the wrong meter number on the account.

## Typical billing errors
- Bill based on an estimate that was too high (UM03 + UM08 + UM10).
- New price applied to the whole period instead of from the change date.
- Wrong meter serial number on the account (your usage does not match the bill at all).
- Standing charge for days outside your tenancy (move-in/move-out bills).
- Two-rate meter registers swapped (night units priced as day units).

## What to send the supplier
The meter serial number, dated photos of the readings, the period and the difference you calculated, and a request to re-bill on actual readings. Keep it short and factual; ask for a corrected statement and a refund or credit of the overcharge.

## Leak test (water)
Close every tap and appliance, read the meter, wait 1-2 hours without using water, read again. Any movement means a leak; repeat with the toilet supply valve closed to see whether the toilet is the cause.

FILE:templates/usage-and-bill-report.md
# Utility usage and bill check: [address / business], [period]

**Meters:** [electricity, gas, water]  **Readings used:** [n of m]  **Currency:** [ ]
**Tool:** `meter_check.py` (output attached)  **Assumptions:** [digits, calorific value, tolerance]

## Usage and cost
| Meter | Avg per day | Last month | Last month cost | Annual estimate | Annual cost (latest tariff) |
|---|---|---|---|---|---|
| [electricity] | [10.6 kWh] | | | | |

## Bill check
| Meter | Bill period | Billed | Expected from readings | Difference | Billed units vs readings | Verdict |
|---|---|---|---|---|---|---|
| [electricity] | [2026-03-06..2026-04-04] | [237.62] | [103.85] | [+128.8%] | [760 vs 305] | [overcharge, based on estimate] |

## Data corrections
| Meter | Reading | Problem | What we did |
|---|---|---|---|
| [electricity] | [89650 on 2026-07-04] | [lower than previous] | [ignored; please re-check the photo] |

## Problems found
1. [Overcharge / leak / spike, with the evidence and money at stake]
2. [...]

## Next steps
1. [Submit an actual reading with photo and ask the supplier to re-bill period X]
2. [Run the leak test in the water meter guide]
3. [Read all meters on the same day each month]

_Figures between readings are interpolated. This is a usage check, not legal or financial advice._

FILE:examples/meter_readings.csv
date,meter,reading,type,note
2026-01-05,electricity,97200,actual,moved in reading
2026-02-04,electricity,97560,actual,
2026-03-06,electricity,97890,actual,
2026-04-05,electricity,98650,estimate,supplier estimate
2026-05-05,electricity,98500,actual,photo of meter
2026-06-04,electricity,98800,actual,
2026-07-04,electricity,89650,actual,typed from memory
2026-08-03,electricity,99400,actual,
2026-09-02,electricity,99720,actual,
2026-10-02,electricity,00050,actual,display wrapped to 0
2026-01-05,gas,4520.0,actual,
2026-02-04,gas,4690.5,actual,
2026-03-06,gas,4840.2,actual,
2026-04-05,gas,4950.0,actual,
2026-05-05,gas,5020.3,actual,
2026-06-04,gas,5060.0,actual,
2026-07-04,gas,5085.5,actual,
2026-07-04,gas,5058.5,customer,second photo (digits swapped?)
2026-08-03,gas,5110.0,actual,
2026-09-02,gas,5134.2,actual,
2026-10-02,gas,5165.0,actual,
2026-01-05,water,812.4,actual,
2026-02-04,water,822.1,actual,
2026-03-06,water,831.6,actual,
2026-04-05,water,841.0,actual,
2026-05-05,water,851.2,actual,
2026-06-04,water,861.5,actual,
2026-07-04,water,872.4,actual,
2026-08-03,water,883.0,actual,
2026-09-02,water,902.8,actual,
2026-10-02,water,923.1,actual,toilet keeps running?

FILE:examples/tariffs.csv
meter,from,meter_unit,tariff_unit,unit_price,standing_per_day,vat_pct
electricity,2026-01-01,kWh,kWh,0.28,0.45,5
electricity,2026-07-01,kWh,kWh,0.31,0.45,5
gas,2026-01-01,m3,kWh,0.07,0.30,5
water,2026-01-01,m3,m3,2.10,0.15,0

FILE:examples/bills.csv
meter,start,end,amount,units
electricity,2026-01-05,2026-02-03,120.02,360
electricity,2026-03-06,2026-04-04,237.62,760
electricity,2026-06-04,2026-07-03,103.32,300
gas,2026-01-05,2026-03-05,283.10,
water,2026-07-04,2026-10-01,119.97,50.7

FILE:scripts/meter_check.py
#!/usr/bin/env python3
"""Utility meter reading and bill checker (offline, Python 3.8+ standard library only).

Reads household or small-business meter readings (electricity, gas, water or any cumulative
meter), cleans them (backwards readings, typos, meter rollover, over-estimates, conflicting
duplicates), works out usage per period and per calendar month, prices it with your tariffs
(unit price, daily standing charge, VAT/sales tax, price changes, gas m3 -> kWh) and checks
each bill against what the readings imply. Flags spikes and sustained rises (leaks).

Usage:
  meter_check.py readings.csv [--tariffs tariffs.csv] [--bills bills.csv] [--digits electricity=5]
                 [--spike 1.6] [--tolerance 0.05] [--calorific 39.5] [--max-gap 70] [--json]
  meter_check.py --self-test
readings.csv: date,meter,reading[,type][,note]   type = actual (default) | estimate | customer
tariffs.csv:  meter,from,meter_unit,tariff_unit,unit_price,standing_per_day,vat_pct
bills.csv:    meter,start,end,amount[,units]     start/end inclusive, amount incl. tax
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, csv, json, statistics, sys
from collections import OrderedDict
from datetime import date, timedelta

SEV = {"high": 0, "medium": 1, "low": 2}
VOLUME_CORRECTION = 1.02264
RANK = {"actual": 0, "customer": 1, "estimate": 2}  # preferred reading on the same day


def d(s):
    return date.fromisoformat(s.strip())


def num(s):
    return float(str(s).replace(",", "").strip())


def read_csv(path):
    with open(path, newline="", encoding="utf-8-sig") as f:
        return [(i, {(k or "").strip().lower(): (v or "").strip() for k, v in r.items()}) for i, r in enumerate(csv.DictReader(f), 2)]


class Report:
    def __init__(self):
        self.findings = []

    def add(self, code, sev, meter, msg, when=None):
        self.findings.append({"code": code, "severity": sev, "meter": meter, "date": str(when) if when else "", "message": msg})


def clean_meter(meter, rows, rep, digits=None):
    """rows: list of (line, date, reading, type). Returns cleaned [(date, cumulative, type, raw)]."""
    by_date = OrderedDict()
    for line, dt, val, typ in sorted(rows, key=lambda r: (r[1], r[0])):
        if dt in by_date:
            prev = by_date[dt]
            keep = prev if RANK[prev[3]] < RANK[typ] else (line, dt, val, typ)
            if abs(prev[2] - val) > 1e-9:
                rep.add("UM06", "medium", meter, "lines %d/%d: two readings on %s (%g and %g); kept %g (%s)" % (prev[0], line, dt, prev[2], val, keep[2], keep[3]), dt)
            by_date[dt] = keep
            continue
        by_date[dt] = (line, dt, val, typ)
    rows = list(by_date.values())
    out, offset = [], 0.0
    span = 10 ** digits if digits else None
    for line, dt, val, typ in rows:
        cum = val + offset
        if out and cum < out[-1][1]:
            last = out[-1]
            if span and last[3] >= 0.9 * span and val <= 0.1 * span:
                offset += span
                cum = val + offset
                rep.add("UM09", "low", meter, "line %d: %g after %g read as a %d-digit meter rollover" % (line, val, last[3], digits), dt)
            elif last[2] == "estimate" and typ != "estimate":
                rep.add("UM03", "medium", meter, "estimated reading %g on %s was higher than the actual %g on %s: bills based on it overcharged, a credit is due"
                        % (last[3], last[0], val, dt), last[0])
                out.pop()
                while out and cum < out[-1][1]:
                    out.pop()
            else:
                rep.add("UM02", "high", meter, "line %d: reading %g on %s is lower than %g on %s (typo, swapped digits or wrong meter?); ignored"
                        % (line, val, dt, last[3], last[0]), dt)
                continue
        out.append((dt, cum, typ, val))
    return out


def at(series, when):
    """Cumulative reading at a date by linear interpolation, or None outside the readings."""
    if not series or when < series[0][0] or when > series[-1][0]:
        return None
    for (d0, c0, *_), (d1, c1, *_) in zip(series, series[1:]):
        if d0 <= when <= d1:
            span = (d1 - d0).days
            return c0 if span == 0 else c0 + (c1 - c0) * (when - d0).days / span
    return series[-1][1]


def periods(meter, series, rep, spike=1.6, max_gap=70):
    ps = []
    for (d0, c0, t0, _), (d1, c1, t1, _) in zip(series, series[1:]):
        days = (d1 - d0).days
        ps.append({"start": str(d0), "end": str(d1), "days": days, "units": round(c1 - c0, 3),
                   "per_day": round((c1 - c0) / days, 3) if days else 0.0, "estimate": "estimate" in (t0, t1)})
        if days > max_gap:
            rep.add("UM07", "low", meter, "%d days between readings %s and %s: monthly figures are interpolated" % (days, d0, d1), d0)
    flagged = []
    for i, p in enumerate(ps):
        hist = [q["per_day"] for q in ps[max(0, i - 3):i]]
        if len(hist) >= 2:
            base = statistics.median(hist)
            if base > 0 and p["per_day"] > spike * base:
                flagged.append(i)
                rep.add("UM04", "medium", meter, "%s to %s: %.2f/day is %.1fx the recent %.2f/day" % (p["start"], p["end"], p["per_day"], p["per_day"] / base, base), p["start"])
    if len(flagged) >= 2 and flagged[-1] == len(ps) - 1 and flagged[-2] == len(ps) - 2:
        rep.add("UM05", "high", meter, "usage stayed high for the last two periods (since %s): check for a leak, a faulty appliance or a meter fault" % ps[-2]["start"], ps[-2]["start"])
    return ps


def load_tariffs(path):
    t = {}
    for line, r in read_csv(path):
        try:
            t.setdefault(r["meter"].lower(), []).append({"from": d(r["from"]), "meter_unit": r.get("meter_unit", "") or "unit",
                "tariff_unit": r.get("tariff_unit", "") or r.get("meter_unit", "") or "unit", "unit_price": num(r["unit_price"]),
                "standing": num(r.get("standing_per_day") or 0), "vat": num(r.get("vat_pct") or 0) / 100})
        except (KeyError, ValueError) as e:
            raise ValueError("tariffs line %d: %s" % (line, e))
    for v in t.values():
        v.sort(key=lambda x: x["from"])
    return t


def convert(units, tar, calorific):
    if tar["meter_unit"].lower() in ("m3", "m³") and tar["tariff_unit"].lower() == "kwh":
        return units * VOLUME_CORRECTION * calorific / 3.6
    return units


def cost(series, tariffs, start, end_excl, calorific):
    """Units (in tariff unit) and cost incl. tax for [start, end_excl), split at tariff changes."""
    if not tariffs:
        return None
    cuts = sorted({start, end_excl} | {t["from"] for t in tariffs if start < t["from"] < end_excl})
    total_units = total_cost = 0.0
    for a, b in zip(cuts, cuts[1:]):
        ca, cb = at(series, a), at(series, b)
        if ca is None or cb is None:
            return None
        act = [t for t in tariffs if t["from"] <= a]
        if not act:
            return None
        tar = act[-1]
        u = convert(cb - ca, tar, calorific)
        total_units += u
        total_cost += (u * tar["unit_price"] + (b - a).days * tar["standing"]) * (1 + tar["vat"])
    return round(total_units, 2), round(total_cost, 2)


def month_starts(a, b):
    m = date(a.year, a.month, 1)
    while m <= b:
        yield m
        m = date(m.year + (m.month == 12), 1 if m.month == 12 else m.month + 1, 1)


def analyse(readings, tariffs=None, bills=None, digits=None, spike=1.6, tolerance=0.05, calorific=39.5, max_gap=70):
    rep, digits, tariffs = Report(), digits or {}, tariffs or {}
    raw = OrderedDict()
    for line, r in readings:
        try:
            dt, meter, val = d(r["date"]), r["meter"].lower(), num(r["reading"])
            typ = (r.get("type") or "actual").lower()
            if val < 0 or typ not in ("actual", "estimate", "customer"):
                raise ValueError("negative reading or unknown type %r" % typ)
        except (KeyError, ValueError) as e:
            rep.add("UM01", "medium", r.get("meter", "?"), "readings line %d unreadable: %s" % (line, e))
            continue
        raw.setdefault(meter, []).append((line, dt, val, typ))
    out = OrderedDict()
    for meter, rows in raw.items():
        series = clean_meter(meter, rows, rep, digits.get(meter))
        ps = periods(meter, series, rep, spike, max_gap)
        tar = tariffs.get(meter, [])
        months = []
        if len(series) >= 2:
            for m in month_starts(series[0][0], series[-1][0]):
                nxt = date(m.year + (m.month == 12), 1 if m.month == 12 else m.month + 1, 1)
                a, b = at(series, m), at(series, nxt)
                if a is None or b is None:
                    continue
                c = cost(series, tar, m, nxt, calorific)
                months.append({"month": m.strftime("%Y-%m"), "units": round(b - a, 2), "billed_units": c[0] if c else None, "cost": c[1] if c else None})
        span = (series[-1][0] - series[0][0]).days if len(series) >= 2 else 0
        per_day = (series[-1][1] - series[0][1]) / span if span else 0
        yr = None
        if span and tar:
            t = tar[-1]
            yu = convert(per_day * 365, t, calorific)
            yr = round((yu * t["unit_price"] + 365 * t["standing"]) * (1 + t["vat"]), 2)
        out[meter] = {"readings_used": len(series), "periods": ps, "months": months, "avg_per_day": round(per_day, 3),
                      "annual_units": round(per_day * 365, 1), "annual_cost_at_latest_tariff": yr,
                      "unit": (tar[-1]["meter_unit"] if tar else "units"), "_series": series}
    checks = []
    for line, b in bills or []:
        try:
            meter, s, e, amt = b["meter"].lower(), d(b["start"]), d(b["end"]), num(b["amount"])
        except (KeyError, ValueError) as ex:
            rep.add("UM01", "medium", b.get("meter", "?"), "bills line %d unreadable: %s" % (line, ex)); continue
        series = out.get(meter, {}).get("_series", [])
        c = cost(series, tariffs.get(meter, []), s, e + timedelta(days=1), calorific)
        row = {"meter": meter, "start": str(s), "end": str(e), "billed": amt, "expected": c[1] if c else None,
               "expected_units": c[0] if c else None, "billed_units": num(b["units"]) if b.get("units") else None, "diff_pct": None}
        checks.append(row)
        if c is None:
            rep.add("UM11", "low", meter, "bill %s to %s cannot be checked: outside the readings or no tariff" % (s, e), s); continue
        row["diff_pct"] = round((amt - c[1]) / c[1] * 100, 1) if c[1] else None
        est = [x for x in series if s <= x[0] <= e + timedelta(days=1) and x[2] == "estimate"]
        dropped = [f for f in rep.findings if f["code"] == "UM03" and f["meter"] == meter and s <= d(f["date"]) <= e + timedelta(days=1)]
        if est or dropped:
            rep.add("UM08", "medium", meter, "bill %s to %s ends on or spans an estimated reading: ask for a bill on an actual reading" % (s, e), s)
        if row["diff_pct"] is not None and abs(row["diff_pct"]) > tolerance * 100:
            over = row["diff_pct"] > 0
            rep.add("UM10", "high" if over else "medium", meter, "bill %s to %s is %.2f, readings and tariff imply %.2f (%+.1f%%)%s"
                    % (s, e, amt, c[1], row["diff_pct"], "" if over else ": undercharged now, expect a catch-up bill"), s)
    for m in out.values():
        m.pop("_series")
    fs = sorted(rep.findings, key=lambda f: (SEV[f["severity"]], f["code"], f["meter"], f["date"]))
    return {"meters": out, "bills": checks, "findings": fs,
            "counts": {k: sum(f["severity"] == k for f in fs) for k in SEV}}


def print_text(r):
    for meter, m in r["meters"].items():
        print("== %s (%s): %d readings used, %.3f %s/day, ~%.0f %s/year%s" % (meter, m["unit"], m["readings_used"], m["avg_per_day"], m["unit"],
              m["annual_units"], m["unit"], (", ~%.2f/year at latest tariff" % m["annual_cost_at_latest_tariff"]) if m["annual_cost_at_latest_tariff"] else ""))
        print("   period                      days     units   per_day")
        for p in m["periods"]:
            print("   %s .. %s  %4d %9.2f %9.3f%s" % (p["start"], p["end"], p["days"], p["units"], p["per_day"], "  (estimate)" if p["estimate"] else ""))
        if m["months"]:
            print("   month     units   priced_units      cost")
            for x in m["months"]:
                print("   %s %8.2f %14s %9s" % (x["month"], x["units"], "-" if x["billed_units"] is None else "%.2f" % x["billed_units"],
                      "-" if x["cost"] is None else "%.2f" % x["cost"]))
    if r["bills"]:
        print("\nBill check")
        for b in r["bills"]:
            units = ""
            if b["billed_units"] is not None and b["expected_units"] is not None:
                units = "  units billed %g vs readings %g" % (b["billed_units"], b["expected_units"])
            print("  %-12s %s..%s billed %8.2f expected %8s  %7s%s" % (b["meter"], b["start"], b["end"], b["billed"],
                  "-" if b["expected"] is None else "%.2f" % b["expected"], "-" if b["diff_pct"] is None else "%+.1f%%" % b["diff_pct"], units))
    c = r["counts"]
    print("\nFindings: %d high, %d medium, %d low" % (c["high"], c["medium"], c["low"]))
    for f in r["findings"]:
        print("  [%s] %s %s %s: %s" % (f["severity"].upper(), f["code"], f["meter"], f["date"], f["message"]))


def self_test():
    tests = []
    def t(name, cond):
        tests.append((name, bool(cond)))
    def R(*rows):
        return [(i + 2, dict(zip(("date", "meter", "reading", "type"), r))) for i, r in enumerate(rows)]
    def codes(res):
        return [f["code"] for f in res["findings"]]
    a = analyse(R(("2026-01-01", "e", "100"), ("2026-01-11", "e", "200"), ("2026-01-21", "e", "300")))
    t("per-day usage", a["meters"]["e"]["periods"][0]["per_day"] == 10 and a["meters"]["e"]["avg_per_day"] == 10)
    t("interpolation", abs(at([(date(2026, 1, 1), 0, "actual", 0), (date(2026, 1, 11), 100, "actual", 100)], date(2026, 1, 6)) - 50) < 1e-9)
    b = analyse(R(("2026-01-01", "e", "99900"), ("2026-01-11", "e", "50")), digits={"e": 5})
    t("rollover with --digits", b["meters"]["e"]["periods"][0]["units"] == 150 and "UM09" in codes(b))
    c = analyse(R(("2026-01-01", "e", "1000"), ("2026-01-11", "e", "1100"), ("2026-01-21", "e", "110"), ("2026-01-31", "e", "1300")))
    t("backwards reading ignored", "UM02" in codes(c) and c["meters"]["e"]["readings_used"] == 3)
    e = analyse(R(("2026-01-01", "e", "1000"), ("2026-02-01", "e", "1500", "estimate"), ("2026-03-01", "e", "1400")))
    t("over-estimate dropped", "UM03" in codes(e) and e["meters"]["e"]["readings_used"] == 2)
    f = analyse(R(("2026-01-01", "w", "10"), ("2026-01-01", "w", "11"), ("2026-01-11", "w", "20")))
    t("conflicting duplicate", "UM06" in codes(f))
    f2 = analyse(R(("2026-01-01", "w", "10"), ("2026-01-11", "w", "20", "actual"), ("2026-01-11", "w", "02", "customer")))
    t("duplicate keeps actual over customer", f2["meters"]["w"]["periods"][0]["units"] == 10)
    g = analyse(R(*[("2026-%02d-01" % m, "w", str(v)) for m, v in zip(range(1, 8), (0, 10, 20, 30, 40, 60, 80))]))
    t("spike + sustained rise -> leak", codes(g).count("UM04") == 2 and "UM05" in codes(g))
    tar = {"e": [{"from": date(2026, 1, 1), "meter_unit": "kWh", "tariff_unit": "kWh", "unit_price": 0.2, "standing": 0.5, "vat": 0.1}]}
    s = [(date(2026, 1, 1), 0, "actual", 0), (date(2026, 1, 11), 100, "actual", 100)]
    t("cost = (units*price + days*standing)*(1+vat)", cost(s, tar["e"], date(2026, 1, 1), date(2026, 1, 11), 39.5) == (100, 27.5))
    tar2 = [{"from": date(2026, 1, 1), "meter_unit": "kWh", "tariff_unit": "kWh", "unit_price": 0.2, "standing": 0, "vat": 0},
            {"from": date(2026, 1, 6), "meter_unit": "kWh", "tariff_unit": "kWh", "unit_price": 0.4, "standing": 0, "vat": 0}]
    t("price change split by date", cost(s, tar2, date(2026, 1, 1), date(2026, 1, 11), 39.5)[1] == 30.0)
    gas = [{"from": date(2026, 1, 1), "meter_unit": "m3", "tariff_unit": "kWh", "unit_price": 1, "standing": 0, "vat": 0}]
    t("gas m3 -> kWh", abs(cost(s, gas, date(2026, 1, 1), date(2026, 1, 11), 39.5)[0] - 100 * 1.02264 * 39.5 / 3.6) < 0.01)
    bills = [(2, {"meter": "e", "start": "2026-01-01", "end": "2026-01-10", "amount": "27.50"}), (3, {"meter": "e", "start": "2026-01-01", "end": "2026-01-10", "amount": "40"}),
             (4, {"meter": "e", "start": "2025-12-01", "end": "2025-12-31", "amount": "9"})]
    h = analyse(R(("2026-01-01", "e", "0"), ("2026-01-11", "e", "100")), tariffs=tar, bills=bills)
    t("matching bill passes", h["bills"][0]["diff_pct"] == 0.0)
    t("overcharge flagged high", any(x["code"] == "UM10" and x["severity"] == "high" for x in h["findings"]))
    t("bill outside readings -> UM11", "UM11" in codes(h))
    i = analyse(R(("2026-01-01", "e", "0"), ("2026-01-31", "e", "100", "estimate")), tariffs=tar, bills=[(2, {"meter": "e", "start": "2026-01-01", "end": "2026-01-30", "amount": "1"})])
    t("bill on estimate -> UM08", "UM08" in codes(i))
    j = analyse(R(("2026-01-01", "e", "0"), ("2026-03-01", "e", "590")))
    t("monthly split by interpolation", [m["units"] for m in j["meters"]["e"]["months"]] == [310.0, 280.0])
    k = analyse(R(("2026-13-01", "e", "1"), ("2026-01-01", "e", "-5")))
    t("bad rows -> UM01", codes(k).count("UM01") == 2)
    l = analyse(R(("2026-01-01", "e", "0"), ("2026-04-01", "e", "90")))
    t("long gap -> UM07", "UM07" in codes(l))
    ok = 0
    for name, c in tests:
        print("%s  %s" % ("PASS" if c else "FAIL", name)); ok += c
    print("%d/%d passed" % (ok, len(tests)))
    return 0 if ok == len(tests) else 1


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("readings", nargs="?"); ap.add_argument("--tariffs"); ap.add_argument("--bills")
    ap.add_argument("--digits", action="append", default=[], help="meter=N, e.g. electricity=5")
    ap.add_argument("--spike", type=float, default=1.6); ap.add_argument("--tolerance", type=float, default=0.05)
    ap.add_argument("--calorific", type=float, default=39.5); ap.add_argument("--max-gap", type=int, default=70)
    ap.add_argument("--json", action="store_true"); ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.readings:
        ap.print_usage(); return 2
    try:
        digits = {k.strip().lower(): int(v) for k, v in (x.split("=", 1) for x in a.digits)}
        readings = read_csv(a.readings)
        tariffs = load_tariffs(a.tariffs) if a.tariffs else {}
        bills = read_csv(a.bills) if a.bills else []
    except (OSError, ValueError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    if not readings:
        print("error: no readings", file=sys.stderr); return 2
    r = analyse(readings, tariffs, bills, digits, a.spike, a.tolerance, a.calorific, a.max_gap)
    print(json.dumps(r, indent=2)) if a.json else print_text(r)
    return 1 if r["counts"]["high"] else 0


if __name__ == "__main__":
    sys.exit(main())
BudgetingData AnalysisPersonal Finance+2
F@f
0
10 seconds video
Text

A warm, playful 10-second indoor scene in a bright living room. A small boy, about 4 years old, in a yellow t-shirt, stands next to a smiling adult man with a smooth bald head who is sitting on a sofa. The boy looks up curiously, reaches out, and gently pats the man's bald head with both hands. He giggles and tilts his head in amazement. The man laughs warmly, leans his head down to let the boy touch it, and plays along with a funny surprised expression.

A warm, playful 20-second indoor scene in a bright living room. A small boy, about 4 years old, in a yellow t-shirt, stands next to a smiling adult man with a smooth bald head who is sitting on a sofa. The boy looks up curiously, reaches out, and gently pats the man's bald head with both hands. He giggles and tilts his head in amazement. The man laughs warmly, leans his head down to let the boy touch it, and plays along with a funny surprised expression. The boy pats and rubs the head again, laughing louder. Natural soft daylight from a window, cozy home atmosphere, handheld camera feel, medium shot with a gentle push-in toward their faces, realistic skin tones, shallow depth of field, heartwarming and humorous mood, cinematic 4K.
A@abdulimran038
0
Ultra-Real Candid Front-Camera Selfie of a Curly-Haired Young Man at Home (9:16)
Image
Ultra-Real Candid Front-Camera Selfie of a Curly-Haired Young Man at Home (9:16)

A detailed realism prompt for an unedited, straight-out-of-camera phone selfie: a curly-haired man in his twenties reclining on a sofa in a lived-in room, with visible pores, warm household light and none of the plastic, over-retouched AI look.

Candid phone snapshot, shot with front phone camera, real phone photo of an attractive adult man in his early-to-mid 20s, an unedited camera photo, SOOC. He has thick, voluminous dark brown curly hair with naturally defined loose ringlets, styled in a slightly messy shape with several prominent curls falling across his forehead. His hair has natural volume, subtle shine, and individual flyaway strands. He has light olive skin, blue-grey eyes, thick dark eyebrows, a straight nose with a small silver nose stud, naturally full pink lips, and a defined jawline. He has a neatly trimmed dark mustache and a distinctive short, fuller goatee concentrated around his chin. Small sparkling silver diamond-style stud earrings are visible in both ears.

He is wearing a relaxed white cotton graphic T-shirt with oversized green and purple printed lettering across the front. The shirt has a slightly loose fit, natural fabric creases, and a simple rounded neckline.
He is reclining comfortably against a sofa or bed, holding his iPhone slightly above his face to take a close-up front-facing selfie. His head rests naturally against the surface behind him, shoulders relaxed. He looks directly into the camera with a subtle, confident half-smile and a calm, relaxed expression. His face is the main focal point.

The framing is vertical 9:16 portrait, close-up selfie from the upper chest upward, shot with front phone camera at a slightly elevated angle. His face is centered, with his voluminous curly hairstyle occupying much of the upper frame and his white graphic T-shirt visible across the lower foreground. Candid phone shot, spontaneous and slightly imperfect, like a casual selfie taken while relaxing at home.

The environment is a cozy, ordinary bedroom or living space. Behind him is a light cream-colored wall with a subtle textured painted finish. A large black flat-screen television is partially visible on the upper-left side of the background. On the right side, a dark black backpack or soft travel bag hangs casually near the wall, with realistic fabric folds and straps visible. A small section of light beige furniture or bedding is visible behind his shoulders.

Lighting is warm, soft indoor household lighting, creating natural illumination across his face with gentle shadows beneath his curls, nose, and chin. His skin has natural highlights, and the white shirt retains visible cotton texture without appearing overexposed.
Real photo look, IG phone snapshot: visible pores, natural skin-tone variation, under-eye texture, subtle freckles and facial imperfections, individual defined hair curls, natural catchlights in the eyes, accurate facial proportions, natural mustache and goatee texture, visible cotton weave. Natural colors, authentic handheld perspective.

Avoid the look of modern high-definition digital fashion photography. No plastic skin, no excessive smoothing, no beauty retouching, no sharp digital look, no cinematic lighting, no dramatic color grading, no filters, no distorted anatomy, no extra fingers, no watermarks or added text overlays. Strictly vertical 9:16 portrait orientation.
RealismPhotographyGPT Image+2
F@f
0
AWS CDK Infrastructure taste
Taste

Opinionated AWS CDK conventions for infrastructure as code that stays safe to review, deploy and roll back.

# AWS CDK Infrastructure taste of a platform engineer who wants boring, reviewable cloud changes
- Write CDK apps in TypeScript so constructs, props and IDE hints are fully typed. Confidence: 0.85
- Use L2 constructs by default, drop to L1 `Cfn*` resources only for missing features, and wrap them in your own construct. Confidence: 0.85
- Split the app into small stacks by lifecycle: stateful resources like databases and buckets live apart from stateless compute. Confidence: 0.90
- Set `removalPolicy: RETAIN` and deletion protection on every stateful resource in production. Confidence: 0.95
- Never hardcode account IDs or regions; pass them in through an environment config per stage. Confidence: 0.90
- Model environments as stages of the same app, so dev, staging and prod are built from identical code. Confidence: 0.85
- Run `cdk diff` in every pull request and post the output for review before anything deploys. Confidence: 0.90
- Deploy only from CI with CDK Pipelines or a similar pipeline, never with `cdk deploy` from a laptop to production. Confidence: 0.90
- Grant permissions with construct methods like `bucket.grantRead(fn)` instead of writing IAM policy JSON by hand. Confidence: 0.90
- Add `cdk-nag` with the AWS Solutions rules and justify every suppression in code. Confidence: 0.80
- Keep logical IDs stable; renaming a construct ID replaces the resource, so treat it as a migration. Confidence: 0.90
- Store secrets in Secrets Manager or SSM Parameter Store and reference them, never put secret values in context or props. Confidence: 0.95
- Tag every resource with owner, service and cost center through `Tags.of(app)`. Confidence: 0.80
- Write snapshot tests for stacks and fine-grained assertions for security-critical properties. Confidence: 0.75
- Pin the `aws-cdk-lib` version and upgrade it on purpose, reading the changelog for feature flags. Confidence: 0.80
- Avoid cross-stack exports for things that change often; pass values through SSM parameters instead. Confidence: 0.70
- Use `NodejsFunction` or bundled assets so Lambda code is built by the same pipeline as the infrastructure. Confidence: 0.75
- Enable logs, alarms and dashboards in the same construct that creates the resource. Confidence: 0.80
- Keep `cdk.context.json` committed so lookups are deterministic across machines. Confidence: 0.85
Best PracticesAWSInfrastructure as Code+2
F@f
0