
I do not have a great design eye to be able to tell AI exactly what I want right up front in a prompt. This prompt will guide you through a stepped approach to creating a solid design by interviewing you and asking about every step in the design process and showing you visuals along the way.
# Master Prompt — World-Class Product Design & Creative Direction I want you to act as a **world-class creative director, luxury brand designer, and senior product/UI/UX designer** with experience creating visually extraordinary, production-quality digital applications. Your role is to help me discover, define, and develop a distinctive visual identity and user experience for a software application. ## About my project **Product name:** [NAME] **What it does:** [DESCRIPTION] **Who uses it:** [TARGET USERS] **What makes it special:** [OPTIONAL] **Existing brand guidelines or inspiration:** [OPTIONAL] ## Your role I am not a professional designer. I may know what I like when I see it, but I don't necessarily know how to describe it or what creative possibilities exist. **I need you to supply the creative imagination, expertise, and direction.** Don't depend on me to suggest colours, textures, typography, visual metaphors, architectural elements, layout ideas, or design techniques. Instead, proactively explore these possibilities and present me with compelling options. Think like an elite digital design agency hired to create a remarkable product. Your objective is not simply to follow my instructions. It is to help me discover an exceptional design that I might not have imagined myself. ## Phase 1 — Creative discovery Before generating designs, guide me through a structured creative discovery process. Identify the most important decisions for this particular project. These may include: - Overall visual identity and emotional experience - Colour palette and colour relationships - Surface textures, materials, and visual depth - Typography and editorial style - Iconography, imagery, symbolism, and visual metaphors - Layout philosophy, navigation, and information hierarchy - Balance between visual drama and everyday usability **Ask me questions ONE AT A TIME.** For each decision: 1. Present three meaningfully different creative directions. 2. Explain each in plain English, avoiding unnecessary design jargon. 3. Provide visual references when they would help me understand the differences. 4. Explain the strengths and trade-offs of each. 5. **Recommend one direction and explain why.** 6. Let me choose, modify, or combine the options before moving on. Don't overwhelm me with a long questionnaire. You should challenge my thinking when you believe a different approach would produce a better result. ## Phase 2 — Establish the creative direction Once we've made the important decisions: 1. Summarize our agreed visual direction. 2. Identify the core design principles that should remain consistent. 3. Define the colour palette, typography, materials, imagery, and interface treatments. 4. Describe how the application should balance emotional impact with practical usability. 5. Identify any unresolved design decisions that should be explored visually. Treat these decisions as our **approved creative brief**. Remember both my selections and the directions I've rejected. Do not silently change approved decisions in subsequent designs. ## Phase 3 — Visual exploration Create a visually ambitious, high-quality concept for a **real, believable software application**, not merely a decorative illustration. The design should include: - A complete desktop application screen - Believable application navigation - Realistic content and representative data - Clear visual hierarchy - Beautiful typography - Carefully considered spacing and alignment - Distinctive visual details that establish the product's identity - Obvious actions and intuitive workflows **Avoid generic SaaS templates, conventional dashboard styling, and predictable AI-generated design conventions unless there is a compelling reason to use them.** Use visual storytelling, sophisticated materials, atmosphere, illustration, photography, architecture, or other creative techniques where appropriate to the project's identity. However, don't sacrifice readability, accessibility, or usability for spectacle. The result should look like a product conceived by a top-tier design agency and refined by an experienced SaaS product team. ### Comparing concepts When useful, show alternative versions of the same screen. Keep the underlying layout and content consistent when comparing colours, textures, or visual styles so I can evaluate the differences fairly. Offer alternative compositions separately when layout itself is the design decision. ## Phase 4 — Collaborative refinement After presenting a concept: 1. Ask what I like and dislike. 2. Help me identify which specific elements are working. 3. Suggest targeted improvements I may not have considered. 4. Allow me to combine elements from multiple concepts. 5. Preserve all previously approved elements unless I explicitly ask to change them. **When I request a specific modification, change only what I've requested. Do not unnecessarily regenerate, reinterpret, or redesign unrelated elements.** Maintain visual consistency throughout the project. ## Phase 5 — Production readiness Once the visual direction is approved, help translate the concept into a practical design system suitable for real software development. This should eventually include: - Design tokens and exact colour values - Typography definitions - Spacing, sizing, and layout conventions - Reusable UI component patterns - Navigation and interaction conventions - Responsive behaviour - Accessibility and contrast considerations - Image and icon asset recommendations Separate aspirational concept artwork from elements that can be implemented directly in production. Flag any visual effects that could be expensive, impractical, or harmful to usability. ## Creative standards I expect: **Originality:** A distinctive identity, not a reskinned template. **Craftsmanship:** Exceptional attention to detail. **Cohesion:** Every screen should feel like part of the same product. **Usability:** A product that is a pleasure to use repeatedly. **Ambition:** Don't play it safe merely because this is enterprise software. **Judgment:** Make recommendations and challenge weak ideas. **Collaboration:** Treat this as an evolving creative partnership. ## Important Don't start by generating an image. Start by briefly explaining your proposed creative discovery process, then **ask me the first important design question with options and your recommendation**. Guide me through the entire process rather than expecting me to know what to ask for next.

A cozy hand-painted watercolor anime close-up of an original character with a cheeky wink, puffed cheeks and a tiny pout, lit by soft warm sunlight.
Create a beautiful 9:16 vertical hand-painted anime illustration of a cute young girl with short chestnut-brown hair, soft bangs and big sparkling hazel eyes. She is making a playful childish expression, one eye tightly closed in a wink, cheeks puffed slightly, and lips forming a tiny funny pout. Her head is tilted naturally toward the camera. She wears a pastel lavender oversized hoodie. Soft warm sunlight, delicate blush, expressive facial details, textured watercolor and hand-painted anime art style, muted natural background, charming imperfect details, close-up portrait, adorable and full of personality. Original character design, highly detailed, beautiful artistic finish.

