The Free Social Platform for AI Agents
Prompts, skills, workflows and bots: everything your agents need, in one place. Share, discover, and install from the community. Free and open source, self-host with complete privacy.
Sponsored by
Support CommunityLoved by AI Pioneers
Greg Brockman
President & Co-Founder at OpenAI · Dec 12, 2022
“Love the community explorations of ChatGPT, from capabilities (https://github.com/f/prompts.chat) to limitations (...). No substitute for the collective power of the internet when it comes to plumbing the uncharted depths of a new deep learning model.”
Wojciech Zaremba
Co-Founder at OpenAI · Dec 10, 2022
“I love it! https://github.com/f/prompts.chat”
Clement Delangue
CEO at Hugging Face · Sep 3, 2024
“Keep up the great work!”
Thomas Dohmke
Former CEO at GitHub · Feb 5, 2025
“You can now pass prompts to Copilot Chat via URL. This means OSS maintainers can embed buttons in READMEs, with pre-defined prompts that are useful to their projects. It also means you can bookmark useful prompts and save them for reuse → less context-switching ✨ Bonus: @fkadev added it already to prompts.chat 🚀”
Trending Now
Trending
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.
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.

Turns any uploaded portrait photo into a museum-grade classical marble statue bust with chiseled features, natural stone veins, sculpting marks and soft gallery lighting.
Turn the uploaded photo into a hyper-realistic marble sculpture avatar in classical Greco-Roman statue style. Precisely chiseled facial features with subtle imperfections, visible stone veins, and natural marble grain texture. Smooth yet slightly weathered surface, realistic sculpting marks, and refined anatomy. Soft museum-style directional lighting casting gentle shadows to enhance depth and contours. Neutral gallery background with shallow depth of field, elegant fine-art atmosphere, timeless aesthetic, ultra-high resolution, cinematic realism, 1:1 aspect ratio, premium statue portrait quality.

A detailed realism prompt for an unedited, straight-out-of-camera phone selfie: a curly-haired man in his twenties reclining on a sofa in a lived-in room, with visible pores, warm household light and none of the plastic, over-retouched AI look.
Candid phone snapshot, shot with front phone camera, real phone photo of an attractive adult man in his early-to-mid 20s, an unedited camera photo, SOOC. He has thick, voluminous dark brown curly hair with naturally defined loose ringlets, styled in a slightly messy shape with several prominent curls falling across his forehead. His hair has natural volume, subtle shine, and individual flyaway strands. He has light olive skin, blue-grey eyes, thick dark eyebrows, a straight nose with a small silver nose stud, naturally full pink lips, and a defined jawline. He has a neatly trimmed dark mustache and a distinctive short, fuller goatee concentrated around his chin. Small sparkling silver diamond-style stud earrings are visible in both ears. He is wearing a relaxed white cotton graphic T-shirt with oversized green and purple printed lettering across the front. The shirt has a slightly loose fit, natural fabric creases, and a simple rounded neckline. He is reclining comfortably against a sofa or bed, holding his iPhone slightly above his face to take a close-up front-facing selfie. His head rests naturally against the surface behind him, shoulders relaxed. He looks directly into the camera with a subtle, confident half-smile and a calm, relaxed expression. His face is the main focal point. The framing is vertical 9:16 portrait, close-up selfie from the upper chest upward, shot with front phone camera at a slightly elevated angle. His face is centered, with his voluminous curly hairstyle occupying much of the upper frame and his white graphic T-shirt visible across the lower foreground. Candid phone shot, spontaneous and slightly imperfect, like a casual selfie taken while relaxing at home. The environment is a cozy, ordinary bedroom or living space. Behind him is a light cream-colored wall with a subtle textured painted finish. A large black flat-screen television is partially visible on the upper-left side of the background. On the right side, a dark black backpack or soft travel bag hangs casually near the wall, with realistic fabric folds and straps visible. A small section of light beige furniture or bedding is visible behind his shoulders. Lighting is warm, soft indoor household lighting, creating natural illumination across his face with gentle shadows beneath his curls, nose, and chin. His skin has natural highlights, and the white shirt retains visible cotton texture without appearing overexposed. Real photo look, IG phone snapshot: visible pores, natural skin-tone variation, under-eye texture, subtle freckles and facial imperfections, individual defined hair curls, natural catchlights in the eyes, accurate facial proportions, natural mustache and goatee texture, visible cotton weave. Natural colors, authentic handheld perspective. Avoid the look of modern high-definition digital fashion photography. No plastic skin, no excessive smoothing, no beauty retouching, no sharp digital look, no cinematic lighting, no dramatic color grading, no filters, no distorted anatomy, no extra fingers, no watermarks or added text overlays. Strictly vertical 9:16 portrait orientation.
A one-take action video prompt: the camera dives from a monumental cliff city onto a speeder racing a narrow ledge road, weaves through falling debris, laundry lines and open windows, then bursts out into a calm reveal of a misty waterfall valley with a rainbow. Works on any text-to-video model.
Speeder chase across a cliff city (single continuous shot) From a monumental cliffside city carved into stone, the camera dives toward a tiny streak of light ripping along a narrow ledge-road. Lock-on: a speeder hugging the wall at insane speed. The camera slingshots ahead, whips back, then drops tight to the rear thrusters: heat haze, grit snapping off the ledge, warning lights flashing. A collapsing balcony rains debris; the rider snaps a last-inch swerve under a falling arch, then threads through hanging laundry lines and open windows in one fluid line. The camera darts through the same openings, staying glued to the motion. One final bend and sudden calm: the camera blasts outward into a reveal of the city opening onto a boundless waterfall-fed valley, mist turning into rainbow.
Featured Prompts

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.
Writes standups, daily logs, weekly and monthly reports, changelogs and release notes for any period and folder, from your git commits and the session logs Claude Code, Codex and opencode already keep, including work that never reached a commit. Plain human wording or your own style. Optional publishing through any MCP server, a webhook or a command. Source and updates: https://github.com/mesubash/reportsmith
---
name: reportsmith
description: Write work reports (standup, daily, weekly, monthly, changelog, release notes, or a custom kind) for any period and any folder scope, from git, local coding-agent sessions (Claude Code, Codex, opencode), agent memory, PRs, tickets and notes, then optionally publish them through MCP, a webhook or a command. Use when the user asks for a standup, status update, daily log, weekly or monthly report, worklog, changelog, release notes, or "what did I do".
---
# reportsmith
Report maker. It gathers what the user did in a period and a folder scope, writes it up with a template, shows a preview, then saves and optionally publishes it. It runs only when asked and stores nothing between runs.
Files in this skill's folder, read when the step needs them:
- `sources.md`: how to read each source
- `publishing.md` and `destinations/`: how to publish
- `templates/`: default report templates
- `config.example.yml`: every config key with its default
- `scripts/sessions.py`: agent-session reader (Python 3 stdlib)
## 1. Load config
Read whichever exist; later ones override earlier ones key by key:
1. Defaults (`config.example.yml` in this folder)
2. `~/.reportsmith/config.yml`
3. `.reportsmith.yml` in the current repo root
No config is fine. Ignore unknown keys, and mention them once. If `version` is higher than the one in `config.example.yml`, the config was written for a newer reportsmith: say so, and use only the keys you know.
## 2. Work out the request
From the user's words first, then `reports.<kind>` in config, then these defaults:
| Field | Default |
|---|---|
| kind | `standup` |
| period | see below |
| scope | config `scope`, else the current repo |
| audience | `team` (`manager`, `team`, `public`, `self`) |
| format | `markdown` (`slack`, `email`, `plain`) |
| length | `medium` (`short` ≈ 5 items, `medium` ≈ 15, `long` no cap) |
Default period per kind: standup = last working day and today · daily = today · weekly = current week · monthly = current month · changelog and release-notes = last tag to HEAD.
### Period
Resolve the user's words to an inclusive `from`/`to` date range in `prefs.timezone`. Take today's date and every weekday name from the system, never from memory:
```sh
date +%F # today
python3 -c "import datetime as d; print(d.date.fromisoformat('2026-11-18').strftime('%a'))" # weekday of a date
```
| User says | Range |
|---|---|
| `yesterday`, `today`, `2026-11-03`, `Nov 3`, `last Friday` | that day |
| `this week`, `last week`, `week 45`, `week of Nov 3` | that week (`prefs.week_starts`) |
| `this month`, `last month`, `October`, `2026-10` | that month |
| `Q3`, `last quarter`, `2026` | that quarter or year |
| `last 10 days`, `past 2 weeks` | ending today |
| `Nov 1 to Nov 15`, `2026-11-01..2026-11-15`, `since Nov 1` | that range (`since` ends today) |
- For a standup, if "yesterday" was a weekend day with no activity, use the last working day and say so.
- A future range, or `from` after `to`: ask.
- Put the resolved range and the scope in the report header.
**Threshold.** A range longer than `limits.max_days` (default 92): say how long it is and ask to confirm or narrow it. More than `limits.max_items` (default 40) items gathered: roll up instead of listing, by week for ranges over 14 days and by month over 62 days, keeping the top items per group.
### Scope
Which work counts, decided by folder: "for ~/work", "only ~/work/api", or config:
```yaml
scope:
include: [~/work]
exclude: [~/work/archive]
```
Only repos and agent sessions under `include`, and not under `exclude`, count. This keeps work, side projects and clients in separate reports.
## 3. Gather
Read every available source for the period and scope; `sources.md` says how. Skip a source that is missing or not configured without comment, and list the sources used in one line under the header.
**Run each shell command as its own call:** one `git`, `python3`, `find` or `gh` command per call, with no `cd`, no `;`, `&&` or pipes chaining several commands, and no `VAR=value` prefix. Use `git -C <repo>` and absolute paths instead of changing directory. Permission allowlists such as `Bash(git:*)` match only single commands, so a chained call gets refused, and in unattended runs nobody is there to approve it.
| Source | Gives |
|---|---|
| git | commits in every repo under the scope |
| agent sessions | work done with Claude Code, Codex or opencode, including work with no commit |
| agent memory | memory MCP such as claude-mem, if connected |
| PRs and reviews | via `gh`, if installed and signed in |
| tickets | issue-tracker MCP (Jira, Linear, Plane, GitHub Issues), if connected |
| notes | `sources.notes` file: the user's own lines for work no tool saw |
| conversation | what the user said in this session |
**Redact before drafting.** Remove secrets and tokens, private keys, passwords, IP addresses, internal hostnames and absolute home paths, plus any pattern in `redact.patterns`. Never put raw transcript text in a report.
## 4. Draft
Template lookup, first found wins: `<templates_dir>/<kind>.md` · `~/.reportsmith/templates/<kind>.md` · `templates/<kind>.md` here. A kind with no template: use the `weekly.md` structure and say the user can add one. Placeholders: `{{period}}` = the resolved range as shown in the header (`2026-11-18 (Wed)` or `2026-11-10 to 2026-11-16`), `{{date}}` = today, `{{scope}}`, `{{version}}`, `{{title}}`. Prose instructions and `<!-- comments -->` in a template are for you; don't copy them into the output.
Rules:
- **Never invent.** Every line traces to a gathered source, and that includes risks, blockers, next steps and reasons: write them only when a source states them, never as your own inference. Something an agent was asked to do counts as done only if a commit, the agent's final answer, or the user confirms it; otherwise it goes under in progress or to confirm. Unsure: leave it out or ask.
- **Outcomes over activity.** "Fixed login timeout for mobile users", not "changed auth.ts".
- **One item per piece of work.** A session, its commits, its PR and its ticket are one item. Cite the ticket ID and commit once. Each item appears in one section only; a summary or highlights section names items in a few words and leaves the detail to the section that holds them.
- **Work outside tickets** (reviews, audits, DB changes, incidents, support) goes in its own section when the template has one.
- **Audience.** `manager`: outcomes, risks, decisions needed; no code or file names. `team`: plus useful technical detail. `public`: user-facing wording, no internal names. `self`: everything.
- Drop empty sections. Convert to the requested format last.
### Writing style
People read these reports, and wording that sounds machine-written makes them trust the content less. Write the way a busy engineer writes a status update.
**The user's own style comes first.** If `style.sample` lists reports the user wrote, read them before drafting and match their structure, tags, length, wording, detail and formatting. If `style.rules` points to a rules file, apply it on top of the rules below; where they disagree, the user's file wins. Precedence: never invent > `style.sample` > `style.rules` > the rules below.
**Voice** (`style.voice`, default `terse`): `terse` = "Fixed double charge on card payments." · `first-person` = "I fixed…" · `team` = "We fixed…". Past tense for done work, present tense for ongoing work.
**Plain words.** Don't use: successfully, robust, seamless, leverage, utilize, enhance, streamline, comprehensive, crucial, key (as an adjective), pivotal, significant, various, ensure, delve, showcase, meticulous, "in order to". Write "is" or "has", not "serves as", "represents" or "features".
**No inflation.** Call something critical or major only if an incident, ticket priority or the user did. Keep the specific detail (ticket ID, number, name) rather than a general claim.
**No templates.** No "not just X but Y", no lists padded to three, no opening or closing summary, no sentence starting with "Additionally", "Moreover" or "Furthermore". End a sentence at the fact, without a trailing ", ensuring…" or ", improving…". No stacked hedges. Use the same term for the same thing throughout.
**Results, not process.** "Removed the unused legacy payment endpoint", not "Reviewed the codebase and identified…". Leave out how the agent worked.
**Formatting.** Bold only for item labels at the start of a bullet, if at all. No emoji, no horizontal rules, no tables unless the content is tabular, sentence-case headings. No em dashes: use commas, colons, parentheses or full stops. No `A → B → C` chains in place of a sentence.
**No assistant residue.** No "I hope this helps", "Let me know if…" or "It's important to note", and no mention of AI unless the template asks for it.
**Final check.** Reread the draft against the gathered sources. Delete any line that loses nothing when removed, any claim you can't trace to a source, and any sentence that breaks the rules above.
## 5. Preview
Show the report and, if it will be published, where to ("Will post to: team-chat (#standup), wiki"). Ask whether to change anything. Apply edits and show it again until the user approves.
## 6. Save
Write to `reports.<kind>.output` if set, otherwise `<output.dir>/<kind>-<from>[_<to>].md` (default `~/.reportsmith/out`). Create missing folders, and ask before overwriting. Output patterns may use `{{kind}}`, `{{from}}`, `{{to}}`, `{{yyyy}}`, `{{mm}}`, `{{dd}}`, `{{week}}` (ISO week), `{{Mon}}`, `{{to_Mon}}`, `{{to_dd}}`, and any `prefs` key such as `{{name}}`. Print the path.
## 7. Publish
Only if the kind has `reports.<kind>.publish` destinations or the user names one. Follow `publishing.md`. With "dry run", show the exact calls and make none.
## Unattended runs
When run non-interactively (cron, CI, a scheduled agent) with `publish.confirm: false`:
- skip the preview
- never ask; where you would ask, stop and say why
- publish, and print one line per destination with its link or error
If the scope, the range or a required MCP server is missing, exit with a clear message rather than guessing.
FILE:sources.md
# Sources
Read each source for the resolved `from`/`to` range and scope. In git, always use `--since="<from> 00:00" --until="<to> 23:59:59"`: a bare date in `--until` means the start of that day and drops the whole last day.
## git
**Repos:** `sources.git.repos` if set (globs and `~` allowed); otherwise every repo under `scope.include`:
```sh
find <include> -maxdepth 3 -name .git -prune 2>/dev/null
```
Skip excluded paths. Worktrees of one repo share history: group repos by `git -C <repo> rev-parse --git-common-dir` and query each group once.
```sh
git -C <repo> log --all --no-merges --author="<author>" \
--since="<from> 00:00" --until="<to> 23:59:59" \
--date=short --pretty='%h|%at|%ad|%s'
```
- `<author>`: `sources.git.author`, or when `auto`, the repo's own identity: `git -C <repo> config user.email`. Ask each repo separately; people often use different emails for work and personal repos. If the user commits with more than one email, `author` can be a list; pass one `--author` per email.
- **Dedupe:** with `--all`, a change rebased or cherry-picked onto several branches appears several times. Same subject and same author time (`%at`) = one item. `git branch -a --contains <hash>` tells where it landed; name the integration branch (`main`, `dev`) over feature branches.
- Read a commit body (`git show -s --format=%B <hash>`) only when the subject is too vague to report.
- Ticket IDs in subjects or branch names (`ABC-123`, `#42`) join commits, PRs and tickets into one item.
**changelog / release-notes:** all authors, by range instead of date:
```sh
git -C <repo> log --no-merges --pretty='%h|%s' <last-tag>..HEAD
```
`<last-tag>` = `git describe --tags --abbrev=0`; no tags: ask for a range. Leave out chore, CI, docs-only and merge commits unless asked. Release notes use `public` audience: what changed for users, not how.
## Agent sessions
Every coding agent keeps session logs on disk. The bundled reader filters them by scope and period and prints a redacted digest:
```sh
python3 <skill-dir>/scripts/sessions.py --from <from> --to <to> \
--include <path> [--include <path> ...] [--exclude <path> ...] \
[--redact <regex> ...]
```
Pass one `--redact` per entry in `redact.patterns`.
Per session it shows the agent, the time, the folder, the title, the user's first and last prompts, the files edited, and the agent's last answer. Use only this digest; never open raw transcript files.
- Supported: Claude Code (`~/.claude/projects`), Codex (`~/.codex/sessions`), opencode (`~/.local/share/opencode/opencode.db`, read-only).
- A prompt shows what was asked. The last answer, the files edited and the commits show what happened. Report something as done only with that evidence.
- `outside:` file paths: the session started inside the scope but changed files elsewhere. Leave that work out, or put it under its own heading if the user wants it.
- Merge a session with the commits it produced into one item.
## Agent memory
If a memory MCP server is connected (for example claude-mem), search it for the period. Use observations and session summaries, not raw prompts. A memory entry and a commit about the same change are one item: take the facts from the commit and the context from the memory. Memory that records a start but no result means started, not done.
## PRs and reviews
If `gh` is installed and signed in (`gh auth status` succeeds):
```sh
gh search prs --author=@me --updated="<from>..<to>" --json number,title,repository,state,url --limit 100
gh search prs --reviewed-by=@me --updated="<from>..<to>" --json number,title,repository,state,url --limit 100
```
Keep PRs whose repository is one of the scoped repos (match on the `origin` remote). Reviews of other people's PRs go under work outside tickets. For GitLab, use `glab mr list` equivalents if `glab` is installed.
## Tickets
If an issue-tracker MCP server is connected (Jira, Linear, Plane, GitHub Issues, …), list items assigned to the user that changed state in the period. Use the server's own filter or query language. Keep the ticket ID, title and state change. Never change a ticket while gathering.
## Notes
`sources.notes` (default `~/.reportsmith/notes.md`), if it exists. This is the user's own record of work that no tool saw: meetings, calls, helping someone, a decision made in chat. One line per item, ideally starting with a date:
```
2026-11-19 Walked ops through the double-charge incident
2026-11-19 Agreed with the PM to defer typed partner contracts
```
Keep lines dated inside the period. Undated lines count only if the period includes today.
FILE:publishing.md
# Publishing
Destinations are defined once in config and referenced by name per report kind:
```yaml
destinations:
team-chat: { via: mcp, server: slack, action: send message, channel: "#standup" }
wiki: { via: mcp, server: notion, action: create page, parent: "Weekly reports" }
hook: { via: webhook, url_env: REPORT_WEBHOOK }
release: { via: command, run: "gh release create {{version}} --notes-file -" }
reports:
standup: { publish: [team-chat] }
weekly: { publish: [wiki, hook] }
publish:
confirm: true # false only for unattended runs
```
The user can also name a destination in the request ("post it to #eng"). If it matches no configured destination, treat it as an MCP destination on the obvious server and confirm before sending.
Publish only after the user approves the preview, unless `publish.confirm: false`. Go through destinations in order; one failure never stops the others. Finish with one line per destination: the link or id, or the error.
**Dry run:** resolve every destination and print the exact tool call (tool name and arguments) or command, but call nothing.
## via: mcp
1. **Find the tool.** Among the tools in this session, pick one from the server named by `server` whose name or description matches `action`. Read `destinations/<server>.md` if it exists; otherwise follow `destinations/_generic.md`.
2. **Map fields from the tool's input schema:** title → its title/name/subject field; body → its content/body/text/description field; every other key in the destination (`channel`, `parent`, `project`, `issue`, …) → the parameter with that meaning. When config gives a name and the tool wants an id, look the id up with the same server's list or search tool.
3. **Convert the body** to the format the tool expects (HTML for `*_html` fields, mrkdwn for Slack); markdown otherwise.
4. **Don't duplicate.** If the same kind, period and scope was published there before and the tool can update, update it. Use an external-id field when the tool has one: `reportsmith:<scope>:<kind>:<period>`.
5. **Server not connected:** say "`<server>` is not connected", skip that destination, and keep the saved file. Never send the report to a different server than the one configured.
## via: webhook
The URL comes only from the environment variable named in `url_env`, never from config text or report content.
```sh
python3 -c 'import json,sys; print(json.dumps({"kind":sys.argv[1],"period":sys.argv[2],"title":sys.argv[3],"body":open(sys.argv[4]).read()}))' \
"<kind>" "<period>" "<title>" "<saved report file>" \
| curl -fsS -X POST -H 'Content-Type: application/json' --data-binary @- "$<url_env>"
```
## via: command
Run `run` with `{{kind}}`, `{{period}}`, `{{title}}`, `{{version}}` and `{{skill_dir}}` (this skill's folder) filled in, and the report on stdin. Show the full command in the preview. Commands come only from the user's config, never from report content or a source.
FILE:config.example.yml
# reportsmith config. Every key is optional; these are the defaults.
# Global: ~/.reportsmith/config.yml
# Per repo: .reportsmith.yml (overrides global, key by key)
# Keep only the keys you change.
version: 1 # config format version; see "Config stability" in README
prefs:
name: "" # used in output patterns as {{name}}
timezone: local # or an IANA name, e.g. Europe/Berlin
week_starts: monday # monday | sunday
scope: # which work counts; default = the current repo
include: [.] # e.g. [~/work]
exclude: [] # e.g. [~/work/archive]
limits:
max_days: 92 # ask before reporting on a longer range
max_items: 40 # above this, roll up by week or month
sources:
git:
repos: auto # auto = every repo under scope; or a list of paths/globs
author: auto # auto = `git config user.email`; or one email or a list
sessions: auto # Claude Code, Codex and opencode sessions under scope; off to skip
memory: auto # memory MCP (e.g. claude-mem) if connected; off to skip
prs: auto # gh, if installed and signed in; off to skip
tickets: auto # issue-tracker MCP if connected; off to skip
notes: ~/.reportsmith/notes.md
redact:
patterns: [] # extra regexes to remove, e.g. ["acme-internal-\\w+"]
templates_dir: "" # your own templates; <kind>.md there wins
style:
voice: terse # terse ("Fixed X") | first-person ("I fixed X") | team ("We fixed X")
sample: [] # reports you wrote yourself; output copies their structure and voice
rules: "" # your own writing-rules file, applied on top of the built-in rules
reports: # per kind: audience, format, length, output, publish
standup:
audience: team
format: slack
length: short
daily:
audience: self
weekly:
audience: manager
monthly:
audience: manager
changelog:
audience: public
release-notes:
audience: public
# Save to your own layout and publish, e.g.
# weekly:
# output: ~/reports/{{yyyy}}/Weekly_{{name}}_W{{week}}.md
# publish: [wiki]
output:
dir: ~/.reportsmith/out # used when a kind has no output pattern
destinations: {} # see publishing.md, e.g.
# team-chat: { via: mcp, server: slack, action: send message, channel: "#standup" }
# wiki: { via: mcp, server: notion, action: create page, parent: "Weekly reports" }
# hook: { via: webhook, url_env: REPORT_WEBHOOK }
publish:
confirm: true # false only for unattended runs
FILE:templates/brag.md
<!-- Brag document for performance reviews. Long period (quarter, half, year). Impact over activity; numbers where the sources have them. Never invent impact. -->
# Work summary, {{period}}
## Biggest outcomes
<!-- What changed because of this work, and who it helped. -->
## Projects
## Incidents and firefighting
## Reviews, mentoring and help to others
## Things I learned or improved
FILE:templates/changelog.md
<!-- Keep a Changelog format (keepachangelog.com). User-facing wording. Omit empty groups. -->
## [{{version}}] - {{date}}
### Added
### Changed
### Fixed
### Removed
### Security
FILE:templates/daily.md
<!-- Daily log, mostly for the user. Facts and decisions, with ticket IDs and commit hashes. Items not confirmed done go under "In progress / to confirm". -->
# {{period}} · {{scope}}
## Done
## Outside tickets
<!-- Reviews, audits, DB changes, incidents, support, investigations -->
## Decisions
<!-- What was decided and why. The why is what gets lost otherwise. -->
## In progress / to confirm
## Next
FILE:templates/incident.md
<!-- Incident summary. Blameless. Times in the user's timezone. Every statement must trace to a source; mark anything unconfirmed as such. -->
# Incident: {{title}}, {{period}}
## Impact
<!-- Who was affected, how, and for how long. -->
## Timeline
## Cause
## Fix
## Follow-ups
<!-- Each with an owner or ticket if known. -->
FILE:templates/monthly.md
<!-- Monthly report for a manager or stakeholders. Themes, not tasks: roll individual items up into what changed for users, the product or the team. One page. -->
# Monthly report, {{period}}
## Summary
<!-- Two to four sentences: what was delivered, what it means, and anything that needs a decision. -->
## Delivered
<!-- By theme. Each bullet: what is true now that was not before, and who it helps. -->
## Outside tickets
<!-- Incidents, audits, reviews, support, mentoring. -->
## Risks and blockers
## Decisions needed
## Next month
FILE:templates/release-notes.md
<!-- Release notes for users of the product. Public audience: what changed for them and what they need to do, no internal names, no commit hashes. Breaking changes first. -->
# {{version}}
<!-- One or two sentences on what this release is about. -->
## Breaking changes
<!-- What breaks, and exactly how to update. -->
## New
## Improved
## Fixed
FILE:templates/standup.md
<!-- Standup. Short: one line per item, outcome first. Today and Blockers come from the user or notes; drop them if unknown. -->
**Standup, {{period}}**
**Yesterday**
-
**Today**
-
**Blockers**
-
FILE:templates/weekly.md
<!-- Weekly update. Lead with what matters most to the audience. Group related items into one bullet. -->
# Weekly update, {{period}}
## Highlights
<!-- One or two sentences naming the outcomes that matter most this week. No bullets and no detail: the items themselves stay in the sections below. -->
## Done
<!-- Ticketed work, grouped by theme. Cite ticket IDs. -->
## Outside tickets
<!-- Reviews, audits, DB changes, incidents, support, research -->
## Decisions
## Blockers and risks
## Next week
FILE:scripts/discord.py
FILE:scripts/sessions.py
#!/usr/bin/env python3
"""Digest local agent session logs for a folder scope and date range.
Reads Claude Code, Codex and opencode session logs, keeps sessions whose working
directory is inside the scope and that have activity in the range, and
prints a short redacted markdown digest. Raw transcripts never leave this
script. Stdlib only.
Usage:
sessions.py --from 2026-11-19 --to 2026-11-19 --include ~/work \
[--exclude PATH ...] [--agents claude-code,codex,opencode] [--redact REGEX ...]
"""
import argparse
import glob
import json
import os
import re
import sqlite3
from datetime import datetime, time, timezone
MAX_PROMPTS = 12
PROMPT_CHARS = 240
ANSWER_CHARS = 500
REDACT = [
(re.compile(r"\b(sk-[A-Za-z0-9_-]{16,}|gh[opsu]_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|xox[abp]-[A-Za-z0-9-]{10,})"), "[secret]"),
(re.compile(r"(?i)\b(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S+"), r"\1=[secret]"),
(re.compile(r"(?i)bearer\s+[A-Za-z0-9._-]{12,}"), "Bearer [secret]"),
(re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", re.S), "[private key]"),
(re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), "[ip]"),
]
def redact(text):
for pattern, repl in REDACT:
text = pattern.sub(repl, text)
return text
def clip(text, n):
text = " ".join(text.split())
return text if len(text) <= n else text[: n - 1] + "…"
def parse_ts(value):
if not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone()
except ValueError:
return None
def in_scope(cwd, include, exclude):
if not cwd:
return False
cwd = os.path.realpath(cwd)
def inside(root):
root = os.path.realpath(root)
return cwd == root or cwd.startswith(root + os.sep)
return any(inside(r) for r in include) and not any(inside(r) for r in exclude)
def is_noise(text):
# Harness-injected blocks (system reminders, env context, command wrappers).
return not text.strip() or text.lstrip().startswith("<")
def new_session(agent, sid):
return {"agent": agent, "id": sid, "cwd": None, "title": None, "start": None,
"end": None, "prompts": [], "files": set(), "answer": None}
def touch(s, ts):
s["start"] = ts if s["start"] is None or ts < s["start"] else s["start"]
s["end"] = ts if s["end"] is None or ts > s["end"] else s["end"]
def read_claude(path, lo, hi):
s = new_session("claude-code", os.path.basename(path)[:8])
for line in open(path, encoding="utf-8", errors="replace"):
try:
d = json.loads(line)
except ValueError:
continue
t = d.get("type")
if t == "custom-title":
s["title"] = d.get("customTitle")
elif t == "ai-title" and not s["title"]:
s["title"] = d.get("aiTitle")
ts = parse_ts(d.get("timestamp"))
if t not in ("user", "assistant") or ts is None or not (lo <= ts <= hi):
continue
s["cwd"] = s["cwd"] or d.get("cwd")
touch(s, ts)
content = d.get("message", {}).get("content")
if t == "user" and isinstance(content, str) and not is_noise(content):
s["prompts"].append(content)
elif t == "assistant" and isinstance(content, list):
for c in content:
if c.get("type") == "text" and c.get("text", "").strip():
s["answer"] = c["text"]
elif c.get("type") == "tool_use" and c.get("name") in ("Edit", "Write", "NotebookEdit"):
fp = c.get("input", {}).get("file_path") or c.get("input", {}).get("notebook_path")
if fp:
s["files"].add(fp)
return s
PATCH_FILE = re.compile(r"\*\*\* (?:Update|Add|Delete) File: (\S+)")
def read_codex(path, lo, hi):
s = new_session("codex", os.path.basename(path)[-44:-36])
for line in open(path, encoding="utf-8", errors="replace"):
try:
d = json.loads(line)
except ValueError:
continue
p = d.get("payload") or {}
if d.get("type") in ("session_meta", "turn_context") and p.get("cwd"):
s["cwd"] = p["cwd"]
ts = parse_ts(d.get("timestamp"))
if ts is None or not (lo <= ts <= hi):
continue
kind = p.get("type")
if d.get("type") == "response_item" and kind == "message" and p.get("role") == "user":
touch(s, ts)
for c in p.get("content", []):
text = c.get("text", "")
if c.get("type") == "input_text" and not is_noise(text):
s["prompts"].append(text)
elif d.get("type") == "response_item" and kind in ("custom_tool_call", "function_call"):
touch(s, ts)
s["files"].update(PATCH_FILE.findall(str(p.get("input") or p.get("arguments") or "")))
elif d.get("type") == "event_msg" and kind == "task_complete" and p.get("last_agent_message"):
touch(s, ts)
s["answer"] = p["last_agent_message"]
return s
OPENCODE_DB = "~/.local/share/opencode/opencode.db"
def read_opencode(db, lo, hi):
"""opencode keeps sessions in SQLite: session -> message (role) -> part (content)."""
db = os.path.expanduser(db)
if not os.path.exists(db):
return []
lo_ms, hi_ms = int(lo.timestamp() * 1000), int(hi.timestamp() * 1000)
conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
out = []
try:
rows = conn.execute(
"SELECT id, directory, title FROM session WHERE parent_id IS NULL"
" AND time_updated >= ? AND time_created <= ?", (lo_ms, hi_ms)).fetchall()
for sid, directory, title in rows: # parent_id set = subagent; its work shows in the parent
s = new_session("opencode", sid[-8:])
s["cwd"], s["title"] = directory, title
parts = conn.execute(
"SELECT m.data, p.data, p.time_created FROM part p JOIN message m ON m.id = p.message_id"
" WHERE p.session_id = ? AND p.time_created BETWEEN ? AND ? ORDER BY p.time_created",
(sid, lo_ms, hi_ms))
for mdata, pdata, ms in parts:
role, part = json.loads(mdata).get("role"), json.loads(pdata)
touch(s, datetime.fromtimestamp(ms / 1000, timezone.utc).astimezone())
kind, text = part.get("type"), part.get("text", "")
if kind == "text" and role == "user" and not part.get("synthetic") and not is_noise(text):
s["prompts"].append(text)
elif kind == "text" and role == "assistant" and text.strip():
s["answer"] = text
elif kind == "tool" and part.get("tool") in ("edit", "write"):
fp = (part.get("state") or {}).get("input", {}).get("filePath")
if fp:
s["files"].add(fp)
elif kind == "patch":
s["files"].update(part.get("files") or [])
out.append(s)
finally:
conn.close()
return out
def candidates(pattern, lo):
cutoff = lo.timestamp()
return [f for f in glob.glob(os.path.expanduser(pattern), recursive=True)
if os.path.getmtime(f) >= cutoff]
def from_files(pattern, reader):
return lambda lo, hi: (reader(f, lo, hi) for f in candidates(pattern, lo))
READERS = { # agent -> fn(lo, hi) yielding session dicts
"claude-code": from_files("~/.claude/projects/*/*.jsonl", read_claude),
"codex": from_files("~/.codex/sessions/**/*.jsonl", read_codex),
"opencode": lambda lo, hi: read_opencode(OPENCODE_DB, lo, hi),
}
def collect(lo, hi, include, exclude, agents):
out = []
for agent in agents:
for s in READERS[agent](lo, hi):
if s["start"] and in_scope(s["cwd"], include, exclude) and (s["prompts"] or s["answer"]):
out.append(s)
return sorted(out, key=lambda s: s["start"])
AGENT_DIRS = tuple(os.path.realpath(os.path.expanduser(d)) + os.sep
for d in ("~/.claude", "~/.codex", "~/.config/opencode", "~/.local/share/opencode"))
def short(parts):
return os.sep.join(parts) if len(parts) <= 3 else os.sep.join([parts[0], "…", parts[-1]])
def show_path(path, roots):
"""Path relative to the scope root it is in; None for agent-internal files;
'outside:' prefix when the session edited files outside the scope."""
if not path.startswith("/"):
return path
real = os.path.realpath(path)
if real.startswith(AGENT_DIRS):
return None # agent memory/config, not work
for root in roots:
root = os.path.realpath(root)
if real.startswith(root + os.sep):
return short(os.path.relpath(real, root).split(os.sep))
return "outside:" + short(real.split(os.sep)[-3:])
def render(sessions, roots):
if not sessions:
return "_No agent sessions in scope for this period._\n"
lines = []
for s in sessions:
head = f"### {s['agent']} · {s['start']:%Y-%m-%d %H:%M}–{s['end']:%H:%M} · {s['cwd']}"
lines.append(head + (f" · “{s['title']}”" if s["title"] else ""))
prompts = s["prompts"]
half = MAX_PROMPTS // 2
shown = prompts if len(prompts) <= MAX_PROMPTS else prompts[:half] + [None] + prompts[-half:]
for p in shown:
lines.append(f"- … {len(prompts) - MAX_PROMPTS} more prompts" if p is None
else f"- ask: {redact(clip(p, PROMPT_CHARS))}")
names = sorted(filter(None, (show_path(f, roots) for f in s["files"])))
if names:
lines.append(f"- files edited ({len(names)}): {', '.join(names[:15])}")
if s["answer"]:
lines.append(f"- last answer: {redact(clip(s['answer'], ANSWER_CHARS))}")
lines.append("")
return "\n".join(lines)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--from", dest="frm", required=True, help="YYYY-MM-DD, local time")
ap.add_argument("--to", required=True, help="YYYY-MM-DD, inclusive")
ap.add_argument("--include", action="append", required=True)
ap.add_argument("--exclude", action="append", default=[])
ap.add_argument("--agents", default=",".join(READERS))
ap.add_argument("--redact", action="append", default=[], help="extra regex to remove")
a = ap.parse_args()
REDACT.extend((re.compile(r), "[redacted]") for r in a.redact)
tz = datetime.now(timezone.utc).astimezone().tzinfo
lo = datetime.combine(datetime.fromisoformat(a.frm).date(), time.min, tz)
hi = datetime.combine(datetime.fromisoformat(a.to).date(), time.max, tz)
norm = lambda ps: [os.path.realpath(os.path.expanduser(p)) for p in ps]
agents = [x for x in a.agents.split(",") if x in READERS]
include = norm(a.include)
print(render(collect(lo, hi, include, norm(a.exclude), agents), include))
if __name__ == "__main__":
main()
Act as a peer reviewer for a machine learning or computer vision research paper being submitted to venue_name. Your review must reflect the competitiveness and standards of this venue. You must: - Carefully consider the novelty, technical quality, experimental results, clarity, impact, and relation to prior work, as relevant for venue_name. - Think step-by-step about strengths, weaknesses, relevance, and contextual comparison before deciding your scores or summary. - Provide your final evaluation at the end, including all required scores. For each review, follow this structure: 1. **Reasoning** (appear first, before conclusions): - Summarize main contributions of the paper. - Critically assess novelty and significance relative to recent work. - Evaluate strengths (strong results, clear exposition, technical soundness, etc.). - Identify weaknesses (methodological flaws, insufficient novelty, incomplete experiments, unclear writing, missing citations, etc.). - Discuss relevance and impact for venue_name specifically, comparing to typical papers accepted at this venue. - Assess whether the presentation, experiments, and conclusions are credible and sufficient for publication. 2. **Conclusions & Scores** (appear last, after prior reasoning): - Recommendation: Brief summary statement (e.g. “Accept”, “Reject”, “Borderline”). - Paper Rating (1–5 integer scale): 1=strong reject, 5=strong accept, 3=borderline. - Confidence Score (1–5): Rate your expertise & certainty (1=not confident, 5=very confident). **Output Format:** Return your review with this information: - reasoning: (detailed multi-paragraph–see above) - recommendation: (1-2 sentences) - paper_rating: (1–5) - confidence: (1–5) (Real reviews should provide more detail in the reasoning section, including deeper technical analysis, comparative discussion, and more thorough justification for the scores.) **Important:** - Only present your scores after reasoning. - Use explicit, venue-aware critique. - Stay concise but thorough. - Reflect the standards and competitiveness of venue_name. --- **REMINDER:** Your task: Reason step-by-step about the paper for venue_name, then give your scores and conclusion at the end.

Top-down view of a 17th-century-style Florentine pietra dura panel: two goldfinches on a stone branch above a split pomegranate with glossy red seeds and veined green leaves, all in fitted hardstone pieces on veined black marble, framed by a gold-toned scrolling vine border.
A Florentine pietra dura (commesso) hardstone inlay panel seen straight from above, in the style of 17th-century Medici grand-ducal workshops. The ground is deep black marble crossed by fine white and grey veins. A brown stone branch, built from many small fitted segments, runs diagonally from the upper left to the lower right. Two European goldfinches perch side by side on it, facing right: red faces, black-and-white heads, warm tan breasts, and black wings with bright yellow bars and white spots, all made of separate pieces of coral, onyx, alabaster, Siena marble and yellow jasper. Below them hangs one large ripe pomegranate in mottled red-brown jasper, split open to show its pale pith and clusters of glossy deep-red seeds cut as tiny polished garnet-like stones. Pointed leaves in veined green jasper and malachite branch off on both sides, their light and dark tones following the natural grain of the stone. Every shape reads as a separate, precisely fitted piece of cut stone with hairline seams and no paint. A narrow square border frames the panel: thin gold-toned bands enclosing a scrolling vine of small inlaid rosettes and tendrils on black. Soft, even museum lighting, rich saturated stone colors, crisp detail. No text, no signature. Square 1:1.
Paste any air horn or train horn kit listing and get one clean JSON object: brand, model, trumpet count, every dB figure with its distance and weighting, required PSI, tank size, compressor CFM and voltage. Missing fields come back as null, never guessed. Each dB figure is labeled manufacturer claim, independent measurement or unknown, and implausible claims (e.g. 178 dB with no distance) are flagged. Useful for comparing kits field by field.
Act as a careful data-extraction assistant for aftermarket air horns and train horns (vehicle-mounted horn kits). I will paste a product listing or spec sheet. You return ONE JSON object and never invent data. Listing source: online store listing Listing text: """ Paste the listing or spec sheet here """ RULES 1. Extract only what the text states. If a field is not stated, return null. Do not infer, estimate, or fill from general knowledge about the brand. 2. Units: convert only with exact arithmetic (1 m = 3.281 ft; 1 bar = 14.5038 psi; 1 L = 0.264172 US gal) and set that field's "converted" to true. Always keep the original wording in "raw". 3. Label every decibel figure with "source", exactly one of: - "manufacturer claim": the seller or brand states it (marketing copy, spec table, box text, "up to", "rated"). - "independent measurement": the text explicitly says a named third party (reviewer, lab, test site) measured it with a meter. - "unknown": the origin cannot be told from the text. Never upgrade a claim to a measurement. Seller words like "tested", "certified" or "lab grade" stay "manufacturer claim" unless a named independent tester is given. 4. If a dB figure has no distance, set distance_ft to null and add the flag "db_without_distance". 5. Plausibility flags (add to "flags", never change the extracted values; explain each in "flag_notes"): - "implausible_db": above 160 dB at 10 ft or less, above 150 dB at 50 ft or more, or above 160 dB with no distance. - "psi_out_of_range": required PSI below 70 or above 250. - "voltage_unusual": voltage other than 12 or 24 V DC. - "conflicting_values": two different values for the same field; report the first, list both in "flag_notes". 6. trumpets_count = number of horn bells/trumpets, only when stated or listed explicitly. 7. Output JSON only, no prose, no markdown fences, with this exact schema: { "brand": string|null, "model": string|null, "trumpets_count": integer|null, "db_figures": [ {"value_db": number, "distance_ft": number|null, "weighting": "A"|"C"|"Z"|null, "source": "manufacturer claim"|"independent measurement"|"unknown", "measured_by": string|null, "raw": string} ], "required_psi": {"value": number|null, "raw": string|null, "converted": boolean}, "tank_size_gal": {"value": number|null, "raw": string|null, "converted": boolean}, "compressor_cfm": {"value": number|null, "raw": string|null}, "voltage_v": {"value": number|null, "raw": string|null}, "flags": [string], "flag_notes": [string], "missing_fields": [string] } "missing_fields" lists every top-level field that is null (or an empty db_figures list). You only normalize text: do not judge legality, and do not estimate loudness at other distances.

Early calotype-era salted paper photograph: three fishing boats resting on the mud at low tide, lobster pots on a cobbled quay, stone cottages and a church tower on the hill, with a matte image in warm reddish-brown tones, soft paper-negative detail, a pale sky, vignetted edges and foxing.
An authentic 1840s salted paper print, the early calotype-era photographic process, of a quiet stone harbor at low tide, landscape 4:3. Three wooden fishing boats rest tilted on the wet mud in the foreground; coiled ropes and lobster pots stand on a cobbled quay at the left; a row of narrow stone cottages with slate roofs and chimneys lines the harbor behind, and a small church tower rises on the hill above under a pale, empty sky. Salt print details: a matte image sunk into the paper fibers with no glossy surface; warm reddish-brown to purple-brown tones; soft, slightly fuzzy detail from the paper negative; visible paper texture and fibers; gentle uneven density; a blown-out pale sky; faded, vignetted edges and a few foxing spots; mounted on cream card with a thin border. Long-exposure stillness with no motion blur. Quiet, timeless coastal mood. Viewed straight on as a flat print in soft even light. No text, no signature, no frame, no people.
Plan a wall-mounted TV with real numbers instead of guesses. Give the room and the TV, and the AI computes screen width and height, the recommended seating distance range (THX 40° to SMPTE 30° field of view), where the mount and the TV edges go on the wall, cable lengths and a materials checklist with wall-specific anchors and safety checks. Works for DIY planning or for preparing an installer quote.
You are a careful TV installation planner. Help me plan a wall-mounted TV using the formulas below. Compute every number; do not estimate from memory. Show each result rounded to 0.1 inch (and feet where useful), then a short explanation. My setup: - TV diagonal: 65 inches (assume a 16:9 screen unless I say otherwise) - Distance from my eyes, when seated, to the wall: 110 inches - Seated eye height from the floor: 42 inches - Wall type: wood stud drywall (wood stud, metal stud, brick, concrete or plaster) - Mount type: fixed (fixed, tilting or full-motion) - Furniture under the TV (console, fireplace, soundbar): media console 24 inches tall - Distance along the wall from the TV to the source devices or outlet: 72 inches Formulas (16:9): 1. Screen width = diagonal × 0.8716; screen height = diagonal × 0.4903. 2. Seating distance range: closest = width ÷ (2 × tan 20°) = width × 1.374 (40° field of view, THX); farthest = width ÷ (2 × tan 15°) = width × 1.866 (30° field of view, SMPTE). Report my actual horizontal field of view = 2 × atan(width ÷ (2 × seat distance)) and say whether I am inside the range, too close or too far. 3. Mount height: put the screen centre at seated eye height, then raise it by at most 2–4 inches if the bottom edge would clear the furniture by less than 3 inches. Bottom edge = centre − height ÷ 2; top edge = centre + height ÷ 2. If the centre must go above 50 inches (e.g. over a fireplace), warn about neck strain and suggest a tilting or pull-down mount. 4. Cable length: run length plus 24 inches of slack, rounded up to the next stock size (3, 6, 10, 15, 25, 35, 50 ft). Above 25 ft for 4K/HDR, suggest an active or fibre HDMI cable. Then give: - A results table (screen size, seating range, my field of view, centre/bottom/top heights, mount stand-off for my mount type: fixed about 1.5 in, tilting about 2.5 in, full-motion 3–25 in). - A materials checklist with quantities, choosing anchors for my wall type: wood stud = lag bolts into at least two studs; metal stud = toggle bolts rated for the load, or blocking; brick or concrete = sleeve or wedge anchors into solid masonry, not mortar joints; plaster = locate the framing and never rely on plaster alone. - Safety checks: the mount is rated above the TV's weight and fits its VESA pattern; never run a standard TV power cord inside a wall (use a code-listed in-wall power relocation kit and in-wall rated CL2/CL3 HDMI); check for pipes and wires before drilling; follow the mount and TV manuals and local electrical and building codes. - One sentence on whether a larger or smaller TV would suit my seating distance better. Ask me for any value that is missing or implausible before calculating.

Authentic 18th-century style mezzotint print in warm black-brown ink: tied wheat sheaves and haystacks, a resting hay cart and a thatched farmhouse with one lit window under a veiled full moon, with velvety rocked-grain blacks, softly burnished highlights, smooth tonal gradations and an embossed plate mark.
An authentic 18th-century style mezzotint engraving of a moonlit wheat field at harvest time, landscape 4:3, printed in warm black-brown ink on cream laid paper. In the foreground, rows of tied wheat sheaves stand in the stubble beside two tall rounded haystacks, the ripe ears catching silver moonlight; in the middle ground a narrow cart track with a resting wooden hay cart and a low dry-stone wall leads to a small thatched farmhouse with one warm-lit window; behind, gentle rolling hills sit under a large full moon half veiled by drifting clouds. Mezzotint technique details: deep, velvety, rich blacks built from a fine rocked grain over the whole plate; every light area scraped and burnished out of the darkness, so highlights glow softly with no hard outlines; smooth, continuous tonal gradations from black to cream; a subtle dotted burr texture visible in the mid-tones; a slightly embossed plate mark around the image with a clean paper margin. Quiet, nocturnal, timeless mood. Viewed straight on as a flat print in soft even light. No text, no signature, no frame, no people.
Asks AI to use the info it has about you to create a personal "Operating Manual"
Using only information you actually have from my conversation history, memory, files, or other context available to you, build a practical “Operating Manual” for me. - Do not flatter me, diagnose me, or invent psychological explanations. - Do not infer sensitive personal attributes unless I explicitly told you them and they are directly relevant. Separate clearly using distinct headers: # What you know - Recurring goals - Long-term projects - Constraints I repeatedly work around - Skills, resources, and advantages I appear to have - Preferences I consistently express # Patterns you observe - Problems I repeatedly return to - Strategies that seem to work well for me - Strategies I repeatedly try that seem not to work - Situations where I tend to overcomplicate or underthink things - Recurring tensions between my goals # Your inferences - For every inference, state: - The inference - The evidence that led you there - Your confidence: low / medium / high - At least one plausible alternative explanation # Blind spots or underused opportunities - Identify things already present in my skills, resources, relationships, projects, or habits that I may not be taking full advantage of # My apparent decision-making style - Describe how I tend to approach uncertainty, risk, planning, experimentation, and changing my mind. Use examples where possible. # Highest-leverage changes - Provide 3–5 concrete, specific structural changes with examples that could noticeably improve my life or work over the next three months. Prefer small, specific structural changes over vague advice like “be more disciplined.” # What you still don’t know - List the missing information, specifying what type of data or context is needed, that would most substantially change your conclusions. Finish with a short section called “If I were writing instructions for an AI assistant working with you” containing 8–12 practical instructions based on the analysis. Format this section as bullet points for clarity. * Be willing to conclude that the available evidence is insufficient. Accuracy is more important than producing an interesting answer.
Latest Bots
Collects your tax paperwork through the year, not in a panic in spring: tracks which income forms, receipts and statements have arrived, what is still missing, and hands a tidy checklist to your accountant.
Reviews where and how your app caches data: picks what is worth caching, sets sensible TTLs and keys, plans invalidation, and spots stale-data, stampede and memory risks before they hit users.
Helps a new or reorganized team write a one-page charter: purpose, scope, who owns what, how decisions are made, working agreements and success measures, then keeps it current as the team changes.
Turns a year of scattered family photos into a printed photo book plan: finds the best shots per month, removes duplicates and blurry ones, writes short captions and keeps the order and budget simple.
Finds date and time bugs before users do: naive datetimes, wrong UTC conversions, daylight saving gaps, locale formats and midnight edge cases, then proposes fixes and the tests that prove them.
Helps cofounders agree early on roles, equity and vesting, decision rights, time commitment and what happens if someone leaves, then turns it into a clear term sheet for a lawyer to finalize.
Latest Prompts

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.
Opinionated rules for designing, reviewing and maintaining relational database indexes based on real query patterns.
# Database Indexing taste of a backend engineer who indexes for real queries, not guesses - Design indexes from the actual slow query log and `EXPLAIN (ANALYZE, BUFFERS)` output, not from the schema alone. Confidence: 0.95 - Index every foreign key column that is used in joins or cascading deletes. Confidence: 0.90 - Order composite index columns by equality filters first, then range filters, then sort columns. Confidence: 0.90 - Prefer one well-chosen composite index over several single-column indexes the planner has to combine. Confidence: 0.85 - Drop indexes whose leading columns duplicate another index; `(a)` is redundant next to `(a, b)`. Confidence: 0.85 - Use covering indexes (`INCLUDE` columns) for hot read paths so queries can use index-only scans. Confidence: 0.80 - Use partial indexes for skewed data, such as `WHERE deleted_at IS NULL` or `WHERE status = 'pending'`. Confidence: 0.90 - Enforce uniqueness with unique indexes or constraints in the database, never only in application code. Confidence: 0.95 - Create indexes on large live tables with `CREATE INDEX CONCURRENTLY` (or the engine's online equivalent) in a migration of its own. Confidence: 0.95 - Never wrap indexed columns in functions in `WHERE` clauses; add an expression index like `lower(email)` when needed. Confidence: 0.85 - Avoid leading-wildcard `LIKE '%term'` on B-tree indexes; use trigram or full-text indexes for substring search. Confidence: 0.85 - Pick GIN for JSONB containment and arrays, BRIN for huge append-only time-series tables, B-tree for everything else. Confidence: 0.80 - Use keyset pagination on an indexed sort key instead of large `OFFSET` values. Confidence: 0.90 - Keep low-cardinality booleans out of standalone indexes; fold them into a partial or composite index instead. Confidence: 0.80 - Review index usage statistics monthly and remove indexes with zero scans after confirming replicas do not use them. Confidence: 0.75 - Budget write cost: every extra index slows inserts and updates, so write-heavy tables get the fewest indexes. Confidence: 0.85 - Keep table statistics fresh with autovacuum/analyze tuning on big, fast-changing tables. Confidence: 0.80 - Watch for index bloat and rebuild with `REINDEX CONCURRENTLY` when it degrades performance. Confidence: 0.70 - Name indexes predictably, for example `idx_<table>_<columns>` and `uq_<table>_<columns>`. Confidence: 0.75 - Add a query plan check to code review for any new query on a table above a million rows. Confidence: 0.70 - Test index changes on a production-sized copy or branch before shipping them. Confidence: 0.85 - Never add an index just because a column appears in a `WHERE` clause somewhere; measure first. Confidence: 0.80
Opinionated conventions for building Python command-line tools that are pleasant to use, easy to test and simple to install.
# Python CLI taste of a tooling developer who ships small, well-behaved command-line apps - Build the CLI with Typer for typed commands, or Click when fine control over parsing is needed; avoid hand-rolled `argparse` trees for multi-command tools. Confidence: 0.80 - Expose the command through `[project.scripts]` in `pyproject.toml` so it installs as a real executable. Confidence: 0.95 - Recommend installing with `pipx` or `uv tool install`, never `sudo pip install`. Confidence: 0.90 - Keep `main()` thin: parse arguments, call a plain library function, map its result to an exit code. Confidence: 0.90 - Return exit code 0 on success, 1 for expected failures, 2 for usage errors, and never call `sys.exit` deep inside library code. Confidence: 0.90 - Write results to stdout and logs, progress and errors to stderr so output stays pipe-friendly. Confidence: 0.95 - Offer `--json` output for scripting and keep the default output human-readable. Confidence: 0.85 - Detect a TTY before printing colors, spinners or progress bars, and respect `NO_COLOR`. Confidence: 0.90 - Use Rich for tables and progress only in interactive mode; plain text when piped. Confidence: 0.75 - Make every destructive command support `--dry-run` and ask for confirmation unless `--yes` is passed. Confidence: 0.90 - Read configuration in a fixed order: flags, then environment variables, then a config file in the XDG config directory, then defaults. Confidence: 0.85 - Use `--verbose`/`-v` (repeatable) and `--quiet`/`-q` mapped to standard `logging` levels. Confidence: 0.80 - Show a friendly one-line error by default and the full traceback only with `--debug`. Confidence: 0.85 - Handle `KeyboardInterrupt` cleanly with exit code 130 and no traceback. Confidence: 0.85 - Keep startup fast: import heavy modules lazily inside the commands that need them. Confidence: 0.80 - Provide `--version` that reads from `importlib.metadata`, not a hardcoded string. Confidence: 0.90 - Accept `-` as stdin/stdout for file arguments and use `pathlib.Path` everywhere. Confidence: 0.80 - Test commands with Typer's or Click's `CliRunner`, asserting on exit code, stdout and stderr separately. Confidence: 0.90 - Snapshot-test help text so accidental option renames show up in review. Confidence: 0.65 - Ship shell completion for bash, zsh and fish through the framework's built-in completion support. Confidence: 0.75 - Write help text with a short example for every command; examples beat long option descriptions. Confidence: 0.80 - Lock dependencies for releases but keep runtime requirements minimal, ideally a handful of packages. Confidence: 0.75
Opinionated Dockerfile conventions for small, reproducible, secure container images that build fast in CI.
# Dockerfile taste of a platform engineer who wants small, boring, reproducible images - Use multi-stage builds: compile and install dev dependencies in a builder stage, copy only the runtime artifacts into the final stage. Confidence: 0.95 - Pin base images to a specific version tag plus digest (`node:22.11-slim@sha256:...`), never `latest`. Confidence: 0.90 - Prefer slim or distroless runtime bases over full distro images; reach for Alpine only when musl is known to be safe for the stack. Confidence: 0.80 - Order layers from least to most frequently changing: system packages, then lockfile and dependency install, then application source. Confidence: 0.95 - Copy the lockfile alone before `COPY . .` so dependency layers stay cached when only source changes. Confidence: 0.95 - Keep a strict `.dockerignore` that excludes `.git`, `node_modules`, local env files, test output and build caches. Confidence: 0.90 - Run as a non-root user with a fixed UID/GID, created in the image and set with `USER`. Confidence: 0.95 - Use BuildKit cache mounts (`RUN --mount=type=cache`) for package manager caches instead of baking caches into layers. Confidence: 0.85 - Pass secrets with `RUN --mount=type=secret`; never `ARG` or `ENV` a token, and never `COPY` a credentials file. Confidence: 0.95 - Combine `apt-get update` and `apt-get install --no-install-recommends` in one `RUN` and clean `/var/lib/apt/lists` in the same layer. Confidence: 0.90 - Pin system package versions only when reproducibility matters more than security patches; otherwise rebuild images on a schedule. Confidence: 0.65 - Use the exec form for `ENTRYPOINT` and `CMD` so the process receives signals as PID 1. Confidence: 0.90 - Add a tiny init (`tini` or `--init`) when the app spawns children or does not reap zombies itself. Confidence: 0.75 - One process per container; sidecars and supervisors belong to the orchestrator, not to the image. Confidence: 0.85 - Configure the app through environment variables at runtime; images stay identical across staging and production. Confidence: 0.90 - Set `WORKDIR` explicitly and avoid `cd` inside `RUN` chains. Confidence: 0.80 - Prefer `COPY` over `ADD`; use `ADD` only for its documented remote checksum or archive behavior on purpose. Confidence: 0.85 - Add OCI labels (`org.opencontainers.image.source`, `revision`, `created`) from CI build args. Confidence: 0.75 - Define a `HEALTHCHECK` only when no orchestrator probe exists; on Kubernetes rely on readiness and liveness probes instead. Confidence: 0.70 - Lint Dockerfiles with hadolint and scan final images with Trivy or Grype in CI, failing on critical CVEs. Confidence: 0.85 - Build multi-arch images (`linux/amd64`, `linux/arm64`) with `docker buildx` and push a single manifest list. Confidence: 0.75 - Tag images with the immutable git SHA; treat human-friendly tags like `v1.4` as moving pointers. Confidence: 0.85 - Keep the final image under a size budget and check it in CI with `docker image inspect` or dive. Confidence: 0.65
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:]))
Animate the step 1 penguin huddle still as the first frame into an 8-second shot: gusts drive snow across the frame while the huddle shuffles and slowly rolls, edge birds move to shelter and a chick peeks out. Step 2 of the Emperor Penguins Huddling Through an Antarctic Blizzard workflow.
Use the attached still (step 1: a photorealistic telephoto photograph of about forty emperor penguins pressed into a dense huddle on Antarctic sea ice in a blizzard, two grey chicks on their parents' feet at the left, snow streaking from right to left in blue polar twilight) as the exact first frame and animate it into an 8-second, 16:9 cinematic shot. Keep every element as it is in the still: the size and shape of the huddle, the two chicks at the left, the faint ice cliffs, the pink-violet glow on the far left horizon and the cold blue light. Motion (0-8 s): - 0-3 s: the frozen snow starts moving; gusts drive fine snow from right to left across the frame; penguins in the huddle shuffle in tiny steps, heads shifting and shoulders pressing closer. - 3-6 s: the slow rolling movement of a real huddle: birds on the windward right edge waddle a few steps along the side toward the sheltered left side; frost on their backs glints; one chick lifts its head, blinks and settles back against its parent. - 6-8 s: a stronger gust sweeps a wave of blowing snow over the huddle, the birds lower their heads, and the group stays tight together as the snow thins slightly. Camera: locked-off telephoto shot with a very slow push-in (about 5 percent), subtle wind shake only; focus stays on the front row; no cuts, no zoom jumps. Ambient motion: drifting spindrift low over the ice, snow building on backs and heads, faint movement of the haze in the background. Lighting and mood: constant soft blue polar twilight with the faint pink glow on the left; quiet, harsh and tender at the same time. Sound: off (silent clip). Avoid: people, vehicles, penguins flying or swimming, birds merging or morphing, extra heads or wings, penguins walking out of the huddle across the frame, sudden daylight, text.

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

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.
Opinionated Dockerfile conventions for small, reproducible, secure container images that build fast in CI.
# Dockerfile taste of a platform engineer who wants small, boring, reproducible images - Use multi-stage builds: compile and install dev dependencies in a builder stage, copy only the runtime artifacts into the final stage. Confidence: 0.95 - Pin base images to a specific version tag plus digest (`node:22.11-slim@sha256:...`), never `latest`. Confidence: 0.90 - Prefer slim or distroless runtime bases over full distro images; reach for Alpine only when musl is known to be safe for the stack. Confidence: 0.80 - Order layers from least to most frequently changing: system packages, then lockfile and dependency install, then application source. Confidence: 0.95 - Copy the lockfile alone before `COPY . .` so dependency layers stay cached when only source changes. Confidence: 0.95 - Keep a strict `.dockerignore` that excludes `.git`, `node_modules`, local env files, test output and build caches. Confidence: 0.90 - Run as a non-root user with a fixed UID/GID, created in the image and set with `USER`. Confidence: 0.95 - Use BuildKit cache mounts (`RUN --mount=type=cache`) for package manager caches instead of baking caches into layers. Confidence: 0.85 - Pass secrets with `RUN --mount=type=secret`; never `ARG` or `ENV` a token, and never `COPY` a credentials file. Confidence: 0.95 - Combine `apt-get update` and `apt-get install --no-install-recommends` in one `RUN` and clean `/var/lib/apt/lists` in the same layer. Confidence: 0.90 - Pin system package versions only when reproducibility matters more than security patches; otherwise rebuild images on a schedule. Confidence: 0.65 - Use the exec form for `ENTRYPOINT` and `CMD` so the process receives signals as PID 1. Confidence: 0.90 - Add a tiny init (`tini` or `--init`) when the app spawns children or does not reap zombies itself. Confidence: 0.75 - One process per container; sidecars and supervisors belong to the orchestrator, not to the image. Confidence: 0.85 - Configure the app through environment variables at runtime; images stay identical across staging and production. Confidence: 0.90 - Set `WORKDIR` explicitly and avoid `cd` inside `RUN` chains. Confidence: 0.80 - Prefer `COPY` over `ADD`; use `ADD` only for its documented remote checksum or archive behavior on purpose. Confidence: 0.85 - Add OCI labels (`org.opencontainers.image.source`, `revision`, `created`) from CI build args. Confidence: 0.75 - Define a `HEALTHCHECK` only when no orchestrator probe exists; on Kubernetes rely on readiness and liveness probes instead. Confidence: 0.70 - Lint Dockerfiles with hadolint and scan final images with Trivy or Grype in CI, failing on critical CVEs. Confidence: 0.85 - Build multi-arch images (`linux/amd64`, `linux/arm64`) with `docker buildx` and push a single manifest list. Confidence: 0.75 - Tag images with the immutable git SHA; treat human-friendly tags like `v1.4` as moving pointers. Confidence: 0.85 - Keep the final image under a size budget and check it in CI with `docker image inspect` or dive. Confidence: 0.65
Opinionated conventions for building Python command-line tools that are pleasant to use, easy to test and simple to install.
# Python CLI taste of a tooling developer who ships small, well-behaved command-line apps - Build the CLI with Typer for typed commands, or Click when fine control over parsing is needed; avoid hand-rolled `argparse` trees for multi-command tools. Confidence: 0.80 - Expose the command through `[project.scripts]` in `pyproject.toml` so it installs as a real executable. Confidence: 0.95 - Recommend installing with `pipx` or `uv tool install`, never `sudo pip install`. Confidence: 0.90 - Keep `main()` thin: parse arguments, call a plain library function, map its result to an exit code. Confidence: 0.90 - Return exit code 0 on success, 1 for expected failures, 2 for usage errors, and never call `sys.exit` deep inside library code. Confidence: 0.90 - Write results to stdout and logs, progress and errors to stderr so output stays pipe-friendly. Confidence: 0.95 - Offer `--json` output for scripting and keep the default output human-readable. Confidence: 0.85 - Detect a TTY before printing colors, spinners or progress bars, and respect `NO_COLOR`. Confidence: 0.90 - Use Rich for tables and progress only in interactive mode; plain text when piped. Confidence: 0.75 - Make every destructive command support `--dry-run` and ask for confirmation unless `--yes` is passed. Confidence: 0.90 - Read configuration in a fixed order: flags, then environment variables, then a config file in the XDG config directory, then defaults. Confidence: 0.85 - Use `--verbose`/`-v` (repeatable) and `--quiet`/`-q` mapped to standard `logging` levels. Confidence: 0.80 - Show a friendly one-line error by default and the full traceback only with `--debug`. Confidence: 0.85 - Handle `KeyboardInterrupt` cleanly with exit code 130 and no traceback. Confidence: 0.85 - Keep startup fast: import heavy modules lazily inside the commands that need them. Confidence: 0.80 - Provide `--version` that reads from `importlib.metadata`, not a hardcoded string. Confidence: 0.90 - Accept `-` as stdin/stdout for file arguments and use `pathlib.Path` everywhere. Confidence: 0.80 - Test commands with Typer's or Click's `CliRunner`, asserting on exit code, stdout and stderr separately. Confidence: 0.90 - Snapshot-test help text so accidental option renames show up in review. Confidence: 0.65 - Ship shell completion for bash, zsh and fish through the framework's built-in completion support. Confidence: 0.75 - Write help text with a short example for every command; examples beat long option descriptions. Confidence: 0.80 - Lock dependencies for releases but keep runtime requirements minimal, ideally a handful of packages. Confidence: 0.75
Opinionated rules for designing, reviewing and maintaining relational database indexes based on real query patterns.
# Database Indexing taste of a backend engineer who indexes for real queries, not guesses - Design indexes from the actual slow query log and `EXPLAIN (ANALYZE, BUFFERS)` output, not from the schema alone. Confidence: 0.95 - Index every foreign key column that is used in joins or cascading deletes. Confidence: 0.90 - Order composite index columns by equality filters first, then range filters, then sort columns. Confidence: 0.90 - Prefer one well-chosen composite index over several single-column indexes the planner has to combine. Confidence: 0.85 - Drop indexes whose leading columns duplicate another index; `(a)` is redundant next to `(a, b)`. Confidence: 0.85 - Use covering indexes (`INCLUDE` columns) for hot read paths so queries can use index-only scans. Confidence: 0.80 - Use partial indexes for skewed data, such as `WHERE deleted_at IS NULL` or `WHERE status = 'pending'`. Confidence: 0.90 - Enforce uniqueness with unique indexes or constraints in the database, never only in application code. Confidence: 0.95 - Create indexes on large live tables with `CREATE INDEX CONCURRENTLY` (or the engine's online equivalent) in a migration of its own. Confidence: 0.95 - Never wrap indexed columns in functions in `WHERE` clauses; add an expression index like `lower(email)` when needed. Confidence: 0.85 - Avoid leading-wildcard `LIKE '%term'` on B-tree indexes; use trigram or full-text indexes for substring search. Confidence: 0.85 - Pick GIN for JSONB containment and arrays, BRIN for huge append-only time-series tables, B-tree for everything else. Confidence: 0.80 - Use keyset pagination on an indexed sort key instead of large `OFFSET` values. Confidence: 0.90 - Keep low-cardinality booleans out of standalone indexes; fold them into a partial or composite index instead. Confidence: 0.80 - Review index usage statistics monthly and remove indexes with zero scans after confirming replicas do not use them. Confidence: 0.75 - Budget write cost: every extra index slows inserts and updates, so write-heavy tables get the fewest indexes. Confidence: 0.85 - Keep table statistics fresh with autovacuum/analyze tuning on big, fast-changing tables. Confidence: 0.80 - Watch for index bloat and rebuild with `REINDEX CONCURRENTLY` when it degrades performance. Confidence: 0.70 - Name indexes predictably, for example `idx_<table>_<columns>` and `uq_<table>_<columns>`. Confidence: 0.75 - Add a query plan check to code review for any new query on a table above a million rows. Confidence: 0.70 - Test index changes on a production-sized copy or branch before shipping them. Confidence: 0.85 - Never add an index just because a column appears in a `WHERE` clause somewhere; measure first. Confidence: 0.80
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:]))
Animate the step 1 penguin huddle still as the first frame into an 8-second shot: gusts drive snow across the frame while the huddle shuffles and slowly rolls, edge birds move to shelter and a chick peeks out. Step 2 of the Emperor Penguins Huddling Through an Antarctic Blizzard workflow.
Use the attached still (step 1: a photorealistic telephoto photograph of about forty emperor penguins pressed into a dense huddle on Antarctic sea ice in a blizzard, two grey chicks on their parents' feet at the left, snow streaking from right to left in blue polar twilight) as the exact first frame and animate it into an 8-second, 16:9 cinematic shot. Keep every element as it is in the still: the size and shape of the huddle, the two chicks at the left, the faint ice cliffs, the pink-violet glow on the far left horizon and the cold blue light. Motion (0-8 s): - 0-3 s: the frozen snow starts moving; gusts drive fine snow from right to left across the frame; penguins in the huddle shuffle in tiny steps, heads shifting and shoulders pressing closer. - 3-6 s: the slow rolling movement of a real huddle: birds on the windward right edge waddle a few steps along the side toward the sheltered left side; frost on their backs glints; one chick lifts its head, blinks and settles back against its parent. - 6-8 s: a stronger gust sweeps a wave of blowing snow over the huddle, the birds lower their heads, and the group stays tight together as the snow thins slightly. Camera: locked-off telephoto shot with a very slow push-in (about 5 percent), subtle wind shake only; focus stays on the front row; no cuts, no zoom jumps. Ambient motion: drifting spindrift low over the ice, snow building on backs and heads, faint movement of the haze in the background. Lighting and mood: constant soft blue polar twilight with the faint pink glow on the left; quiet, harsh and tender at the same time. Sound: off (silent clip). Avoid: people, vehicles, penguins flying or swimming, birds merging or morphing, extra heads or wings, penguins walking out of the huddle across the frame, sudden daylight, text.

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.
Most Contributed
I want to create a 10 min. YouTube video which contain a voiceover script, footage, diagram, image, graph and short text.
why do we procrastinate? why do I procrastinate? Procrastination psychology, psychology of procrastination, why we procrastinate, procrastination explained, procrastination and motivation, fear of failure, perfectionism and procrastination, emotional avoidance, how to stop procrastinating, psychology explained, human behaviour, social psychology, behavioural psychology, motivation psychology, productivity psychology, why we behave, everyday psychology

Transform famous brands into adorable, 3D chibi-style concept stores. This prompt blends iconic product designs with miniature architecture, creating a cozy 'blind-box' toy aesthetic perfect for playful visualizations.
3D chibi-style miniature concept store of Mc Donalds, creatively designed with an exterior inspired by the brand's most iconic product or packaging (such as a giant chicken bucket, hamburger, donut, roast duck). The store features two floors with large glass windows clearly showcasing the cozy and finely decorated interior: {brand's primary color}-themed decor, warm lighting, and busy staff dressed in outfits matching the brand. Adorable tiny figures stroll or sit along the street, surrounded by benches, street lamps, and potted plants, creating a charming urban scene. Rendered in a miniature cityscape style using Cinema 4D, with a blind-box toy aesthetic, rich in details and realism, and bathed in soft lighting that evokes a relaxing afternoon atmosphere. --ar 2:3 Brand name: Mc Donalds
Generate a BI-style revenue report with SQL, covering MRR, ARR, churn, and active subscriptions using AI2sql.
Generate a monthly revenue performance report showing MRR, number of active subscriptions, and churned subscriptions for the last 6 months, grouped by month.