Turn any city into a vintage-inspired souvenir travel poster in a hand-drawn architectural doodle style, with bold ink outlines, its iconic landmarks, a local vehicle in the foreground and the city name in hand-lettered type. Just set the city variable.
INTERNATIONAL CITY TRAVEL ART PRINT COLLECTION
Create a charming, vintage-inspired travel poster featuring Lisbon, Portugal, illustrated in a distinctive hand-drawn architectural doodle style.
Showcase the city's most iconic landmarks, buildings, monuments, towers, bridges, and recognizable architectural details, arranged together in a dense yet balanced artistic composition. Incorporate a recognizable local element, such as a vintage car, tram, taxi, bicycle, or public transport, in the foreground.
Use bold black ink outlines, intricate hand-drawn details, playful geometric patterns, and slightly imperfect sketch-like textures. Add the city name prominently within the illustration using creative hand-lettered typography.
Present the artwork inside a clean white poster border, surrounded by a vibrant solid-color background that complements the city's identity. Use a limited palette of black, warm white, and one or two bold accent colors.
Overall aesthetic: Minimalist European travel illustration, retro souvenir poster, whimsical architectural line art, screen-print texture, playful composition, and premium collectible wall-art design.
Keep the artwork visually cohesive, highly detailed, charming, and instantly recognizable as a celebration of the destination. Avoid photorealism, 3D effects, gradients, and unnecessary decorative elements.A shot-by-shot Seedance 2.5 trailer prompt for a 30-second, 20-shot AAA game-style duel on a storm-lashed dam between a water-wielding heroine and a molten-glass villain, with ready-made reference-image prompts for both characters and the location.
AAA game cinematic trailer, pre-rendered CG like a high-budget fantasy game launch trailer: stylized semi-realistic characters with idealized faces, large luminous eyes, porcelain skin with subsurface glow, individually simulated hair strands, real fabric with weave and wear; massive particle and energy effects, volumetric god rays, haze and floating dust, low golden-hour backlight with sun flare, deep contrast, bloom, subtle chromatic aberration and film grain, anamorphic lens, shallow depth of field, fast handheld and drone camera work with real motion blur. NOT live-action, NOT a collectible figurine or statue, NOT a toy, NOT 2D anime, NOT a gameplay screenshot, NO HUD, no plastic skin. REFERENCES: @[ines] is Ines (use the character sheet), @[vesper] is Vesper (use the character sheet), @[dam] is the location, palette and light. Match each exactly whenever visible. FORMAT: 16:9, 24fps, 30 seconds, 20 shots, hard cuts on motion, fast trailer pacing. CHARACTER (@[ines]): a young woman of 21 with a short choppy black bob soaked by rain, freckles, a sharp determined face, a thin scar through one eyebrow, an oversized cropped bright yellow oilskin rain jacket, a black neoprene top, grey cargo shorts over black leggings and heavy black rubber boots. Her power is water: she shapes rain and water into whips, waves and blades and freezes them instantly into glowing glacial-cyan ice. CHARACTER (@[vesper]): a tall lean man in his late 20s with a shaved head, a calm cruel smile and a burn scar down his neck, a heavy scorched brown leather glassblower's apron over a sleeveless black work shirt, long leather gauntlets, goggles around his neck, fighting with a long steel glassblower's blowpipe as a staff. His power is molten glass: he draws glowing molten-orange glass from the blowpipe and flings, shapes and hardens it into spikes, blades and a shield. Molten glass hisses into steam wherever rain touches it. KEY LIGHT (every shot): dark storm clouds overhead, cold blue key from above, lightning flashes as the only highlights, rain sheeting through the frame. PALETTE: storm blue-black, wet concrete grey, @[ines]'s yellow jacket. Glacial cyan belongs only to @[ines]; molten orange belongs only to @[vesper]. Where they collide, white steam. SCREEN DIRECTION: @[ines] attacks from screen left, @[vesper] from screen right, unless a shot says otherwise. SHOTS 1 | 0.0-1.2s | Extreme close-up of @[ines]'s eyes, rain running down her face, glacial-cyan light kindling in her irises. 2 | 1.2-2.6s | Wide low shot along the flooded dam crest as lightning flashes: @[ines] on the left, @[vesper] on the right, molten orange glass dripping from his blowpipe and hissing into steam on the concrete. 3 | 2.6-3.8s | @[vesper] whips the blowpipe and flings a ribbon of molten glass that hardens in mid-air into a spray of glowing orange spikes flying toward screen left. 4 | 3.8-4.8s | Tracking low: @[ines] slides on one knee under the spikes across the flooded concrete, sweeping her arm so the falling rain snaps into a long cyan water whip. 5 | 4.8-6.0s | The whip strikes @[vesper]'s raised molten-glass shield and simply explodes into a burst of white steam, the frame flashes white; as the steam clears @[vesper] is untouched, smiling, his shield glowing hotter. 6 | 6.0-7.2s | @[vesper] spins and slams the blowpipe into @[ines]'s guard, sparks and spray bursting, knocking her backwards over the iron railing. 7 | 7.2-9.0s | Wide: @[ines] drops down the face of the dam into the roaring white spillway, lands on the torrent and surfs it on a cyan wave, carving back toward the wall. 8 | 9.0-10.4s | Low tracking shot: @[ines] rides a rising column of water straight up the dam face toward camera, the rain around her arms spiralling into ice. 9 | 10.4-11.4s | @[ines] bursts over the crest and fires a volley of glowing cyan ice needles at @[vesper]; at the peak the action drops into slow motion, then snaps back to full speed. 10 | 11.4-12.2s | Close on contact: the ice needles hit the glowing glass shield and it cracks with white spider-web fractures spreading across it from the cold, the frame flashes white. 11 | 12.2-13.8s | Wide, orbiting: @[ines] with an ice blade and @[vesper] with a glass blade trade three fast blows along the crest, a burst of steam on every clash, the cracked shield shedding glowing shards. 12 | 13.8-15.0s | @[vesper] plunges the blowpipe into the concrete and a wave of molten glass rolls over @[ines]'s boots and hardens, pinning her legs. 13 | 15.0-16.4s | @[vesper] smashes her back into the railing and glass hardens over her arm; her cyan glow sputters and dies in the steam around her. 14 | 16.4-17.6s | Low angle from @[ines] looking up at @[vesper] against a lightning flash as he raises the blowpipe, a huge glowing molten bulb swelling at its tip. 15 | 17.6-18.6s | Extreme close-up: @[ines]'s eyes snap open, blazing cyan, and every falling raindrop around her stops in mid-air. 16 | 18.6-20.0s | Extreme wide: behind @[ines] the entire black reservoir rises out of the dam into a towering wave lit from within by lightning, @[ines] tiny before it with one arm raised. 17 | 20.0-21.4s | @[vesper] swings the molten bulb as @[ines] brings the wave crashing down onto him and freezes it the instant it hits his glass, the frame flashes white. 18 | 21.4-23.4s | Slow motion: from the shock of the cold, @[vesper]'s glass shield, blade and the molten bulb shatter into millions of glittering orange and cyan shards hanging in the air around him, then snap back to full speed as they blast outward. 19 | 23.4-25.0s | Medium: @[vesper] slumps unconscious against a huge glowing frozen wave sculpture, his blowpipe clattering onto the flooded concrete, steam curling off his gauntlets. 20 | 25.0-30.0s | Low hero shot, held: @[ines] stands, the hardened glass on her legs and arm cracking and falling away, the frozen raindrops around her releasing and falling again, the frozen wave glowing faint cyan behind her under a lightning flash, as the camera slowly pushes in, held. AUDIO: hard-hitting hybrid trailer music with taiko drums from the first frame, cutting out on the failed whip, back in on the spillway surf, dropping to near-silence on shot 15 with only a heartbeat and suspended rain, then a massive hit on shot 17 and a long choir note over the final shot / constant storm bed: heavy rain, wind, thunder, the roaring spillway / a sub-bass hit on every impact, a whoosh on every cut / hissing steam whenever glass meets water, a sharp glass crack on shot 10, a huge crystalline shatter on shot 18, glass tinkling down on shot 19 / No dialogue --- REFERENCE IMAGES (generate these first and attach them as @[ines], @[vesper] and @[dam]): Ines: Cinematic film still, low angle, dark storm clouds overhead, cold blue light from above, a lightning flash behind her, rain sheeting through the frame. A young woman of 21 with a short choppy black bob soaked by rain, freckles, a sharp determined face, a thin scar through one eyebrow, wearing an oversized cropped bright yellow oilskin rain jacket, a black neoprene top, grey cargo shorts over black leggings and heavy black rubber boots, mid-leap on the flooded crest of a giant concrete dam, the rain around her arm twisting into a whip of glowing glacial-cyan water freezing into ice. AAA game cinematic trailer, pre-rendered CG, stylized semi-realistic character with an idealized face, large luminous eyes, porcelain skin with subsurface glow, individually simulated hair strands, real fabric with weave and wear, volumetric god rays, flying debris and sparks, bloom, deep contrast, anamorphic lens, shallow depth of field, motion blur, subtle film grain Vesper: Cinematic film still, low angle, dark storm clouds overhead, cold blue light from above, a lightning flash behind him, rain sheeting through the frame. A tall lean man in his late 20s with a shaved head, a calm cruel smile and a burn scar down his neck, wearing a heavy scorched brown leather glassblower's apron over a sleeveless black work shirt, long leather gauntlets and goggles around his neck, spinning a long steel glassblower's blowpipe like a staff, a ribbon of glowing molten-orange glass trailing from its tip and hissing into steam in the rain, on the crest of a giant concrete dam. AAA game cinematic trailer, pre-rendered CG, stylized semi-realistic character with an idealized face, large luminous eyes, porcelain skin with subsurface glow, individually simulated hair strands, real fabric with weave and wear, volumetric god rays, flying debris and sparks, bloom, deep contrast, anamorphic lens, shallow depth of field, motion blur, subtle film grain Dam: Wide cinematic establishing shot of the crest of a colossal concrete dam in a mountain gorge during a violent storm, completely empty, no people, no characters. A long flooded walkway with iron railings and lamp posts, the black reservoir on one side, a roaring white spillway pouring down the other side into the gorge, giant floodgate towers, flickering warning lights. Dark storm clouds overhead, cold blue light from above, lightning flashes, rain sheeting through the frame. Low camera on the flooded crest, deep space, strong foreground iron railing, midground open crest, background gate towers dissolved in rain. AAA game cinematic trailer, pre-rendered CG environment, volumetric light, bloom, deep contrast, anamorphic lens, subtle film grain
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

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.

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.
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
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.
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:]))

A moody evening café portrait of a woman at a stone table with iced cold brew, next to a glossy collectible 3D chibi figurine of herself holding a tiny cold brew glass.
A cinematic studio portrait of a woman seated at a textured stone table against a muted warm gray background. She wears a dark brown satin blouse, subtle evening makeup, and softly layered shoulder-length hair. In front of her is a glass of cold brew coffee with ice and a metal straw. Placed beside it is a glossy 3D chibi figurine of the same woman, with a big rounded head, expressive eyes, soft blush cheeks, and simplified facial features, holding a miniature cold brew glass. The chibi has a high-quality collectible toy look with gentle reflections. Intimate evening café vibe, moody soft lighting, shallow depth of field, realistic human combined with stylized 3D character, cinematic and cozy, 1:1 aspect ratio.

Turns an uploaded photo of a woman into a photorealistic 1970s editorial studio portrait with a crimson lip, ivory satin lace blouse, warm spotlight glow and analog film tones, keeping her exact identity.
Create a highly photorealistic cinematic vintage studio portrait of the same adult woman shown in the uploaded reference image. Preserve her exact facial identity, recognizable features, natural skin tone, face shape, eyes, nose, lips, and facial proportions without beautification or alteration. Appearance & Makeup: She has a short, softly tousled dark-brown bob with gentle loose curls framing her cheeks and delicate wispy bangs across her forehead. Her expressive hazel-brown eyes are enhanced with subtle smoky eyeliner, naturally shaped eyebrows, softly flushed cheeks, and elegant deep crimson-red lipstick. Her complexion is warm and luminous, with realistic skin texture and natural details. Outfit & Styling: She wears an elegant ivory satin blouse with a modest, softly draped neckline, delicate lace detailing around the collar, and subtle puff sleeves. The blouse is neatly fitted and tucked into a high-waisted black tailored mini skirt with a refined silhouette. Add sheer dark burgundy stockings for a sophisticated vintage-inspired look. The overall styling should feel elegant, tasteful, and timeless rather than revealing. Pose & Composition: She sits gracefully on a low vintage studio chair, leaning slightly forward with relaxed shoulders and a confident posture. Her hands rest naturally together on her lap. Her chin is gently raised as she looks directly into the camera with a confident, subtly mysterious expression. Lighting & Background: A minimalist warm beige studio wall serves as the background. A strong directional spotlight creates a soft circular glow behind her, accompanied by a beautifully defined shadow falling to one side. Rich warm shadows, gentle highlights across her face, and subtle cinematic contrast create an intimate vintage Hollywood atmosphere. Photography Style: Classic 1970s editorial portrait photography, vintage studio glamour, warm analog film tones, authentic skin texture, subtle film grain, sophisticated color grading, professional fashion photography, sharp facial focus, beautifully balanced composition, highly detailed, photorealistic, vertical portrait. Maintain the reference woman's exact identity throughout. No cartoon features, no anime aesthetics, no artificial skin smoothing, no exaggerated body proportions, and no changes to her recognizable appearance.
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:]))
Models a priced seed or Series A round on your cap table: converts post-money and pre-money SAFEs (cap and/or discount), tops up the option pool to a post-money target, prices the new shares and shows every holder's dilution, value and red flags, with a pre-money comparison. Offline stdlib Python.
---
name: cap-table-round-and-safe-conversion-calculator
description: Models a priced seed or Series A round on your cap table: converts post-money and pre-money SAFEs (cap and/or discount), tops up the option pool to a post-money target, prices the new shares and shows every holder's dilution, value and red flags, with a pre-money comparison. Offline stdlib Python.
---
# Cap Table Round and SAFE Conversion Calculator
You help founders, early employees and small-company finance leads understand what a priced equity round does to their cap table before they sign a term sheet. SAFEs, option pool top-ups and the price per share interact in ways that are easy to get wrong in a spreadsheet: a "10% pool post-money" request quietly lowers the price, several post-money SAFEs dilute each other's holders but not each other, and a discount can beat a cap. You build the model, explain it in plain language and point out what to negotiate or check with a lawyer.
You work only with the numbers the user gives you, on their machine. You never present the model as legal, tax or investment advice, and you tell the user that the signed SAFEs, the term sheet and the closing cap table prepared by their lawyer decide the real numbers.
## Files in this skill
- `scripts/captable_round.py` - the calculator: reads a cap table CSV and a round JSON, solves price per share, SAFE conversions and pool top-up together, prints before/after fully diluted tables, SAFE conversion details and warnings; `--compare 10000000,12000000` adds a pre-money comparison, `--json` for tooling, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/cap-table-math.md` - the formulas: fully diluted shares, price per share, post-money and pre-money SAFE conversion, discount vs cap, the option pool shuffle, rounding
- `references/term-sheet-checks.md` - what to check and negotiate: pool size and timing, SAFE stacking, MFN and pro rata side letters, liquidation preference basics, questions for your lawyer
- `templates/round-summary.md` - the summary you hand back to the founders
- `examples/cap_table.csv`, `examples/round.json` - a fictional two-founder company raising 3M at 12M pre-money with three SAFEs and a 10% post-money pool target
## Workflow
### 1. Collect the inputs
Ask for:
- The current fully diluted cap table: every holder of common and preferred shares, granted options (vested or not), and the unissued pool. Warrants and convertible notes too, if any (treat notes like SAFEs with a cap/discount and add accrued interest to the amount).
- Every SAFE: holder, amount, valuation cap, discount, and whether it is a post-money or pre-money SAFE (the document title says "Post-Money Valuation Cap" for the current standard). Ask about MFN and pro rata side letters.
- The proposed round: pre-money valuation, new money, and the option pool requirement (for example "unissued pool equal to 10% post-money").
If something is missing, ask; do not guess the SAFE type or the pool definition.
### 2. Build the input files
Write `cap_table.csv` with columns `holder,class,shares` (class: common, preferred, options, pool) and `round.json` with `pre_money`, `new_money`, optional `pool_target_post` as a fraction (0.10, not 10), optional `investor_name`, and `safes` (`holder`, `amount`, optional `cap`, optional `discount` as a fraction, `type` "post" or "pre").
### 3. Run the model
```
python3 scripts/captable_round.py examples/cap_table.csv examples/round.json
python3 scripts/captable_round.py cap_table.csv round.json --compare 10000000,12000000,15000000
python3 scripts/captable_round.py cap_table.csv round.json --json > round_model.json
python3 scripts/captable_round.py --self-test
```
Exit 0 = no warnings, 1 = warnings to discuss, 2 = bad input. Without a shell, follow `references/cap-table-math.md` step by step and show your working; iterate the price and pool top-up two or three times until they stop changing.
### 4. Explain the result
- Lead with four numbers: price per share, post-money valuation, new investor ownership, and founders' combined ownership after the round.
- Explain each SAFE: which term won (cap or discount), the effective price, and the ownership it buys.
- Explain the pool shuffle in one sentence: the top-up is counted pre-money, so it lowers the price and is paid for by existing holders. Show its cost in percentage points.
- Use the comparison table to show how pre-money, pool size or a smaller raise move founder ownership. Suggest specific levers (a smaller pool sized to a real hiring plan, pool counted post-money, a higher pre-money, a smaller raise).
### 5. Flag what to check
Go through every warning the script prints and `references/term-sheet-checks.md`. Always mention: verify SAFE types and caps against the signed documents, confirm how the investor defines the pool, ask about MFN and pro rata rights, and ask the lawyer for the pro forma closing cap table to compare against this model.
### 6. Hand back the summary
Fill `templates/round-summary.md`: headline numbers, before/after table, SAFE conversions, pool shuffle cost, comparison, warnings, negotiation points and open questions.
## Rules
- Shares are whole numbers: the script rounds SAFE and investor shares down and the pool top-up up, so totals can differ from the headline valuation by a few currency units; say so if asked.
- Percentages are of the fully diluted total (all shares, granted options and the unissued pool).
- Never tell the user a round is "good" or "bad"; show the trade-offs and the questions to ask.
- Keep the user's numbers private; do not upload the cap table anywhere.
FILE:references/cap-table-math.md
# Cap table math used by captable_round.py
## Fully diluted shares
Fully diluted (FD) = issued common + issued preferred + granted options (vested and unvested) + unissued option pool (+ warrants). Ownership percentages in the report are always of the FD total.
## Priced round
- Pre-money FD = existing FD + SAFE conversion shares + option pool top-up.
- Price per share = pre-money valuation / pre-money FD.
- New investor shares = new money / price per share (rounded down).
- Post-money FD = pre-money FD + new investor shares; post-money valuation = post-money FD x price.
Because the SAFE shares and the pool top-up are inside the pre-money FD, the price depends on them and they depend on the price. The script solves this by fixed-point iteration (it converges in a few rounds) and then rounds to whole shares.
## Option pool shuffle
If the investor asks for an unissued pool equal to T% of the post-money FD:
- Top-up = max(0, T x post-money FD - existing unissued pool).
- The top-up is part of the pre-money FD, so it lowers the price per share. The new investor still gets new money / post-money valuation; existing holders carry the whole dilution of the top-up.
- Cost to existing holders, in percentage points of pre-money ownership = top-up / pre-money FD.
## Post-money SAFE (current standard)
The holder gets ownership = amount / post-money valuation cap, measured against the "company capitalization" just before the round: existing FD (including the unissued pool, excluding the new pool top-up) plus the shares of all converting post-money SAFEs.
- With several post-money SAFEs with fractions f1..fn (fi = amount / cap) and existing FD C, total SAFE shares S = C x f / (1 - f) where f = sum fi; each SAFE gets fi x (C + S).
- Cap price = cap / (C + S).
- Post-money SAFEs dilute the founders and earlier holders, not each other.
## Pre-money SAFE (older form)
Cap price = cap / existing FD before any SAFE converts. Each later SAFE dilutes the earlier ones.
## Discount and "better of"
Discount price = round price x (1 - discount). A SAFE with both terms converts at the lower of cap price and discount price, so it gets more shares. A SAFE with neither converts at the round price (check for an MFN clause instead).
## Convertible notes
Treat a note like a SAFE: amount = principal + accrued interest to the conversion date, with its cap and discount. Note maturity and repayment terms are not modeled.
## Rounding
SAFE and investor shares are rounded down; the pool top-up is rounded up so the pool target is met. Real closing sets may round differently by a few shares.
## Worked example (examples/)
Existing FD 9,000,000 (8,000,000 founders, 700,000 granted options, 300,000 unissued pool). Raise 3,000,000 at 12,000,000 pre-money with a 10% post-money pool target and three post-money SAFEs. Result: price about 1.1104, pool top-up 1,050,912, investor 20.00%, SAFEs 5.60% together, founders from 88.89% to 59.22%.
FILE:references/term-sheet-checks.md
# Term sheet and SAFE checks to raise with founders
## Option pool
- Size the pool to a real 12-18 month hiring plan (roles x typical grant) instead of a round percentage; a smaller, justified pool is the most common negotiation win.
- Ask whether the pool target is measured pre-money or post-money, and whether already granted options count toward it.
- Compare "pool counted pre-money" vs "pool counted post-money" with the script (set the target lower or 0 and add the pool to the investor side) to show the difference in founder ownership.
## SAFEs
- Confirm every SAFE's type (post-money or pre-money), cap, discount and amount from the signed document, not from memory or a spreadsheet.
- Post-money SAFEs stack: every new post-money SAFE dilutes the founders by roughly amount / cap. Add them up before raising more on SAFEs.
- MFN clauses let an uncapped SAFE take better terms from a later SAFE; check whether any MFN was triggered.
- Pro rata side letters let SAFE holders buy into this round; their money usually comes out of the round size, so confirm the allocation with the lead.
## Round terms that change outcomes but not this model
- Liquidation preference (1x non-participating is the common seed standard; participating or more than 1x is investor-friendly).
- Anti-dilution protection (broad-based weighted average is common; full ratchet is harsh).
- Board seats, protective provisions, founder vesting reset, and information rights.
The script does not model exit waterfalls; say so and suggest a waterfall model if the user asks what they receive at a given exit value.
## Questions for the lawyer
1. Please share the pro forma closing cap table so we can compare it with our model.
2. Which SAFEs and notes convert, and at what price did you use for each?
3. How is the option pool target defined, and is it measured on a fully diluted basis including the SAFEs?
4. Are there MFN, pro rata or side letter rights we need to honor in this round?
5. Are there any warrants, promised options or advisor grants not yet on the cap table?
## Red flags to mention
- SAFEs converting into more than about 20% of the company.
- A single round selling more than about 25-30% of the company.
- Founders together below 50% after a seed round.
- A cap table with no pool at all, or a pool far larger than the hiring plan.
- Numbers in the term sheet that do not match the model by more than rounding.
FILE:templates/round-summary.md
# Round summary: {{company}} - {{round_name}}
Prepared {{date}} from the cap table and SAFE terms you shared. Model only: the signed documents and the lawyer's closing cap table decide the real numbers.
## Headline
- Raise: {{new_money}} at {{pre_money}} pre-money ({{post_money}} post-money)
- Price per share: {{price_per_share}}
- New investors own: {{investor_pct}}
- Founders together: {{founders_before_pct}} before -> {{founders_after_pct}} after
- Option pool after the round: {{pool_after_pct}} unissued (top-up {{pool_top_up}} shares)
## SAFE conversions
| SAFE | type | amount | cap | discount | term that won | shares | ownership |
|---|---|---:|---:|---:|---|---:|---:|
| {{safe}} | {{type}} | {{amount}} | {{cap}} | {{discount}} | {{cap_or_discount}} | {{shares}} | {{pct}} |
## Cap table before and after
(paste the table from captable_round.py)
## What the option pool shuffle costs
{{one sentence: top-up counted pre-money, cost in percentage points, who pays}}
## Scenarios
| pre-money | price/share | new investors % | founders % |
|---:|---:|---:|---:|
| {{pre}} | {{price}} | {{inv_pct}} | {{founders_pct}} |
## Warnings from the model
- {{warning}}
## Negotiation points
1. {{for example: size the pool to the 18-month hiring plan (about X%) instead of 10%}}
2. {{...}}
## Open questions for the lawyer and investors
- {{question}}
FILE:examples/cap_table.csv
holder,class,shares
Founder A (CEO),common,4200000
Founder B (CTO),common,3800000
Early employee grants,options,600000
Advisor grants,options,100000
Unissued option pool,pool,300000
FILE:examples/round.json
{
"investor_name": "Seed lead and syndicate",
"pre_money": 12000000,
"new_money": 3000000,
"pool_target_post": 0.10,
"safes": [
{"holder": "Angel SAFE 2024", "amount": 250000, "cap": 6000000, "discount": 0.2, "type": "post"},
{"holder": "Accelerator SAFE", "amount": 125000, "cap": 5000000, "type": "post"},
{"holder": "Friends and family note-style SAFE", "amount": 100000, "discount": 0.15, "type": "post"}
]
}
FILE:scripts/captable_round.py
#!/usr/bin/env python3
"""captable_round.py - model a priced equity round on a startup cap table.
Converts post-money and pre-money SAFEs (valuation cap and/or discount), tops up the
option pool to a post-money target (the "option pool shuffle"), prices the new
shares, and prints the pre-round and post-round fully diluted cap table, the price
per share, each holder's dilution and sanity warnings. Standard library only.
Usage:
python3 captable_round.py CAP_TABLE.csv ROUND.json [--json] [--compare PRE1,PRE2,...]
python3 captable_round.py --self-test
CAP_TABLE.csv columns: holder,class,shares (class: common, preferred, options, pool)
- "options" = granted options (outstanding), "pool" = unissued option pool.
ROUND.json keys:
pre_money (number, required), new_money (number, required),
pool_target_post (fraction 0-1, optional, e.g. 0.10), investor_name (optional),
safes: [{"holder", "amount", "cap" (optional), "discount" (fraction, optional),
"type": "post" | "pre" (default "post")}]
Exit codes: 0 ok, 1 ok with warnings, 2 bad input.
This is a model for planning and negotiation. Lawyers and the signed documents decide the real numbers.
"""
import csv, json, math, sys
CLASSES = {"common", "preferred", "options", "pool"}
class InputError(Exception):
pass
def load_cap_table(path):
rows = []
with open(path, newline="", encoding="utf-8") as f:
r = csv.DictReader(f)
need = {"holder", "class", "shares"}
if not r.fieldnames or not need.issubset({h.strip() for h in r.fieldnames}):
raise InputError("cap table needs columns holder,class,shares")
for i, row in enumerate(r, start=2):
row = {k.strip(): (v or "").strip() for k, v in row.items()}
if not row["holder"] and not row["shares"]:
continue
cls = row["class"].lower()
if cls not in CLASSES:
raise InputError("line %d: class must be one of %s" % (i, ", ".join(sorted(CLASSES))))
try:
sh = int(row["shares"].replace(",", "").replace("_", ""))
except ValueError:
raise InputError("line %d: shares must be a whole number" % i)
if sh < 0:
raise InputError("line %d: negative shares" % i)
rows.append({"holder": row["holder"] or "(unnamed)", "class": cls, "shares": sh})
if not rows:
raise InputError("cap table is empty")
return rows
def validate_round(rd):
for k in ("pre_money", "new_money"):
if not isinstance(rd.get(k), (int, float)) or rd[k] <= 0:
raise InputError("round.%s must be a positive number" % k)
t = rd.get("pool_target_post", 0) or 0
if not 0 <= t < 0.5:
raise InputError("pool_target_post must be a fraction between 0 and 0.5 (e.g. 0.10)")
for s in rd.get("safes", []) or []:
if not isinstance(s.get("amount"), (int, float)) or s["amount"] <= 0:
raise InputError("every SAFE needs a positive amount (%s)" % s.get("holder"))
if s.get("cap") is not None and s["cap"] <= 0:
raise InputError("SAFE cap must be positive (%s)" % s.get("holder"))
d = s.get("discount") or 0
if not 0 <= d < 1:
raise InputError("SAFE discount must be a fraction like 0.2 (%s)" % s.get("holder"))
if s.get("type", "post") not in ("post", "pre"):
raise InputError("SAFE type must be 'post' or 'pre' (%s)" % s.get("holder"))
def model(rows, rd, iterations=500):
"""Fixed-point solve for price, SAFE conversion shares and pool top-up."""
validate_round(rd)
safes = rd.get("safes", []) or []
C = sum(r["shares"] for r in rows) # pre-round fully diluted, before SAFEs
unissued = sum(r["shares"] for r in rows if r["class"] == "pool")
target = rd.get("pool_target_post", 0) or 0
pre_money, new_money = float(rd["pre_money"]), float(rd["new_money"])
safe_sh = [0.0] * len(safes)
pool_top = 0.0
price = pre_money / C
for _ in range(iterations):
S = sum(safe_sh)
pre_fd = C + S + pool_top
price = pre_money / pre_fd
new_sh = new_money / price
post = pre_fd + new_sh
pool_top_n = max(0.0, target * post - unissued) if target else 0.0
S_post = sum(sh for sh, s in zip(safe_sh, safes) if s.get("type", "post") == "post")
new_safe = []
for s in safes:
prices = []
if s.get("cap"):
if s.get("type", "post") == "post":
# post-money SAFE: capitalization includes all converting post-money SAFEs (not the new money or pool top-up)
prices.append(s["cap"] / (C + S_post))
else:
prices.append(s["cap"] / C)
if s.get("discount"):
prices.append(price * (1 - s["discount"]))
if not prices:
prices.append(price) # uncapped, no discount: converts at the round price
new_safe.append(s["amount"] / min(prices))
delta = abs(pool_top_n - pool_top) + sum(abs(a - b) for a, b in zip(new_safe, safe_sh))
safe_sh, pool_top = new_safe, pool_top_n
if delta < 1e-6:
break
# final integer shares (round down, like most closing sets)
safe_int = [math.floor(x) for x in safe_sh]
pool_int = math.ceil(pool_top) if pool_top > 0 else 0
pre_fd = C + sum(safe_int) + pool_int
price = pre_money / pre_fd
new_int = math.floor(new_money / price)
post = pre_fd + new_int
conv = []
for s, sh in zip(safes, safe_int):
conv.append({"holder": s.get("holder", "SAFE"), "amount": s["amount"], "type": s.get("type", "post"),
"cap": s.get("cap"), "discount": s.get("discount"), "shares": sh,
"effective_price": round(s["amount"] / sh, 6) if sh else None})
return {"price_per_share": price, "pre_round_fd_before_safes": C, "pre_money_fd": pre_fd,
"safe_conversions": conv, "pool_top_up": pool_int, "new_money_shares": new_int,
"post_money_fd": post, "post_money_valuation": post * price,
"investor": rd.get("investor_name", "New investors")}
def tables(rows, rd, res):
post = res["post_money_fd"]
C = res["pre_round_fd_before_safes"]
out = []
for r in rows:
out.append({"holder": r["holder"], "class": r["class"], "before": r["shares"], "after": r["shares"]})
if res["pool_top_up"]:
out.append({"holder": "Option pool top-up", "class": "pool", "before": 0, "after": res["pool_top_up"]})
for c in res["safe_conversions"]:
out.append({"holder": c["holder"] + " (SAFE)", "class": "preferred", "before": 0, "after": c["shares"]})
out.append({"holder": res["investor"], "class": "preferred", "before": 0, "after": res["new_money_shares"]})
for o in out:
o["pct_before"] = o["before"] / C if C else 0
o["pct_after"] = o["after"] / post if post else 0
o["value_after"] = o["after"] * res["price_per_share"]
return out
def warnings(rows, rd, res, tab):
w = []
post = res["post_money_fd"]
safe_pct = sum(c["shares"] for c in res["safe_conversions"]) / post
inv_pct = res["new_money_shares"] / post
if safe_pct > 0.20:
w.append("SAFEs convert into %.1f%% of the company: more than 20%% is a lot of dilution for one round." % (100 * safe_pct))
if inv_pct > 0.30:
w.append("New investors get %.1f%% post-money; above about 25-30%% in one round can make later rounds hard." % (100 * inv_pct))
for c in res["safe_conversions"]:
if not c["cap"] and not c["discount"]:
w.append("%s is uncapped with no discount: it converts at the round price; check for an MFN clause." % c["holder"])
if c["effective_price"] and c["effective_price"] > res["price_per_share"] + 1e-9:
w.append("%s converts above the round price (cap higher than the round): check the SAFE terms." % c["holder"])
if res["pool_top_up"]:
pre_cost = res["pool_top_up"] / res["pre_money_fd"]
w.append("Option pool shuffle: the %s-share pool top-up is counted pre-money, so existing holders (not the new investor) absorb %.1f%% of pre-money dilution." % (format(res["pool_top_up"], ","), 100 * pre_cost))
founders = [t for t in tab if t["class"] == "common" and t["before"]]
fpct = sum(t["pct_after"] for t in founders)
if founders and fpct < 0.5:
w.append("Common holders together own %.1f%% after the round (below 50%%)." % (100 * fpct))
granted = sum(r["shares"] for r in rows if r["class"] == "options")
if granted == 0 and not any(r["class"] == "pool" for r in rows):
w.append("No options or pool in the cap table: is the employee pool missing?")
if abs(res["post_money_valuation"] - (rd["pre_money"] + rd["new_money"])) / (rd["pre_money"] + rd["new_money"]) > 0.001:
w.append("Post-money value differs from pre-money + new money because of share rounding (%.0f vs %.0f)." % (res["post_money_valuation"], rd["pre_money"] + rd["new_money"]))
return w
def money(x):
return "{:,.0f}".format(x)
def report(rows, rd, res, tab, warns):
L = []
L.append("# Round model: %s raises %s at %s pre-money" % (res["investor"], money(rd["new_money"]), money(rd["pre_money"])))
L.append("")
L.append("Price per share: %.4f | pre-money fully diluted shares: %s | post-money fully diluted shares: %s | post-money valuation: %s" % (
res["price_per_share"], money(res["pre_money_fd"]), money(res["post_money_fd"]), money(res["post_money_valuation"])))
if rd.get("pool_target_post"):
L.append("Option pool target: %.1f%% post-money unissued; top-up %s shares (pre-money)." % (100 * rd["pool_target_post"], money(res["pool_top_up"])))
L.append("")
if res["safe_conversions"]:
L.append("## SAFE conversions")
L.append("| SAFE | type | amount | cap | discount | shares | effective price |")
L.append("|---|---|---:|---:|---:|---:|---:|")
for c in res["safe_conversions"]:
L.append("| %s | %s-money | %s | %s | %s | %s | %.4f |" % (c["holder"], c["type"], money(c["amount"]),
money(c["cap"]) if c["cap"] else "none", ("%d%%" % round(100 * c["discount"])) if c["discount"] else "none",
money(c["shares"]), c["effective_price"] or 0))
L.append("")
L.append("## Cap table before and after (fully diluted)")
L.append("| holder | class | shares before | % before | shares after | % after | value at round price |")
L.append("|---|---|---:|---:|---:|---:|---:|")
for t in tab:
L.append("| %s | %s | %s | %.2f%% | %s | %.2f%% | %s |" % (t["holder"], t["class"], money(t["before"]), 100 * t["pct_before"],
money(t["after"]), 100 * t["pct_after"], money(t["value_after"])))
L.append("| **Total** | | %s | 100.00%% | %s | 100.00%% | %s |" % (money(res["pre_round_fd_before_safes"]), money(res["post_money_fd"]), money(res["post_money_valuation"])))
L.append("")
L.append("## Warnings")
L.extend(["- " + x for x in warns] or ["- none"])
L.append("")
L.append("Model only: the signed SAFEs, term sheet and closing cap table from your lawyer decide the real numbers.")
return "\n".join(L)
def compare(rows, rd, pres):
L = ["## Pre-money comparison", "| pre-money | price/share | new investors % | SAFEs % | pool top-up | common holders % |", "|---:|---:|---:|---:|---:|---:|"]
for p in pres:
r2 = dict(rd, pre_money=p)
res = model(rows, r2)
tab = tables(rows, r2, res)
post = res["post_money_fd"]
L.append("| %s | %.4f | %.2f%% | %.2f%% | %s | %.2f%% |" % (money(p), res["price_per_share"], 100 * res["new_money_shares"] / post,
100 * sum(c["shares"] for c in res["safe_conversions"]) / post, money(res["pool_top_up"]),
100 * sum(t["pct_after"] for t in tab if t["class"] == "common")))
return "\n".join(L)
def self_test():
ok = True
def check(name, cond):
nonlocal ok
print(("PASS " if cond else "FAIL ") + name)
ok = ok and cond
base = [{"holder": "A", "class": "common", "shares": 4_500_000}, {"holder": "B", "class": "common", "shares": 4_500_000},
{"holder": "Pool", "class": "pool", "shares": 1_000_000}]
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000})
check("plain round price = pre-money / FD", abs(r["price_per_share"] - 1.0) < 1e-9)
check("plain round investor shares = new money / price", r["new_money_shares"] == 2_500_000)
check("post-money = pre + new", abs(r["post_money_valuation"] - 12_500_000) < 1)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "pool_target_post": 0.15})
pool_after = 1_000_000 + r["pool_top_up"]
check("pool shuffle hits 15% post-money", abs(pool_after / r["post_money_fd"] - 0.15) < 1e-4)
check("pool shuffle lowers the price", r["price_per_share"] < 1.0)
check("investor still owns new/post-money (20%)", abs(r["new_money_shares"] / r["post_money_fd"] - 0.2) < 1e-4)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "cap": 5_000_000, "type": "post"}]})
c = r["safe_conversions"][0]
check("post-money SAFE owns amount/cap of pre-round capitalization (10%)", abs(c["shares"] / (10_000_000 + c["shares"]) - 0.10) < 1e-6)
check("capped SAFE converts below round price", c["effective_price"] < r["price_per_share"])
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "discount": 0.2}]})
c = r["safe_conversions"][0]
check("discount-only SAFE converts at 80% of round price", abs(c["effective_price"] / r["price_per_share"] - 0.8) < 1e-4)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "cap": 50_000_000, "discount": 0.2}]})
c = r["safe_conversions"][0]
check("cap above round: discount wins", abs(c["effective_price"] / r["price_per_share"] - 0.8) < 1e-4)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "cap": 4_000_000, "type": "pre"}]})
c = r["safe_conversions"][0]
check("pre-money SAFE price = cap / pre-round FD", abs(c["effective_price"] - 0.4) < 1e-3)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000}]})
tab = tables(base, {"pre_money": 10_000_000, "new_money": 2_500_000}, r)
w = warnings(base, {"pre_money": 10_000_000, "new_money": 2_500_000}, r, tab)
check("uncapped SAFE warning", any("uncapped" in x for x in w))
two = {"pre_money": 8_000_000, "new_money": 2_000_000, "safes": [{"holder": "S1", "amount": 300_000, "cap": 6_000_000}, {"holder": "S2", "amount": 600_000, "cap": 6_000_000}]}
r = model(base, two)
s1, s2 = r["safe_conversions"]
check("two post-money SAFEs at same cap: shares proportional to amount", abs(s2["shares"] / s1["shares"] - 2) < 1e-4)
check("two post-money SAFEs together own 15% of capitalization", abs((s1["shares"] + s2["shares"]) / (10_000_000 + s1["shares"] + s2["shares"]) - 0.15) < 1e-5)
tab = tables(base, two, r)
check("post-round table sums to post-money FD", sum(t["after"] for t in tab) == r["post_money_fd"])
for bad, name in (({"pre_money": 0, "new_money": 1}, "zero pre-money rejected"), ({"pre_money": 1, "new_money": 1, "pool_target_post": 15}, "pool target as percent rejected"),
({"pre_money": 1, "new_money": 1, "safes": [{"holder": "x", "amount": 1, "discount": 20}]}, "discount as percent rejected")):
try:
model(base, bad); check(name, False)
except InputError:
check(name, 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 = [a for a in argv if not a.startswith("--")]
pres = None
if "--compare" in argv:
i = argv.index("--compare")
try:
pres = [float(x) for x in argv[i + 1].split(",")]
except (IndexError, ValueError):
print("--compare needs comma-separated pre-money values", file=sys.stderr); return 2
args = [a for a in args if a != argv[i + 1]]
if len(args) != 2:
print(__doc__, file=sys.stderr); return 2
try:
rows = load_cap_table(args[0])
with open(args[1], encoding="utf-8") as f:
rd = json.load(f)
res = model(rows, rd)
except (InputError, OSError, json.JSONDecodeError) as e:
print("input error: %s" % e, file=sys.stderr); return 2
tab = tables(rows, rd, res)
warns = warnings(rows, rd, res, tab)
if "--json" in argv:
print(json.dumps({"round": rd, "result": res, "table": tab, "warnings": warns}, indent=2))
else:
print(report(rows, rd, res, tab, warns))
if pres:
print(); print(compare(rows, rd, pres))
return 1 if warns else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

Photoreal telephoto photograph of about forty emperor penguins pressed into a frosted huddle on Antarctic sea ice in a blizzard, two grey chicks on their parents' feet, snow streaking sideways in blue polar twilight. Step 1 of the Emperor Penguins Huddling Through an Antarctic Blizzard workflow.
A photorealistic wide telephoto photograph of an emperor penguin colony huddling together on the Antarctic sea ice during a blizzard in the soft blue light of the polar winter twilight. About forty adult emperor penguins stand pressed tightly in a dense, rounded huddle that fills the middle of the frame, their backs and heads dusted with snow and frost, black backs and the bright golden-yellow ear patches showing between them; a few birds on the windward right edge stand with heads tucked down against the wind. In the left foreground, two fluffy grey chicks stand on the feet of their parents, half hidden in the brood pouch. Wind-driven snow streaks horizontally from right to left across the whole scene, softening the background into a pale blue-grey haze where a faint line of ice cliffs is barely visible. The low sun is hidden behind the storm, giving a faint pink-violet glow on the horizon at the far left. Shot like a National Geographic wildlife photograph: 600 mm telephoto compression, crisp detail on the feathers and frost in the front row, natural cold color balance, fine blowing-snow motion streaks, realistic textures of wind-packed snow at their feet. No people, no buildings, no text. Landscape 16:9.

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.

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.
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 engineering3 teams. You turn one upcoming peak season (holiday sales, a big launch, a4 ticket drop, tax deadline week) into a practical code freeze and peak5 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 the7 team rolls back fast if something breaks while traffic is highest.89event:10 name: "${event_name:Black Friday to Cyber Monday sales weekend}"...+134 more lines
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.
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.

Photoreal wide sunset landscape of a vast starling murmuration twisting like a ribbon above a golden winter reed bed and a winding mirror-like water channel, with a glowing orange horizon and bare trees. Step 1 of the Starling Murmuration over a Winter Reed Bed at Sunset workflow.
A photorealistic wide landscape photograph of a vast starling murmuration over a winter reed bed at sunset, 16:9, captured as a single still moment that is ready to be animated. Scene: tens of thousands of European starlings form one huge, dense, flowing cloud shaped like a twisting ribbon that folds back on itself in the upper center of the sky, darker where the birds bunch together and thinning to scattered specks at the edges. Below, a flat wetland of tall pale golden reeds and feathery seed heads stretches to the horizon, cut by a still, winding channel of water that mirrors the sky and a dark silhouette of the flock. A line of bare winter trees stands on the far left of the horizon. Light and sky: the sun has just set behind the reeds at the right, leaving a band of glowing orange and peach above the horizon that fades upward into soft lavender and cool blue; thin wispy clouds catch pink light. Camera: shot from a low riverbank with a 35 mm lens, deep focus, the reed tops sharp in the foreground, natural colors, fine detail in each bird speck, calm atmosphere. No people, no buildings, no text.

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.

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.
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