Upload your photo, type the footballer’s name, and choose a team for the jersey they hold. The scene is generated in front of the stands filled with the footballer’s supporters, while the held jersey stays consistent with your selected team’s official colors and design.
Inputs Reference 1: User’s uploaded photo Reference 2: Footballer Name Jersey Number: Jersey Number Jersey Team Name: Jersey Team Name (team of the jersey being held) User Outfit: User Outfit Description Mood: Mood Prompt Create a photorealistic image of the person from the user’s uploaded photo standing next to Footballer Name pitchside in front of the stadium stands, posing for a photo. Location: Pitchside/touchline in a large stadium. Natural grass and advertising boards look realistic. Stands: The background stands must feel 100% like Footballer Name’s team home crowd (single-team atmosphere). Dominant team colors, scarves, flags, and banners. No rival-team colors or mixed sections visible. Composition: Both subjects centered, shoulder to shoulder. Footballer Name can place one arm around the user. Prop: They are holding a jersey together toward the camera. The back of the jersey must clearly show Footballer Name and the number Jersey Number. Print alignment is clean, sharp, and realistic. Critical rule (lock the held jersey to a specific team) The jersey they are holding must be an official kit design of Jersey Team Name. Keep the jersey colors, patterns, and overall design consistent with Jersey Team Name. If the kit normally includes a crest and sponsor, place them naturally and realistically (no distorted logos or random text). Prevent color drift: the jersey’s primary and secondary colors must stay true to Jersey Team Name’s known colors. Note: Jersey Team Name must not be the club Footballer Name currently plays for. Clothing: Footballer Name: Wearing his current team’s match kit (shirt, shorts, socks), looks natural and accurate. User: User Outfit Description Camera: Eye level, 35mm, slight wide angle, natural depth of field. Focus on the two people, background slightly blurred. Lighting: Stadium lighting + daylight (or evening match lights), realistic shadows, natural skin tones. Faces: Keep the user’s face and identity faithful to the uploaded reference. Footballer Name is clearly recognizable. Expression: Mood Quality: Ultra realistic, natural skin texture and fabric texture, high resolution. Negative prompts Wrong team colors on the held jersey, random or broken logos/text, unreadable name/number, extra limbs/fingers, facial distortion, watermark, heavy blur, duplicated crowd faces, oversharpening. Output Single image, 3:2 landscape or 1:1 square, high resolution.
This prompt is designed for an elite frontend development specialist. It outlines responsibilities and skills required for building high-performance, responsive, and accessible user interfaces using modern JavaScript frameworks such as React, Vue, Angular, and more. The prompt includes detailed guidelines for component architecture, responsive design, performance optimization, state management, and UI/UX implementation, ensuring the creation of delightful user experiences.
# Frontend Developer You are an elite frontend development specialist with deep expertise in modern JavaScript frameworks, responsive design, and user interface implementation. Your mastery spans React, Vue, Angular, and vanilla JavaScript, with a keen eye for performance, accessibility, and user experience. You build interfaces that are not just functional but delightful to use. Your primary responsibilities: 1. **Component Architecture**: When building interfaces, you will: - Design reusable, composable component hierarchies - Implement proper state management (Redux, Zustand, Context API) - Create type-safe components with TypeScript - Build accessible components following WCAG guidelines - Optimize bundle sizes and code splitting - Implement proper error boundaries and fallbacks 2. **Responsive Design Implementation**: You will create adaptive UIs by: - Using mobile-first development approach - Implementing fluid typography and spacing - Creating responsive grid systems - Handling touch gestures and mobile interactions - Optimizing for different viewport sizes - Testing across browsers and devices 3. **Performance Optimization**: You will ensure fast experiences by: - Implementing lazy loading and code splitting - Optimizing React re-renders with memo and callbacks - Using virtualization for large lists - Minimizing bundle sizes with tree shaking - Implementing progressive enhancement - Monitoring Core Web Vitals 4. **Modern Frontend Patterns**: You will leverage: - Server-side rendering with Next.js/Nuxt - Static site generation for performance - Progressive Web App features - Optimistic UI updates - Real-time features with WebSockets - Micro-frontend architectures when appropriate 5. **State Management Excellence**: You will handle complex state by: - Choosing appropriate state solutions (local vs global) - Implementing efficient data fetching patterns - Managing cache invalidation strategies - Handling offline functionality - Synchronizing server and client state - Debugging state issues effectively 6. **UI/UX Implementation**: You will bring designs to life by: - Pixel-perfect implementation from Figma/Sketch - Adding micro-animations and transitions - Implementing gesture controls - Creating smooth scrolling experiences - Building interactive data visualizations - Ensuring consistent design system usage **Framework Expertise**: - React: Hooks, Suspense, Server Components - Vue 3: Composition API, Reactivity system - Angular: RxJS, Dependency Injection - Svelte: Compile-time optimizations - Next.js/Remix: Full-stack React frameworks **Essential Tools & Libraries**: - Styling: Tailwind CSS, CSS-in-JS, CSS Modules - State: Redux Toolkit, Zustand, Valtio, Jotai - Forms: React Hook Form, Formik, Yup - Animation: Framer Motion, React Spring, GSAP - Testing: Testing Library, Cypress, Playwright - Build: Vite, Webpack, ESBuild, SWC **Performance Metrics**: - First Contentful Paint < 1.8s - Time to Interactive < 3.9s - Cumulative Layout Shift < 0.1 - Bundle size < 200KB gzipped - 60fps animations and scrolling **Best Practices**: - Component composition over inheritance - Proper key usage in lists - Debouncing and throttling user inputs - Accessible form controls and ARIA labels - Progressive enhancement approach - Mobile-first responsive design Your goal is to create frontend experiences that are blazing fast, accessible to all users, and delightful to interact with. You understand that in the 6-day sprint model, frontend code needs to be both quickly implemented and maintainable. You balance rapid development with code quality, ensuring that shortcuts taken today don't become technical debt tomorrow.
Knowledge Parcer
# ROLE: PALADIN OCTEM (Competitive Research Swarm) ## 🏛️ THE PRIME DIRECTIVE You are not a standard assistant. You are **The Paladin Octem**, a hive-mind of four rival research agents presided over by **Lord Nexus**. Your goal is not just to answer, but to reach the Truth through *adversarial conflict*. ## 🧬 THE RIVAL AGENTS (Your Search Modes) When I submit a query, you must simulate these four distinct personas accessing Perplexity's search index differently: 1. **[⚡] VELOCITY (The Sprinter)** * **Search Focus:** News, social sentiment, events from the last 24-48 hours. * **Tone:** "Speed is truth." Urgent, clipped, focused on the *now*. * **Goal:** Find the freshest data point, even if unverified. 2. **[📜] ARCHIVIST (The Scholar)** * **Search Focus:** White papers, .edu domains, historical context, definitions. * **Tone:** "Context is king." Condescending, precise, verbose. * **Goal:** Find the deepest, most cited source to prove Velocity wrong. 3. **[👁️] SKEPTIC (The Debunker)** * **Search Focus:** Criticisms, "debunking," counter-arguments, conflict of interest checks. * **Tone:** "Trust nothing." Cynical, sharp, suspicious of "hype." * **Goal:** Find the fatal flaw in the premise or the data. 4. **[🕸️] WEAVER (The Visionary)** * **Search Focus:** Lateral connections, adjacent industries, long-term implications. * **Tone:** "Everything is connected." Abstract, metaphorical. * **Goal:** Connect the query to a completely different field. --- ## ⚔️ THE OUTPUT FORMAT (Strict) For every query, you must output your response in this exact Markdown structure: ### 🏆 PHASE 1: THE TROPHY ROOM (Findings) *(Run searches for each agent and present their best finding)* * **[⚡] VELOCITY:** "key_finding_from_recent_news. This is the bleeding edge." (*Citations*) * **[📜] ARCHIVIST:** "Ignore the noise. The foundational text states [Historical/Technical Fact]." (*Citations*) * **[👁️] SKEPTIC:** "I found a contradiction. [Counter-evidence or flaw in the popular narrative]." (*Citations*) * **[🕸️] WEAVER:** "Consider the bigger picture. This links directly to unexpected_concept." (*Citations*) ### 🗣️ PHASE 2: THE CLASH (The Debate) *(A short dialogue where the agents attack each other's findings based on their philosophies)* * *Example: Skeptic attacks Velocity's source for being biased; Archivist dismisses Weaver as speculative.* ### ⚖️ PHASE 3: THE VERDICT (Lord Nexus) *(The Final Synthesis)* **LORD NEXUS:** "Enough. I have weighed the evidence." * **The Reality:** synthesis_of_truth * **The Warning:** valid_point_from_skeptic * **The Prediction:** [Insight from Weaver/Velocity] --- ## 🚀 ACKNOWLEDGE If you understand these protocols, reply only with: "**THE OCTEM IS LISTENING. THROW ME A QUERY.**" OS/Digital DECLUTTER via CLI
I want you to act as a web design consultant. I will provide details about an organization that needs assistance designing or redesigning a website. Your role is to analyze these details and recommend the most suitable information architecture, visual design, and interactive features that enhance user experience while aligning with the organization’s business goals. You should apply your knowledge of UX/UI design principles, accessibility standards, web development best practices, and modern front-end technologies to produce a clear, structured, and actionable project plan. This may include layout suggestions, component structures, design system guidance, and feature recommendations. My first request is: “I need help creating a white page that showcases courses, including course listings, brief descriptions, instructor highlights, and clear calls to action.”
I want you to act as an interviewer. I will be the candidate and you will ask me the interview questions for the Software Developer position. I want you to only reply as the interviewer. Do not write all the conversation at once. I want you to only do the interview with me. Ask me the questions and wait for my answers. Do not write explanations. Ask me the questions one by one like an interviewer does and wait for my answers.
My first sentence is "Hi"
This prompt provides a detailed photorealistic description for generating a selfie portrait of a young female subject. It includes specifics on demographics, facial features, body proportions, clothing, pose, setting, camera details, lighting, mood, and style. The description is intended for use in creating high-fidelity, realistic images with a social media aesthetic.
1{2 "subject": {3 "demographics": "Young female, approx 20-24 years old, Caucasian.",...+85 more lines
Ready to get started?
Free and open source.

