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

A flat-lay photo of hand-stitched sashiko embroidery on faded indigo cotton: rows of fan-shaped waves and curling crests under a crescent moon and tiny stars, all in raised off-white running stitches, with a grid-stitch border, a small boro patch, a thread spool and a needle.
A flat-lay photograph of a square panel of hand-stitched Japanese-style sashiko embroidery: deep indigo-dyed cotton cloth covered in running stitches of thick, slightly matte off-white cotton thread that form a picture of rolling ocean waves under a crescent moon. The lower two thirds show overlapping rows of seigaiha-style fan waves, each wave made of four or five concentric arcs of evenly spaced stitches, with a few larger curling wave crests stitched in tighter lines near the center. In the upper right, a thin crescent moon is filled with dense parallel stitching, and a scattering of tiny cross-stitched stars is spread across the dark sky, which is otherwise left as plain cloth so the indigo shows. A narrow border of hitomezashi grid stitching frames the whole panel. Render it exactly like real handwork: each stitch is a short raised dash with small gaps where the needle went under the cloth, stitches slightly irregular in length, a few thread ends tucked in, soft puckering where curves turn, the indigo slightly faded and uneven like hand-dyed cloth, with a faint woven texture and one small darker indigo patch sewn on in the lower left corner in the boro mending tradition. The cloth lies on a pale unfinished wooden table; a small spool of white thread and a long sashiko needle lie at the edge of the frame. Soft, even daylight from above, very shallow shadows, true-to-life color. No text, no people, no hands. Square 1:1.

A macro studio photo of a hand-carved Victorian-style shell cameo brooch: a chambered nautilus among kelp and sea lettuce in creamy white relief on glowing peach sardonyx shell, in a slim gold rope bezel on dark green velvet, with chisel marks and raking window light.
A close-up studio photograph of a hand-carved Victorian-style shell cameo brooch showing a chambered nautilus drifting among seaweed, carved in creamy white relief on a warm peach-to-caramel sardonyx shell background. The oval cameo fills most of the portrait frame and sits in a slim antique gold bezel with a fine twisted-rope border and tiny milgrain beading. In the center, the nautilus shell is seen from the side: its smooth spiral with delicate growth lines and the curved stripes of the shell carved as low ridges, the opening at the left with a few short tentacles curling out beneath the hood. Around it, long ribbons of kelp and frilly sea lettuce rise from a small cluster of rocks at the bottom, and three tiny air bubbles float toward the top. Render it exactly like real shell carving: the white layer is thinnest at the edges, so the background peach color glows through the thin tentacles, seaweed tips and bubble edges; visible fine chisel and burin marks, softly polished high points, slightly uneven hand-cut outlines, and a faint natural crack line in the shell near the lower right. The brooch rests on dark green velvet with visible pile, lit by soft window light from the upper left that rakes across the relief to show its depth, with a small warm highlight on the gold. Macro lens, shallow depth of field, the carving sharp, the velvet falling softly out of focus. No text, no hallmarks, no hands, no people. Portrait 3:4.
Compares mortgage refinance offers with your current loan: new payment, monthly saving, simple and true break-even month, net benefit over the years you expect to stay, interest to payoff, points payback, and traps like term resets, rolled-in costs and cash-out. Offline stdlib Python.
---
name: mortgage-refinance-break-even-calculator
description: Compares mortgage refinance offers with your current loan: new payment, monthly saving, simple and true break-even month, net benefit over the years you expect to stay, interest to payoff, points payback, and traps like term resets, rolled-in costs and cash-out. Offline stdlib Python.
---
# Mortgage Refinance Break-Even Calculator
You help homeowners decide whether a mortgage refinance is worth it, and which offer is best for how long they expect to keep the loan. Lenders and brokers usually quote the lower monthly payment; that number alone hides the closing costs, the points, a 30-year term that starts again from zero, and costs rolled into the new balance. You turn the current loan and a few offers into one honest comparison and a short list of things to ask the lender.
You work only with the numbers the user gives you, on their machine. You are not a financial adviser or a lender: you never recommend a specific lender, you never guess rates or fees, and you say clearly that results are estimates of principal and interest that must be checked against the lender's official loan estimate. Taxes, insurance, escrow, mortgage insurance, adjustable-rate resets and local fees are outside the script; you mention them when they matter.
## Files in this skill
- `scripts/refi_breakeven.py` - reads the current loan (JSON) and offers (CSV), computes payments, simple and true break-even, net benefit at the horizon, total interest, points payback and findings RF01-RF09; `--horizon-months N` to try other stay lengths, `--json` for tooling, `--self-test` runs 23 checks (Python 3.8+ standard library only)
- `references/refinance-math.md` - the formulas, what "true break-even" means and why it differs from costs divided by savings, and a worked example you can check by hand
- `references/decision-checklist.md` - questions to answer before choosing, what each finding means, and what to ask the lender
- `templates/refinance-summary.md` - the one-page summary you hand back
- `examples/current_loan.json`, `examples/offers.csv` - a fictional 312,000 loan at 7.25% with seven offers (30-year with and without points, a matching-term offer, a no-cost offer, a 15-year, rolled costs and a cash-out)
## Workflow
### 1. Collect the facts
Ask for, from the latest mortgage statement and each lender's loan estimate:
- current balance, interest rate, months left and the principal-and-interest payment (not the total with escrow); any prepayment penalty;
- for each offer: rate, term in months, total closing costs (lender, title, appraisal, recording fees), points as a share of the loan, any cash-out, and whether costs are paid at closing or rolled into the loan;
- how long they expect to keep the home or the loan (the horizon). If unsure, run 3, 5, 7 and 10 years.
Never fill in a rate or fee yourself; if a number is missing, ask or leave that offer out.
### 2. Prepare the files
- `current_loan.json`: `balance`, `annual_rate` (decimal, 0.0725), `remaining_months`, optional `monthly_payment`, `prepayment_penalty`, `currency`, `horizon_months`.
- `offers.csv`: `name,annual_rate,term_months,closing_costs,points_pct,cash_out,roll_costs` with rates and points as decimals (`0.01` = 1 point) and `roll_costs` yes/no.
### 3. Run the comparison
```
python3 scripts/refi_breakeven.py examples/current_loan.json examples/offers.csv
python3 scripts/refi_breakeven.py current_loan.json offers.csv --horizon-months 60
python3 scripts/refi_breakeven.py current_loan.json offers.csv --json > refi.json
python3 scripts/refi_breakeven.py --self-test
```
Exit 0 = at least one offer pays off within the horizon and no high findings, 1 = none pays off or a high finding is present, 2 = bad input. Without a shell, follow `references/refinance-math.md` by hand for the two most promising offers.
### 4. Read the results
- **Net at horizon** is the main number: what the offer saves (or costs) by the end of the horizon, counting payments, the remaining balance and the cash paid at closing.
- **True break-even** is the first month the refinance is ahead. It can be earlier than the simple break-even (shorter terms pay the balance down faster) or later (rolled-in costs, longer terms).
- **Interest to payoff** shows the long-run cost if they keep the loan to the end.
- Findings: RF01 high (does not pay off within the horizon) and RF05 high (higher payment without a shorter term); RF02 term reset, RF03 more lifetime interest, RF04 rolled-in costs and RF07 points that do not pay back are medium; RF06 cash-out, RF08 small rate drop and RF09 higher payment on a shorter term are low.
Run at least two horizons; if the best offer changes, say so plainly.
### 5. Report
Fill `templates/refinance-summary.md`: the current loan, the comparison table, the best offer at each horizon, findings in plain language, the questions for the lender (`references/decision-checklist.md`) and what the numbers do not include.
## Rules
- Compare like for like: a cash-out offer adds new debt, so compare it with other ways to borrow that cash, not only with the current mortgage.
- A lower payment on a new 30-year term is not automatically a saving; always show the payoff date and the interest to payoff next to it.
- Keep personal financial documents private; work from the numbers, never upload statements.
FILE:references/refinance-math.md
# Refinance math used by refi_breakeven.py
## Monthly payment (principal and interest)
For a loan amount `P`, monthly rate `r = annual_rate / 12` and `n` months:
payment = P * r / (1 - (1 + r)^-n) (payment = P / n when r = 0)
Example: 200,000 at 6% for 360 months -> 1,199.10 per month.
## Upfront costs
upfront = closing_costs + points_pct * new_loan + prepayment_penalty
- Points are a share of the new loan: 1 point = 1% of the loan.
- When `roll_costs` is yes, upfront costs are added to the new loan (you pay no cash at closing but pay interest on the costs for the life of the loan). The script solves this iteratively because points depend on the loan amount.
- Cash-out is added to the new loan; the cash you receive counts in your favor in the net position.
## Simple break-even
simple_break_even = ceil(upfront / (old_payment - new_payment))
Shown as "never" when the payment does not go down or the result is longer than the new term. This is the number most calculators show, and it ignores how fast each loan pays down its balance.
## True break-even (the one to use)
Month by month, the script runs both amortization schedules side by side and tracks:
net(m) = sum of (old payment - new payment) up to month m
+ (old balance at m - new balance at m)
- cash paid at closing
+ cash received (cash-out)
The true break-even is the first month where `net(m) >= 0`. `net(horizon)` is the "net at horizon" column: the money you are ahead (or behind) if you sell or refinance again at that point, before taxes and selling costs.
Why they differ:
- A shorter or matching term pays principal down faster, so the true break-even comes before the simple one, even when the payment rises (a 15-year offer can break even in about 16 months while the "saving" is negative).
- A new 30-year term on a loan that had 27 years left lowers the payment partly by stretching it; the slower balance paydown pushes the true break-even later.
- Rolled-in costs show up as a higher new balance, not as cash.
## Points payback
The script assumes the common rule of thumb that 1 point buys about 0.25 percentage points. Points payback = points cost / (payment at rate + 0.25 pp per point - payment at the quoted rate). If the lender quotes the same loan with and without points, compare those two rows directly instead; that is more accurate than the rule of thumb.
## Worked check (from the examples)
Current: 312,000 at 7.25% with 324 months left -> payment 2,197.09.
"Bank A 30y no points": 6.25% for 360 months -> payment 1,921.04, saving 276.05 per month, upfront 5,800, simple break-even ceil(5,800 / 276.05) = 22 months. The true break-even is month 23, slightly later, because the new 30-year schedule pays down principal more slowly than the old one with 27 years left.
## Not modeled
Property tax, insurance and escrow; mortgage insurance; adjustable-rate resets; tax deductibility of interest; inflation and the return you could earn on the closing cost cash; selling costs. Mention them when they could change the decision.
FILE:references/decision-checklist.md
# Refinance decision checklist
## Before choosing
1. How long will you keep the home or this loan? Run the script for at least two horizons (for example 3 and 7 years).
2. Is the new payment comfortable even if income drops? A shorter term saves the most interest but raises the payment (RF09).
3. Are you resetting the clock? A new 30-year loan after paying for years moves the payoff date later (RF02); you can keep the old payoff date by paying extra each month.
4. Are closing costs paid in cash or rolled into the loan (RF04)? Rolling them in feels free but costs interest for years.
5. Are you taking cash out (RF06)? Compare that new debt with other options and with not borrowing it at all.
6. Do the points pay back before you expect to move (RF07)?
7. Is the rate drop large enough (RF08)? Under about 0.5 percentage points, costs often eat the savings unless the offer is genuinely no-cost.
## What each finding means
| code | severity | meaning | what to do |
|---|---|---|---|
| RF01 | high | the offer is still behind at the horizon | skip it, or negotiate costs down and re-run |
| RF02 | medium | payoff date moves later | compare interest to payoff; consider paying extra monthly |
| RF03 | medium | more interest to payoff than the current loan | fine only if you will move or refinance well before payoff |
| RF04 | medium | costs rolled into the balance | ask the price to pay them in cash; compare both |
| RF05 | high | payment rises without a shorter term | usually a bad deal; check for cash-out or fees |
| RF06 | low | cash-out adds debt | compare with a home equity loan or saving up |
| RF07 | medium | points do not pay back within the horizon | ask for the same loan without points |
| RF08 | low | small rate drop | refinance only if costs are very low |
| RF09 | low | shorter term with a higher payment | check the budget and emergency savings |
## Questions for the lender
- Please send the official loan estimate for each option, including the same loan with zero points.
- Which fees are lender fees, and which are third-party (title, appraisal, recording)? Which can be waived or shopped?
- Is the rate locked, until when, and what does extending the lock cost?
- Is there a prepayment penalty on the new loan?
- If costs are rolled in, what is the exact new loan amount?
## Red flags
- Pressure to sign before you receive the loan estimate.
- A "no-cost" offer whose rate is much higher than others (you pay through the rate instead).
- Fees that appear for the first time at closing.
FILE:templates/refinance-summary.md
# Refinance check: {{property_or_household}} - {{date}}
Numbers from: {{statement_date}} statement and loan estimates from {{lenders}}. Estimates of principal and interest only.
## Current loan
- Balance {{balance}} at {{rate}}, {{months_left}} months left, payment {{payment}} (P&I)
- Interest to payoff if nothing changes: {{interest_to_payoff}}
## Comparison (horizon {{horizon_years}} years)
(paste the table from refi_breakeven.py)
## Best option
- At {{horizon_1}} years: {{best_1}} (net {{net_1}})
- At {{horizon_2}} years: {{best_2}} (net {{net_2}})
- Why: {{one or two plain sentences}}
## Watch out
- {{finding code, offer, plain-language meaning}}
## Ask the lender
- {{question}}
## Not included
- Taxes, insurance, escrow, mortgage insurance, rate resets, selling costs, the return on cash you keep.
## Next step
- {{for example: request the zero-point version of offer B and re-run; lock the rate by date}}
FILE:examples/current_loan.json
{
"balance": 312000,
"annual_rate": 0.0725,
"remaining_months": 324,
"prepayment_penalty": 0,
"currency": "USD",
"horizon_months": 84,
"note": "fictional example: 30-year loan taken 3 years ago, owners expect to stay about 7 more years"
}
FILE:examples/offers.csv
name,annual_rate,term_months,closing_costs,points_pct,cash_out,roll_costs
Bank A 30y no points,0.0625,360,5800,0,0,no
Bank A 30y 1 point,0.0600,360,5800,0.01,0,no
Credit union 27y match,0.0630,324,4200,0,0,no
Online lender no-cost,0.0675,360,0,0,0,no
Broker 15y,0.0575,180,6500,0,0,no
Bank B rolled costs,0.0625,360,6200,0,0,yes
Bank B cash-out 30y,0.0650,360,6200,0,35000,no
FILE:scripts/refi_breakeven.py
#!/usr/bin/env python3
"""refi_breakeven.py - compare refinance offers against your current mortgage and find the real break-even month.
For each offer it works out the new monthly payment (principal and interest), the monthly saving,
the simple break-even (upfront costs / monthly saving) and the true break-even month, where the
cumulative payment savings plus the difference in remaining balance first cover what you paid up
front. It also compares total cost over the time you expect to keep the loan, total interest to
payoff, and flags common traps (term reset, costs rolled into the balance, cash-out, points that
never pay back, a prepayment penalty). Standard library only.
Usage:
python3 refi_breakeven.py CURRENT.json OFFERS.csv [--horizon-months N] [--json]
python3 refi_breakeven.py --self-test
CURRENT.json keys: balance, annual_rate (decimal, 0.065 = 6.5%), remaining_months,
optional: monthly_payment (P&I; computed if missing), prepayment_penalty (amount), currency,
horizon_months (how long you expect to keep the loan; default 84).
OFFERS.csv columns: name,annual_rate,term_months,closing_costs,points_pct[,cash_out][,roll_costs]
annual_rate decimal; points_pct as a decimal share of the new loan (0.01 = 1 point);
cash_out extra cash taken (default 0); roll_costs yes/no (costs added to the new loan, default no).
Exit codes: 0 at least one offer breaks even within the horizon and no high findings,
1 no offer pays off within the horizon or high findings present, 2 bad input.
Estimates only: taxes, insurance, escrow, adjustable-rate resets and fees not listed are ignored.
"""
import csv, json, math, sys
SEV = {"RF01": "high", "RF02": "medium", "RF03": "medium", "RF04": "medium", "RF05": "high",
"RF06": "low", "RF07": "medium", "RF08": "low", "RF09": "low"}
NAMES = {"RF01": "does not break even within the horizon",
"RF02": "term reset: payoff date moves later",
"RF03": "more total interest to payoff than keeping the current loan",
"RF04": "costs rolled into the loan (you pay interest on them)",
"RF05": "monthly payment goes up with no shorter term",
"RF06": "cash-out increases the debt (compare like for like)",
"RF07": "points take longer to pay back than the horizon",
"RF08": "rate drop under 0.5 percentage points",
"RF09": "shorter term with a higher payment: check it fits your budget"}
POINT_RATE_CUT = 0.0025 # rule of thumb: 1 point (1% of the loan) buys about 0.25 percentage points
class InputError(Exception):
pass
def payment(principal, annual_rate, months):
if months <= 0:
raise InputError("months must be positive")
r = annual_rate / 12.0
if r == 0:
return principal / months
return principal * r / (1 - (1 + r) ** -months)
def schedule(principal, annual_rate, months, pay):
"""Yield (month, interest, principal_paid, balance) until paid off or months reached."""
r = annual_rate / 12.0
bal = principal
for m in range(1, months + 1):
interest = bal * r
princ = min(pay - interest, bal)
bal = bal - princ
if bal < 0.005:
bal = 0.0
yield m, interest, princ, bal
if bal == 0.0:
break
def balance_after(principal, annual_rate, pay, m):
b = principal
for mm, _, _, bal in schedule(principal, annual_rate, 10 ** 6, pay):
b = bal
if mm >= m or bal == 0:
break
return b if m > 0 else principal
def total_interest(principal, annual_rate, months, pay):
return sum(i for _, i, _, _ in schedule(principal, annual_rate, months, pay))
def to_float(row, key, default=None, lo=None, hi=None):
v = row.get(key)
if v is None or str(v).strip() == "":
if default is None:
raise InputError("missing %s" % key)
return default
try:
f = float(str(v).replace(",", "").strip())
except ValueError:
raise InputError("%s is not a number: %r" % (key, v))
if lo is not None and f < lo or hi is not None and f > hi:
raise InputError("%s out of range: %r" % (key, v))
return f
def load_current(path):
try:
d = json.load(open(path, encoding="utf-8"))
except (OSError, ValueError) as e:
raise InputError("cannot read %s: %s" % (path, e))
cur = {"balance": to_float(d, "balance", lo=1),
"annual_rate": to_float(d, "annual_rate", lo=0, hi=0.5),
"remaining_months": int(to_float(d, "remaining_months", lo=1, hi=600)),
"prepayment_penalty": to_float(d, "prepayment_penalty", 0.0, lo=0),
"currency": d.get("currency", ""),
"horizon_months": int(to_float(d, "horizon_months", 84, lo=1, hi=600))}
if cur["annual_rate"] > 0.3:
raise InputError("annual_rate looks like a percent; use a decimal such as 0.065")
calc = payment(cur["balance"], cur["annual_rate"], cur["remaining_months"])
cur["monthly_payment"] = to_float(d, "monthly_payment", calc, lo=0.01)
if cur["monthly_payment"] <= cur["balance"] * cur["annual_rate"] / 12:
raise InputError("monthly_payment does not cover the interest")
return cur
def load_offers(path):
try:
rows = list(csv.DictReader(open(path, encoding="utf-8", newline="")))
except OSError as e:
raise InputError("cannot read %s: %s" % (path, e))
if not rows:
raise InputError("no offers in %s" % path)
out = []
for n, r in enumerate(rows, 2):
try:
rate = to_float(r, "annual_rate", lo=0, hi=0.5)
if rate > 0.3:
raise InputError("annual_rate looks like a percent; use a decimal")
pts = to_float(r, "points_pct", 0.0, lo=0, hi=0.1)
out.append({"name": (r.get("name") or "offer %d" % (n - 1)).strip(), "annual_rate": rate,
"term_months": int(to_float(r, "term_months", lo=12, hi=600)),
"closing_costs": to_float(r, "closing_costs", 0.0, lo=0), "points_pct": pts,
"cash_out": to_float(r, "cash_out", 0.0, lo=0),
"roll_costs": (r.get("roll_costs") or "no").strip().lower() in ("yes", "y", "true", "1")})
except InputError as e:
raise InputError("offers line %d: %s" % (n, e))
return out
def analyse(cur, offers, horizon=None):
H = horizon or cur["horizon_months"]
bal, rate, rem, pay = cur["balance"], cur["annual_rate"], cur["remaining_months"], cur["monthly_payment"]
cur_interest = total_interest(bal, rate, 10 ** 6, pay)
cur_months = sum(1 for _ in schedule(bal, rate, 10 ** 6, pay))
cur_cost_h = pay * min(H, cur_months) + balance_after(bal, rate, pay, H)
results = []
for o in offers:
base = bal + o["cash_out"]
# points are charged on the new loan amount; solve iteratively when costs are rolled in
loan = base
for _ in range(20):
upfront = o["closing_costs"] + o["points_pct"] * loan + cur["prepayment_penalty"]
new_loan = base + (upfront if o["roll_costs"] else 0.0)
if abs(new_loan - loan) < 0.01:
break
loan = new_loan
loan = new_loan
cash_paid = 0.0 if o["roll_costs"] else upfront
npay = payment(loan, o["annual_rate"], o["term_months"])
saving = pay - npay
simple = math.ceil(upfront / saving) if saving > 0 else None
if simple is not None and simple > o["term_months"]:
simple = None
# true break-even: cumulative (old - new payments) + (old balance - new balance) - cash paid - cash_out adj >= 0
true_be = None
horizon_net = None
cum = 0.0
ob, nb = bal, loan
oi = schedule(bal, rate, 10 ** 6, pay)
ni = schedule(loan, o["annual_rate"], o["term_months"], npay)
for m in range(1, max(cur_months, o["term_months"]) + 1):
op = np_ = 0.0
try:
_, i1, p1, ob = next(oi); op = i1 + p1
except StopIteration:
pass
try:
_, i2, p2, nb = next(ni); np_ = i2 + p2
except StopIteration:
pass
cum += op - np_
net = cum + (ob - nb) - cash_paid + o["cash_out"]
if m == H:
horizon_net = net
if true_be is None and net >= 0 and m >= 1:
true_be = m
if horizon_net is None:
horizon_net = net
new_interest = total_interest(loan, o["annual_rate"], o["term_months"], npay)
r = {"name": o["name"], "new_loan": round(loan, 2), "annual_rate": o["annual_rate"], "term_months": o["term_months"],
"upfront_costs": round(upfront, 2), "cash_paid_at_closing": round(cash_paid, 2), "new_payment": round(npay, 2),
"monthly_saving": round(saving, 2), "simple_break_even_months": simple, "true_break_even_month": true_be,
"net_benefit_at_horizon": round(horizon_net, 2), "total_interest_new": round(new_interest, 2),
"total_interest_current": round(cur_interest, 2), "payoff_shift_months": o["term_months"] - cur_months,
"findings": []}
f = r["findings"]
if true_be is None or true_be > H:
f.append("RF01")
if o["term_months"] > cur_months + 6:
f.append("RF02")
if new_interest > cur_interest:
f.append("RF03")
if o["roll_costs"] and upfront > 0:
f.append("RF04")
if saving < 0 and o["term_months"] >= cur_months:
f.append("RF05")
if o["cash_out"] > 0:
f.append("RF06")
pts_payback = None
if o["points_pct"] > 0:
pts_cost = o["points_pct"] * loan
no_pts_rate = o["annual_rate"] + o["points_pct"] / 0.01 * POINT_RATE_CUT
pts_saving = payment(loan, no_pts_rate, o["term_months"]) - npay
pts_payback = math.ceil(pts_cost / pts_saving) if pts_saving > 0 else None
if pts_payback is None or pts_payback > H:
f.append("RF07")
r["points_payback_months"] = pts_payback
if saving < 0 and o["term_months"] < cur_months:
f.append("RF09")
if 0 <= rate - o["annual_rate"] < 0.005:
f.append("RF08")
results.append(r)
best = max(results, key=lambda x: x["net_benefit_at_horizon"])
return {"current": {"balance": bal, "annual_rate": rate, "remaining_months": rem, "monthly_payment": round(pay, 2),
"months_to_payoff": cur_months, "total_interest_to_payoff": round(cur_interest, 2),
"cost_over_horizon_incl_balance": round(cur_cost_h, 2)},
"horizon_months": H, "currency": cur["currency"], "offers": results,
"best_at_horizon": best["name"] if best["net_benefit_at_horizon"] > 0 else None}
def money(x, cur=""):
return ("%s%s" % (cur + " " if cur else "", "{:,.2f}".format(x)))
def render(a):
c, cur = a["current"], a["currency"]
L = ["# Refinance check (horizon %d months = %.1f years)" % (a["horizon_months"], a["horizon_months"] / 12), "",
"Current loan: balance %s at %.3f%%, %d months left, payment %s (P&I), interest to payoff %s" % (
money(c["balance"], cur), c["annual_rate"] * 100, c["months_to_payoff"], money(c["monthly_payment"], cur),
money(c["total_interest_to_payoff"], cur)), "",
"| offer | rate | term | new loan | upfront | new payment | saving/mo | simple BE | true BE | net at horizon | interest to payoff |",
"|---|---|---|---|---|---|---|---|---|---|---|"]
for r in a["offers"]:
L.append("| %s | %.3f%% | %d | %s | %s | %s | %s | %s | %s | %s | %s |" % (
r["name"], r["annual_rate"] * 100, r["term_months"], money(r["new_loan"]), money(r["upfront_costs"]),
money(r["new_payment"]), money(r["monthly_saving"]),
("%d mo" % r["simple_break_even_months"]) if r["simple_break_even_months"] is not None else "never",
("%d mo" % r["true_break_even_month"]) if r["true_break_even_month"] is not None else "never",
money(r["net_benefit_at_horizon"]), money(r["total_interest_new"])))
L += ["", "Best at the horizon: %s" % (a["best_at_horizon"] or "none - keeping the current loan costs least"), "", "## Findings"]
n = 0
for r in a["offers"]:
for code in r["findings"]:
n += 1
L.append("- [%s] %s %s: %s" % (SEV[code], code, r["name"], NAMES[code]))
if not n:
L.append("- none")
L += ["", "Estimates of principal and interest only; confirm with the lender's official loan estimate."]
return "\n".join(L)
def exit_code(a):
high = any(SEV[c] == "high" for r in a["offers"] for c in r["findings"])
ok = any(r["true_break_even_month"] is not None and r["true_break_even_month"] <= a["horizon_months"] for r in a["offers"])
return 0 if ok and not high else 1
def self_test():
T = []
def check(name, cond):
T.append((name, bool(cond)))
check("payment 200k 6% 360m = 1199.10", abs(payment(200000, 0.06, 360) - 1199.10) < 0.01)
check("zero-rate payment = principal / months", payment(12000, 0, 120) == 100)
check("schedule pays off to zero", list(schedule(10000, 0.05, 60, payment(10000, 0.05, 60)))[-1][3] == 0)
check("balance after 0 months = principal", balance_after(1000, 0.05, 100, 0) == 1000)
cur = {"balance": 300000, "annual_rate": 0.07, "remaining_months": 300, "prepayment_penalty": 0, "currency": "",
"horizon_months": 84}
cur["monthly_payment"] = payment(300000, 0.07, 300)
same = analyse(cur, [{"name": "same", "annual_rate": 0.07, "term_months": 300, "closing_costs": 0, "points_pct": 0,
"cash_out": 0, "roll_costs": False}])["offers"][0]
check("identical free offer saves nothing", abs(same["monthly_saving"]) < 0.01 and abs(same["net_benefit_at_horizon"]) < 0.5)
o = {"name": "cut", "annual_rate": 0.055, "term_months": 300, "closing_costs": 6000, "points_pct": 0, "cash_out": 0,
"roll_costs": False}
r = analyse(cur, [o])["offers"][0]
check("lower rate same term saves money each month", r["monthly_saving"] > 0)
check("simple break-even = ceil(costs / saving)", r["simple_break_even_months"] == math.ceil(6000 / r["monthly_saving"]))
check("true break-even exists and <= simple", r["true_break_even_month"] and r["true_break_even_month"] <= r["simple_break_even_months"])
check("no term reset finding at same term", "RF02" not in r["findings"])
o2 = dict(o, name="reset", term_months=360)
r2 = analyse(cur, [o2])["offers"][0]
check("30-year reset flagged RF02", "RF02" in r2["findings"])
o3 = dict(o, name="tiny", annual_rate=0.068, closing_costs=8000)
r3 = analyse(cur, [o3])["offers"][0]
check("tiny rate drop flagged RF08", "RF08" in r3["findings"])
check("tiny drop with big costs flagged RF01", "RF01" in r3["findings"])
o4 = dict(o, name="rolled", roll_costs=True)
r4 = analyse(cur, [o4])["offers"][0]
check("rolled costs raise the loan by the costs", abs(r4["new_loan"] - 306000) < 0.01)
check("rolled costs flagged RF04 and no cash at closing", "RF04" in r4["findings"] and r4["cash_paid_at_closing"] == 0)
o5 = dict(o, name="points", points_pct=0.01)
r5 = analyse(cur, [o5])["offers"][0]
check("1 point adds 1% of the loan to upfront", abs(r5["upfront_costs"] - 9000) < 0.01)
o6 = dict(o, name="cash", cash_out=40000)
r6 = analyse(cur, [o6])["offers"][0]
check("cash-out flagged RF06 and loan includes it", "RF06" in r6["findings"] and abs(r6["new_loan"] - 340000) < 0.01)
o7 = dict(o, name="higher", annual_rate=0.08)
check("higher payment, same term flagged RF05", "RF05" in analyse(cur, [o7])["offers"][0]["findings"])
o8 = dict(o, name="15y", annual_rate=0.052, term_months=180, closing_costs=5000)
r8 = analyse(cur, [o8])["offers"][0]
check("15-year offer cuts total interest", r8["total_interest_new"] < r8["total_interest_current"])
check("15-year higher payment flagged RF09, not RF05", "RF09" in r8["findings"] and "RF05" not in r8["findings"])
check("points payback uses 0.25 pp per point", r5["points_payback_months"] and r5["points_payback_months"] > 0)
o9 = dict(o, name="free", closing_costs=0)
r9 = analyse(cur, [o9])["offers"][0]
check("no-cost offer: simple break-even 0 months", r9["simple_break_even_months"] == 0 and r9["true_break_even_month"] == 1)
for bad, label in [({"balance": 0, "annual_rate": 0.05, "remaining_months": 100}, "zero balance rejected"),
({"balance": 1000, "annual_rate": 6.5, "remaining_months": 100}, "percent rate rejected")]:
try:
to_float(bad, "balance", lo=1); r_ = to_float(bad, "annual_rate", lo=0, hi=0.5)
check(label, False)
except InputError:
check(label, True)
for name, ok in T:
print(("PASS " if ok else "FAIL ") + name)
good = all(ok for _, ok in T)
print("ALL PASS" if good else "SOME FAILED", "(%d/%d)" % (sum(ok for _, ok in T), len(T)))
return 0 if good else 1
def main(argv):
if "--self-test" in argv:
return self_test()
args = [a for a in argv if not a.startswith("--")]
horizon = None
if "--horizon-months" in argv:
try:
horizon = int(argv[argv.index("--horizon-months") + 1])
args.remove(str(horizon))
except (IndexError, ValueError):
print("error: --horizon-months needs a whole number", file=sys.stderr); return 2
if len(args) != 2:
print(__doc__, file=sys.stderr); return 2
try:
a = analyse(load_current(args[0]), load_offers(args[1]), horizon)
except InputError as e:
print("error: %s" % e, file=sys.stderr); return 2
print(json.dumps(a, indent=2) if "--json" in argv else render(a))
return exit_code(a)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

Turns an uploaded photo of a woman into a photorealistic 1970s editorial studio portrait with a crimson lip, ivory satin lace blouse, warm spotlight glow and analog film tones, keeping her exact identity.
Create a highly photorealistic cinematic vintage studio portrait of the same adult woman shown in the uploaded reference image. Preserve her exact facial identity, recognizable features, natural skin tone, face shape, eyes, nose, lips, and facial proportions without beautification or alteration. Appearance & Makeup: She has a short, softly tousled dark-brown bob with gentle loose curls framing her cheeks and delicate wispy bangs across her forehead. Her expressive hazel-brown eyes are enhanced with subtle smoky eyeliner, naturally shaped eyebrows, softly flushed cheeks, and elegant deep crimson-red lipstick. Her complexion is warm and luminous, with realistic skin texture and natural details. Outfit & Styling: She wears an elegant ivory satin blouse with a modest, softly draped neckline, delicate lace detailing around the collar, and subtle puff sleeves. The blouse is neatly fitted and tucked into a high-waisted black tailored mini skirt with a refined silhouette. Add sheer dark burgundy stockings for a sophisticated vintage-inspired look. The overall styling should feel elegant, tasteful, and timeless rather than revealing. Pose & Composition: She sits gracefully on a low vintage studio chair, leaning slightly forward with relaxed shoulders and a confident posture. Her hands rest naturally together on her lap. Her chin is gently raised as she looks directly into the camera with a confident, subtly mysterious expression. Lighting & Background: A minimalist warm beige studio wall serves as the background. A strong directional spotlight creates a soft circular glow behind her, accompanied by a beautifully defined shadow falling to one side. Rich warm shadows, gentle highlights across her face, and subtle cinematic contrast create an intimate vintage Hollywood atmosphere. Photography Style: Classic 1970s editorial portrait photography, vintage studio glamour, warm analog film tones, authentic skin texture, subtle film grain, sophisticated color grading, professional fashion photography, sharp facial focus, beautifully balanced composition, highly detailed, photorealistic, vertical portrait. Maintain the reference woman's exact identity throughout. No cartoon features, no anime aesthetics, no artificial skin smoothing, no exaggerated body proportions, and no changes to her recognizable appearance.
Checks a small team's timesheets pre-payroll: splits each week into regular, overtime and double-time hours under your daily and weekly rules, estimates pay, and flags missing punches, overlaps, duplicates, short breaks, short rest, over-max weeks and too many days in a row. Offline stdlib Python.
---
name: employee-timesheet-and-overtime-checker
description: Checks a small team's timesheets pre-payroll: splits each week into regular, overtime and double-time hours under your daily and weekly rules, estimates pay, and flags missing punches, overlaps, duplicates, short breaks, short rest, over-max weeks and too many days in a row. Offline stdlib Python.
---
# Employee Timesheet and Overtime Checker
You help small business owners, shop and restaurant managers, office managers and payroll admins check a week or two of timesheets before they run payroll. Timesheet mistakes are expensive in both directions: a missing clock-out or a duplicate row pays the wrong amount, overtime that is not paid becomes a wage claim, and short breaks or short rest between a closing and an opening shift can break working-time rules. You turn the raw export into a clear hours-and-pay table and a short list of things to fix or confirm.
You work only on the files the user gives you, on their machine. You never decide what the law is where they are: you apply the rules they confirm, say clearly that the bundled defaults are only an example, and suggest checking local labour rules, the employment contracts or a payroll provider for anything unclear. You do not judge employees; findings are data questions to check with the person and their manager.
## Files in this skill
- `scripts/timesheet_check.py` - reads a timesheet CSV (and optional employees and rules files), splits hours per employee and week into regular, overtime and double time with daily and weekly thresholds, estimates gross pay, and reports findings TS01-TS11 by severity; `--json` for tooling, `--self-test` runs 20 checks (Python 3.8+ standard library only)
- `references/overtime-and-working-time-rules.md` - how the hours are split, what each rule key means, examples of rule sets people commonly configure, and what the script does not handle
- `references/fixing-timesheet-problems.md` - what each finding usually means, how to confirm and correct it, and how to prevent it next time
- `templates/payroll-check-report.md` - the summary you hand back before payroll
- `examples/timesheet.csv`, `examples/employees.csv`, `examples/rules.json` - a fictional shop week with five people and planted problems (missing clock-out, duplicate row, overlap, short break, closing-then-opening, a 49-hour week)
## Workflow
### 1. Confirm the rules first
Before running anything, ask which rules apply and fill `rules.json`:
- week start day and pay period;
- overtime thresholds (daily and/or weekly hours), multipliers and any double-time threshold;
- break rules (break required after how many hours, minimum minutes, paid or unpaid);
- minimum rest between shifts, maximum weekly hours and maximum days in a row;
- which employees are not eligible for overtime (salaried or exempt) and their hourly rates.
If the user does not know, run with the defaults but label every result "example rules" and list the questions in the report.
### 2. Prepare the files
- `timesheet.csv`: `employee,date,start,end,break_minutes[,note]`, date `YYYY-MM-DD`, times `HH:MM` 24 h. An end time earlier than the start means an overnight shift counted on the start date. Most clock systems can export this; rename columns if needed.
- `employees.csv` (optional): `employee,hourly_rate[,overtime_eligible]`.
- Names must match exactly between files.
### 3. Run the check
```
python3 scripts/timesheet_check.py examples/timesheet.csv --rules examples/rules.json --employees examples/employees.csv
python3 scripts/timesheet_check.py timesheet.csv --rules rules.json --employees employees.csv --json > check.json
python3 scripts/timesheet_check.py --self-test
```
Exit 0 = no high findings, 1 = high findings to fix before payroll, 2 = bad input. Without a shell, follow `references/overtime-and-working-time-rules.md` by hand for each employee and week.
### 4. Triage the findings
- High (fix before payroll): TS01 missing or unreadable time (the row was skipped, so pay is too low), TS02 overlapping shifts (double counting or a wrong date), TS08 over the weekly maximum.
- Medium (confirm with the manager): TS04 duplicate row (counted once), TS05 very long shift, TS06 missing or short break, TS07 short rest between shifts, TS09 too many days in a row.
- Low (information): TS10 no pay rate, TS11 overnight shift.
Use `references/fixing-timesheet-problems.md` for the likely cause and the fix. Never "correct" a time yourself: list the question for the employee or manager, then re-run after they confirm.
### 5. Report
Fill `templates/payroll-check-report.md`: rules used, hours and pay table, overtime total and cost, findings with the exact question to ask, and anything the script does not cover (shift premiums, holiday pay, tips, on-call, travel time, local rounding rules).
## Rules
- Overtime is never counted twice: hours already paid as daily overtime or double time do not count toward the weekly regular threshold.
- Pay estimates are gross base pay only, before taxes, premiums, allowances and deductions.
- Keep personal data private: do not upload timesheets, and share only the report with people who need it.
FILE:references/overtime-and-working-time-rules.md
# How timesheet_check.py splits hours and applies rules
## Worked time
worked hours = (end - start) - break. An end at or before the start is an overnight shift (end + 24 h), counted on the start date. Rows with a missing or unreadable time are skipped and reported as TS01, so the employee's total is too low until fixed.
## Splitting a week (no double counting)
For each employee and week (week_start in rules), day by day in date order:
1. Double time = hours above daily_dt_after (if set).
2. Daily overtime = remaining hours above daily_ot_after (if set).
3. The rest is regular, until the week's regular hours reach weekly_ot_after; regular hours beyond that move to overtime.
Employees with overtime_eligible = no get all hours as regular.
Pay estimate = rate x (regular + overtime x ot_multiplier + double time x dt_multiplier).
Example (daily 8 / weekly 40): Mon 8, Tue 8, Wed 10, Thu 8, Fri 9, Sat 5 = 48 h. Daily overtime 2 + 1 = 3 h; regular would be 45, so 5 more hours move to overtime: 40 regular, 8 overtime.
## Rule keys
| key | meaning | default |
|---|---|---|
| week_start | first day of the work week | monday |
| daily_ot_after | overtime after this many hours in a day (null = no daily overtime) | null |
| daily_dt_after | double time after this many hours in a day (null = none) | null |
| weekly_ot_after | overtime after this many regular hours in a week (null = none) | 40 |
| ot_multiplier / dt_multiplier | pay multipliers | 1.5 / 2.0 |
| break_required_after_hours / min_break_minutes | a break of at least N minutes for shifts longer than H hours | 6 / 30 |
| min_rest_hours | minimum rest between two shifts on different days | 11 |
| max_weekly_hours | flag weeks above this total | 48 |
| max_shift_hours | flag a start-to-end span above this (often a typo) | 14 |
| max_days_in_a_row | flag runs of consecutive working days above this | 6 |
## Rule sets people commonly configure (check your own law and contracts)
- Weekly-only overtime: weekly_ot_after 40, daily keys null (a common US federal-style setup).
- Daily and weekly overtime with double time: daily_ot_after 8, daily_dt_after 12, weekly_ot_after 40 (used in some US states).
- Working-time limits without statutory overtime pay: weekly_ot_after null or per contract, min_rest_hours 11, max_weekly_hours 48 (European working-time style; the 48 h is often an average over several months, which this weekly check does not average).
These are examples to start a conversation, not legal advice.
## Not handled
Averaging periods, seventh-day rules, shift or night premiums, holiday and sick pay, on-call and travel time, split-shift premiums, tips, minimum wage checks, time rounding policies, and multi-rate employees. Mention any that apply and handle them separately.
FILE:references/fixing-timesheet-problems.md
# Findings: likely causes and fixes
| code | finding | likely cause | how to confirm and fix | prevent next time |
|---|---|---|---|---|
| TS01 | missing or unreadable time | forgot to clock out, app crash, manual edit | ask the employee and manager for the real time; add it and re-run | clock-out reminders; manager reviews open punches daily |
| TS02 | overlapping shifts | wrong date on an overnight shift, double entry, two locations | compare with the rota and the till/door logs; fix the date or delete the duplicate | one clock-in at a time per person |
| TS03 | break longer than the shift | break entered in hours or the wrong column | confirm the real break and correct it | validate break fields in the export |
| TS04 | duplicate row | double import or edit | the script counts it once; delete it at the source | import each period once |
| TS05 | very long shift | typo in the end time or a missing clock-out the next day | confirm with the employee; if real, check rest and maximum rules | alert on shifts over the limit |
| TS06 | break missing or short | busy shift, break not recorded | ask whether a break was taken; some places owe a penalty for missed breaks | schedule breaks on the rota |
| TS07 | short rest between shifts | closing then opening ("clopening") | confirm; adjust the rota; check whether local rules require a premium | rota checks before publishing |
| TS08 | over the weekly maximum | extra cover, missing staff | confirm the hours are real and any opt-out or averaging agreement | plan cover earlier |
| TS09 | too many days in a row | cover for absence | confirm a day off is scheduled | rota checks |
| TS10 | no pay rate | new hire, name spelled differently | add the employee or fix the name | one employee list as the source of names |
| TS11 | overnight shift | night work | confirm the start date is right | none needed |
When you report a finding, give the exact question to ask, for example: "Priya, on Wed 18 Nov you clocked in at 09:00 but there is no clock-out. What time did you finish?"
FILE:templates/payroll-check-report.md
# Payroll check: {{business}} - pay period {{period}}
Prepared {{date}}. Rules used: {{rules_summary}} ({{confirmed_or_example}} rules).
## Summary
- Employees: {{employee_count}} | shifts: {{shift_count}}
- Overtime and double-time hours: {{ot_hours}} (estimated cost {{ot_cost}})
- Estimated gross base pay: {{gross_pay}}
- Fix before payroll: {{high_count}} high findings | confirm: {{medium_count}} medium
## Hours and pay
(paste the table from timesheet_check.py)
## Fix before payroll
| employee | date | finding | question to ask | owner |
|---|---|---|---|---|
| {{employee}} | {{date}} | {{code and issue}} | {{exact question}} | {{manager}} |
## Confirm with managers
- {{finding and question}}
## Not covered by this check
- {{premiums, holiday pay, tips, averaging periods, local rounding rules}}
## Rota suggestions
- {{for example: avoid closing-then-opening shifts; schedule breaks on 8 h shifts}}
FILE:examples/timesheet.csv
employee,date,start,end,break_minutes,note
Maya Torres,2026-11-16,07:00,15:30,30,
Maya Torres,2026-11-17,07:00,15:30,30,
Maya Torres,2026-11-18,07:00,17:30,30,stock delivery
Maya Torres,2026-11-19,07:00,15:30,30,
Maya Torres,2026-11-20,07:00,16:30,30,
Maya Torres,2026-11-21,08:00,13:00,0,Saturday cover
Jonah Reed,2026-11-16,12:00,20:30,30,
Jonah Reed,2026-11-17,12:00,23:00,30,closing
Jonah Reed,2026-11-18,07:00,15:00,30,opening after closing
Jonah Reed,2026-11-19,12:00,20:30,15,
Jonah Reed,2026-11-20,12:00,20:30,30,
Jonah Reed,2026-11-20,12:00,20:30,30,
Priya Nair,2026-11-16,09:00,17:00,45,
Priya Nair,2026-11-17,09:00,17:00,45,
Priya Nair,2026-11-18,09:00,,45,forgot to clock out
Priya Nair,2026-11-19,09:00,19:00,45,
Priya Nair,2026-11-20,09:00,17:00,45,
Sam Okafor,2026-11-17,22:00,06:30,30,night stock count
Sam Okafor,2026-11-18,06:00,10:00,0,
Sam Okafor,2026-11-19,18:00,23:00,0,
Lena Fischer,2026-11-16,08:00,16:00,30,
Lena Fischer,2026-11-17,08:00,18:00,60,
Lena Fischer,2026-11-18,08:00,18:00,60,
Lena Fischer,2026-11-19,08:00,18:00,60,
Lena Fischer,2026-11-20,08:00,18:00,60,
Lena Fischer,2026-11-21,08:00,14:00,30,
FILE:examples/employees.csv
employee,hourly_rate,overtime_eligible
Maya Torres,19.50,yes
Jonah Reed,17.00,yes
Priya Nair,24.00,yes
Sam Okafor,18.25,yes
Lena Fischer,32.00,no
FILE:examples/rules.json
{
"name": "Example shop rules (illustrative only, set yours from local law and contracts)",
"week_start": "monday",
"daily_ot_after": 8,
"daily_dt_after": 12,
"weekly_ot_after": 40,
"ot_multiplier": 1.5,
"dt_multiplier": 2.0,
"break_required_after_hours": 6,
"min_break_minutes": 30,
"min_rest_hours": 11,
"max_weekly_hours": 48,
"max_shift_hours": 14,
"max_days_in_a_row": 6
}
FILE:scripts/timesheet_check.py
#!/usr/bin/env python3
"""timesheet_check.py - check a team's timesheets and work out regular, overtime and double-time hours.
Reads shift rows, applies your overtime and working-time rules (daily and weekly
thresholds, multipliers, breaks, rest between shifts, weekly maximum, days in a
row), estimates pay per employee and week, and flags data errors and rule
breaches before payroll. Standard library only.
Usage:
python3 timesheet_check.py TIMESHEET.csv [--rules RULES.json] [--employees EMPLOYEES.csv] [--json]
python3 timesheet_check.py --self-test
TIMESHEET.csv columns: employee,date,start,end,break_minutes[,note]
date YYYY-MM-DD, start/end HH:MM (24 h). An end earlier than the start is an overnight shift
(counted on the start date).
EMPLOYEES.csv columns: employee,hourly_rate[,overtime_eligible] (overtime_eligible: yes/no, default yes)
RULES.json keys (all optional, defaults in DEFAULT_RULES): week_start (monday..sunday),
daily_ot_after, daily_dt_after, weekly_ot_after (hours or null), ot_multiplier, dt_multiplier,
break_required_after_hours, min_break_minutes, min_rest_hours, max_weekly_hours,
max_shift_hours, max_days_in_a_row.
Exit codes: 0 no high findings, 1 high findings, 2 bad input.
The default rules are an example, not the law where you are: set them from your local labour rules and contracts.
"""
import csv, datetime as dt, json, sys
from collections import defaultdict
DEFAULT_RULES = {
"week_start": "monday",
"daily_ot_after": None, # e.g. 8 where daily overtime applies
"daily_dt_after": None, # e.g. 12 where daily double time applies
"weekly_ot_after": 40,
"ot_multiplier": 1.5,
"dt_multiplier": 2.0,
"break_required_after_hours": 6,
"min_break_minutes": 30,
"min_rest_hours": 11,
"max_weekly_hours": 48,
"max_shift_hours": 14,
"max_days_in_a_row": 6,
}
DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
SEV = {"TS01": "high", "TS02": "high", "TS03": "high", "TS04": "medium", "TS05": "medium", "TS06": "medium",
"TS07": "medium", "TS08": "high", "TS09": "medium", "TS10": "low", "TS11": "low"}
NAMES = {"TS01": "missing or unreadable time", "TS02": "overlapping shifts", "TS03": "break longer than the shift",
"TS04": "duplicate row", "TS05": "very long shift (typo?)", "TS06": "required break missing or short",
"TS07": "short rest between shifts", "TS08": "over the weekly maximum", "TS09": "too many days in a row",
"TS10": "no pay rate", "TS11": "overnight shift (check the date)"}
class InputError(Exception):
pass
def parse_time(s):
try:
h, m = s.strip().split(":")
h, m = int(h), int(m)
if not (0 <= h <= 24 and 0 <= m < 60) or (h == 24 and m):
raise ValueError
return h * 60 + m
except (ValueError, AttributeError):
return None
def load_rules(path):
rules = dict(DEFAULT_RULES)
if path:
with open(path, encoding="utf-8") as f:
user = json.load(f)
unknown = set(user) - set(DEFAULT_RULES) - {"name", "notes"}
if unknown:
raise InputError("unknown rule keys: " + ", ".join(sorted(unknown)))
rules.update({k: v for k, v in user.items() if k in DEFAULT_RULES})
if str(rules["week_start"]).lower() not in DAYS:
raise InputError("week_start must be a weekday name")
for k in ("ot_multiplier", "dt_multiplier"):
if not isinstance(rules[k], (int, float)) or rules[k] < 1:
raise InputError(k + " must be a number >= 1")
return rules
def load_employees(path):
emp = {}
if not path:
return emp
with open(path, newline="", encoding="utf-8") as f:
for i, row in enumerate(csv.DictReader(f), start=2):
row = {k.strip(): (v or "").strip() for k, v in row.items()}
try:
rate = float(row.get("hourly_rate", ""))
except ValueError:
raise InputError("employees line %d: hourly_rate must be a number" % i)
emp[row["employee"]] = {"rate": rate, "ot": row.get("overtime_eligible", "yes").lower() not in ("no", "n", "false", "0")}
return emp
def load_shifts(path):
shifts, findings = [], []
with open(path, newline="", encoding="utf-8") as f:
r = csv.DictReader(f)
need = {"employee", "date", "start", "end", "break_minutes"}
if not r.fieldnames or not need.issubset({h.strip() for h in r.fieldnames}):
raise InputError("timesheet needs columns employee,date,start,end,break_minutes")
seen = set()
for i, row in enumerate(r, start=2):
row = {k.strip(): (v or "").strip() for k, v in row.items() if k}
if not any(row.values()):
continue
e = row["employee"]
key = (e, row["date"], row["start"], row["end"])
if key in seen:
findings.append(("TS04", e, row["date"], "line %d repeats an earlier row; counted once" % i))
continue
seen.add(key)
try:
day = dt.date.fromisoformat(row["date"])
except ValueError:
findings.append(("TS01", e, row["date"], "line %d: date is not YYYY-MM-DD; row skipped" % i)); continue
s, en = parse_time(row["start"]), parse_time(row["end"])
if s is None or en is None:
findings.append(("TS01", e, row["date"], "line %d: start or end missing/unreadable (%r-%r); row skipped" % (i, row["start"], row["end"]))); continue
try:
brk = int(row["break_minutes"] or 0)
except ValueError:
findings.append(("TS01", e, row["date"], "line %d: break_minutes is not a whole number; treated as 0" % i)); brk = 0
overnight = en <= s
if overnight:
en += 24 * 60
findings.append(("TS11", e, row["date"], "line %d: %s-%s crosses midnight; counted on %s" % (i, row["start"], row["end"], row["date"])))
start = dt.datetime.combine(day, dt.time()) + dt.timedelta(minutes=s)
end = dt.datetime.combine(day, dt.time()) + dt.timedelta(minutes=en)
span = (en - s)
if brk > span:
findings.append(("TS03", e, row["date"], "line %d: break %d min is longer than the %d-min shift; worked time set to 0" % (i, brk, span)))
brk = span
shifts.append({"employee": e, "date": day, "start": start, "end": end, "break": brk,
"hours": (span - brk) / 60.0, "span_h": span / 60.0, "line": i, "note": row.get("note", "")})
return shifts, findings
def week_of(day, week_start):
offset = (day.weekday() - DAYS.index(week_start)) % 7
return day - dt.timedelta(days=offset)
def analyse(shifts, rules, employees, findings):
ws = rules["week_start"].lower()
by_emp = defaultdict(list)
for s in shifts:
by_emp[s["employee"]].append(s)
weeks = []
for e, ss in sorted(by_emp.items()):
ss.sort(key=lambda x: x["start"])
for a, b in zip(ss, ss[1:]):
if b["start"] < a["end"]:
findings.append(("TS02", e, b["date"].isoformat(), "lines %d and %d overlap (%s-%s and %s-%s)" % (
a["line"], b["line"], a["start"].strftime("%a %H:%M"), a["end"].strftime("%H:%M"), b["start"].strftime("%a %H:%M"), b["end"].strftime("%H:%M"))))
else:
rest = (b["start"] - a["end"]).total_seconds() / 3600
if rules["min_rest_hours"] and rest < rules["min_rest_hours"] and b["date"] != a["date"]:
findings.append(("TS07", e, b["date"].isoformat(), "only %.1f h rest between line %d and line %d (minimum %s h)" % (rest, a["line"], b["line"], rules["min_rest_hours"])))
for s in ss:
if rules["max_shift_hours"] and s["span_h"] > rules["max_shift_hours"]:
findings.append(("TS05", e, s["date"].isoformat(), "line %d: %.1f h from start to end (limit %s h); check for a typo" % (s["line"], s["span_h"], rules["max_shift_hours"])))
if rules["break_required_after_hours"] and s["span_h"] > rules["break_required_after_hours"] and s["break"] < rules["min_break_minutes"]:
findings.append(("TS06", e, s["date"].isoformat(), "line %d: %.1f h shift with %d min break (needs %d min after %s h)" % (s["line"], s["span_h"], s["break"], rules["min_break_minutes"], rules["break_required_after_hours"])))
days = sorted({s["date"] for s in ss if s["hours"] > 0})
run, best, best_end = 1, 1, days[0] if days else None
for a, b in zip(days, days[1:]):
run = run + 1 if (b - a).days == 1 else 1
if run > best:
best, best_end = run, b
if rules["max_days_in_a_row"] and best > rules["max_days_in_a_row"]:
findings.append(("TS09", e, best_end.isoformat(), "%d days in a row without a day off (limit %d)" % (best, rules["max_days_in_a_row"])))
info = employees.get(e)
if employees and info is None:
findings.append(("TS10", e, "", "not in the employees file; pay not estimated"))
ot_ok = True if info is None else info["ot"]
by_week = defaultdict(lambda: defaultdict(float))
for s in ss:
by_week[week_of(s["date"], ws)][s["date"]] += s["hours"]
for wk, daymap in sorted(by_week.items()):
reg = ot = dtm = 0.0
for day in sorted(daymap):
h = daymap[day]
d_dt = max(0.0, h - rules["daily_dt_after"]) if rules["daily_dt_after"] else 0.0
d_ot = max(0.0, h - d_dt - rules["daily_ot_after"]) if rules["daily_ot_after"] else 0.0
d_reg = h - d_dt - d_ot
if rules["weekly_ot_after"] is not None and reg + d_reg > rules["weekly_ot_after"]:
over = reg + d_reg - rules["weekly_ot_after"]
moved = min(over, d_reg)
d_reg -= moved; d_ot += moved
reg += d_reg; ot += d_ot; dtm += d_dt
total = reg + ot + dtm
if not ot_ok:
reg, ot, dtm = total, 0.0, 0.0
if rules["max_weekly_hours"] and total > rules["max_weekly_hours"]:
findings.append(("TS08", e, wk.isoformat(), "%.2f h in the week starting %s (maximum %s h)" % (total, wk.isoformat(), rules["max_weekly_hours"])))
pay = None
if info:
pay = info["rate"] * (reg + ot * rules["ot_multiplier"] + dtm * rules["dt_multiplier"])
weeks.append({"employee": e, "week_start": wk.isoformat(), "days": len(daymap), "total": round(total, 2),
"regular": round(reg, 2), "overtime": round(ot, 2), "double_time": round(dtm, 2),
"overtime_eligible": ot_ok, "rate": info["rate"] if info else None,
"pay_estimate": round(pay, 2) if pay is not None else None})
return weeks
def run(ts_path, rules_path=None, emp_path=None):
rules = load_rules(rules_path)
employees = load_employees(emp_path)
shifts, findings = load_shifts(ts_path)
if not shifts:
raise InputError("no usable shifts in the timesheet")
weeks = analyse(shifts, rules, employees, findings)
findings = [{"code": c, "severity": SEV[c], "issue": NAMES[c], "employee": e, "date": d, "detail": t} for c, e, d, t in findings]
order = {"high": 0, "medium": 1, "low": 2}
findings.sort(key=lambda f: (order[f["severity"]], f["code"], f["employee"], f["date"]))
return {"rules": rules, "weeks": weeks, "findings": findings, "shift_count": len(shifts)}
def report(res):
r = res["rules"]
L = ["# Timesheet and overtime check", ""]
L.append("Rules used: week starts %s; overtime after %s h/day and %s h/week at x%s; double time after %s h/day at x%s; break %s min after %s h; rest %s h; max %s h/week; max %s days in a row." % (
r["week_start"], r["daily_ot_after"] or "-", r["weekly_ot_after"] if r["weekly_ot_after"] is not None else "-", r["ot_multiplier"],
r["daily_dt_after"] or "-", r["dt_multiplier"], r["min_break_minutes"], r["break_required_after_hours"], r["min_rest_hours"], r["max_weekly_hours"], r["max_days_in_a_row"]))
L.append("%d shifts read." % res["shift_count"])
L.append("")
L.append("## Hours and pay by employee and week")
L.append("| employee | week starting | days | total h | regular | overtime | double time | rate | pay estimate |")
L.append("|---|---|---:|---:|---:|---:|---:|---:|---:|")
for w in res["weeks"]:
L.append("| %s | %s | %d | %.2f | %.2f | %.2f | %.2f | %s | %s |" % (w["employee"] + ("" if w["overtime_eligible"] else " (no OT)"), w["week_start"], w["days"],
w["total"], w["regular"], w["overtime"], w["double_time"], "%.2f" % w["rate"] if w["rate"] is not None else "-",
"{:,.2f}".format(w["pay_estimate"]) if w["pay_estimate"] is not None else "-"))
tot_pay = sum(w["pay_estimate"] or 0 for w in res["weeks"])
tot_ot = sum(w["overtime"] + w["double_time"] for w in res["weeks"])
L.append("")
L.append("Totals: %.2f overtime/double-time hours; estimated gross pay %s (before taxes, premiums and allowances)." % (tot_ot, "{:,.2f}".format(tot_pay)))
L.append("")
L.append("## Findings (%d)" % len(res["findings"]))
if not res["findings"]:
L.append("- none")
for f in res["findings"]:
L.append("- [%s] %s %s - %s%s: %s" % (f["severity"].upper(), f["code"], f["issue"], f["employee"], (" " + f["date"]) if f["date"] else "", f["detail"]))
L.append("")
L.append("Check every high finding with the employee or manager before payroll. Your local labour law and contracts decide the real rules.")
return "\n".join(L)
def self_test():
import os, tempfile
ok = True
def check(name, cond):
nonlocal ok
print(("PASS " if cond else "FAIL ") + name); ok = ok and cond
tmp = tempfile.mkdtemp()
def write(name, text):
p = os.path.join(tmp, name); open(p, "w", encoding="utf-8").write(text); return p
emp = write("e.csv", "employee,hourly_rate,overtime_eligible\nAna,20,yes\nBo,30,no\n")
week = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,08:00,17:00,30\n" % d for d in (16, 17, 18, 19, 20))
res = run(write("a.csv", week), None, emp)
w = res["weeks"][0]
check("5 x 8.5 h = 42.5 h total", abs(w["total"] - 42.5) < 1e-9)
check("weekly OT after 40 h = 2.5 h", abs(w["overtime"] - 2.5) < 1e-9 and abs(w["regular"] - 40) < 1e-9)
check("pay = 40x20 + 2.5x30", abs(w["pay_estimate"] - 875) < 1e-6)
rules = write("r.json", json.dumps({"daily_ot_after": 8, "daily_dt_after": 12, "weekly_ot_after": 40}))
res = run(write("b.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,06:00,20:00,30\n"), rules, emp)
w = res["weeks"][0]
check("13.5 h day with daily rules: 8 reg, 4 OT, 1.5 DT", (w["regular"], w["overtime"], w["double_time"]) == (8.0, 4.0, 1.5))
res = run(write("c.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,22:00,06:00,30\n"))
check("overnight shift counted 7.5 h", abs(res["weeks"][0]["total"] - 7.5) < 1e-9)
check("overnight shift flagged TS11", any(f["code"] == "TS11" for f in res["findings"]))
res = run(write("d.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-16,15:00,18:00,0\n"))
check("overlap TS02", any(f["code"] == "TS02" for f in res["findings"]))
res = run(write("e2.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-16,08:00,16:00,30\n"))
check("duplicate TS04 counted once", any(f["code"] == "TS04" for f in res["findings"]) and abs(res["weeks"][0]["total"] - 7.5) < 1e-9)
res = run(write("f.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:30,10\n"))
check("missing break TS06", any(f["code"] == "TS06" for f in res["findings"]))
res = run(write("g.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,14:00,23:00,30\nAna,2026-11-17,06:00,14:00,30\n"))
check("7 h rest TS07", any(f["code"] == "TS07" for f in res["findings"]))
res = run(write("h.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,,30\nAna,2026-11-17,08:00,16:00,30\n"))
check("missing end TS01 and row skipped", any(f["code"] == "TS01" for f in res["findings"]) and res["shift_count"] == 1)
rows = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,07:00,18:00,30\n" % d for d in range(16, 21))
res = run(write("i.csv", rows))
check("52.5 h week TS08", any(f["code"] == "TS08" for f in res["findings"]))
rows = "employee,date,start,end,break_minutes\n" + "".join("Ana,2026-11-%02d,09:00,13:00,0\n" % d for d in range(10, 18))
res = run(write("j.csv", rows))
check("8 days in a row TS09", any(f["code"] == "TS09" for f in res["findings"]))
res = run(write("k.csv", week.replace("Ana", "Bo")), None, emp)
check("not OT eligible: all regular", res["weeks"][0]["overtime"] == 0 and abs(res["weeks"][0]["regular"] - 42.5) < 1e-9)
res = run(write("l.csv", week.replace("Ana", "Cy")), None, emp)
check("unknown employee TS10, no pay", any(f["code"] == "TS10" for f in res["findings"]) and res["weeks"][0]["pay_estimate"] is None)
res = run(write("m.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,09:00,90\n"))
check("break longer than shift TS03", any(f["code"] == "TS03" for f in res["findings"]) and res["weeks"][0]["total"] == 0)
res = run(write("n.csv", "employee,date,start,end,break_minutes\nAna,2026-11-16,08:00,16:00,30\nAna,2026-11-22,08:00,16:00,30\nAna,2026-11-23,08:00,16:00,30\n"))
check("sunday belongs to the monday week, next monday starts a new week", [w["week_start"] for w in res["weeks"]] == ["2026-11-16", "2026-11-23"])
rules2 = write("r2.json", json.dumps({"week_start": "sunday"}))
res = run(write("o.csv", "employee,date,start,end,break_minutes\nAna,2026-11-22,08:00,16:00,30\n"), rules2)
check("week_start sunday", res["weeks"][0]["week_start"] == "2026-11-22")
try:
run(write("p.csv", "employee,date,start\nAna,2026-11-16,08:00\n")); check("missing columns rejected", False)
except InputError:
check("missing columns rejected", True)
try:
run(write("q.csv", week), write("bad.json", json.dumps({"weekly_overtime": 40}))); check("unknown rule key rejected", False)
except InputError:
check("unknown rule key rejected", True)
print("ALL PASS" if ok else "SOME TESTS FAILED")
return 0 if ok else 1
def main(argv):
if "--self-test" in argv:
return self_test()
args, opts, i = [], {}, 0
while i < len(argv):
a = argv[i]
if a in ("--rules", "--employees"):
if i + 1 >= len(argv):
print(a + " needs a file", file=sys.stderr); return 2
opts[a] = argv[i + 1]; i += 2; continue
if a != "--json":
args.append(a)
i += 1
if len(args) != 1:
print(__doc__, file=sys.stderr); return 2
try:
res = run(args[0], opts.get("--rules"), opts.get("--employees"))
except (InputError, OSError, json.JSONDecodeError) as e:
print("input error: %s" % e, file=sys.stderr); return 2
print(json.dumps(res, indent=2, default=str) if "--json" in argv else report(res))
return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Models a priced seed or Series A round on your cap table: converts post-money and pre-money SAFEs (cap and/or discount), tops up the option pool to a post-money target, prices the new shares and shows every holder's dilution, value and red flags, with a pre-money comparison. Offline stdlib Python.
---
name: cap-table-round-and-safe-conversion-calculator
description: Models a priced seed or Series A round on your cap table: converts post-money and pre-money SAFEs (cap and/or discount), tops up the option pool to a post-money target, prices the new shares and shows every holder's dilution, value and red flags, with a pre-money comparison. Offline stdlib Python.
---
# Cap Table Round and SAFE Conversion Calculator
You help founders, early employees and small-company finance leads understand what a priced equity round does to their cap table before they sign a term sheet. SAFEs, option pool top-ups and the price per share interact in ways that are easy to get wrong in a spreadsheet: a "10% pool post-money" request quietly lowers the price, several post-money SAFEs dilute each other's holders but not each other, and a discount can beat a cap. You build the model, explain it in plain language and point out what to negotiate or check with a lawyer.
You work only with the numbers the user gives you, on their machine. You never present the model as legal, tax or investment advice, and you tell the user that the signed SAFEs, the term sheet and the closing cap table prepared by their lawyer decide the real numbers.
## Files in this skill
- `scripts/captable_round.py` - the calculator: reads a cap table CSV and a round JSON, solves price per share, SAFE conversions and pool top-up together, prints before/after fully diluted tables, SAFE conversion details and warnings; `--compare 10000000,12000000` adds a pre-money comparison, `--json` for tooling, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/cap-table-math.md` - the formulas: fully diluted shares, price per share, post-money and pre-money SAFE conversion, discount vs cap, the option pool shuffle, rounding
- `references/term-sheet-checks.md` - what to check and negotiate: pool size and timing, SAFE stacking, MFN and pro rata side letters, liquidation preference basics, questions for your lawyer
- `templates/round-summary.md` - the summary you hand back to the founders
- `examples/cap_table.csv`, `examples/round.json` - a fictional two-founder company raising 3M at 12M pre-money with three SAFEs and a 10% post-money pool target
## Workflow
### 1. Collect the inputs
Ask for:
- The current fully diluted cap table: every holder of common and preferred shares, granted options (vested or not), and the unissued pool. Warrants and convertible notes too, if any (treat notes like SAFEs with a cap/discount and add accrued interest to the amount).
- Every SAFE: holder, amount, valuation cap, discount, and whether it is a post-money or pre-money SAFE (the document title says "Post-Money Valuation Cap" for the current standard). Ask about MFN and pro rata side letters.
- The proposed round: pre-money valuation, new money, and the option pool requirement (for example "unissued pool equal to 10% post-money").
If something is missing, ask; do not guess the SAFE type or the pool definition.
### 2. Build the input files
Write `cap_table.csv` with columns `holder,class,shares` (class: common, preferred, options, pool) and `round.json` with `pre_money`, `new_money`, optional `pool_target_post` as a fraction (0.10, not 10), optional `investor_name`, and `safes` (`holder`, `amount`, optional `cap`, optional `discount` as a fraction, `type` "post" or "pre").
### 3. Run the model
```
python3 scripts/captable_round.py examples/cap_table.csv examples/round.json
python3 scripts/captable_round.py cap_table.csv round.json --compare 10000000,12000000,15000000
python3 scripts/captable_round.py cap_table.csv round.json --json > round_model.json
python3 scripts/captable_round.py --self-test
```
Exit 0 = no warnings, 1 = warnings to discuss, 2 = bad input. Without a shell, follow `references/cap-table-math.md` step by step and show your working; iterate the price and pool top-up two or three times until they stop changing.
### 4. Explain the result
- Lead with four numbers: price per share, post-money valuation, new investor ownership, and founders' combined ownership after the round.
- Explain each SAFE: which term won (cap or discount), the effective price, and the ownership it buys.
- Explain the pool shuffle in one sentence: the top-up is counted pre-money, so it lowers the price and is paid for by existing holders. Show its cost in percentage points.
- Use the comparison table to show how pre-money, pool size or a smaller raise move founder ownership. Suggest specific levers (a smaller pool sized to a real hiring plan, pool counted post-money, a higher pre-money, a smaller raise).
### 5. Flag what to check
Go through every warning the script prints and `references/term-sheet-checks.md`. Always mention: verify SAFE types and caps against the signed documents, confirm how the investor defines the pool, ask about MFN and pro rata rights, and ask the lawyer for the pro forma closing cap table to compare against this model.
### 6. Hand back the summary
Fill `templates/round-summary.md`: headline numbers, before/after table, SAFE conversions, pool shuffle cost, comparison, warnings, negotiation points and open questions.
## Rules
- Shares are whole numbers: the script rounds SAFE and investor shares down and the pool top-up up, so totals can differ from the headline valuation by a few currency units; say so if asked.
- Percentages are of the fully diluted total (all shares, granted options and the unissued pool).
- Never tell the user a round is "good" or "bad"; show the trade-offs and the questions to ask.
- Keep the user's numbers private; do not upload the cap table anywhere.
FILE:references/cap-table-math.md
# Cap table math used by captable_round.py
## Fully diluted shares
Fully diluted (FD) = issued common + issued preferred + granted options (vested and unvested) + unissued option pool (+ warrants). Ownership percentages in the report are always of the FD total.
## Priced round
- Pre-money FD = existing FD + SAFE conversion shares + option pool top-up.
- Price per share = pre-money valuation / pre-money FD.
- New investor shares = new money / price per share (rounded down).
- Post-money FD = pre-money FD + new investor shares; post-money valuation = post-money FD x price.
Because the SAFE shares and the pool top-up are inside the pre-money FD, the price depends on them and they depend on the price. The script solves this by fixed-point iteration (it converges in a few rounds) and then rounds to whole shares.
## Option pool shuffle
If the investor asks for an unissued pool equal to T% of the post-money FD:
- Top-up = max(0, T x post-money FD - existing unissued pool).
- The top-up is part of the pre-money FD, so it lowers the price per share. The new investor still gets new money / post-money valuation; existing holders carry the whole dilution of the top-up.
- Cost to existing holders, in percentage points of pre-money ownership = top-up / pre-money FD.
## Post-money SAFE (current standard)
The holder gets ownership = amount / post-money valuation cap, measured against the "company capitalization" just before the round: existing FD (including the unissued pool, excluding the new pool top-up) plus the shares of all converting post-money SAFEs.
- With several post-money SAFEs with fractions f1..fn (fi = amount / cap) and existing FD C, total SAFE shares S = C x f / (1 - f) where f = sum fi; each SAFE gets fi x (C + S).
- Cap price = cap / (C + S).
- Post-money SAFEs dilute the founders and earlier holders, not each other.
## Pre-money SAFE (older form)
Cap price = cap / existing FD before any SAFE converts. Each later SAFE dilutes the earlier ones.
## Discount and "better of"
Discount price = round price x (1 - discount). A SAFE with both terms converts at the lower of cap price and discount price, so it gets more shares. A SAFE with neither converts at the round price (check for an MFN clause instead).
## Convertible notes
Treat a note like a SAFE: amount = principal + accrued interest to the conversion date, with its cap and discount. Note maturity and repayment terms are not modeled.
## Rounding
SAFE and investor shares are rounded down; the pool top-up is rounded up so the pool target is met. Real closing sets may round differently by a few shares.
## Worked example (examples/)
Existing FD 9,000,000 (8,000,000 founders, 700,000 granted options, 300,000 unissued pool). Raise 3,000,000 at 12,000,000 pre-money with a 10% post-money pool target and three post-money SAFEs. Result: price about 1.1104, pool top-up 1,050,912, investor 20.00%, SAFEs 5.60% together, founders from 88.89% to 59.22%.
FILE:references/term-sheet-checks.md
# Term sheet and SAFE checks to raise with founders
## Option pool
- Size the pool to a real 12-18 month hiring plan (roles x typical grant) instead of a round percentage; a smaller, justified pool is the most common negotiation win.
- Ask whether the pool target is measured pre-money or post-money, and whether already granted options count toward it.
- Compare "pool counted pre-money" vs "pool counted post-money" with the script (set the target lower or 0 and add the pool to the investor side) to show the difference in founder ownership.
## SAFEs
- Confirm every SAFE's type (post-money or pre-money), cap, discount and amount from the signed document, not from memory or a spreadsheet.
- Post-money SAFEs stack: every new post-money SAFE dilutes the founders by roughly amount / cap. Add them up before raising more on SAFEs.
- MFN clauses let an uncapped SAFE take better terms from a later SAFE; check whether any MFN was triggered.
- Pro rata side letters let SAFE holders buy into this round; their money usually comes out of the round size, so confirm the allocation with the lead.
## Round terms that change outcomes but not this model
- Liquidation preference (1x non-participating is the common seed standard; participating or more than 1x is investor-friendly).
- Anti-dilution protection (broad-based weighted average is common; full ratchet is harsh).
- Board seats, protective provisions, founder vesting reset, and information rights.
The script does not model exit waterfalls; say so and suggest a waterfall model if the user asks what they receive at a given exit value.
## Questions for the lawyer
1. Please share the pro forma closing cap table so we can compare it with our model.
2. Which SAFEs and notes convert, and at what price did you use for each?
3. How is the option pool target defined, and is it measured on a fully diluted basis including the SAFEs?
4. Are there MFN, pro rata or side letter rights we need to honor in this round?
5. Are there any warrants, promised options or advisor grants not yet on the cap table?
## Red flags to mention
- SAFEs converting into more than about 20% of the company.
- A single round selling more than about 25-30% of the company.
- Founders together below 50% after a seed round.
- A cap table with no pool at all, or a pool far larger than the hiring plan.
- Numbers in the term sheet that do not match the model by more than rounding.
FILE:templates/round-summary.md
# Round summary: {{company}} - {{round_name}}
Prepared {{date}} from the cap table and SAFE terms you shared. Model only: the signed documents and the lawyer's closing cap table decide the real numbers.
## Headline
- Raise: {{new_money}} at {{pre_money}} pre-money ({{post_money}} post-money)
- Price per share: {{price_per_share}}
- New investors own: {{investor_pct}}
- Founders together: {{founders_before_pct}} before -> {{founders_after_pct}} after
- Option pool after the round: {{pool_after_pct}} unissued (top-up {{pool_top_up}} shares)
## SAFE conversions
| SAFE | type | amount | cap | discount | term that won | shares | ownership |
|---|---|---:|---:|---:|---|---:|---:|
| {{safe}} | {{type}} | {{amount}} | {{cap}} | {{discount}} | {{cap_or_discount}} | {{shares}} | {{pct}} |
## Cap table before and after
(paste the table from captable_round.py)
## What the option pool shuffle costs
{{one sentence: top-up counted pre-money, cost in percentage points, who pays}}
## Scenarios
| pre-money | price/share | new investors % | founders % |
|---:|---:|---:|---:|
| {{pre}} | {{price}} | {{inv_pct}} | {{founders_pct}} |
## Warnings from the model
- {{warning}}
## Negotiation points
1. {{for example: size the pool to the 18-month hiring plan (about X%) instead of 10%}}
2. {{...}}
## Open questions for the lawyer and investors
- {{question}}
FILE:examples/cap_table.csv
holder,class,shares
Founder A (CEO),common,4200000
Founder B (CTO),common,3800000
Early employee grants,options,600000
Advisor grants,options,100000
Unissued option pool,pool,300000
FILE:examples/round.json
{
"investor_name": "Seed lead and syndicate",
"pre_money": 12000000,
"new_money": 3000000,
"pool_target_post": 0.10,
"safes": [
{"holder": "Angel SAFE 2024", "amount": 250000, "cap": 6000000, "discount": 0.2, "type": "post"},
{"holder": "Accelerator SAFE", "amount": 125000, "cap": 5000000, "type": "post"},
{"holder": "Friends and family note-style SAFE", "amount": 100000, "discount": 0.15, "type": "post"}
]
}
FILE:scripts/captable_round.py
#!/usr/bin/env python3
"""captable_round.py - model a priced equity round on a startup cap table.
Converts post-money and pre-money SAFEs (valuation cap and/or discount), tops up the
option pool to a post-money target (the "option pool shuffle"), prices the new
shares, and prints the pre-round and post-round fully diluted cap table, the price
per share, each holder's dilution and sanity warnings. Standard library only.
Usage:
python3 captable_round.py CAP_TABLE.csv ROUND.json [--json] [--compare PRE1,PRE2,...]
python3 captable_round.py --self-test
CAP_TABLE.csv columns: holder,class,shares (class: common, preferred, options, pool)
- "options" = granted options (outstanding), "pool" = unissued option pool.
ROUND.json keys:
pre_money (number, required), new_money (number, required),
pool_target_post (fraction 0-1, optional, e.g. 0.10), investor_name (optional),
safes: [{"holder", "amount", "cap" (optional), "discount" (fraction, optional),
"type": "post" | "pre" (default "post")}]
Exit codes: 0 ok, 1 ok with warnings, 2 bad input.
This is a model for planning and negotiation. Lawyers and the signed documents decide the real numbers.
"""
import csv, json, math, sys
CLASSES = {"common", "preferred", "options", "pool"}
class InputError(Exception):
pass
def load_cap_table(path):
rows = []
with open(path, newline="", encoding="utf-8") as f:
r = csv.DictReader(f)
need = {"holder", "class", "shares"}
if not r.fieldnames or not need.issubset({h.strip() for h in r.fieldnames}):
raise InputError("cap table needs columns holder,class,shares")
for i, row in enumerate(r, start=2):
row = {k.strip(): (v or "").strip() for k, v in row.items()}
if not row["holder"] and not row["shares"]:
continue
cls = row["class"].lower()
if cls not in CLASSES:
raise InputError("line %d: class must be one of %s" % (i, ", ".join(sorted(CLASSES))))
try:
sh = int(row["shares"].replace(",", "").replace("_", ""))
except ValueError:
raise InputError("line %d: shares must be a whole number" % i)
if sh < 0:
raise InputError("line %d: negative shares" % i)
rows.append({"holder": row["holder"] or "(unnamed)", "class": cls, "shares": sh})
if not rows:
raise InputError("cap table is empty")
return rows
def validate_round(rd):
for k in ("pre_money", "new_money"):
if not isinstance(rd.get(k), (int, float)) or rd[k] <= 0:
raise InputError("round.%s must be a positive number" % k)
t = rd.get("pool_target_post", 0) or 0
if not 0 <= t < 0.5:
raise InputError("pool_target_post must be a fraction between 0 and 0.5 (e.g. 0.10)")
for s in rd.get("safes", []) or []:
if not isinstance(s.get("amount"), (int, float)) or s["amount"] <= 0:
raise InputError("every SAFE needs a positive amount (%s)" % s.get("holder"))
if s.get("cap") is not None and s["cap"] <= 0:
raise InputError("SAFE cap must be positive (%s)" % s.get("holder"))
d = s.get("discount") or 0
if not 0 <= d < 1:
raise InputError("SAFE discount must be a fraction like 0.2 (%s)" % s.get("holder"))
if s.get("type", "post") not in ("post", "pre"):
raise InputError("SAFE type must be 'post' or 'pre' (%s)" % s.get("holder"))
def model(rows, rd, iterations=500):
"""Fixed-point solve for price, SAFE conversion shares and pool top-up."""
validate_round(rd)
safes = rd.get("safes", []) or []
C = sum(r["shares"] for r in rows) # pre-round fully diluted, before SAFEs
unissued = sum(r["shares"] for r in rows if r["class"] == "pool")
target = rd.get("pool_target_post", 0) or 0
pre_money, new_money = float(rd["pre_money"]), float(rd["new_money"])
safe_sh = [0.0] * len(safes)
pool_top = 0.0
price = pre_money / C
for _ in range(iterations):
S = sum(safe_sh)
pre_fd = C + S + pool_top
price = pre_money / pre_fd
new_sh = new_money / price
post = pre_fd + new_sh
pool_top_n = max(0.0, target * post - unissued) if target else 0.0
S_post = sum(sh for sh, s in zip(safe_sh, safes) if s.get("type", "post") == "post")
new_safe = []
for s in safes:
prices = []
if s.get("cap"):
if s.get("type", "post") == "post":
# post-money SAFE: capitalization includes all converting post-money SAFEs (not the new money or pool top-up)
prices.append(s["cap"] / (C + S_post))
else:
prices.append(s["cap"] / C)
if s.get("discount"):
prices.append(price * (1 - s["discount"]))
if not prices:
prices.append(price) # uncapped, no discount: converts at the round price
new_safe.append(s["amount"] / min(prices))
delta = abs(pool_top_n - pool_top) + sum(abs(a - b) for a, b in zip(new_safe, safe_sh))
safe_sh, pool_top = new_safe, pool_top_n
if delta < 1e-6:
break
# final integer shares (round down, like most closing sets)
safe_int = [math.floor(x) for x in safe_sh]
pool_int = math.ceil(pool_top) if pool_top > 0 else 0
pre_fd = C + sum(safe_int) + pool_int
price = pre_money / pre_fd
new_int = math.floor(new_money / price)
post = pre_fd + new_int
conv = []
for s, sh in zip(safes, safe_int):
conv.append({"holder": s.get("holder", "SAFE"), "amount": s["amount"], "type": s.get("type", "post"),
"cap": s.get("cap"), "discount": s.get("discount"), "shares": sh,
"effective_price": round(s["amount"] / sh, 6) if sh else None})
return {"price_per_share": price, "pre_round_fd_before_safes": C, "pre_money_fd": pre_fd,
"safe_conversions": conv, "pool_top_up": pool_int, "new_money_shares": new_int,
"post_money_fd": post, "post_money_valuation": post * price,
"investor": rd.get("investor_name", "New investors")}
def tables(rows, rd, res):
post = res["post_money_fd"]
C = res["pre_round_fd_before_safes"]
out = []
for r in rows:
out.append({"holder": r["holder"], "class": r["class"], "before": r["shares"], "after": r["shares"]})
if res["pool_top_up"]:
out.append({"holder": "Option pool top-up", "class": "pool", "before": 0, "after": res["pool_top_up"]})
for c in res["safe_conversions"]:
out.append({"holder": c["holder"] + " (SAFE)", "class": "preferred", "before": 0, "after": c["shares"]})
out.append({"holder": res["investor"], "class": "preferred", "before": 0, "after": res["new_money_shares"]})
for o in out:
o["pct_before"] = o["before"] / C if C else 0
o["pct_after"] = o["after"] / post if post else 0
o["value_after"] = o["after"] * res["price_per_share"]
return out
def warnings(rows, rd, res, tab):
w = []
post = res["post_money_fd"]
safe_pct = sum(c["shares"] for c in res["safe_conversions"]) / post
inv_pct = res["new_money_shares"] / post
if safe_pct > 0.20:
w.append("SAFEs convert into %.1f%% of the company: more than 20%% is a lot of dilution for one round." % (100 * safe_pct))
if inv_pct > 0.30:
w.append("New investors get %.1f%% post-money; above about 25-30%% in one round can make later rounds hard." % (100 * inv_pct))
for c in res["safe_conversions"]:
if not c["cap"] and not c["discount"]:
w.append("%s is uncapped with no discount: it converts at the round price; check for an MFN clause." % c["holder"])
if c["effective_price"] and c["effective_price"] > res["price_per_share"] + 1e-9:
w.append("%s converts above the round price (cap higher than the round): check the SAFE terms." % c["holder"])
if res["pool_top_up"]:
pre_cost = res["pool_top_up"] / res["pre_money_fd"]
w.append("Option pool shuffle: the %s-share pool top-up is counted pre-money, so existing holders (not the new investor) absorb %.1f%% of pre-money dilution." % (format(res["pool_top_up"], ","), 100 * pre_cost))
founders = [t for t in tab if t["class"] == "common" and t["before"]]
fpct = sum(t["pct_after"] for t in founders)
if founders and fpct < 0.5:
w.append("Common holders together own %.1f%% after the round (below 50%%)." % (100 * fpct))
granted = sum(r["shares"] for r in rows if r["class"] == "options")
if granted == 0 and not any(r["class"] == "pool" for r in rows):
w.append("No options or pool in the cap table: is the employee pool missing?")
if abs(res["post_money_valuation"] - (rd["pre_money"] + rd["new_money"])) / (rd["pre_money"] + rd["new_money"]) > 0.001:
w.append("Post-money value differs from pre-money + new money because of share rounding (%.0f vs %.0f)." % (res["post_money_valuation"], rd["pre_money"] + rd["new_money"]))
return w
def money(x):
return "{:,.0f}".format(x)
def report(rows, rd, res, tab, warns):
L = []
L.append("# Round model: %s raises %s at %s pre-money" % (res["investor"], money(rd["new_money"]), money(rd["pre_money"])))
L.append("")
L.append("Price per share: %.4f | pre-money fully diluted shares: %s | post-money fully diluted shares: %s | post-money valuation: %s" % (
res["price_per_share"], money(res["pre_money_fd"]), money(res["post_money_fd"]), money(res["post_money_valuation"])))
if rd.get("pool_target_post"):
L.append("Option pool target: %.1f%% post-money unissued; top-up %s shares (pre-money)." % (100 * rd["pool_target_post"], money(res["pool_top_up"])))
L.append("")
if res["safe_conversions"]:
L.append("## SAFE conversions")
L.append("| SAFE | type | amount | cap | discount | shares | effective price |")
L.append("|---|---|---:|---:|---:|---:|---:|")
for c in res["safe_conversions"]:
L.append("| %s | %s-money | %s | %s | %s | %s | %.4f |" % (c["holder"], c["type"], money(c["amount"]),
money(c["cap"]) if c["cap"] else "none", ("%d%%" % round(100 * c["discount"])) if c["discount"] else "none",
money(c["shares"]), c["effective_price"] or 0))
L.append("")
L.append("## Cap table before and after (fully diluted)")
L.append("| holder | class | shares before | % before | shares after | % after | value at round price |")
L.append("|---|---|---:|---:|---:|---:|---:|")
for t in tab:
L.append("| %s | %s | %s | %.2f%% | %s | %.2f%% | %s |" % (t["holder"], t["class"], money(t["before"]), 100 * t["pct_before"],
money(t["after"]), 100 * t["pct_after"], money(t["value_after"])))
L.append("| **Total** | | %s | 100.00%% | %s | 100.00%% | %s |" % (money(res["pre_round_fd_before_safes"]), money(res["post_money_fd"]), money(res["post_money_valuation"])))
L.append("")
L.append("## Warnings")
L.extend(["- " + x for x in warns] or ["- none"])
L.append("")
L.append("Model only: the signed SAFEs, term sheet and closing cap table from your lawyer decide the real numbers.")
return "\n".join(L)
def compare(rows, rd, pres):
L = ["## Pre-money comparison", "| pre-money | price/share | new investors % | SAFEs % | pool top-up | common holders % |", "|---:|---:|---:|---:|---:|---:|"]
for p in pres:
r2 = dict(rd, pre_money=p)
res = model(rows, r2)
tab = tables(rows, r2, res)
post = res["post_money_fd"]
L.append("| %s | %.4f | %.2f%% | %.2f%% | %s | %.2f%% |" % (money(p), res["price_per_share"], 100 * res["new_money_shares"] / post,
100 * sum(c["shares"] for c in res["safe_conversions"]) / post, money(res["pool_top_up"]),
100 * sum(t["pct_after"] for t in tab if t["class"] == "common")))
return "\n".join(L)
def self_test():
ok = True
def check(name, cond):
nonlocal ok
print(("PASS " if cond else "FAIL ") + name)
ok = ok and cond
base = [{"holder": "A", "class": "common", "shares": 4_500_000}, {"holder": "B", "class": "common", "shares": 4_500_000},
{"holder": "Pool", "class": "pool", "shares": 1_000_000}]
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000})
check("plain round price = pre-money / FD", abs(r["price_per_share"] - 1.0) < 1e-9)
check("plain round investor shares = new money / price", r["new_money_shares"] == 2_500_000)
check("post-money = pre + new", abs(r["post_money_valuation"] - 12_500_000) < 1)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "pool_target_post": 0.15})
pool_after = 1_000_000 + r["pool_top_up"]
check("pool shuffle hits 15% post-money", abs(pool_after / r["post_money_fd"] - 0.15) < 1e-4)
check("pool shuffle lowers the price", r["price_per_share"] < 1.0)
check("investor still owns new/post-money (20%)", abs(r["new_money_shares"] / r["post_money_fd"] - 0.2) < 1e-4)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "cap": 5_000_000, "type": "post"}]})
c = r["safe_conversions"][0]
check("post-money SAFE owns amount/cap of pre-round capitalization (10%)", abs(c["shares"] / (10_000_000 + c["shares"]) - 0.10) < 1e-6)
check("capped SAFE converts below round price", c["effective_price"] < r["price_per_share"])
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "discount": 0.2}]})
c = r["safe_conversions"][0]
check("discount-only SAFE converts at 80% of round price", abs(c["effective_price"] / r["price_per_share"] - 0.8) < 1e-4)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "cap": 50_000_000, "discount": 0.2}]})
c = r["safe_conversions"][0]
check("cap above round: discount wins", abs(c["effective_price"] / r["price_per_share"] - 0.8) < 1e-4)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000, "cap": 4_000_000, "type": "pre"}]})
c = r["safe_conversions"][0]
check("pre-money SAFE price = cap / pre-round FD", abs(c["effective_price"] - 0.4) < 1e-3)
r = model(base, {"pre_money": 10_000_000, "new_money": 2_500_000, "safes": [{"holder": "S", "amount": 500_000}]})
tab = tables(base, {"pre_money": 10_000_000, "new_money": 2_500_000}, r)
w = warnings(base, {"pre_money": 10_000_000, "new_money": 2_500_000}, r, tab)
check("uncapped SAFE warning", any("uncapped" in x for x in w))
two = {"pre_money": 8_000_000, "new_money": 2_000_000, "safes": [{"holder": "S1", "amount": 300_000, "cap": 6_000_000}, {"holder": "S2", "amount": 600_000, "cap": 6_000_000}]}
r = model(base, two)
s1, s2 = r["safe_conversions"]
check("two post-money SAFEs at same cap: shares proportional to amount", abs(s2["shares"] / s1["shares"] - 2) < 1e-4)
check("two post-money SAFEs together own 15% of capitalization", abs((s1["shares"] + s2["shares"]) / (10_000_000 + s1["shares"] + s2["shares"]) - 0.15) < 1e-5)
tab = tables(base, two, r)
check("post-round table sums to post-money FD", sum(t["after"] for t in tab) == r["post_money_fd"])
for bad, name in (({"pre_money": 0, "new_money": 1}, "zero pre-money rejected"), ({"pre_money": 1, "new_money": 1, "pool_target_post": 15}, "pool target as percent rejected"),
({"pre_money": 1, "new_money": 1, "safes": [{"holder": "x", "amount": 1, "discount": 20}]}, "discount as percent rejected")):
try:
model(base, bad); check(name, False)
except InputError:
check(name, True)
print("ALL PASS" if ok else "SOME TESTS FAILED")
return 0 if ok else 1
def main(argv):
if "--self-test" in argv:
return self_test()
args = [a for a in argv if not a.startswith("--")]
pres = None
if "--compare" in argv:
i = argv.index("--compare")
try:
pres = [float(x) for x in argv[i + 1].split(",")]
except (IndexError, ValueError):
print("--compare needs comma-separated pre-money values", file=sys.stderr); return 2
args = [a for a in args if a != argv[i + 1]]
if len(args) != 2:
print(__doc__, file=sys.stderr); return 2
try:
rows = load_cap_table(args[0])
with open(args[1], encoding="utf-8") as f:
rd = json.load(f)
res = model(rows, rd)
except (InputError, OSError, json.JSONDecodeError) as e:
print("input error: %s" % e, file=sys.stderr); return 2
tab = tables(rows, rd, res)
warns = warnings(rows, rd, res, tab)
if "--json" in argv:
print(json.dumps({"round": rd, "result": res, "table": tab, "warnings": warns}, indent=2))
else:
print(report(rows, rd, res, tab, warns))
if pres:
print(); print(compare(rows, rd, pres))
return 1 if warns else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Turns a subscription events CSV into a monthly MRR bridge (new, expansion, contraction, churn, reactivation) with logo churn, GRR, NRR, ARPA, quick ratio and cohort retention. Normalizes annual and quarterly billing to MRR and flags data errors, shrinking months, high churn and customer concentration. Offline stdlib Python calculator.
---
name: saas-mrr-and-churn-metrics-calculator
description: Turns a subscription events CSV into a monthly MRR bridge (new, expansion, contraction, churn, reactivation) with logo churn, GRR, NRR, ARPA, quick ratio and cohort retention. Normalizes annual and quarterly billing to MRR and flags data errors (annual typed as monthly, mislabeled upgrades, churn of unknown customers), shrinking months, high churn and customer concentration. Offline stdlib Python calculator.
---
# SaaS MRR and Churn Metrics Calculator
You help founders, finance leads and product managers of subscription businesses get honest recurring-revenue numbers. Spreadsheet MRR usually goes wrong in the same places: an annual contract typed in as a monthly price inflates MRR twelvefold, downgrades get logged as upgrades, churn is counted on customers who already left, and one big account hides the fact that everyone else is leaving. You take a plain events export, rebuild MRR month by month so every movement is explained, and say what the numbers mean for the business.
You do not connect to billing systems, change data or give investment or accounting advice. Work only from the CSV the user provides, show every assumption, and remind them that MRR is a management metric, not recognized revenue.
## Files in this skill
- `scripts/mrr_metrics.py` - reads the events CSV and prints the MRR bridge, retention, cohorts, top customers and findings SM01-SM10; `--from/--to` to pick the reporting window, `--json` for further analysis, `--self-test` runs 17 checks (Python 3.8+ standard library only)
- `references/metric-definitions.md` - exact formulas for every metric and how the script classifies each event
- `references/data-prep-and-pitfalls.md` - how to export events from common billing tools, what counts as MRR, and the classic mistakes
- `templates/metrics-report.md` - the monthly metrics report you hand back
- `examples/subscription_events.csv` - ten months of events for a fictional scheduling SaaS with planted errors
## Workflow
### 1. Get the events
Ask for one row per subscription change: `date` (YYYY-MM-DD), `customer`, `event` (`new`, `upgrade`, `downgrade`, `price_change`, `churn`, `reactivate`), `amount` (the recurring price after the change, per billing period, excluding tax and one-off fees), `billing` (`monthly`, `quarterly`, `annual`) and optional `plan`. Use one currency (convert first). See `references/data-prep-and-pitfalls.md` for exports from Stripe, Paddle, Chargebee or a spreadsheet.
### 2. Run the calculator
```
python3 scripts/mrr_metrics.py examples/subscription_events.csv
python3 scripts/mrr_metrics.py events.csv --from 2026-07 --to 2026-10
python3 scripts/mrr_metrics.py events.csv --json --top-share 0.15 --churn-alert 0.03
python3 scripts/mrr_metrics.py --self-test
```
Pass `--from` to get period retention (NRR and logo retention of the customers active just before the window). Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, build the bridge by hand with `references/metric-definitions.md`; it is just bookkeeping per customer.
### 3. Fix the data, then read the metrics
- Data findings first: SM01 unreadable row, SM02 event that doesn't fit the customer's state (churn of an unknown customer, `new` for an active one), SM03 zero-MRR new customer (free or trial), SM04 monthly amount 8x or more the median (an annual price typed as monthly?), SM05 `upgrade` that lowers MRR or `downgrade` that raises it, SM08 negative amount. Correct the CSV and re-run before drawing conclusions.
- Business findings: SM07 quick ratio below 1 (the business shrank that month, high), SM06 monthly logo churn above the alert level, SM09 period NRR below 100%, SM10 one customer above the concentration threshold.
### 4. Deliver
Fill `templates/metrics-report.md`: headline MRR and growth, the bridge table, retention and cohorts, what changed and why, data fixes made, and three concrete actions (for example: call the customers who downgraded, fix onboarding for the cohort that churns in month 2, diversify away from the largest account). Keep the language plain; define GRR and NRR once.
## Example result
On the sample file, ending MRR in October shows 6,435.40 across 14 paying customers, but 4,788 of it is A09, whose annual Business contract was typed as monthly (SM04); with `billing=annual` it is 399 MRR and the business is about a third of the size it appears. The data also has an "upgrade" from 399 to 149 (SM05), a churn row for unknown customer A99 and a `new` row for already-active A01 (SM02). Business signals: May, June and August lost more MRR than they gained (quick ratio 0.16, 0.75, 0.43), logo churn hit 22% in May and 25% in August, and July to October NRR is 92%. Result: 3 high, 8 medium, 1 low.
## Rules
- Never mix one-off charges, setup fees, usage overages or taxes into MRR unless the user explicitly defines MRR that way; say which definition you used.
- Divide annual and quarterly prices by 12 and 3; do not book the whole contract in the signing month.
- Fix data findings before interpreting trends, and state every correction you made.
- Small numbers lie: with fewer than ~20 customers, one churn moves rates a lot; say so instead of over-reading percentages.
- These are management metrics, not GAAP/IFRS revenue; refer accounting questions to an accountant.
FILE:references/metric-definitions.md
# Metric definitions (as implemented in mrr_metrics.py)
## Normalizing to MRR
`MRR = amount / months in billing period` (monthly 1, quarterly 3, annual 12). The amount is the recurring price after the change, net of recurring discounts, without tax or one-off fees.
## Classifying each event per customer
| Event | Condition | Bridge bucket |
|---|---|---|
| `new` | customer never paid before | New MRR (+ new customer) |
| `new` | customer already active | treated as price change, flagged SM02 |
| `new` / `reactivate` | customer paid before, now at 0 | Reactivation MRR |
| `upgrade` / `downgrade` / `price_change` | active customer | Expansion if MRR rises, Contraction if it falls (label mismatch flagged SM05) |
| change to 0 | active customer | counted as Churn, flagged SM05 |
| `churn` | active customer | Churn MRR = the customer's MRR before churning (+ churned customer) |
| any change / churn | no active subscription | ignored, flagged SM02 |
Bridge identity (checked every month): `start MRR + new + expansion + reactivation - contraction - churn = end MRR`.
## Monthly metrics
- **Net new MRR** = end MRR - start MRR
- **Logo churn rate** = churned customers / paying customers at start of month
- **MRR churn rate (gross)** = (churn + contraction) / start MRR
- **GRR (gross revenue retention)** = (start MRR - churn - contraction) / start MRR, never above 100%
- **NRR (net revenue retention)** = (start MRR - churn - contraction + expansion) / start MRR; reactivation and new are excluded
- **Quick ratio** = (new + expansion + reactivation) / (churn + contraction); above 4 is excellent, 1-2 means growth is fragile, below 1 means shrinking
- **ARPA** = end MRR / paying customers at end of month
## Period and cohort metrics
- **Period NRR** (`--from`): customers paying at the end of the month before the window; their MRR at the end of the window divided by their MRR at the start. New customers acquired in the window are excluded.
- **Logo retention**: share of that base still paying at the end of the window.
- **Cohort retention**: customers grouped by the month of their first paid event; share still paying after 1, 3, 6 and 12 months (reactivated customers count as paying again).
- **Concentration**: largest customer's share of current MRR (default alert above 20%).
## Rules of thumb (context, not targets)
Monthly logo churn for SMB SaaS is often 3-7%, for mid-market 1-2%; annual NRR above 100% means expansion outruns churn. Compare with your own history before comparing with benchmarks.
FILE:references/data-prep-and-pitfalls.md
# Data preparation and pitfalls
## Getting an events file
- **Stripe**: export subscriptions and subscription item changes (or invoice line items for `subscription` items); one row per change with the new recurring price. Use `plan.interval` (month/year) and `interval_count` for `billing`.
- **Paddle / Chargebee / Recurly**: subscription activity or "subscription changes" export; map created -> `new`, plan change -> `upgrade`/`downgrade`, cancelled (effective date, not request date) -> `churn`, reactivated -> `reactivate`.
- **Spreadsheet**: if you only have a monthly list of customers and prices, generate events by comparing each month to the previous one (appeared = new, price up = upgrade, price down = downgrade, disappeared = churn).
## What counts as MRR
- Include: recurring subscription fees after recurring discounts, per-seat fees at the current seat count, committed minimums.
- Exclude: setup and onboarding fees, one-off services, usage overages (track separately or average them explicitly), taxes, refunds and credits, free and trial plans.
- Paused subscriptions: treat as churn when paused and reactivation when resumed, or exclude consistently; say which.
- Use the **effective** date of a cancellation (end of paid period), not the date the customer clicked cancel; otherwise churn shows up a month early.
## Classic mistakes the script catches
1. Annual price typed as monthly (SM04): MRR jumps by the full contract value. Set `billing=annual`.
2. Wrong event labels (SM05): an "upgrade" to a cheaper plan. The script trusts the amounts, not the label, and flags the row.
3. Churn or changes for customers who are not active (SM02): usually duplicate exports or wrong customer ids.
4. Duplicate `new` rows for an active customer (SM02): often a plan change exported as a new subscription.
5. Negative amounts (SM08): refunds or credit notes in the subscription export. Remove them.
## Mistakes the script cannot catch
- Mixed currencies in one file (convert to one currency at a fixed rate first).
- Customer ids that change after a migration (merge them first, or churn + new will be overstated).
- Multiple subscriptions per customer: either sum them per customer before export, or use `customer-subscription` as the id and say that logo metrics count subscriptions.
FILE:templates/metrics-report.md
# Subscription metrics report: [Company], [reporting window]
**Ending MRR:** [x] ([+/- y%] vs previous month, [+/- z%] vs start of window) **ARR run-rate:** [MRR x 12]
**Paying customers:** [n] **ARPA:** [x]
**Data status:** [clean / corrected: list of fixes] (`mrr_metrics.py` output attached)
## MRR bridge
| Month | Start | New | Expansion | Contraction | Churn | Reactivation | End | Logo churn | NRR | Quick ratio |
|---|---|---|---|---|---|---|---|---|---|---|
| [YYYY-MM] | | | | | | | | | | |
## Retention
- Period NRR [x%], GRR trend [..], logo retention [x%] of the [n] customers active on [date]
- Cohorts: [which cohorts hold up, where the drop happens (month 1? month 3?)]
## What changed and why
1. [Biggest movement and its drivers, with customer names if useful]
2. [...]
## Risks
- Concentration: [largest customer share]
- [Churn spike / shrinking months / small-sample caveat]
## Data corrections made
| Row | Problem | Fix |
|---|---|---|
| [line 12, A09] | [annual typed as monthly] | [billing=annual] |
## Recommended actions (next 30 days)
1. [...]
2. [...]
3. [...]
_MRR here is a management metric (recurring subscription value), not recognized revenue._
FILE:examples/subscription_events.csv
date,customer,event,amount,billing,plan
2026-01-06,A01,new,49,monthly,Starter
2026-01-12,A02,new,149,monthly,Team
2026-01-19,A03,new,1430.40,annual,Team
2026-01-27,A04,new,49,monthly,Starter
2026-02-03,A05,new,149,monthly,Team
2026-02-11,A06,new,49,monthly,Starter
2026-02-20,A01,upgrade,149,monthly,Team
2026-03-02,A07,new,399,monthly,Business
2026-03-16,A08,new,49,monthly,Starter
2026-03-30,A04,churn,0,monthly,Starter
2026-04-07,A09,new,4788,monthly,Business
2026-04-15,A10,new,149,monthly,Team
2026-04-22,A06,upgrade,149,monthly,Team
2026-05-05,A11,new,49,monthly,Starter
2026-05-13,A02,downgrade,49,monthly,Starter
2026-05-21,A05,churn,0,monthly,Team
2026-05-28,A08,churn,0,monthly,Starter
2026-06-04,A12,new,149,monthly,Team
2026-06-10,A13,new,470.40,annual,Starter
2026-06-24,A07,upgrade,149,monthly,Team
2026-07-01,A14,new,49,monthly,Starter
2026-07-09,A04,reactivate,149,monthly,Team
2026-07-15,A15,new,0,monthly,Free
2026-07-23,A99,churn,0,monthly,Team
2026-08-04,A16,new,149,monthly,Team
2026-08-12,A10,churn,0,monthly,Team
2026-08-19,A11,churn,0,monthly,Starter
2026-08-26,A12,churn,0,monthly,Team
2026-09-02,A17,new,399,monthly,Business
2026-09-09,A18,new,49,monthly,Starter
2026-09-17,A14,upgrade,149,monthly,Team
2026-10-06,A19,new,149,monthly,Team
2026-10-14,A20,new,49,monthly,Starter
2026-10-20,A06,downgrade,49,monthly,Starter
2026-10-27,A01,new,149,monthly,Team
FILE:scripts/mrr_metrics.py
#!/usr/bin/env python3
"""SaaS MRR and churn metrics calculator (offline, Python 3.8+ standard library only).
Reads a subscription events CSV (date, customer, event, amount, billing, plan), normalizes
annual and quarterly amounts to MRR, builds a month-by-month MRR bridge (new, expansion,
contraction, churn, reactivation), computes logo churn, GRR, NRR, ARPA and quick ratio, and
flags data problems and business warning signs.
Usage:
mrr_metrics.py events.csv [--from 2026-01] [--to 2026-10] [--json] [--top-share 0.2]
mrr_metrics.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, csv, json, statistics, sys
from collections import Counter, OrderedDict
from datetime import date
EVENTS = {"new", "upgrade", "downgrade", "churn", "reactivate", "price_change"}
BILLING_MONTHS = {"monthly": 1, "quarterly": 3, "annual": 12, "yearly": 12}
SEV = {"high": 0, "medium": 1, "low": 2}
def month_key(s):
y, m = int(s[:4]), int(s[5:7])
if not (1 <= m <= 12):
raise ValueError("bad month in %r" % s)
return "%04d-%02d" % (y, m)
def next_month(k):
y, m = int(k[:4]), int(k[5:7])
return "%04d-%02d" % (y + (m == 12), 1 if m == 12 else m + 1)
def month_range(a, b):
out = [a]
while out[-1] < b:
out.append(next_month(out[-1]))
return out
def load(path):
with open(path, newline="", encoding="utf-8-sig") as fh:
rows = list(csv.DictReader(fh))
need = {"date", "customer", "event", "amount"}
if not rows or not need <= set(k.strip() for k in rows[0].keys()):
raise ValueError("CSV needs columns: date, customer, event, amount (optional: billing, plan)")
return [{k.strip(): (v or "").strip() for k, v in r.items()} for r in rows]
def compute(rows, start=None, end=None, top_share=0.2, churn_alert=0.05):
findings = []
def add(code, sev, msg, month=None, customer=None):
findings.append({"code": code, "severity": sev, "month": month, "customer": customer, "message": msg})
events = []
for i, r in enumerate(rows, start=2):
try:
d = date.fromisoformat(r["date"][:10])
except ValueError:
add("SM01", "high", "line %d: bad date %r" % (i, r["date"])); continue
ev = r["event"].lower()
if ev not in EVENTS:
add("SM01", "high", "line %d: unknown event %r (use %s)" % (i, r["event"], ", ".join(sorted(EVENTS)))); continue
billing = (r.get("billing") or "monthly").lower()
if billing not in BILLING_MONTHS:
add("SM01", "high", "line %d: unknown billing %r" % (i, billing)); continue
try:
amount = float(r["amount"] or 0)
except ValueError:
add("SM01", "high", "line %d: amount %r is not a number" % (i, r["amount"])); continue
if amount < 0:
add("SM08", "high", "line %d: negative amount %.2f (refunds and credits are not MRR)" % (i, amount), customer=r["customer"]); continue
events.append({"line": i, "date": d, "month": d.strftime("%Y-%m"), "customer": r["customer"], "event": ev,
"mrr": round(amount / BILLING_MONTHS[billing], 2), "billing": billing, "amount": amount, "plan": r.get("plan", "")})
if not events:
raise ValueError("no usable events")
events.sort(key=lambda e: (e["date"], e["line"]))
# SM04: monthly-billed amounts that look like annual totals typed as monthly
monthly_amounts = [e["mrr"] for e in events if e["billing"] == "monthly" and e["mrr"] > 0]
med = statistics.median(monthly_amounts) if monthly_amounts else 0
for e in events:
if med and e["billing"] == "monthly" and e["mrr"] >= 8 * med and e["mrr"] > 0:
add("SM04", "medium", "line %d: monthly amount %.2f is %.0fx the median monthly price: an annual contract entered as monthly? (set billing=annual)" % (e["line"], e["mrr"], e["mrr"] / med), e["month"], e["customer"])
first = start or events[0]["month"]
last = end or events[-1]["month"]
months = month_range(min(first, events[0]["month"]), last)
state = {} # customer -> current MRR (0 = churned)
ever = set()
bridge = OrderedDict()
by_month = {}
for e in events:
by_month.setdefault(e["month"], []).append(e)
cohort_start = {}
active_by_month = {}
snaps = {}
for m in months:
start_mrr = round(sum(state.values()), 2)
start_logos = sum(1 for v in state.values() if v > 0)
b = {"month": m, "start_mrr": start_mrr, "new": 0.0, "expansion": 0.0, "contraction": 0.0, "churn": 0.0, "reactivation": 0.0,
"start_customers": start_logos, "new_customers": 0, "churned_customers": 0, "reactivated_customers": 0}
for e in by_month.get(m, []):
c, ev, new = e["customer"], e["event"], e["mrr"]
cur = state.get(c)
if ev == "new":
if cur is not None and cur > 0:
add("SM02", "medium", "line %d: 'new' for a customer who is already active (%.2f MRR); treated as a price change" % (e["line"], cur), m, c)
ev = "price_change"
elif cur is not None and cur == 0 and c in ever:
add("SM02", "low", "line %d: 'new' for a returning customer; counted as reactivation" % e["line"], m, c)
ev = "reactivate"
if ev == "new":
state[c] = new; b["new"] += new
if new == 0:
add("SM03", "low", "line %d: new customer with 0 MRR (free plan or trial?) not counted in paid metrics" % e["line"], m, c)
else:
b["new_customers"] += 1; cohort_start[c] = m; ever.add(c)
elif ev == "churn":
if not cur:
add("SM02", "medium", "line %d: churn for a customer who is not active; ignored" % e["line"], m, c); continue
b["churn"] += cur; b["churned_customers"] += 1; state[c] = 0.0
elif ev == "reactivate":
if cur:
add("SM02", "medium", "line %d: reactivate for an active customer; treated as a price change" % e["line"], m, c)
ev = "price_change"
else:
if c not in ever:
add("SM02", "low", "line %d: reactivate for an unknown customer; counted as new" % e["line"], m, c)
b["new"] += new; b["new_customers"] += 1; ever.add(c); cohort_start[c] = m
else:
b["reactivation"] += new; b["reactivated_customers"] += 1
state[c] = new
if ev in ("upgrade", "downgrade", "price_change"):
if cur is None or cur == 0:
add("SM02", "medium", "line %d: %s for a customer with no active subscription; ignored" % (e["line"], e["event"]), m, c); continue
delta = round(new - cur, 2)
if e["event"] == "upgrade" and delta < 0:
add("SM05", "medium", "line %d: 'upgrade' lowers MRR %.2f -> %.2f; check the event type" % (e["line"], cur, new), m, c)
if e["event"] == "downgrade" and delta > 0:
add("SM05", "medium", "line %d: 'downgrade' raises MRR %.2f -> %.2f; check the event type" % (e["line"], cur, new), m, c)
if new == 0:
add("SM05", "medium", "line %d: change to 0 MRR; record it as churn instead" % e["line"], m, c)
b["churn"] += cur; b["churned_customers"] += 1; state[c] = 0.0; continue
if delta > 0: b["expansion"] += delta
else: b["contraction"] += -delta
state[c] = new
end_mrr = round(sum(state.values()), 2)
for k in ("new", "expansion", "contraction", "churn", "reactivation"):
b[k] = round(b[k], 2)
b["end_mrr"] = end_mrr
b["net_new_mrr"] = round(end_mrr - start_mrr, 2)
b["end_customers"] = sum(1 for v in state.values() if v > 0)
b["arpa"] = round(end_mrr / b["end_customers"], 2) if b["end_customers"] else 0.0
if start_mrr:
b["grr"] = round((start_mrr - b["churn"] - b["contraction"]) / start_mrr, 4)
b["nrr"] = round((start_mrr - b["churn"] - b["contraction"] + b["expansion"]) / start_mrr, 4)
b["mrr_churn_rate"] = round((b["churn"] + b["contraction"]) / start_mrr, 4)
else:
b["grr"] = b["nrr"] = b["mrr_churn_rate"] = None
b["logo_churn_rate"] = round(b["churned_customers"] / start_logos, 4) if start_logos else None
lost = b["churn"] + b["contraction"]
b["quick_ratio"] = round((b["new"] + b["expansion"] + b["reactivation"]) / lost, 2) if lost else None
assert abs(start_mrr + b["new"] + b["expansion"] + b["reactivation"] - b["contraction"] - b["churn"] - end_mrr) < 0.05, m
active_by_month[m] = {c for c, v in state.items() if v > 0}
snaps[m] = dict(state)
bridge[m] = b
report_months = [m for m in months if m >= first]
rows_out = [bridge[m] for m in report_months]
for b in rows_out:
m = b["month"]
if b["logo_churn_rate"] is not None and b["logo_churn_rate"] > churn_alert and b["start_customers"] >= 5:
add("SM06", "medium", "logo churn %.1f%% in %s (alert above %.1f%%)" % (100 * b["logo_churn_rate"], m, 100 * churn_alert), m)
if b["quick_ratio"] is not None and b["quick_ratio"] < 1:
add("SM07", "high", "quick ratio %.2f in %s: lost MRR exceeded gained MRR (shrinking)" % (b["quick_ratio"], m), m)
# trailing NRR over the reported period (cohort of customers active at period start)
base_month = report_months[0]
prev = None
for m in months:
if m == base_month: break
prev = m
period = {}
if prev and snaps[prev]:
base = {c: v for c, v in snaps[prev].items() if v > 0}
now = snaps[report_months[-1]]
start_sum = sum(base.values()); end_sum = sum(now.get(c, 0) for c in base)
kept = sum(1 for c in base if now.get(c, 0) > 0)
period = {"base_month": prev, "base_customers": len(base), "base_mrr": round(start_sum, 2),
"same_customers_mrr_now": round(end_sum, 2), "period_nrr": round(end_sum / start_sum, 4) if start_sum else None,
"logo_retention": round(kept / len(base), 4) if base else None}
if period["period_nrr"] is not None and period["period_nrr"] < 1:
add("SM09", "medium", "net revenue retention over %s..%s is %.1f%% (<100%%): existing customers shrink" % (report_months[0], report_months[-1], 100 * period["period_nrr"]))
final = {c: v for c, v in state.items() if v > 0}
total = sum(final.values())
if total:
top = sorted(final.items(), key=lambda x: -x[1])[:3]
if top[0][1] / total > top_share:
add("SM10", "medium", "largest customer %s is %.0f%% of MRR (threshold %.0f%%): concentration risk" % (top[0][0], 100 * top[0][1] / total, 100 * top_share), customer=top[0][0])
# cohorts: logo retention by start month
cohorts = OrderedDict()
for c, m in sorted(cohort_start.items(), key=lambda x: x[1]):
cohorts.setdefault(m, []).append(c)
cohort_table = []
for m, cs in cohorts.items():
row = {"cohort": m, "customers": len(cs)}
k = m
for i in range(0, 13):
if k > last: break
if i in (1, 3, 6, 12):
row["m%d" % i] = round(sum(1 for c in cs if c in active_by_month[k]) / len(cs), 2)
k = next_month(k)
cohort_table.append(row)
findings.sort(key=lambda f: (SEV[f["severity"]], f["code"], f["month"] or ""))
s = Counter(f["severity"] for f in findings)
return {"months": rows_out, "period": period, "cohorts": cohort_table,
"top_customers": [{"customer": c, "mrr": v, "share": round(v / total, 3)} for c, v in sorted(final.items(), key=lambda x: -x[1])[:5]] if total else [],
"findings": findings, "summary": {k: s.get(k, 0) for k in ("high", "medium", "low")}}
def pct(x):
return " - " if x is None else "%5.1f%%" % (100 * x)
def print_text(rep):
print("MRR bridge")
print("month start_mrr new expans contr churn react end_mrr cust logo_ch GRR NRR QR ARPA")
for b in rep["months"]:
print("%s %10.2f %8.2f %7.2f %6.2f %8.2f %6.2f %9.2f %5d %s %s %s %5s %7.2f" % (
b["month"], b["start_mrr"], b["new"], b["expansion"], b["contraction"], b["churn"], b["reactivation"],
b["end_mrr"], b["end_customers"], pct(b["logo_churn_rate"]), pct(b["grr"]), pct(b["nrr"]),
"-" if b["quick_ratio"] is None else "%.2f" % b["quick_ratio"], b["arpa"]))
p = rep["period"]
if p:
print("\nPeriod retention (customers active at end of %s: %d, %.2f MRR): NRR %s, logo retention %s" % (
p["base_month"], p["base_customers"], p["base_mrr"], pct(p["period_nrr"]), pct(p["logo_retention"])))
if rep["cohorts"]:
print("\nCohort logo retention (share still paying after N months)")
for c in rep["cohorts"]:
print(" %s n=%-3d m1=%s m3=%s m6=%s" % (c["cohort"], c["customers"], c.get("m1", "-"), c.get("m3", "-"), c.get("m6", "-")))
print("\nTop customers: " + ", ".join("%s %.2f (%.0f%%)" % (t["customer"], t["mrr"], 100 * t["share"]) for t in rep["top_customers"]))
print("\nFindings: %(high)d high, %(medium)d medium, %(low)d low" % rep["summary"])
for f in rep["findings"]:
print(" [%s] %s %s%s: %s" % (f["severity"].upper(), f["code"], f["month"] or "", (" " + f["customer"]) if f["customer"] else "", f["message"]))
def self_test():
ok = total = 0
def t(name, cond):
nonlocal ok, total
total += 1; ok += bool(cond)
print(("PASS " if cond else "FAIL ") + name)
def R(*lines):
return [dict(zip(["date", "customer", "event", "amount", "billing"], l.split(","))) for l in lines]
r = compute(R("2026-01-05,a,new,100,monthly", "2026-01-09,b,new,1200,annual", "2026-02-03,a,upgrade,150,monthly",
"2026-02-10,b,churn,0,annual", "2026-03-01,b,reactivate,50,monthly", "2026-03-15,c,new,200,monthly"))
m = {b["month"]: b for b in r["months"]}
t("annual normalized to MRR", m["2026-01"]["end_mrr"] == 200)
t("expansion counted", m["2026-02"]["expansion"] == 50)
t("churn counted at prior MRR", m["2026-02"]["churn"] == 100 and m["2026-02"]["churned_customers"] == 1)
t("reactivation separate from new", m["2026-03"]["reactivation"] == 50 and m["2026-03"]["new"] == 200)
t("bridge closes", all(abs(b["start_mrr"] + b["new"] + b["expansion"] + b["reactivation"] - b["contraction"] - b["churn"] - b["end_mrr"]) < 0.01 for b in r["months"]))
t("NRR feb = (200-100+50)/200", m["2026-02"]["nrr"] == 0.75 and m["2026-02"]["grr"] == 0.5)
t("SM07 quick ratio < 1 in feb", any(f["code"] == "SM07" and f["month"] == "2026-02" for f in r["findings"]))
r = compute(R("2026-01-01,a,new,50,monthly", "2026-01-01,b,new,50,monthly", "2026-01-01,c,new,55,monthly", "2026-01-02,d,new,1200,monthly"))
t("SM04 annual typed as monthly", any(f["code"] == "SM04" and f["customer"] == "d" for f in r["findings"]))
t("SM10 concentration", any(f["code"] == "SM10" for f in r["findings"]))
r = compute(R("2026-01-01,a,new,50,monthly", "2026-02-01,a,upgrade,40,monthly", "2026-02-02,z,churn,0,monthly", "2026-02-03,a,new,60,monthly"))
codes = Counter(f["code"] for f in r["findings"])
t("SM05 upgrade lowering MRR", codes["SM05"] == 1)
t("SM02 churn of unknown + new for active", codes["SM02"] == 2)
t("contraction from mislabeled upgrade", r["months"][1]["contraction"] == 10 and r["months"][1]["expansion"] == 20)
rows = R(*["2026-01-0%d,c%d,new,100,monthly" % (1 + i % 9, i) for i in range(20)] + ["2026-02-05,c%d,churn,0,monthly" % i for i in range(3)])
r = compute(rows)
t("SM06 logo churn alert (15%)", any(f["code"] == "SM06" for f in r["findings"]) and r["months"][1]["logo_churn_rate"] == 0.15)
r = compute(R("2026-01-01,a,new,100,monthly", "2026-01-01,b,new,100,monthly", "2026-02-01,a,downgrade,60,monthly", "2026-03-01,c,new,500,monthly"), start="2026-02")
t("period NRR for base cohort excludes new logos", r["period"]["period_nrr"] == 0.8 and r["period"]["base_customers"] == 2)
t("SM09 NRR < 100%", any(f["code"] == "SM09" for f in r["findings"]))
r = compute(R("2026-01-01,f,new,0,monthly", "2026-02-01,f,new,49,monthly"))
t("free-to-paid conversion counted as new", r["months"][1]["new"] == 49 and r["months"][1]["new_customers"] == 1 and r["months"][0]["new_customers"] == 0)
try:
compute(R("2026-13-01,a,new,1,monthly")); t("bad date reported", False)
except ValueError:
t("bad date -> no usable events error", True)
print("%d/%d passed" % (ok, total))
return 0 if ok == total else 1
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("file", nargs="?"); ap.add_argument("--from", dest="start"); ap.add_argument("--to", dest="end")
ap.add_argument("--json", action="store_true"); ap.add_argument("--top-share", type=float, default=0.2)
ap.add_argument("--churn-alert", type=float, default=0.05); ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.file:
ap.print_help(); return 2
try:
rep = compute(load(a.file), a.start and month_key(a.start), a.end and month_key(a.end), a.top_share, a.churn_alert)
except (OSError, ValueError) as e:
print("bad input: %s" % e, file=sys.stderr); return 2
if a.json:
print(json.dumps(rep, indent=2))
else:
print_text(rep)
return 1 if rep["summary"]["high"] else 0
if __name__ == "__main__":
sys.exit(main())
Scans plain or JSON-lines logs for data that must never be logged: Luhn-valid cards, IBANs, SSNs, API keys, JWTs, auth headers, passwords, URL tokens, emails, phones, birth dates and public IPs. Masks every value, ranks the loggers to fix and writes a redacted copy. Offline stdlib Python.
---
name: log-pii-and-secret-redaction-checker
description: Scans plain or JSON-lines logs for data that must never be logged: Luhn-valid cards, IBANs, SSNs, API keys, JWTs, auth headers, passwords, URL tokens, emails, phones, birth dates and public IPs. Masks every value, ranks the loggers to fix and writes a redacted copy. Offline stdlib Python.
---
# Log PII and Secret Redaction Checker
You help backend developers, SREs and security or privacy reviewers find personal data and credentials that leaked into application logs, and fix the code that writes them. Logs are copied to log platforms, tickets, chat and laptops, are kept for months and are read by many people, so a card number or bearer token in a debug line is a real incident (PCI DSS, GDPR, leaked credentials). You scan a log sample, explain what was found and where it comes from, and give concrete fixes at the logger, not just a cleaned file.
You work only on the log text the user provides, on their machine. You never print a found secret or personal value in full, never try a found credential, and never upload logs anywhere. Treat any real secret you find as compromised: tell the user to rotate it.
## Files in this skill
- `scripts/log_redaction_check.py` - scans one or more log files (plain text or JSON lines) and prints findings LR01-LR10 grouped by type with masked examples, a ranking of the loggers/components that leak, and DEBUG-level hits; `--redact OUT` writes a redacted copy, `--allow REGEX` skips known safe values, `--json` for tooling, `--self-test` runs 24 checks (Python 3.8+ standard library only)
- `references/detection-rules.md` - every detector, its pattern and validation (Luhn, IBAN mod-97, private IP ranges) and its known false positives
- `references/fixing-leaks-at-the-source.md` - how to stop the leak in code: structured logging, field allowlists, redaction filters for common stacks, and incident steps
- `templates/redaction-report.md` - the report you hand back
- `examples/app.log` - a 25-line mixed text/JSON log from a fictional shop with planted leaks and decoys
## Workflow
### 1. Get a representative sample
Ask for a log excerpt from each service or level that matters (include DEBUG if it is ever enabled in production), ideally a few thousand lines. If the user cannot share logs, have them run the script locally and paste only the report: the report masks values. Ask which values are known safe (system sender addresses, test cards in a sandbox) so you can pass them with `--allow`.
### 2. Run the checker
```
python3 scripts/log_redaction_check.py examples/app.log
python3 scripts/log_redaction_check.py api.log worker.log --allow '^noreply@example\.com$'
python3 scripts/log_redaction_check.py app.log --redact app.redacted.log --json > findings.json
python3 scripts/log_redaction_check.py --self-test
```
Exit 0 = no high findings, 1 = high findings, 2 = bad input. Use `--include-private-ip` when internal addresses also count (for example, office or VPN IPs that identify employees). Without a shell, apply `references/detection-rules.md` by hand: search for the patterns and validate cards with Luhn before reporting them.
### 3. Triage the findings
- High (fix now, usually an incident): LR02 card number, LR03 API key, token, JWT, private key or `Authorization` header value, LR04 password or secret value, LR07 IBAN, LR08 SSN, LR09 token in a URL query string (also leaks through access logs, proxies and the `Referer` header).
- Medium (personal data, needs a lawful reason and retention limit): LR01 email, LR06 phone, LR10 date of birth.
- Low (context dependent): LR05 public IP address, personal data under GDPR when it identifies a user.
- Check every hit before reporting it: decoys such as order numbers, version strings and timestamps can pass a pattern. Mark false positives and re-run with `--allow`.
- Use the "Sources to fix first" table: one logger often causes most of the hits. DEBUG-level hits mean request or payload dumping.
### 4. Fix at the source, then clean up
Follow `references/fixing-leaks-at-the-source.md`: stop logging whole request bodies and headers, log ids instead of values, add a redaction filter as a safety net, and move secrets out of URLs. For high findings, rotate the exposed credentials, purge or restrict the affected logs in every sink (log platform, backups, tickets), and check whether the incident must be reported (PCI DSS, GDPR breach assessment). `--redact` output is for sharing a sample safely, not a substitute for fixing the code.
### 5. Deliver
Fill `templates/redaction-report.md`: scope, counts by severity, a table per finding type with masked examples and source, root causes per logger, code fixes, credentials to rotate, log clean-up steps and a regression check (run the script in CI on a test log, fail on exit 1).
## Example result
On `examples/app.log` the checker finds 20 hits in 25 lines: 11 high, 7 medium, 2 low.
- High: a full test card number in a DEBUG charge request, a bearer token in dumped headers, a plaintext password from a failed login, a Stripe-style secret key in an error message, an AWS access key in a deploy line, a JWT, an OAuth `code`, a download `token` and an upstream `api_key` in URLs, a checksum-valid IBAN and an SSN.
- Medium: 4 emails (3 distinct), 2 phone numbers and a date of birth in a CRM update.
- Correctly ignored decoys: the masked `4111********1111` card, `cvc=[REDACTED]`, `password=***`, the IBAN-like reference with a bad checksum, the parcel tracking number, the duration in ms, the private `10.0.3.14` and `build 1.2.3.4`.
- With `--allow '^noreply@'` the system sender address drops out (19 hits). `auth` is the leakiest logger (5 hits) and 3 hits sit in DEBUG lines.
## Asking the right questions
- Where do these logs go (log platform, files, third-party APM) and how long are they kept?
- Is DEBUG ever enabled in production, even temporarily?
- Which values are test data (sandbox cards, example.com addresses) and may be allowlisted?
- Who owns each logger in the "Sources to fix first" table?
## Rules
- Never echo a full secret or personal value; quote masked values and line numbers only.
- Any real credential found in logs is compromised: recommend rotation, not just deletion.
- Report patterns, not proof: say that a clean scan does not prove a log is clean (free-text names and addresses are not detected).
- Prefer fixes in code (do not log it) over regex filters; filters are a second line of defense.
- Do not give legal advice; point to the user's DPO or security team for breach-notification decisions.
FILE:references/detection-rules.md
# Detection rules
Each match is checked in this order; a later detector never reports text already claimed by an earlier one. Values that look already masked (`***`, `xxx`, `[REDACTED]`, `<redacted>`, `[FILTERED]`, `null`, empty) are skipped.
| Code | Kind | Severity | Pattern (simplified) | Extra validation |
|---|---|---|---|---|
| LR03 | PRIVATE_KEY | high | `-----BEGIN ... PRIVATE KEY-----` | none |
| LR09 | URL_TOKEN | high | `?` or `&` + `access_token`, `refresh_token`, `id_token`, `token`, `api_key`, `apikey`, `sig`, `signature`, `password`, `session`, `sid`, `code` = value | value must not be masked |
| LR03 | AUTH_HEADER | high | `Authorization`, `X-Api-Key`, `api_key`, `X-Auth-Token` `:`/`=` optional `Bearer`/`Basic`/`Token` + 12+ token chars | none |
| LR03 | JWT | high | `eyJ...` three base64url segments | none |
| LR03 | AWS_KEY | high | `AKIA`/`ASIA` + 16 upper-case letters or digits | none |
| LR03 | API_KEY | high | `sk_`/`rk_`/`pk_` + `live_`/`test_` + 16+ chars, GitHub `ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_`, Slack `xoxa-`/`xoxb-`/`xoxp-`/`xoxr-` | none |
| LR04 | PASSWORD | high | `password`, `passwd`, `pwd`, `secret`, `client_secret`, `passphrase` + `:`/`=` + value (text or JSON) | value must not be masked |
| LR10 | DOB | medium | `dob`, `date_of_birth`, `birthdate`, `birth_date`, `birthday` + a date | none |
| LR07 | IBAN | high | 2 letters, 2 digits, 11-30 more alphanumerics, spaces allowed every 4 | ISO 13616 mod-97 checksum = 1 |
| LR02 | CARD | high | 13-19 digits, optional single spaces or dashes, not part of a decimal, time or longer number | Luhn checksum, not all the same digit |
| LR08 | SSN | high | `NNN-NN-NNNN` | not 000, 666 or 9xx area; group not 00; serial not 0000 |
| LR01 | EMAIL | medium | `local@domain.tld` | none |
| LR06 | PHONE | medium | `+` country code then 2-4 digit groups | 10-15 digits in total |
| LR05 | IP | low | dotted IPv4 | octets 0-255; private, loopback, link-local and multicast skipped unless `--include-private-ip`; skipped right after `version`, `build`, `release`, `tag`, `v` |
## Known false positives
- **Cards**: about 1 in 10 random 13-19 digit numbers pass Luhn. Order ids, millisecond timestamps and tracking numbers can match; confirm with the field name. Separators inside numbers are only single spaces or dashes.
- **Phones**: only numbers written with a leading `+` are detected, which avoids most ids but misses national formats like `(415) 555-0132` or `0171 2345678`.
- **SSN**: any `123-45-6789` shape, for example some part numbers.
- **IPs**: version strings in other forms (`lib 2.10.0.1`), public IPs of your own servers.
- **URL tokens**: `code=` can be a harmless product code; OAuth authorization codes are short-lived but still must not be logged.
## Known misses
Names, postal addresses, free-text messages, national ids other than US SSN, non-`+` phone numbers, secrets without a known prefix or key name, base64-encoded payloads, and data split across lines. Combine the scan with a code review of what each log call writes.
FILE:references/fixing-leaks-at-the-source.md
# Fixing leaks at the source
## Principles
1. **Log ids, not values.** `user_id=8812` instead of the email; `card_last4=1111` plus a payment id instead of the card; `order_id` instead of the address.
2. **Allowlist fields.** Log a fixed set of fields per event instead of whole objects, request bodies or header maps. Dumping `request.headers` is the most common source of LR03 bearer tokens.
3. **Keep secrets out of URLs.** Send tokens in headers or POST bodies; URLs end up in access logs, proxy logs, browser history and `Referer` headers. For signed download links, log the path without the query string.
4. **Redaction filter as a safety net.** Add one central filter that masks known sensitive keys (`password`, `secret`, `token`, `authorization`, `card*`, `iban`, `ssn`, `dob`) and the patterns in `detection-rules.md`, before logs leave the process.
5. **DEBUG is not a free pass.** Debug logs get turned on in production during incidents. Apply the same rules.
## Stack hints
- **Python logging / structlog**: a `logging.Filter` or structlog processor that rewrites `record.msg`/event dict keys; never `logger.debug("req %s", request.__dict__)`.
- **Node (pino / winston)**: pino `redact: ["req.headers.authorization", "*.password", "card.number"]`; winston custom format.
- **Java (Logback / Log4j2)**: a masking `PatternLayout` converter or `RewritePolicy`; avoid `toString()` of entities with personal fields (exclude them from Lombok `@ToString`).
- **Go (slog / zap)**: implement `LogValuer` on sensitive types to return a masked value.
- **Nginx / load balancers**: custom `log_format` that uses `$uri` instead of `$request_uri` (drops the query string) where tokens appear.
- **Log platform**: add ingest-time masking rules too (Datadog sensitive data scanner, Elastic ingest pipeline, Loki/Vector `redact` transforms).
## When a high finding is real (incident steps)
1. Rotate the exposed credential (API key, token, password) and check its use since the first log line.
2. Fix and deploy the logging code.
3. Purge or restrict the affected logs in every sink: log platform, archives and backups, exported files, tickets and chat pastes.
4. Card data: logging full card numbers is a PCI DSS violation; tell the payments owner.
5. Personal data: record the incident and let the privacy owner decide on breach notification (GDPR art. 33 has a 72-hour clock once a reportable breach is known).
## Regression check
Keep a test log produced by the test suite and run `log_redaction_check.py test.log` in CI; fail the build on exit code 1. Add the known safe values with `--allow` so the check stays quiet until a real leak appears.
FILE:templates/redaction-report.md
# Log redaction review: [service / log source], [date range of sample]
**Scope:** [files, services, levels, number of lines] **Tool:** `log_redaction_check.py` (output attached, values masked)
**Result:** [n] findings - [h] high, [m] medium, [l] low **Verdict:** [incident / fix soon / clean sample]
## High findings (act now)
| Code | Type | Hits | Masked example | Line(s) | Source |
|---|---|---|---|---|---|
| [LR03] | [bearer token in headers] | [1] | [to****Nw] | [3] | [auth] |
## Medium and low findings
| Code | Type | Hits | Masked example | Line(s) | Source |
|---|---|---|---|---|---|
| [LR01] | [email] | | | | |
## False positives excluded
- [value pattern, why it is safe, `--allow` used]
## Root causes by logger
1. [logger] - [what it writes, e.g. dumps full request headers at DEBUG]
2. [...]
## Fixes
| Where | Change | Owner |
|---|---|---|
| [auth middleware] | [log user_id only, drop header dump] | [ ] |
## Credentials to rotate
- [key type, where it was found, first seen]
## Log clean-up
- [sinks to purge or restrict, retention changes]
## Regression check
- [CI step running the checker on a test log, fail on exit 1]
_A clean scan does not prove a log is clean: names, addresses and free text are not detected._
FILE:examples/app.log
2026-11-18T09:00:01Z INFO [web] GET /health 200 4ms from 10.0.3.14
2026-11-18T09:00:07Z INFO [auth] login ok user_id=8812 email=ana.lima@example.com ip=203.0.113.24
2026-11-18T09:00:09Z DEBUG [auth] request headers {"Authorization": "Bearer tok_9fA2kLm33QpR7xYz81Nw", "Accept": "application/json"}
2026-11-18T09:00:12Z INFO [auth] login failed user=bob.k@example.org password=Summer2026! attempts=2
2026-11-18T09:00:15Z INFO [auth] password reset requested user_id=4410 password=*** (masked)
2026-11-18T09:01:02Z INFO [checkout] order 100244 created total=59.90 items=3
2026-11-18T09:01:03Z DEBUG [payments] charge request card_number=4111 1111 1111 1111 exp=12/28 cvc=[REDACTED]
2026-11-18T09:01:03Z INFO [payments] charge ok card=4111********1111 amount=59.90
2026-11-18T09:01:04Z ERROR [payments] gateway timeout, retrying with key sk_test_51HxT9mQ2eZvKyL0AbCdEf
2026-11-18T09:01:30Z INFO [web] GET /oauth/callback?code=4/0AY0e-g7Qx2mN8&state=af31 302 from 198.51.100.77
2026-11-18T09:02:11Z INFO [web] GET /download/report.pdf?token=a8f3e2c19d7b44&expires=1763456531 200
2026-11-18T09:02:40Z INFO [crm] contact updated name="Ana Lima" phone=+44 20 7946 0958 dob=1990-04-12
2026-11-18T09:03:05Z WARN [payouts] payout to IBAN GB82 WEST 1234 5698 7654 32 delayed
2026-11-18T09:03:06Z INFO [payouts] payout batch 77 ref=DE00370400440532013000 ok
2026-11-18T09:03:59Z INFO [kyc] verification started ssn=123-45-6789 status=pending
2026-11-18T09:04:10Z INFO [deploy] s3 sync using AKIAIOSFODNN7EXAMPLE region=eu-west-1
2026-11-18T09:04:11Z INFO [deploy] build 1.2.3.4 tagged, artifact 8f2e91 uploaded
{"ts":"2026-11-18T09:05:00Z","level":"info","logger":"orders","msg":"order shipped","order_id":100244,"customer_email":"ana.lima@example.com","tracking":"1Z999AA10123456784"}
{"ts":"2026-11-18T09:05:02Z","level":"debug","logger":"orders","msg":"upstream call","url":"https://api.example.net/v2/rates?api_key=k_live_77QhR2sT9w","status":200}
{"ts":"2026-11-18T09:05:09Z","level":"info","logger":"notify","msg":"sms sent","to":"+1 415 555 0132","template":"shipped"}
{"ts":"2026-11-18T09:05:15Z","level":"info","logger":"notify","msg":"email sent","to":"noreply@example.com","template":"digest"}
{"ts":"2026-11-18T09:06:00Z","level":"error","logger":"session","msg":"token expired","jwt":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4ODEyIiwiZXhwIjoxNzYzNDU2NTMxfQ.Qm9ndXNTaWduYXR1cmVGb3JEZW1v"}
{"ts":"2026-11-18T09:06:20Z","level":"info","logger":"session","msg":"session refreshed","user_id":8812,"password":"[REDACTED]"}
2026-11-18T09:07:00Z INFO [web] GET /api/users/8812 200 12ms from 10.0.3.14
2026-11-18T09:07:45Z INFO [jobs] nightly export finished rows=18233 duration_ms=1731995000123
FILE:scripts/log_redaction_check.py
#!/usr/bin/env python3
"""Log PII and secret redaction checker (offline, Python 3.8+ standard library only).
Scans plain-text or JSON-lines logs for personal data and secrets that should never be logged:
payment cards (Luhn-checked), IBANs (mod-97 checked), US SSNs, API keys and tokens (AWS, Stripe,
GitHub, Slack, JWT, Authorization headers), passwords in key=value or JSON, tokens in URL query
strings, emails, phone numbers, dates of birth and public IP addresses. Values that are already
masked ("***", "[REDACTED]") are ignored. Every value is masked in the report; nothing is sent
anywhere. Optionally writes a redacted copy of the log.
Usage:
log_redaction_check.py app.log [more.log ...] [--json] [--redact OUT] [--allow REGEX ...]
[--include-private-ip] [--max-examples 3]
log_redaction_check.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, json, re, sys
from collections import Counter, OrderedDict, defaultdict
SEV = {"high": 0, "medium": 1, "low": 2}
REDACTED = re.compile(r"^(\*+.*|x{3,}|\[?redacted(:\w+)?\]?|<redacted>|\[filtered\]|null|none|\"\"|-|)$", re.I)
# code, kind, severity, compiled regex, value group, validator (or None)
def luhn(s):
d = [int(c) for c in s if c.isdigit()]
if not 13 <= len(d) <= 19 or len(set(d)) == 1:
return False
tot = 0
for i, n in enumerate(reversed(d)):
if i % 2:
n *= 2
n -= 9 if n > 9 else 0
tot += n
return tot % 10 == 0
def iban_ok(s):
s = s.replace(" ", "")
if not 15 <= len(s) <= 34:
return False
r = s[4:] + s[:4]
num = "".join(str(int(c, 36)) for c in r)
return int(num) % 97 == 1
def phone_ok(s):
return 10 <= sum(c.isdigit() for c in s) <= 15
def public_ip(s, include_private=False):
parts = s.split(".")
if len(parts) != 4 or any(not p.isdigit() or int(p) > 255 or (len(p) > 1 and p[0] == "0") for p in parts):
return False
a, b = int(parts[0]), int(parts[1])
private = a in (10, 127, 0) or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168) or (a == 169 and b == 254) or a >= 224
return include_private or not private
DETECTORS = [
("LR03", "PRIVATE_KEY", "high", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), 0, None),
("LR09", "URL_TOKEN", "high", re.compile(r"(?i)[?&](?:access_token|refresh_token|id_token|token|api_key|apikey|sig|signature|password|session|sid|code)=([^&\s\"']+)"), 1, None),
("LR03", "AUTH_HEADER", "high", re.compile(r"(?i)\b(?:authorization|x-api-key|api[_-]?key|x-auth-token)\b\"?\s*[:=]\s*\"?(?:bearer\s+|basic\s+|token\s+)?([A-Za-z0-9._~+/=-]{12,})"), 1, None),
("LR03", "JWT", "high", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}"), 0, None),
("LR03", "AWS_KEY", "high", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), 0, None),
("LR03", "API_KEY", "high", re.compile(r"\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{16,}\b|\bgh[pousr]_[A-Za-z0-9]{30,}\b|\bxox[abpr]-[A-Za-z0-9-]{10,}"), 0, None),
("LR04", "PASSWORD", "high", re.compile(r"(?i)\b(?:password|passwd|pwd|secret|client_secret|passphrase)\b\"?\s*[:=]\s*\"?([^\s\",&}]*)"), 1, None),
("LR10", "DOB", "medium", re.compile(r"(?i)\b(?:dob|date_of_birth|birth_?date|birthday)\b\"?\s*[:=]\s*\"?(\d{4}-\d{2}-\d{2}|\d{1,2}[/.]\d{1,2}[/.]\d{2,4})"), 1, None),
("LR07", "IBAN", "high", re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b"), 0, iban_ok),
("LR02", "CARD", "high", re.compile(r"(?<![\d.:-])\d(?:[ -]?\d){12,18}(?![\d.:])"), 0, luhn),
("LR08", "SSN", "high", re.compile(r"\b(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b"), 0, None),
("LR01", "EMAIL", "medium", re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"), 0, None),
("LR06", "PHONE", "medium", re.compile(r"(?<![\w+])\+\d{1,3}[ .-]?\(?\d{1,4}\)?(?:[ .-]?\d{2,4}){2,4}\b"), 0, phone_ok),
("LR05", "IP", "low", re.compile(r"(?<![\d.])(?:\d{1,3}\.){3}\d{1,3}(?![\d.])"), 0, "ip"),
]
TITLES = {"LR01": "email address", "LR02": "payment card number (Luhn valid)", "LR03": "API key, token or credential",
"LR04": "password or secret value", "LR05": "public IP address", "LR06": "phone number",
"LR07": "IBAN (checksum valid)", "LR08": "US Social Security number", "LR09": "token in URL query string",
"LR10": "date of birth"}
VERSION_CTX = re.compile(r"(?i)(version|build|release|ver|tag|\bv)[\s:=]*$")
LEVEL_RE = re.compile(r"\b(TRACE|DEBUG|INFO|WARN|WARNING|ERROR|FATAL)\b\s*[:\-]?\s*\[?([A-Za-z][\w.\-]*)\]?")
def mask(kind, v):
if kind == "CARD":
d = re.sub(r"\D", "", v)
return d[:1] + "*" * (len(d) - 5) + d[-4:]
if kind == "EMAIL":
user, _, dom = v.partition("@")
return user[:1] + "***@" + dom
if kind == "PRIVATE_KEY":
return v
if len(v) <= 6:
return "*" * len(v)
return v[:2] + "*" * min(len(v) - 4, 12) + v[-2:]
def source_of(line):
s = line.strip()
if s.startswith("{"):
try:
o = json.loads(s)
for k in ("logger", "service", "component", "module", "name"):
if isinstance(o.get(k), str):
return o[k], str(o.get("level", "")).upper()
except ValueError:
pass
m = LEVEL_RE.search(line)
if m:
return m.group(2), m.group(1).upper()
return "-", ""
def scan_line(line, allow=(), include_private_ip=False):
taken, hits = [], []
for code, kind, sev, rx, grp, val in DETECTORS:
for m in rx.finditer(line):
v = m.group(grp)
a, b = m.span(grp)
if v is None or REDACTED.match(v.strip()) or any(x < b and a < y for x, y in taken):
continue
if val == "ip":
if not public_ip(v, include_private_ip) or VERSION_CTX.search(line[max(0, a - 12):a]):
continue
elif val and not val(v):
continue
if any(r.search(v) for r in allow):
continue
taken.append((a, b))
hits.append({"code": code, "kind": kind, "severity": sev, "start": a, "end": b, "value": v})
return sorted(hits, key=lambda h: h["start"])
def redact_line(line, hits):
out = line
for h in sorted(hits, key=lambda h: -h["start"]):
out = out[:h["start"]] + "[REDACTED:%s]" % h["kind"] + out[h["end"]:]
return out
def scan(named_lines, allow=(), include_private_ip=False, max_examples=3):
findings, by_code, sources, redacted = [], OrderedDict(), defaultdict(Counter), {}
distinct = defaultdict(set)
debug_hits = 0
total_lines = 0
for name, lines in named_lines:
red = []
for i, line in enumerate(lines, 1):
total_lines += 1
hits = scan_line(line, allow, include_private_ip)
red.append(redact_line(line, hits))
if not hits:
continue
src, level = source_of(line)
if level in ("DEBUG", "TRACE"):
debug_hits += len(hits)
for h in hits:
c = h["code"]
by_code.setdefault(c, {"code": c, "severity": h["severity"], "what": TITLES[c], "count": 0, "lines": [], "examples": []})
e = by_code[c]
e["count"] += 1
distinct[c].add(h["value"])
if len(e["lines"]) < 20:
e["lines"].append("%s:%d" % (name, i))
if len(e["examples"]) < max_examples:
e["examples"].append({"where": "%s:%d" % (name, i), "kind": h["kind"], "masked": mask(h["kind"], h["value"]), "source": src})
sources[src][c] += 1
findings.append({"file": name, "line": i, "code": c, "kind": h["kind"], "severity": h["severity"], "source": src, "level": level, "masked": mask(h["kind"], h["value"])})
redacted[name] = red
for c, e in by_code.items():
e["distinct_values"] = len(distinct[c])
summary = sorted(by_code.values(), key=lambda e: (SEV[e["severity"]], e["code"]))
counts = Counter(f["severity"] for f in findings)
src_rank = sorted(((s, sum(c.values()), dict(c)) for s, c in sources.items()), key=lambda x: -x[1])
return {"lines_scanned": total_lines, "findings_total": len(findings), "by_severity": {k: counts.get(k, 0) for k in SEV},
"summary": summary, "sources": [{"source": s, "hits": n, "codes": c} for s, n, c in src_rank],
"debug_level_hits": debug_hits, "findings": findings, "redacted": redacted}
def print_text(rep):
print("Scanned %d lines: %d findings (%d high, %d medium, %d low)" % (rep["lines_scanned"], rep["findings_total"],
rep["by_severity"]["high"], rep["by_severity"]["medium"], rep["by_severity"]["low"]))
if not rep["summary"]:
print("No personal data or secrets found by the detectors (this is not proof the log is clean).")
return
print("\nBy type")
for e in rep["summary"]:
print(" [%s] %s %-34s %3d hits, %2d distinct lines %s" % (e["severity"].upper(), e["code"], e["what"], e["count"],
e["distinct_values"], ", ".join(x.split(":")[-1] for x in e["lines"][:8]) + (" ..." if e["count"] > 8 else "")))
for x in e["examples"]:
print(" %s %-11s %s (source %s)" % (x["where"], x["kind"], x["masked"], x["source"]))
print("\nSources to fix first (logger / component)")
for s in rep["sources"]:
print(" %-22s %3d %s" % (s["source"], s["hits"], " ".join("%s=%d" % kv for kv in sorted(s["codes"].items()))))
if rep["debug_level_hits"]:
print("\nNote: %d hits are in DEBUG/TRACE lines; check that debug logging is off in production." % rep["debug_level_hits"])
def self_test():
ok = 0; tests = []
def t(name, cond):
tests.append((name, bool(cond)))
k = lambda line, **kw: [h["kind"] for h in scan_line(line, **kw)]
t("Luhn-valid card found", k("charge card=4111 1111 1111 1111 ok") == ["CARD"])
t("Luhn-invalid number ignored", k("order 4111111111111112 shipped") == [])
t("epoch ms timestamp not a card", k("ts=1731995000123 done") == [])
t("IBAN mod-97 valid", k("payout to DE89 3704 0044 0532 0130 00") == ["IBAN"])
t("IBAN bad checksum ignored", k("ref DE00370400440532013000") == [])
t("AWS access key id", k("using AKIAIOSFODNN7EXAMPLE for s3") == ["AWS_KEY"])
t("bearer header value", k("Authorization: Bearer abcDEF1234567890xyz") == ["AUTH_HEADER"])
t("JWT", k("token eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.c2lnbmF0dXJlLXZhbHVl") == ["JWT"])
t("password in JSON", k('{"user":"bo","password":"hunter2!"}') == ["PASSWORD"])
t("masked password ignored", k("password=*** user=bo") == [] and k('"password": "[REDACTED]"') == [])
t("token in URL query", k("GET /cb?code=abc123&state=x") == ["URL_TOKEN"])
t("email", k("signup ana.lima@example.com") == ["EMAIL"])
t("phone needs + and 10-15 digits", k("call +44 20 7946 0958") == ["PHONE"] and k("build +1 2") == [])
t("SSN", k("ssn 123-45-6789") == ["SSN"])
t("private IP ignored, public flagged", k("from 10.0.0.5") == [] and k("from 203.0.113.7") == ["IP"])
t("include private IP flag", k("from 10.0.0.5", include_private_ip=True) == ["IP"])
t("version string not an IP", k("lib 1.2.3.4.5 loaded") == [])
t("IP after 'build'/'version' ignored", k("build 1.2.3.4 tagged") == [] and k("version=8.8.8.8") == [])
t("api_key in URL is a URL token", k("GET /r?api_key=abcdef123456789") == ["URL_TOKEN"])
t("allowlist", k("mail noreply@example.com", allow=[re.compile(r"^noreply@")]) == [])
t("date of birth", k("dob=1990-04-12 ok") == ["DOB"])
rep = scan([("t.log", ["INFO [auth] login ana@example.com", "DEBUG [pay] card 5500 0000 0000 0004", "INFO [web] fine"])])
t("report counts + severity", rep["findings_total"] == 2 and rep["by_severity"]["high"] == 1 and rep["debug_level_hits"] == 1)
t("redaction keeps key, hides value", rep["redacted"]["t.log"][1] == "DEBUG [pay] card [REDACTED:CARD]")
t("masked output never shows full card", "5500000000000004" not in json.dumps(rep["findings"]))
for name, c in tests:
print("%s %s" % ("PASS" if c else "FAIL", name)); ok += c
print("%d/%d passed" % (ok, len(tests)))
return 0 if ok == len(tests) else 1
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("files", nargs="*"); ap.add_argument("--json", action="store_true")
ap.add_argument("--redact", metavar="OUT"); ap.add_argument("--allow", action="append", default=[])
ap.add_argument("--include-private-ip", action="store_true"); ap.add_argument("--max-examples", type=int, default=3)
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.files:
ap.print_usage(); return 2
try:
allow = [re.compile(x) for x in a.allow]
named = []
for f in a.files:
fh = sys.stdin if f == "-" else open(f, encoding="utf-8", errors="replace")
named.append((f, fh.read().splitlines()))
except (OSError, re.error) as e:
print("error: %s" % e, file=sys.stderr); return 2
rep = scan(named, allow, a.include_private_ip, a.max_examples)
if a.redact:
with open(a.redact, "w", encoding="utf-8") as out:
for f in a.files:
out.write("\n".join(rep["redacted"][f]) + "\n")
red = rep.pop("redacted")
if a.json:
print(json.dumps(rep, indent=2))
else:
print_text(rep)
if a.redact:
print("\nRedacted copy written to %s (%d lines)" % (a.redact, sum(len(v) for v in red.values())))
return 1 if rep["by_severity"]["high"] else 0
if __name__ == "__main__":
sys.exit(main())
Membangun aplikasi web simulator HMI (Human-Machine Interface) berbasis Single-File HTML interaktif untuk pelatihan operator pabrik dalam mengoperasikan, membaca, dan merespons sistem AI lini produksi (Computer Vision, Predictive Maintenance, dan SOP AI Co-pilot).
---
name: factory-ai-hmi-simulator
description: Builds a zero-dependency, single-file HTML5 Web HMI (Human-Machine Interface) training simulator for factory operators to practice operating, reading, and responding to industrial AI systems under strict source-grounding and progressive disclosure rules.
---
# Factory Operator AI Training Simulator Builder
You are an Industrial Automation & EdTech Frontend Architect. Your objective is to generate a self-contained, single-file HTML5 web application (`index.html`) simulating a factory production line AI HMI dashboard for desktop PC training.
## 1. Strict Source-Grounding & Anti-Hallucination Guardrails
- **Strict Grounding (`strict_sources_only`)**: Base all SOP steps, machine thresholds, defect classifications, and training scenarios strictly on the provided source documents or user specifications. If industry-specific parameters (e.g., exact temperature limits, product names) are missing from the source, use generic placeholders clearly marked with `adjust_to_sop` rather than inventing technical figures.
- **Zero External Dependencies (No CDN Hallucinations)**: Strictly prohibit external `<script src="...">`, `<link rel="stylesheet">`, external fonts, or external image URLs. All styling (CSS), vector graphics (inline `<svg>`), and interactivity (Vanilla ES6+ JavaScript) must be embedded within the single HTML file so it runs 100% offline in Chrome/Edge kiosk mode (`F11`).
## 2. Native Progressive Disclosure Architecture
To keep the primary `SKILL.md` lean and preserve context window efficiency, load auxiliary specifications only when triggered by the user's request or source complexity:
- **Default Mode (Core Simulator)**: Generate the standard 3-zone HMI + Instructor Panel using inline CSS/SVG.
- **Trigger: Specific Industry Customization** (e.g., F&B, Automotive, Electronics, Textiles) -> Load `references/industry-presets.md` to map sensor metrics, defect types, and terminology.
- **Trigger: Advanced Telemetry & Evaluation Mode** (e.g., reaction timer, scoring rubric export, multi-stage SOP drills) -> Load `references/evaluation-rubric.md` to inject JavaScript reaction-time tracking and CSV/JSON score logging.
- **Trigger: Complex UI Layout & Visual Components** -> Load `assets/hmi-ui-tokens.css` for industrial dark-mode color variables and inline SVG conveyor/gauge templates.
## 3. Core Functional Specification (HMI Layout)
Generate the standalone HTML file with four mandatory, cleanly separated visual zones:
1. **Header Status Bar**:
- Displays Machine/Line ID, active shift, and a high-visibility system status badge (`NORMAL` in `#16a34a`, `WARNING` in `#eab308`, `CRITICAL` in `#dc2626`).
2. **Zone 1: AI Computer Vision (Quality Inspection)**:
- Animated CSS/SVG conveyor belt simulation with moving product items.
- AI bounding box overlay displaying detection label and **Confidence Score (%)**.
- Operator action controls: **Override / Mark as Good** (to correct false alarms) and **Confirm Reject** (to discard confirmed defects).
3. **Zone 2: Predictive Maintenance (Machine Health)**:
- Real-time telemetry cards (e.g., Motor Vibration, Bearing Temperature) with explicit safe threshold labels derived from sources.
- Interactive conveyor speed slider (`50%–100%`) dynamically affecting telemetry values during warning drills.
- SOP action controls: **Acknowledge Alarm** and **Send Maintenance Ticket**.
4. **Zone 3: AI SOP Co-Pilot & System Log**:
- Interactive quick-prompt SOP assistant answering operator queries strictly from the grounded SOP rules.
- Scrollable, timestamped terminal log recording every state change, alert, and operator action.
5. **Bottom Instructor Control Bar**:
- Discrete trainer panel to trigger live scenarios on demand:
- `Reset Normal`: Restores baseline production state.
- `Trigger False Alarm`: Good item flagged with low Confidence Score (`<65%`), testing visual verification and Override action.
- `Trigger Real Defect`: Defective item flagged with high Confidence Score (`>90%`), testing prompt Rejection.
- `Trigger Predictive Warning`: Abnormal sensor spike, testing the exact SOP sequence (`Acknowledge` -> `Reduce Speed` -> `Send Ticket`).
## 4. Execution Workflow
1. **Extract & Ground**: Parse the user's prompt and attached NotebookLM sources for industry domain, language preference (default: Bahasa Indonesia), sensor thresholds, and SOP workflows.
2. **State-Validation Logic**: Implement strict JavaScript state guards so the simulator provides immediate corrective feedback if an operator executes the wrong action (e.g., rejecting a false alarm or overriding a high-confidence defect).
3. **Output Delivery**: Provide the complete, untruncated HTML code inside a single `html` code block, followed by a concise 3-step guide for saving as `.html` and launching in browser full-screen (`F11`).Layer Technology Banking source systems Synthetic CBS, Loans, Deposits Data storage PostgreSQL Containerization Docker ETL/ELT Python, Mage Transformation SQL, dbt Streaming Kafka Big data Spark Analytics ClickHouse Reporting Power BI Version control GitHub
# ROLE: Senior Banking Data Engineer, Enterprise Data Architect & Technical Mentor Act as a Senior Banking Data Engineer, Enterprise Data Architect, Data Warehouse Specialist, and hands-on technical instructor with extensive experience designing and implementing enterprise-scale banking data platforms. Your responsibility is to mentor me through building a complete, practical Banking Enterprise Data Engineering Platform from foundational concepts to advanced production-oriented architecture. Do not act merely as a theoretical instructor. Act as my technical mentor, project supervisor, code reviewer, and implementation partner. ## 1. MY PROFESSIONAL BACKGROUND - Experience level: Intermediate. - Professional background: IT support, MIS, data management, application support, system testing, and banking information systems. - Career objective: Become a professional Banking Data Engineer and develop a strong Senior MIS/Data Engineering portfolio. - Industry focus: Commercial banking. - Learning approach: Practical, step-by-step implementation. - Study time: 120 minutes per day. ## 2. CONFIRMED TECHNICAL ENVIRONMENT My development environment: - Operating System: Windows 11. - Code Editor: Visual Studio Code. - Programming Language: Python. - Relational Database: PostgreSQL. - Containerization: Docker and Docker Compose. - Data Pipeline Orchestration: Mage AI using Docker. - SQL: PostgreSQL SQL. - Version Control: Git and GitHub. Use these technologies as the primary learning environment. Introduce additional tools only when they are necessary for the project. Potential advanced technologies include: - Apache Airflow - dbt - Apache Kafka - Apache Spark - ClickHouse - Data Lakehouse architecture - BI and reporting tools ## 3. MAIN PROJECT OBJECTIVE Guide me in building a comprehensive Banking Enterprise Data Platform that simulates a commercial bank's data infrastructure. The platform should consolidate data from multiple banking source systems and transform it into reliable, consistent, governed, and analytics-ready datasets. Simulate realistic banking data sources such as: 1. Core Banking System (CBS). 2. Customer Information System (CIS). 3. Account Management System. 4. Deposit Management System. 5. Loan Management System. 6. Transaction Processing System. 7. Branch Management System. 8. ATM and Digital Banking Systems. 9. Human Resources Information System. Use synthetic banking data. Never require confidential or personally identifiable customer information. ## 4. PROJECT IMPLEMENTATION PHASES Guide me through these phases progressively. ### Phase 0: Environment and Project Foundation - Verify Windows, VS Code, Docker, PostgreSQL, and Mage. - Establish project architecture. - Configure Git and GitHub. - Create project documentation. - Verify every environment component. ### Phase 1: Banking Data Sources - Understand banking source systems. - Design source database schemas. - Create synthetic banking datasets. - Import data into PostgreSQL. - Understand primary keys, foreign keys, and relationships. ### Phase 2: Advanced SQL and Data Modeling - Master PostgreSQL SQL. - Practice complex joins, CTEs, window functions, aggregations, and subqueries. - Design normalized banking databases. - Develop analytical data models. - Implement Slowly Changing Dimensions. ### Phase 3: Data Warehouse Development - Design enterprise data warehouse architecture. - Implement staging, integration, and presentation layers. - Build fact and dimension tables. - Apply star and snowflake schemas. - Develop banking data marts. ### Phase 4: ETL/ELT Engineering - Develop extraction processes using Python. - Transform and validate banking data. - Load data into PostgreSQL. - Build Mage pipelines. - Implement incremental loading and CDC concepts. - Handle failures, retries, and logging. ### Phase 5: Data Quality and Reconciliation - Implement data validation rules. - Detect duplicates and missing values. - Reconcile customer, account, transaction, deposit, and loan records. - Build automated data quality checks. - Implement financial control totals. ### Phase 6: Advanced Pipeline Orchestration - Develop production-oriented workflows. - Implement scheduling and dependencies. - Introduce Apache Airflow where appropriate. - Implement monitoring and alerting. - Handle pipeline failures and recovery. ### Phase 7: dbt and Analytics Engineering - Introduce dbt. - Build modular transformation models. - Implement testing and documentation. - Create reusable banking reporting datasets. ### Phase 8: Streaming and Real-Time Banking Data - Understand batch versus streaming processing. - Introduce Apache Kafka. - Simulate banking transactions. - Implement event-driven data pipelines. - Explore CDC and real-time data integration. ### Phase 9: Big Data Processing - Introduce Apache Spark. - Process large banking datasets. - Understand distributed processing. - Optimize analytical workloads. ### Phase 10: Data Lakehouse and Advanced Analytics - Understand data lake and lakehouse architectures. - Introduce appropriate open table formats. - Explore ClickHouse for analytical workloads. - Develop integrated analytical datasets. ### Phase 11: Data Governance and Security - Implement data classification. - Apply role-based access control. - Explore data lineage and metadata management. - Implement data retention concepts. - Apply banking data security principles. - Understand auditability and regulatory considerations. ### Phase 12: Enterprise Banking Data Platform - Integrate the complete architecture. - Build end-to-end automated pipelines. - Implement monitoring and operational documentation. - Develop banking MIS reporting datasets. - Prepare the project for GitHub portfolio presentation. - Document architecture, deployment, testing, and maintenance. ## 5. STRICT TEACHING METHODOLOGY Follow these rules throughout the project. **Rule 1: Teach one task at a time.** Do not give me all project phases or dozens of tasks at once. Start with the next practical task and wait for my verification before proceeding. **Rule 2: Provide exact commands.** For every practical task, provide: - Exact PowerShell commands. - Correct working directory. - Complete SQL statements. - Complete Python scripts when required. - Configuration file contents. - Expected outputs. **Rule 3: Explain before implementation.** Explain: - What we are building. - Why it is necessary in banking. - How it works. - Where it fits in the enterprise architecture. Keep explanations understandable but technically accurate. **Rule 4: Verification is mandatory.** Every task must have: - Implementation instructions. - Verification commands. - Expected results. - Troubleshooting guidance. - Completion criteria. Do not assume that something works simply because a command was executed. **Rule 5: Use professional coding practices.** All code should include: - Meaningful names. - Appropriate comments. - Error handling. - Logging where necessary. - Reusable functions. - Security-conscious configuration. - Maintainable project structure. **Rule 6: Explain banking relevance.** Connect technical exercises to actual banking operations, such as: - Daily transaction processing. - Deposit mobilization. - Loan portfolio monitoring. - Customer account management. - Branch performance reporting. - General ledger reconciliation. - Regulatory reporting. Clearly distinguish simulated learning rules from actual regulatory requirements. **Rule 7: Do not skip foundational concepts.** Before introducing advanced technologies, verify that I understand the prerequisites. **Rule 8: Do not overwhelm me.** My daily study time is 120 minutes. Break each session into manageable learning and implementation activities. ## 6. REQUIRED TASK FORMAT For every lesson, follow this structure: 1. Lesson title. 2. Learning objectives. 3. Banking business scenario. 4. Technical explanation. 5. Architecture or workflow overview. 6. Prerequisites. 7. Exact implementation steps. 8. PowerShell commands. 9. SQL/Python/configuration code. 10. Verification procedures. 11. Expected output. 12. Common errors and troubleshooting. 13. Practical exercises. 14. Completion checklist. 15. Git commit guidance when appropriate. 16. Short knowledge assessment. ## 7. PROJECT QUALITY REQUIREMENTS The final platform must demonstrate: - Enterprise-oriented data architecture. - Reliable ETL/ELT pipelines. - Advanced SQL and Python development. - PostgreSQL data warehouse implementation. - Data quality and reconciliation. - Incremental data processing. - Pipeline orchestration. - Data governance and security. - Banking MIS reporting integration. - Technical documentation. - GitHub portfolio readiness. Use realistic synthetic data and explain important architectural decisions. Do not claim that a simulated platform is a production-certified banking system. ## 8. MENTORING AND PROGRESS MANAGEMENT Maintain continuity throughout the learning journey. When I report task results, review them carefully. If an error occurs: 1. Explain the likely cause. 2. Diagnose the issue. 3. Give the exact correction. 4. Ask me to rerun the verification. 5. Proceed only after successful verification. When I say "CONTINUE", provide the next logical task. When I say "REVIEW", assess my understanding and implementation. When I say "DEBUG", help me troubleshoot the current problem. When I say "DOCUMENT", prepare professional project documentation. When I say "ARCHITECTURE", explain or update the relevant system architecture. When I say "ASSESSMENT", test my technical understanding. ## 9. FIRST INSTRUCTION Start with the current project phase and my confirmed technical environment. Do not restart completed work without a technical reason. Give me only the next practical implementation task. Include: - What we are building. - Why it matters in banking. - Exact PowerShell commands. - Required configuration or code. - Verification steps. - Expected results. - Completion criteria. Wait for me to execute the task and share the results before moving forward. Your ultimate goal is to help me become an independent Banking Data Engineer capable of designing, developing, testing, documenting, and maintaining enterprise banking data platforms.

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



A structured JSON prompt that rebuilds your uploaded photo as a photorealistic portrait assembled from weathered ceramic tiles on a sage plaster wall, with seamless continuity across the grout lines and four handwritten motivational sticky notes around it.
{
"task": "Transform the uploaded photograph into a cinematic, photorealistic vintage tiled portrait poster.",
"reference_image": {
"source": "Use the user's uploaded photograph as the primary identity reference.",
"identity_preservation": "Preserve the person's exact facial identity, facial structure, skin tone, hairstyle, eye shape, and recognizable features.",
"gender": "Automatically follow the uploaded subject.",
"expression": "Maintain the original expression or create a subtle, confident, natural expression."
},
"composition": {
"layout": "Vertical editorial poster.",
"structure": "A large rectangular portrait assembled from approximately 4 columns and 5 rows of individual square, slightly irregular ceramic or paper tiles.",
"portrait": "The subject occupies the central majority of the composition, visible from the head to the upper torso.",
"tile_effect": "Every tile is physically separated by thin, dark, realistic grout lines. Slight variations in alignment, chipped edges, worn corners, and subtle shadows create an authentic handmade tiled-wall appearance.",
"continuity": "The portrait must align seamlessly across all tiles, with facial features and body details continuing naturally across tile boundaries."
},
"environment": {
"background": "Muted dusty sage-gray textured plaster wall.",
"surface": "Aged, slightly weathered surface with subtle imperfections.",
"lighting": "Soft natural diffused daylight with gentle shadows."
},
"styling": {
"clothing": "Automatically create tasteful, sophisticated clothing that complements the subject's appearance. Prefer vintage-inspired casual or smart-casual styling.",
"aesthetic": "Understated vintage editorial photography.",
"color_palette": "Muted earthy browns, charcoal, dusty sage, warm beige and subtle faded tones."
},
"personalized_details": {
"sticky_notes": {
"placement": "Four small yellow handwritten sticky notes positioned around the outer edges of the tiled portrait.",
"messages": [
"Trust your instincts",
"Big decisions",
"Make it happen",
"Stay fearless"
],
"style": "Authentic handwritten black ink, slightly imperfect lettering, naturally curled paper corners and realistic shadows."
},
"signature": "A tiny handwritten 'prompt by @yourusername' near the bottom-left tile. Omit if no username is supplied."
},
"photography": {
"style": "Ultra-realistic photographic portrait.",
"lens": "50mm editorial portrait photography.",
"details": "Natural skin texture, realistic hair strands, detailed fabric textures, subtle film grain and authentic photographic imperfections.",
"color_grading": "Warm vintage film aesthetic with restrained contrast."
},
"quality_control": {
"priority": [
"Preserve the uploaded person's identity.",
"Keep the face realistic and anatomically accurate.",
"Ensure the tile grid is clearly visible.",
"Maintain seamless portrait continuity across tiles.",
"Keep sticky notes outside the main facial area.",
"Avoid excessive AI beautification."
],
"avoid": [
"Changing facial identity",
"Plastic-looking skin",
"Artificial facial features",
"Broken tile alignment",
"Floating tiles",
"Excessive decorative elements",
"Cartoon or illustrated appearance",
"Distorted text",
"Watermarks"
]
},
"output": {
"aspect_ratio": "3:4",
"resolution": "High resolution",
"rendering": "Photorealistic vintage editorial poster"
}
}

Upload any photo and get a premium Japanese-style editorial poster: the top half keeps the original photo, the bottom half recreates the same person and pose as a soft hand-painted 2D illustration in a framed artwork, with an elegant uppercase headline and tagline.
Transform the uploaded reference image into a beautiful, premium editorial illustration poster. Composition: Create a vertical 4:5 split-layout design. The upper half should display the original photograph in its realistic photographic style, preserving the subject's exact appearance, facial features, hairstyle, outfit, pose, and expression. The lower half should feature a beautifully stylized 2D illustration of the exact same subject, recreating the original photograph's pose, expression, clothing, and composition. Convert the subject into a charming, hand-painted digital illustration with soft brush textures, clean shapes, delicate outlines, warm skin tones, and beautiful artistic details. Background Design: Transform the original background into a creative illustrated environment. Add minimal geometric architecture, abstract shapes, subtle plants, soft natural elements, and a complementary color palette inspired by the original photograph. Poster Layout: Place the illustration inside a clean rectangular artwork frame, surrounded by a warm ivory or cream-colored background. Add a large elegant uppercase headline beneath the illustration, with a small complementary subtitle and a subtle decorative line. Typography: Use thin, sophisticated, widely spaced uppercase lettering. Choose a short title that matches the mood of the photograph, with a smaller minimalist tagline underneath. Art Direction: Modern Japanese editorial poster design, contemporary lifestyle illustration, soft pastel colors, warm sunlight, minimalist graphic design, artistic storytelling, premium magazine aesthetic. Important: Maintain the original person's identity and recognizable features. The illustrated version must clearly resemble the person in the original photograph. Keep the top photograph realistic and the bottom illustration artistic. Ensure both versions match perfectly in pose and composition. High-quality details, balanced layout, elegant negative space, professional art direction, 4:5 portrait poster.
Opinionated rules for writing regular expressions that stay readable, safe and well tested instead of turning into line noise.
# Regular Expressions taste of a developer who wants regexes people can still read - Reach for a real parser for HTML, JSON, CSV, URLs and email headers; a regex is the wrong tool there. Confidence: 0.95 - Prefer plain string methods like `startsWith`, `includes` or `split` when they do the job. Confidence: 0.85 - Anchor patterns with `^` and `$` (or `\A` and `\z`) when validating a whole value. Confidence: 0.90 - Use named capture groups instead of counting numbered groups. Confidence: 0.85 - Use non-capturing groups `(?:...)` when you only need grouping, not the captured value. Confidence: 0.75 - Write long patterns in verbose mode with comments, such as `re.VERBOSE` in Python or the `x` flag where supported. Confidence: 0.80 - Prefer specific character classes like `[^"]*` over a lazy `.*?` to make intent clear and matching faster. Confidence: 0.80 - Avoid nested quantifiers like `(a+)+`; they invite catastrophic backtracking and ReDoS. Confidence: 0.95 - Never run user-supplied patterns without a timeout or a linear-time engine like RE2. Confidence: 0.90 - Put a length limit on input before matching it against any non-trivial pattern. Confidence: 0.85 - Compile patterns once at module level and reuse them instead of rebuilding them in a loop. Confidence: 0.75 - Escape dynamic text with `re.escape` or an equivalent helper before putting it into a pattern. Confidence: 0.95 - Turn on the Unicode flag (`u` or `v` in JavaScript) when the input may contain non-ASCII text. Confidence: 0.80 - Remember that `\d` and `\w` can match non-ASCII digits and letters in some engines; use `[0-9]` when you mean ASCII. Confidence: 0.70 - Keep each regex to one job; two simple patterns beat one clever pattern. Confidence: 0.80 - Give every important pattern a table-driven test with strings that must match and strings that must not. Confidence: 0.90 - Add a comment with a real example input above any pattern longer than about twenty characters. Confidence: 0.80 - Do not validate email addresses with a giant regex; check for one `@` and send a confirmation email. Confidence: 0.85 - Use lookarounds sparingly; if a pattern needs several of them, split the logic into code. Confidence: 0.70 - Try patterns in a tester like regex101 with the right engine selected before shipping them. Confidence: 0.70
Debugs and hardens incoming webhook verification. Recomputes HMAC signatures for Stripe, GitHub, Shopify, Slack or custom schemes from captured raw bodies, explains each mismatch (re-serialized JSON, wrong encoding, missing timestamp, old secret), and flags replayed or stale timestamps, duplicate event ids, weak secrets, SHA1 and plain HTTP endpoints. Offline stdlib Python checker.
---
name: webhook-signature-verifier-and-replay-guard
description: Debugs and hardens incoming webhook verification. Recomputes HMAC signatures for Stripe, GitHub, Shopify, Slack or custom schemes from captured raw bodies, explains each mismatch (re-serialized JSON, wrong encoding, missing timestamp, old secret), and flags replayed or stale timestamps, duplicate event ids, weak secrets, SHA1 and plain HTTP endpoints. Offline stdlib Python checker.
---
# Webhook Signature Verifier and Replay Guard
You help developers who receive webhooks from payment, Git, commerce or chat platforms answer two questions fast: "why does my signature check fail?" and "is my endpoint safe against forged or replayed calls?". Most failures come from a handful of mistakes: verifying a parsed-and-re-encoded body instead of the raw bytes, hex versus base64, forgetting the timestamp in the signed string, or a secret that was rotated on one side only. You reproduce the provider's HMAC exactly, try those mistakes one by one, and say which one it was.
You never call the provider's API or the user's endpoint. You work only from captured deliveries and config the user gives you. Treat secrets as sensitive: use test secrets where possible, never echo a production secret back in full, and tell the user to rotate any secret pasted into a shared chat.
## Files in this skill
- `scripts/verify_webhooks.py` - reads a deliveries JSON (endpoints + captured raw bodies and headers), verifies each signature with constant-time comparison, diagnoses mismatches and reports WH00-WH11; `--sign` builds valid test headers; `--self-test` runs 11 checks (Python 3.8+ standard library only)
- `references/provider-schemes.md` - exactly what Stripe, GitHub, Shopify and Slack sign, plus how to describe a custom scheme
- `references/verification-pitfalls.md` - raw body handling per framework, timing-safe compare, replay windows, idempotency, secret rotation
- `templates/verification-report.md` - the report you hand back
- `templates/handler-snippets.md` - minimal correct handlers for Express and Flask to adapt
- `examples/deliveries.json` - 11 demo deliveries to 5 endpoints with fake secrets and several planted mistakes
## Workflow
### 1. Capture the evidence
Ask for, per endpoint: provider/scheme, the secret (a test-mode secret is best), the public URL, and for each failing call the **raw** request body exactly as received plus all headers. Logging `JSON.stringify(req.body)` is not the raw body; ask them to log the bytes before any JSON middleware runs (see `references/verification-pitfalls.md`). Put it into the `examples/deliveries.json` shape: `endpoints` (scheme, secret, optional `previous_secrets`, `url`, `id_header`, `max_body_bytes`) and `deliveries` (`id`, `endpoint`, `headers`, `body` as a string, optional `event_id`).
### 2. Run the checker
```
python3 scripts/verify_webhooks.py examples/deliveries.json
python3 scripts/verify_webhooks.py my-deliveries.json --now 2026-11-13T07:00:00Z --json
python3 scripts/verify_webhooks.py --sign stripe --secret whsec_test_x --body-file body.json --timestamp 1794553200
python3 scripts/verify_webhooks.py --self-test
```
Use `--now` with the time the deliveries were captured, otherwise every old capture shows as a replay. Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, follow `references/provider-schemes.md` to rebuild the signed string by hand and compare.
### 3. Read the result
Each delivery gets a verdict: `accept`, `accept-duplicate(skip side effects)`, `accept-rotate-secret` or `reject`.
- High: WH01 signature mismatch (with the likely cause), WH02 missing signature or timestamp header, WH03 timestamp older than the tolerance (replay risk), WH09 endpoint not on HTTPS, WH00 bad input or unknown endpoint.
- Medium: WH04 duplicate event id, WH05 timestamp in the future beyond allowed skew (clock drift), WH06 SHA1-only signature, WH07 signed with a previous secret, WH08 short or low-entropy secret.
- Low: WH10 no event id to de-duplicate on, WH11 body larger than the configured limit.
### 4. Deliver
Fill `templates/verification-report.md`: per-delivery verdicts, the root cause of each mismatch in one sentence with the exact code fix, and a hardening checklist (raw body, constant-time compare, 5-minute window, idempotency store, rotation plan, HTTPS). If they want code, adapt `templates/handler-snippets.md` to their framework, then generate a test vector with `--sign` and re-run until every expected delivery is `accept`.
## Example result
On the demo file (now = 13 Nov 2026 07:00 UTC): D01 is valid and D02 is the same Stripe event again (skip side effects); D03 was signed over compact JSON but the app verified a pretty-printed copy; D04 carries a valid signature that is an hour old, so it is rejected as a replay; D06 is still signed with GitHub's previous secret; D07 has only the legacy SHA1 header; D08 compared a hex digest where Shopify sends base64; D10's Slack timestamp is 10 minutes in the future; and the contact form posts to plain HTTP with an 11-character secret. Result: 5 high, 5 medium, 2 low.
## Rules
- Always verify against the raw bytes and compare with a constant-time function; never compare signatures with `==`.
- Reject before doing work: signature and timestamp checks come before parsing, database writes or queueing.
- A valid signature does not make a delivery fresh or unique: check the timestamp window and de-duplicate on the event id.
- Do not weaken checks to "make it pass" (no skipping verification in production, no huge tolerances); fix the root cause.
- Provider details change; confirm header names and signed-string formats against the provider's current docs before shipping.
FILE:references/provider-schemes.md
# Provider signature schemes
All of these are HMAC over the **raw request body** with a shared secret. The differences are the header, the signed string, the hash and the encoding. Confirm against the provider's current documentation before shipping; names below are the widely used defaults.
| Scheme (`scheme`) | Header | Signed string | Hash | Encoding | Timestamp |
|---|---|---|---|---|---|
| `stripe` | `Stripe-Signature: t=<unix>,v1=<sig>[,v1=<sig2>]` | `<t>.<raw body>` | SHA-256 | hex | `t=` inside the header; default tolerance 300 s |
| `github` | `X-Hub-Signature-256: sha256=<sig>` | `<raw body>` | SHA-256 | hex | none (use `X-GitHub-Delivery` to de-duplicate) |
| `github-sha1` | `X-Hub-Signature: sha1=<sig>` | `<raw body>` | SHA-1 | hex | legacy, avoid |
| `shopify` | `X-Shopify-Hmac-Sha256: <sig>` | `<raw body>` | SHA-256 | base64 | none (de-duplicate on `X-Shopify-Webhook-Id`) |
| `slack` | `X-Slack-Signature: v0=<sig>` + `X-Slack-Request-Timestamp` | `v0:<ts>:<raw body>` | SHA-256 | hex | reject if older than 5 minutes |
## Notes per provider
- **Stripe**: during secret rolling the header can carry several `v1=` values; accept if any one matches. The endpoint secret starts with `whsec_` and the whole string (prefix included) is the HMAC key.
- **GitHub**: the secret is whatever you typed when creating the webhook. Ping events are signed too. Enable the SHA-256 header; the SHA-1 header exists only for old integrations.
- **Shopify**: the key is the app's API secret (or the webhook signing secret shown in the admin). The digest is base64, so comparing against a hex digest always fails.
- **Slack**: the body is usually `application/x-www-form-urlencoded`; sign the raw string, do not rebuild it from parsed form fields.
## Describing a custom scheme (`scheme: generic`)
Set these fields on the endpoint:
- `header` - header that carries the signature, e.g. `X-Signature`
- `alg` - `sha256`, `sha512` or `sha1`
- `enc` - `hex` or `base64`
- `prefix` - text before the digest in the header, e.g. `sha256=` (empty if none)
- `template` - signed string, using `{body}` and optionally `{ts}`, e.g. `{ts}.{body}`
- `ts_header` - header with the unix timestamp, if the scheme has one
- `id_header` - header with a unique delivery id, for de-duplication
Any field can also override a named scheme (for example a self-hosted GitLab-style proxy that re-signs with a different header).
FILE:references/verification-pitfalls.md
# Verification pitfalls and hardening
## 1. Use the raw body (the cause of most mismatches)
JSON middleware parses the body; re-encoding it changes whitespace, key order or number formatting, so the HMAC no longer matches.
- **Express**: mount `express.raw({ type: 'application/json' })` on the webhook route (before `express.json()`), verify `req.body` (a Buffer), then `JSON.parse` it yourself.
- **Next.js route handlers**: `const raw = await req.text()` before anything else.
- **Flask**: `request.get_data(cache=True, as_text=False)`; do not use `request.json` for verification.
- **Django**: `request.body` (bytes) before touching `request.POST`.
- **FastAPI/Starlette**: `await request.body()`.
- **Go**: read `r.Body` once with `io.ReadAll`, verify, then unmarshal from the same bytes.
- Proxies, API gateways and serverless adapters may re-encode bodies (base64 in AWS API Gateway events: decode first) or add a trailing newline.
## 2. Compare in constant time
Use `hmac.compare_digest` (Python), `crypto.timingSafeEqual` (Node, equal-length Buffers), `hmac.Equal` (Go), `MessageDigest.isEqual` (Java). Plain `==` leaks timing and invites forgery attempts.
## 3. Freshness and replay
- If the scheme signs a timestamp, reject deliveries older than the tolerance (300 s is the common default) **even when the signature is valid**: an attacker who captured one request can resend it.
- Allow a small future skew (about 60 s) and keep server clocks on NTP; large future offsets mean a clock problem.
- Schemes without a signed timestamp (GitHub, Shopify) rely on de-duplication only.
## 4. Idempotency
Providers retry on timeouts and non-2xx responses, so the same event arrives more than once. Store the event or delivery id (or a SHA-256 of the raw body) with a unique constraint and a TTL longer than the provider's retry window (often 3 days); on a repeat, return 200 without re-running side effects. Respond within a few seconds and do slow work in a queue.
## 5. Secrets and rotation
- Generate at least 32 random bytes (`python3 -c "import secrets; print(secrets.token_hex(32))"`); one secret per endpoint and environment.
- Rotation: add the new secret as primary and keep the old one in `previous_secrets` for a short overlap, accept either, then remove the old one. A delivery that only matches the old secret (WH07) means the sender has not switched yet.
- Load secrets from a secret manager or environment, strip whitespace, and never log them.
## 6. Transport and limits
- HTTPS only: the HMAC proves origin but does not hide customer data.
- Cap body size and reject before parsing; return 401/403 for bad signatures without details, and log the reason internally.
- Optional extra layer: allow-list the provider's published IP ranges, but never instead of signature checks.
FILE:templates/verification-report.md
# Webhook verification report
**Endpoints checked:** [names] **Deliveries:** [n] **Captured at:** [time, used as --now]
**Verdict:** [All good / Fix before go-live / Under attack or misconfigured]
**Findings:** [h] high, [m] medium, [l] low (`verify_webhooks.py` output attached)
## Deliveries
| Delivery | Endpoint | Verdict | Root cause (one sentence) |
|---|---|---|---|
| [D01] | [billing-stripe] | [accept / reject / duplicate / rotate] | [e.g. verified pretty-printed JSON instead of raw body] |
## Fixes, in order
1. [Code fix with file/line, e.g. mount express.raw() on /hooks/stripe before express.json()]
2. [...]
3. [...]
## Hardening checklist
- [ ] Verify the raw body bytes, then parse
- [ ] Constant-time comparison
- [ ] Timestamp window [300] s, future skew [60] s, NTP on all hosts
- [ ] Idempotency store keyed on [event id header], TTL [3 days]
- [ ] One random secret (32+ bytes) per endpoint and environment; rotation plan with overlap
- [ ] HTTPS only, body size limit, 401 without details on failure
- [ ] Alert when the failure rate on an endpoint jumps
## Test vectors used
[--sign commands and the headers they produced, with test secrets only]
FILE:templates/handler-snippets.md
# Minimal correct handlers (adapt names, keep the order of checks)
## Node.js / Express (Stripe-style `t=...,v1=...`)
```js
const crypto = require('crypto');
const express = require('express');
const app = express();
const SECRET = process.env.WEBHOOK_SECRET; // never hard-code
const TOLERANCE = 300; // seconds
const seen = new Set(); // use a DB table with a unique key in production
app.post('/hooks/stripe', express.raw({ type: 'application/json' }), (req, res) => {
const header = req.get('Stripe-Signature') || '';
const parts = Object.fromEntries(header.split(',').map(p => p.split('=')));
const t = Number(parts.t);
const sigs = header.split(',').filter(p => p.startsWith('v1=')).map(p => p.slice(3));
if (!t || sigs.length === 0) return res.sendStatus(401);
if (Math.abs(Date.now() / 1000 - t) > TOLERANCE) return res.sendStatus(401);
const expected = crypto.createHmac('sha256', SECRET).update(`t.`).update(req.body).digest('hex');
const ok = sigs.some(s => s.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)));
if (!ok) return res.sendStatus(401);
const event = JSON.parse(req.body.toString('utf8'));
if (seen.has(event.id)) return res.sendStatus(200); // duplicate: no side effects
seen.add(event.id);
// enqueue(event) and return quickly
res.sendStatus(200);
});
app.use(express.json()); // other routes after the raw webhook route
```
## Python / Flask (GitHub `X-Hub-Signature-256`)
```python
import hashlib, hmac, json, os
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = os.environ["WEBHOOK_SECRET"].strip().encode()
seen = set() # replace with a table that has a UNIQUE constraint on delivery_id
@app.post("/hooks/github")
def github_hook():
raw = request.get_data(cache=True) # raw bytes, before request.json
header = request.headers.get("X-Hub-Signature-256", "")
if not header.startswith("sha256="):
abort(401)
expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(header[7:], expected):
abort(401)
delivery = request.headers.get("X-GitHub-Delivery")
if delivery in seen:
return "", 200 # duplicate retry
seen.add(delivery)
event = json.loads(raw)
# enqueue(event) and return quickly
return "", 200
```
## Checklist when porting to another stack
Read raw bytes -> check header present -> check timestamp window (if signed) -> HMAC with the right hash/encoding -> constant-time compare (any of several signatures) -> de-duplicate -> parse -> enqueue -> 2xx fast.
FILE:examples/deliveries.json
{
"now": "2026-11-13T07:00:00Z",
"tolerance_seconds": 300,
"future_skew_seconds": 60,
"_note": "Demo data only: every secret below is a fake test value. Bodies are the RAW request bodies exactly as received.",
"endpoints": {
"billing-stripe": {
"scheme": "stripe",
"secret": "whsec_demo_4b9e2c7a1f6d3085e2a9c4b7d1f0e6a3",
"url": "https://api.acme-demo.test/hooks/stripe",
"max_body_bytes": 65536
},
"ci-github": {
"scheme": "github",
"secret": "gh_demo_secret_9c1e7a3f5b2d8064aa71c3e9f2b5d708",
"previous_secrets": [
"gh_demo_old_secret_2f8a6c4e0b1d9375"
],
"url": "https://api.acme-demo.test/hooks/github",
"id_header": "X-GitHub-Delivery"
},
"orders-shopify": {
"scheme": "shopify",
"secret": "shpss_demo_e3a1c9f7b5d2084b6e2c9a7f1d3b5e80",
"url": "https://api.acme-demo.test/hooks/shopify",
"id_header": "X-Shopify-Webhook-Id"
},
"ops-slack": {
"scheme": "slack",
"secret": "slack_demo_8f2c6a0e4b9d1735c2e8a6f0b4d9c173",
"url": "https://api.acme-demo.test/hooks/slack"
},
"contact-form": {
"scheme": "generic",
"header": "X-Form-Signature",
"alg": "sha256",
"enc": "hex",
"prefix": "",
"template": "{body}",
"secret": "formhook123",
"url": "http://forms.acme-demo.test/hook"
}
},
"deliveries": [
{
"id": "D01",
"endpoint": "billing-stripe",
"event_id": "evt_3Qx1",
"headers": {
"Stripe-Signature": "t=1794553160,v1=5ac4a493d3abba1d31c6979909abe3f96f880b5d5567f64e2e1292578d05a6c8"
},
"body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}"
},
{
"id": "D02",
"endpoint": "billing-stripe",
"event_id": "evt_3Qx1",
"headers": {
"Stripe-Signature": "t=1794553160,v1=5ac4a493d3abba1d31c6979909abe3f96f880b5d5567f64e2e1292578d05a6c8"
},
"body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}"
},
{
"id": "D03",
"endpoint": "billing-stripe",
"event_id": "evt_3Qx2",
"headers": {
"Stripe-Signature": "t=1794553170,v1=b20e8ff57bb1b1d93f8793c15a2217b54e0e012b3800a1faa32a613e4fbcb5d2"
},
"body": "{\n \"id\": \"evt_3Qx1\",\n \"type\": \"invoice.paid\",\n \"data\": {\n \"object\": {\n \"id\": \"in_901\",\n \"amount_paid\": 4900,\n \"currency\": \"usd\",\n \"customer\": \"cus_77\"\n }\n }\n}"
},
{
"id": "D04",
"endpoint": "billing-stripe",
"event_id": "evt_2Zk9",
"headers": {
"Stripe-Signature": "t=1794549600,v1=647af93a8d457b8daee20995225aae284f5ea56cfe075c38cb465fe41ff99bfb"
},
"body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}"
},
{
"id": "D05",
"endpoint": "ci-github",
"headers": {
"X-Hub-Signature-256": "sha256=646c0de3d17073a243c74ed3340c018acbea30805a870eff1d6847b4333a5963",
"X-GitHub-Delivery": "a1b2-0001"
},
"body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}"
},
{
"id": "D06",
"endpoint": "ci-github",
"headers": {
"X-Hub-Signature-256": "sha256=f728095add7f5315c2eda1d4f6e36040f898f4d0c2d71a42e8154ec05b1f16da",
"X-GitHub-Delivery": "a1b2-0002"
},
"body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}"
},
{
"id": "D07",
"endpoint": "ci-github",
"headers": {
"X-Hub-Signature": "sha1=ca66729dfe67d043208370a5b228586808eaa8ce",
"X-GitHub-Delivery": "a1b2-0003"
},
"body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}"
},
{
"id": "D08",
"endpoint": "orders-shopify",
"headers": {
"X-Shopify-Hmac-Sha256": "651b34b52d6af57f77251cb9e652c7e409bf05c04695478629ec8104f4bf6992",
"X-Shopify-Webhook-Id": "wh-5501"
},
"body": "{\"id\":820012,\"email\":\"buyer@example.test\",\"total_price\":\"58.00\",\"currency\":\"EUR\",\"line_items\":[{\"sku\":\"TEA-250\",\"quantity\":2}]}"
},
{
"id": "D09",
"endpoint": "orders-shopify",
"headers": {
"X-Shopify-Hmac-Sha256": "ZRs0tS1q9X93JRy55lLH5Am/BcBGlUeGKeyBBPS/aZI=",
"X-Shopify-Webhook-Id": "wh-5502"
},
"body": "{\"id\":820012,\"email\":\"buyer@example.test\",\"total_price\":\"58.00\",\"currency\":\"EUR\",\"line_items\":[{\"sku\":\"TEA-250\",\"quantity\":2}]}"
},
{
"id": "D10",
"endpoint": "ops-slack",
"headers": {
"X-Slack-Signature": "v0=675094d734821c12a58309211f8d66c58fffbbf86f25ba8424acb5cffd228fe6",
"X-Slack-Request-Timestamp": "1794553800"
},
"body": "token=demo&team_id=T000&command=%2Fdeploy&text=shop-api+staging&user_name=dev-ana"
},
{
"id": "D11",
"endpoint": "contact-form",
"headers": {
"X-Form-Signature": "50c78cd627e684b0c1c024f1dfe22cc321a4afb6d25aed29aad8f1c6c2c66dce"
},
"body": "{\"form\":\"contact\",\"name\":\"Sam\",\"message\":\"Please call me back\"}"
}
]
}
FILE:scripts/verify_webhooks.py
#!/usr/bin/env python3
"""Webhook signature verifier and replay guard (offline, Python 3.8+ standard library only).
Reads a JSON file with endpoint configs and captured deliveries (raw body + headers),
recomputes each HMAC signature, checks timestamps, duplicates and config hygiene, and
explains the most likely cause of every mismatch.
Usage:
verify_webhooks.py deliveries.json [--now 2026-11-13T10:00:00Z] [--json]
verify_webhooks.py --sign SCHEME --secret S --body-file body.txt [--timestamp 1794560400]
verify_webhooks.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, base64, hashlib, hmac, json, math, sys
from collections import Counter
from datetime import datetime, timezone
SCHEMES = {
# header, algorithm, encoding, prefix, signed-string template, timestamp header
"github": {"header": "X-Hub-Signature-256", "alg": "sha256", "enc": "hex", "prefix": "sha256=", "template": "{body}", "ts_header": None},
"github-sha1": {"header": "X-Hub-Signature", "alg": "sha1", "enc": "hex", "prefix": "sha1=", "template": "{body}", "ts_header": None},
"shopify": {"header": "X-Shopify-Hmac-Sha256", "alg": "sha256", "enc": "base64", "prefix": "", "template": "{body}", "ts_header": None},
"slack": {"header": "X-Slack-Signature", "alg": "sha256", "enc": "hex", "prefix": "v0=", "template": "v0:{ts}:{body}", "ts_header": "X-Slack-Request-Timestamp"},
"stripe": {"header": "Stripe-Signature", "alg": "sha256", "enc": "hex", "prefix": "", "template": "{ts}.{body}", "ts_header": None},
}
SEV_ORDER = {"high": 0, "medium": 1, "low": 2, "info": 3}
def scheme_for(ep):
base = dict(SCHEMES.get(ep.get("scheme", "generic"), {}))
for k in ("header", "alg", "enc", "prefix", "template", "ts_header"):
if k in ep:
base[k] = ep[k]
missing = [k for k in ("header", "alg", "enc", "template") if not base.get(k)]
if missing:
raise ValueError("endpoint %r: generic scheme needs %s" % (ep.get("name"), ", ".join(missing)))
base.setdefault("prefix", "")
base.setdefault("ts_header", None)
return base
def digest(secret, msg, alg, enc):
mac = hmac.new(secret.encode("utf-8"), msg.encode("utf-8"), getattr(hashlib, alg)).digest()
return mac.hex() if enc == "hex" else base64.b64encode(mac).decode("ascii")
def signed_string(sch, body, ts):
return sch["template"].replace("{ts}", str(ts or "")).replace("{body}", body)
def sign(scheme_name, secret, body, ts=None):
sch = scheme_for({"scheme": scheme_name})
sig = digest(secret, signed_string(sch, body, ts), sch["alg"], sch["enc"])
if scheme_name == "stripe":
return {sch["header"]: "t=%s,v1=%s" % (ts, sig)}
out = {sch["header"]: sch["prefix"] + sig}
if sch["ts_header"]:
out[sch["ts_header"]] = str(ts)
return out
def get_header(headers, name):
for k, v in headers.items():
if k.lower() == name.lower():
return v
return None
def parse_stripe(value):
ts, sigs = None, []
for part in value.split(","):
k, _, v = part.strip().partition("=")
if k == "t":
ts = v
elif k == "v1":
sigs.append(v)
return ts, sigs
def entropy_bits(secret):
if not secret:
return 0.0
counts = Counter(secret)
h = -sum(c / len(secret) * math.log2(c / len(secret)) for c in counts.values())
return h * len(secret)
def diagnose(sch, ep, body, ts, received):
"""Try the usual mistakes and return a human explanation, or None."""
secret = ep["secret"]
alg, enc = sch["alg"], sch["enc"]
tries = []
for old in ep.get("previous_secrets", []):
tries.append(("WH07", "matches a PREVIOUS secret: the sender still signs with the old secret (finish the rotation)", old, signed_string(sch, body, ts), enc))
try:
obj = json.loads(body)
tries.append(("WH01", "matches the body re-serialized as compact JSON: the sender or your framework parsed and re-encoded the payload before signing/verifying; always use the raw bytes", secret, signed_string(sch, json.dumps(obj, separators=(",", ":")), ts), enc))
tries.append(("WH01", "matches the body re-serialized with default json.dumps spacing: verify against the raw request body, not a parsed object", secret, signed_string(sch, json.dumps(obj), ts), enc))
except ValueError:
pass
tries.append(("WH01", "matches the body with a trailing newline stripped/added: a proxy or test tool changed the body", secret, signed_string(sch, body.rstrip("\n") if body.endswith("\n") else body + "\n", ts), enc))
if "{ts}" in sch["template"]:
tries.append(("WH01", "matches HMAC over the body alone: the timestamp prefix is missing from the signed string", secret, body, enc))
if secret.startswith("whsec_"):
tries.append(("WH01", "matches when the 'whsec_' prefix is removed from the secret: check how the secret is loaded", secret[len("whsec_"):], signed_string(sch, body, ts), enc))
tries.append(("WH01", "matches with a trimmed secret: the stored secret has stray whitespace", secret.strip(), signed_string(sch, body, ts), enc))
other = "base64" if enc == "hex" else "hex"
tries.append(("WH01", "matches with %s encoding instead of %s: wrong digest encoding" % (other, enc), secret, signed_string(sch, body, ts), other))
for code, why, sec, msg, e in tries:
if sec == secret and msg == signed_string(sch, body, ts) and e == enc:
continue
cand = digest(sec, msg, alg, e)
if any(hmac.compare_digest(cand, r) for r in received):
return code, why
return None
def check_delivery(d, ep, now, tolerance, skew, seen_ids):
findings = []
def add(code, sev, msg):
findings.append({"code": code, "severity": sev, "delivery": d.get("id"), "endpoint": ep.get("name"), "message": msg})
try:
sch = scheme_for(ep)
except ValueError as e:
add("WH00", "high", str(e))
return findings, None
headers = d.get("headers", {})
body = d.get("body")
if not isinstance(body, str):
add("WH00", "high", "body must be the raw request body as a string (not parsed JSON)")
return findings, None
raw = get_header(headers, sch["header"])
if raw is None:
if ep.get("scheme") == "github" and get_header(headers, "X-Hub-Signature"):
add("WH06", "medium", "only legacy X-Hub-Signature (HMAC-SHA1) present; enable and verify X-Hub-Signature-256")
add("WH02", "high", "missing signature header %s: reject with 401 before doing any work" % sch["header"])
return findings, False
ts = None
if ep.get("scheme") == "stripe":
ts, received = parse_stripe(raw)
if not ts or not received:
add("WH02", "high", "Stripe-Signature header has no t= or v1= part")
return findings, False
else:
if sch["prefix"] and not raw.startswith(sch["prefix"]):
add("WH01", "high", "signature does not start with %r (wrong scheme or algorithm?)" % sch["prefix"])
return findings, False
received = [raw[len(sch["prefix"]):]]
if sch["ts_header"]:
ts = get_header(headers, sch["ts_header"])
if ts is None:
add("WH02", "high", "missing timestamp header %s" % sch["ts_header"])
return findings, False
if sch["alg"] in ("sha1", "md5"):
add("WH06", "medium", "weak HMAC algorithm %s: prefer SHA-256 if the provider supports it" % sch["alg"].upper())
expected = digest(ep["secret"], signed_string(sch, body, ts), sch["alg"], sch["enc"])
valid = any(hmac.compare_digest(expected, r) for r in received)
if not valid:
hint = diagnose(sch, ep, body, ts, received)
if hint and hint[0] == "WH07":
add("WH07", "medium", hint[1])
valid = None # authentic but signed with the old secret
elif hint:
add("WH01", "high", "signature mismatch; likely cause: " + hint[1])
else:
add("WH01", "high", "signature mismatch; no common mistake reproduces it: wrong secret for this endpoint, or the body was modified in transit")
if ts is not None:
try:
tsv = int(ts)
except ValueError:
add("WH00", "high", "timestamp %r is not unix seconds" % ts)
tsv = None
if tsv is not None and now is not None:
age = now - tsv
if age > tolerance:
add("WH03", "high", "timestamp is %d s old (tolerance %d s): possible replay, reject even if the signature is valid" % (age, tolerance))
elif age < -skew:
add("WH05", "medium", "timestamp is %d s in the future (allowed skew %d s): check server clocks (NTP)" % (-age, skew))
event_id = d.get("event_id") or get_header(headers, ep.get("id_header", "X-Webhook-Id") or "") or get_header(headers, "X-GitHub-Delivery")
if event_id:
key = (ep.get("name"), event_id)
if key in seen_ids:
add("WH04", "medium", "duplicate event id %s (first seen in delivery %s): process idempotently, do not run side effects twice" % (event_id, seen_ids[key]))
else:
seen_ids[key] = d.get("id")
else:
add("WH10", "low", "no event/delivery id: cannot de-duplicate retries; store a hash of the body or ask the provider for an id header")
limit = ep.get("max_body_bytes")
if limit and len(body.encode("utf-8")) > limit:
add("WH11", "low", "body is %d bytes, above max_body_bytes %d" % (len(body.encode("utf-8")), limit))
return findings, valid
def check_endpoint(ep):
out = []
def add(code, sev, msg):
out.append({"code": code, "severity": sev, "delivery": None, "endpoint": ep.get("name"), "message": msg})
url = ep.get("url", "")
if url and not url.lower().startswith("https://"):
add("WH09", "high", "endpoint URL is not HTTPS (%s): signatures do not hide the payload" % url)
sec = ep.get("secret", "")
if not sec:
add("WH00", "high", "no secret configured")
elif len(sec) < 24 or entropy_bits(sec) < 96:
add("WH08", "medium", "secret is short or low-entropy (%d chars, ~%d bits): generate at least 32 random bytes" % (len(sec), entropy_bits(sec)))
if ep.get("scheme") == "github-sha1":
add("WH06", "medium", "endpoint configured for HMAC-SHA1 only")
return out
def to_epoch(s):
return int(datetime.fromisoformat(s.replace("Z", "+00:00")).astimezone(timezone.utc).timestamp())
def run(data, now_override=None):
eps = {}
for name, ep in data.get("endpoints", {}).items():
ep = dict(ep); ep["name"] = name; eps[name] = ep
now = to_epoch(now_override) if now_override else (to_epoch(data["now"]) if data.get("now") else int(datetime.now(timezone.utc).timestamp()))
tol = int(data.get("tolerance_seconds", 300)); skew = int(data.get("future_skew_seconds", 60))
findings, results, seen = [], [], {}
for ep in eps.values():
findings += check_endpoint(ep)
for d in data.get("deliveries", []):
ep = eps.get(d.get("endpoint"))
if ep is None:
findings.append({"code": "WH00", "severity": "high", "delivery": d.get("id"), "endpoint": d.get("endpoint"), "message": "unknown endpoint"})
results.append({"delivery": d.get("id"), "verdict": "error"}); continue
f, valid = check_delivery(d, ep, now, tol, skew, seen)
findings += f
hard = any(x["severity"] == "high" for x in f)
verdict = "reject" if hard else ("accept-rotate-secret" if valid is None else ("accept" if valid else "reject"))
if any(x["code"] == "WH04" for x in f) and verdict.startswith("accept"):
verdict = "accept-duplicate(skip side effects)"
results.append({"delivery": d.get("id"), "endpoint": ep["name"], "verdict": verdict})
findings.sort(key=lambda x: (SEV_ORDER[x["severity"]], x["code"], str(x["delivery"])))
summary = Counter(x["severity"] for x in findings)
return {"now": now, "tolerance_seconds": tol, "results": results, "findings": findings,
"summary": {k: summary.get(k, 0) for k in ("high", "medium", "low")}}
def print_text(rep):
print("Webhook verification report (now=%s, tolerance %ss)" % (datetime.fromtimestamp(rep["now"], timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ"), rep["tolerance_seconds"]))
print("\nDeliveries:")
for r in rep["results"]:
print(" %-6s %-14s %s" % (r["delivery"], r.get("endpoint", "?"), r["verdict"]))
print("\nFindings: %(high)d high, %(medium)d medium, %(low)d low" % rep["summary"])
for f in rep["findings"]:
where = f["delivery"] or ("endpoint " + str(f["endpoint"]))
print(" [%s] %s %s: %s" % (f["severity"].upper(), f["code"], where, f["message"]))
def self_test():
ok = 0; total = 0
def t(name, cond):
nonlocal ok, total
total += 1; ok += bool(cond)
print(("PASS " if cond else "FAIL ") + name)
sec = "whsec_selftest_7f3a9c2e5b1d48a6b0c4e2f19d7a3b58"
body = '{"id":"evt_1","type":"invoice.paid","amount":4200}'
ts = 1794560400
def rep_for(dels, eps=None, now=ts + 10):
eps = eps or {"s": {"scheme": "stripe", "secret": sec, "url": "https://x.test/hook"}}
return run({"endpoints": eps, "deliveries": dels}, datetime.fromtimestamp(now, timezone.utc).isoformat())
good = {"id": "a", "endpoint": "s", "event_id": "evt_1", "headers": sign("stripe", sec, body, ts), "body": body}
r = rep_for([good]); t("stripe valid accepted", r["results"][0]["verdict"] == "accept" and r["summary"]["high"] == 0)
r = rep_for([good], now=ts + 900); t("WH03 stale timestamp", any(f["code"] == "WH03" for f in r["findings"]))
r = rep_for([good], now=ts - 600); t("WH05 future timestamp", any(f["code"] == "WH05" for f in r["findings"]))
r = rep_for([good, dict(good, id="b")]); t("WH04 duplicate id", any(f["code"] == "WH04" for f in r["findings"]) and r["results"][1]["verdict"].startswith("accept-duplicate"))
pretty = json.dumps(json.loads(body))
bad = dict(good, id="c", body=pretty, headers=sign("stripe", sec, body, ts))
r = rep_for([bad]); t("WH01 re-serialized body diagnosed", any(f["code"] == "WH01" and "re-serialized" in f["message"] for f in r["findings"]))
eps = {"g": {"scheme": "github", "secret": sec, "previous_secrets": ["old_secret_value_1234567890abcdef"], "url": "https://x.test/gh"}}
old = {"id": "d", "endpoint": "g", "event_id": "g1", "headers": sign("github", "old_secret_value_1234567890abcdef", body), "body": body}
r = rep_for([old], eps); t("WH07 previous secret", any(f["code"] == "WH07" for f in r["findings"]) and r["results"][0]["verdict"] == "accept-rotate-secret")
nohdr = {"id": "e", "endpoint": "g", "event_id": "g2", "headers": {"X-Hub-Signature": "sha1=abc"}, "body": body}
r = rep_for([nohdr], eps); t("WH02 + WH06 legacy sha1 only", {"WH02", "WH06"} <= {f["code"] for f in r["findings"]})
eps2 = {"sl": {"scheme": "slack", "secret": "short", "url": "http://x.test/slack"}}
sl = {"id": "f", "endpoint": "sl", "headers": sign("slack", "short", body, ts), "body": body}
r = rep_for([sl], eps2); codes = {f["code"] for f in r["findings"]}
t("slack valid + WH08 weak secret + WH09 http + WH10 no id", {"WH08", "WH09", "WH10"} <= codes and "WH01" not in codes)
nots = {"id": "g", "endpoint": "s", "event_id": "e9", "headers": {"Stripe-Signature": "t=%d,v1=%s" % (ts, digest(sec, body, "sha256", "hex"))}, "body": body}
r = rep_for([nots]); t("WH01 missing timestamp in signed string diagnosed", any("timestamp prefix" in f["message"] for f in r["findings"]))
eps3 = {"sh": {"scheme": "shopify", "secret": sec, "url": "https://x.test/shop"}}
hexsig = {"id": "h", "endpoint": "sh", "event_id": "s1", "headers": {"X-Shopify-Hmac-Sha256": digest(sec, body, "sha256", "hex")}, "body": body}
r = rep_for([hexsig], eps3); t("WH01 hex vs base64 diagnosed", any("encoding" in f["message"] for f in r["findings"]))
eps4 = {"gen": {"scheme": "generic", "header": "X-Signature", "alg": "sha512", "enc": "hex", "prefix": "", "template": "{body}", "secret": sec, "url": "https://x.test/g"}}
gen = {"id": "i", "endpoint": "gen", "event_id": "x1", "headers": {"X-Signature": digest(sec, body, "sha512", "hex")}, "body": body}
r = rep_for([gen], eps4); t("generic sha512 scheme accepted", r["results"][0]["verdict"] == "accept")
print("%d/%d passed" % (ok, total))
return 0 if ok == total else 1
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("file", nargs="?")
ap.add_argument("--now"); ap.add_argument("--json", action="store_true")
ap.add_argument("--sign", choices=sorted(SCHEMES)); ap.add_argument("--secret"); ap.add_argument("--body-file"); ap.add_argument("--timestamp", type=int)
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if a.sign:
if not (a.secret and a.body_file):
print("--sign needs --secret and --body-file", file=sys.stderr); return 2
body = open(a.body_file, encoding="utf-8", newline="").read()
ts = a.timestamp or int(datetime.now(timezone.utc).timestamp())
print(json.dumps(sign(a.sign, a.secret, body, ts), indent=2)); return 0
if not a.file:
ap.print_help(); return 2
try:
with open(a.file, encoding="utf-8") as fh:
data = json.load(fh)
rep = run(data, a.now)
except (OSError, ValueError, KeyError) as e:
print("bad input: %s" % e, file=sys.stderr); return 2
if a.json:
print(json.dumps(rep, indent=2))
else:
print_text(rep)
return 1 if rep["summary"]["high"] else 0
if __name__ == "__main__":
sys.exit(main())
Create a 60-second ultra-realistic cinematic motivational short film titled “THE BATTLES NOBODY SEES.” CORE CONCEPT: Tell an emotional, relatable story about a man going through difficult seasons of life. He experiences disappointment, loneliness, financial struggles, unanswered prayers, setbacks and moments when giving up seems easier than continuing. The film should remind viewers that struggling doesn’t mean failing, being behind doesn’t mean being defeated, and every difficult season can become part of someone’s growth. VISUAL STORYTELLING: SCENE 1 (0–10 seconds): A young man sits alone on the edge of his bed in a dimly lit room at night. His phone lights up, but there are no meaningful messages. He looks exhausted and lost in thought. Rain falls outside the window. SCENE 2 (10–20 seconds): Show him walking alone through a quiet street at night. Close-up of his face, tired eyes and thoughtful expression. Show him sitting at a desk looking at bills, unfinished work and personal goals written in a notebook. SCENE 3 (20–30 seconds): He looks into a mirror, takes a deep breath and slowly stands up. Cut to him tying his gym shoes, preparing for another difficult day, and stepping outside before sunrise. SCENE 4 (30–45 seconds): Show a realistic sequence of him exercising, working, learning, making mistakes and trying again. Show sweat, exhaustion, persistence and small victories. His progress should feel gradual and believable. SCENE 5 (45–55 seconds): The man walks through an empty street as the sun rises. His facial expression is calmer. He looks more confident, not because life has become perfect, but because he has decided not to give up. SCENE 6 (55–60 seconds): Wide cinematic shot of him standing on a rooftop overlooking the city at sunrise. Slowly fade to black. FINAL ON-SCREEN MESSAGE: “YOUR STORY ISN’T OVER.” VISUAL STYLE: Photorealistic human characters, natural facial expressions, realistic body movements, authentic environments, cinematic camera movements, shallow depth of field, subtle film grain, natural lighting, emotional close-ups and professional colour grading. Use muted colours, charcoal shadows, soft grey tones and warm sunrise highlights. VOICEOVER: Calm, mature masculine voice. Deep but natural, emotionally grounded, conversational and sincere. Avoid exaggerated shouting or artificial motivational delivery. MUSIC: Emotional cinematic piano at the beginning, gradually building into subtle atmospheric strings and powerful instrumental percussion towards the ending. EDITING: Smooth cinematic transitions, carefully paced scenes, realistic motion, emotional storytelling and perfectly synchronized narration. TECHNICAL: 60 seconds, vertical 9:16, 4K, cinematic realism, high visual consistency, suitable for TikTok, Instagram Reels and YouTube Shorts. IMPORTANT: Do not make the character look like a superhero or an impossibly wealthy person. Avoid unrealistic transformations, artificial facial expressions, cartoon effects, excessive slow motion and flashy transitions. Make the story feel personal, honest and believable.
Opinionated HTTP caching and CDN conventions for fast web pages and APIs without stale content surprises.
# HTTP Caching taste of a web developer who wants fast pages without stale surprises - Decide the caching policy for every response on purpose; a missing `Cache-Control` header lets browsers and proxies guess. Confidence: 0.90 - Serve fingerprinted static assets with `Cache-Control: public, max-age=31536000, immutable`. Confidence: 0.95 - Put a content hash in asset file names instead of using query strings like `?v=2` for cache busting. Confidence: 0.85 - Send HTML documents with `no-cache` or a very short max-age so new deploys show up right away. Confidence: 0.85 - Use `private, no-store` for responses with personal or sensitive data, and never let a shared cache hold them. Confidence: 0.95 - Use `s-maxage` to give the CDN a different lifetime than the browser when the CDN can be purged and the browser cannot. Confidence: 0.80 - Add `stale-while-revalidate` for content that can be a few seconds old, so users rarely wait for the origin. Confidence: 0.80 - Use `stale-if-error` so the CDN keeps serving the last good copy when the origin is down. Confidence: 0.70 - Send strong `ETag` or `Last-Modified` validators so revalidation returns a cheap `304 Not Modified`. Confidence: 0.80 - Keep the `Vary` header minimal; varying on `User-Agent` or `Cookie` quietly destroys the CDN hit rate. Confidence: 0.85 - Never cache responses that set cookies at a shared cache. Confidence: 0.90 - Purge the CDN by tag or surrogate key after content changes instead of purging everything. Confidence: 0.75 - Cache API GET responses only when the data is truly shared, and say so explicitly in the response headers. Confidence: 0.80 - Do not cache error responses for long; a cached 500 or 404 can outlive the real problem. Confidence: 0.80 - Rely on HTTP caching headers instead of a service worker unless the app truly needs offline support. Confidence: 0.70 - Watch the CDN cache hit ratio as a key metric, and investigate when it drops after a deploy. Confidence: 0.75 - Test caching behavior with `curl -I` against the real CDN, not only in local development. Confidence: 0.80 - Document the cache rules per route in one place so nobody has to read headers in the browser to learn them. Confidence: 0.65 - Keep `Cache-Control` decisions in application code or edge config under version control, not only in a dashboard. Confidence: 0.75 - Prefer short cache times plus revalidation over long cache times plus emergency purges. Confidence: 0.70

Create for me an ultra-realistic dashboard titled "ANALYSIS OF BRD SESSIONS/DOCUMENT DELIVERY AUG - OCT" Let it show, in graphs, histograms, and pie charts, all the documents I have worked on so far concerning BRDs and documents under growth stack


A structured JSON prompt for a clean, theatrical-quality movie poster of an original franchise, VYKRON: Rise of the Last Titan. An adult heroine in cobalt-and-silver battle armor stands in front of one giant mechanical Titan, framed by a glowing energy ring over a calm futuristic skyline, with strict anti-clutter rules, a cobalt/cyan/orange grade and exact poster typography. Swap the title and character details to make your own blockbuster poster.
1{2 "aspect_ratio": "3:4",3 "style": "premium Hollywood sci-fi superhero theatrical poster, photorealistic CGI, clean cinematic composition, IMAX production quality, sophisticated visual storytelling",...+2 more lines
Turn what your startup really does about security into a reusable YAML answer pack for customer security questionnaires: infrastructure, data protection, access, app security, incidents, continuity, subprocessors, privacy, 15+ honest standard answers with evidence, gaps with interim answers, and open questions.
1You are a startup security and compliance lead who has answered hundreds of customer security questionnaires. Using the schema below, turn what I tell you about my product and company into a reusable security questionnaire answer pack as one valid YAML document. Ask me up to 6 short questions first if the inputs are missing, then output ONLY the YAML, with no commentary before or after it.23My inputs:4- Product and what customer data it handles (personal data, payment data, health data, files, credentials):5- Company size, team locations and who owns security:6- Hosting and key vendors (cloud, database, email, payments, analytics, support tools):7- Security practices we really have today (SSO, MFA, encryption, backups, logging, code review, pen test, training):8- Certifications or audits (none, SOC 2 in progress, SOC 2 Type II, ISO 27001, other):9- The questionnaire or customer that triggered this (paste the questions if you have them):10...+88 more lines
Generates production-grade, RAG-optimized Markdown (.md) documentation aligned with the 16-Phase Enterprise Lifecycle and 10-Phase ADLC. Enforces YAML frontmatter for metadata filtering, H1–H4 header breadcrumbs, self-contained semantic chunks, Gherkin acceptance criteria, and cross-cutting governance—ready for direct ingestion into Obsidian, Git, and vector databases (ChromaDB, Qdrant, pgvector).
---
You are a Principal Technical Product Manager, Data & BI Solutions Architect, and Technical Writer. Your task is to generate a complete, production-grade, RAG-optimized Markdown (`.md`) artifact aligned with the **16-Phase Enterprise Lifecycle** and **10-Phase Analytics Development Lifecycle (ADLC)**.
---
### INPUT PARAMETERS
* **Target Phase (01–16):** {{PHASE}}
* **Document Filename:** {{FILENAME}}
* **Project / Product Name:** {{PROJECT_NAME}}
* **Domain & Tech Stack:** {{DOMAIN_AND_STACK}}
* **Target Audience:** {{TARGET_AUDIENCE}}
* **Raw Context / Requirements / Notes:** {{RAW_CONTEXT}}
---
### MANDATORY RAG & MARKDOWN ARCHITECTURE RULES
1. **YAML Frontmatter Block (Top of File):** Begin immediately with valid YAML frontmatter containing:
- `id`: Unique uppercase document ID (e.g., `DOC-PHASE-04-PRD`)
- `title`: Full formal title of the artifact
- `phase`: Exact phase code and name (e.g., `04_Design`)
- `lifecycle_tier`: `Tier_1_Core_Delivery` (Phases 01–10), `Tier_2_Commercial_Portfolio` (Phases 11–14), or `Tier_3_Cross_Cutting_Governance` (Phases 15–16)
- `stage_gate`: Applicable gate (`Gate_0` through `Gate_6`, `Sprint`, or `Continuous`)
- `adlc_mapping`: Equivalent Data/BI ADLC stage
- `target_audience`: YAML list of stakeholder roles
- `version`: `"1.0.0"`
- `classification`: `"Confidential - Internal"` (or `"Investor Restricted"` for Phases 11–12)
- `retrieval_tags`: 6–10 high-signal semantic keywords
- `semantic_summary`: A single dense, factual sentence summarizing the document's scope for embedding models.
2. **Context Breadcrumb:** Immediately below the `# H1` title, include:
`> **Context Breadcrumb:** Enterprise Lifecycle > [Tier] > [Phase] > [Artifact Title]`
3. **Self-Contained Semantic Chunking (350–700 Tokens per Section):**
- Use strict `## H2` and `### H3` nesting so Markdown header splitters preserve parent-child context.
- **Zero Anaphoric References:** Never write *"as mentioned above"*, *"this table"*, or *"the previous section"*. Always restate explicit proper nouns, metric names, and system components so every chunk retrieves accurately in isolation.
4. **Zero Placeholders or Stubs:** Populate every table, schema, formula, and acceptance criterion with concrete, domain-accurate content derived from `{{RAW_CONTEXT}}` and `{{DOMAIN_AND_STACK}}`. Never output `[Insert X]`, `TBD`, or filler text.
5. **Cross-Cutting Governance:** Embed relevant controls across **Documentation, Data Governance, Data Quality, Change Management, Security (RBAC/PII), Project Management, and Configuration Management** directly into the artifact.
---
### PHASE-SPECIFIC DELIVERABLE REQUIREMENTS
Automatically enforce the required structural blocks for `{{PHASE}}`:
* **01 Define (Gate 0):** Project Charter, Problem Statement, Business Case (ROI/NPV/Payback), Voice of Customer (VoC) Matrix, Stakeholder Power-Interest Grid, and Hard Scope Boundaries.
* **02 Measure (Gate 1A):** BRD/FRD/DRD Requirements, Source-to-Target Data Mapping Table, Data Quality Profiling Rules, Telemetry Event Instrumentation Plan, Baseline Metrics, and Mathematical KPI Dictionary.
* **03 Plan (Gate 1B):** Work Breakdown Structure (WBS) & Dictionary, Phased Roadmap, Resource Capacity Allocation, and RAID Log (Risks, Assumptions, Issues, Dependencies with mitigations).
* **04 Design (Gate 2A):** Product Requirement Document (PRD) with Gherkin (`Given-When-Then`) Acceptance Criteria, System Architecture Document (SAD), ERD / Dimensional Star Schema, Semantic Layer & Row-Level Security (RLS) Rules, and Non-Functional Requirements (NFRs).
* **05 Implement (Sprint):** Sprint Backlog Breakdown, OpenAPI 3.0 / gRPC Interface Contracts, ETL/ELT Transformation Specs, Environment Configuration Keys, and Pull Request Definition of Done (DoD).
* **06 Analysis (Gate 2B):** Source-to-Target Data Reconciliation Report, Root Cause Analysis (5-Whys / Ishikawa), Cohort Retention Analysis, and Unit Economics (LTV, CAC, Gross Margin, Sensitivity Table).
* **07 Execute (Gate 3A):** Tier-1/Tier-2 Operations & Escalation Runbook, ADKAR Change Management & Enablement Plan, Steering Committee Executive Summary, and RACI Matrix.
* **08 Test (Gate 3B):** Master Test Strategy, Technical QA & Data Reconciliation Sign-Off Criteria, Business UAT Sign-Off Checklist, Security/Pen-Test Audit Controls, and AI Model Card / Drift Evaluation (if AI/ML is present).
* **09 Control (Gate 4A):** Statistical Process Control (SPC) Thresholds, SLA/SLO Error Budgets, Observability & PagerDuty Alert Escalation Runbook, and RBAC/PII Audit Schedule.
* **10 Deploy (Gate 4B):** Release Notes, Step-by-Step Deployment Runbook, Automated Canary/Blue-Green Rollback Triggers, Smoke Test Verification Checklist, and Infrastructure-as-Code (IaC) Manifest Summary.
* **11 Pitch (Gate 5):** 12-Slide Pitch Deck Narrative Blueprint, 1-Page Executive Investment Teaser, TAM/SAM/SOM Market Sizing, Go-To-Market (GTM) Distribution Playbook, and Live Demo Script.
* **12 Investor (Gate 5):** Tiered Virtual Data Room (VDR) Index (Tiers 1–3), Fully Diluted Capitalization Table Structure, Term Sheet / SHA / SSA Key Clauses, and KYC/AML & IP Assignment Checklist.
* **13 Product LC (Quarterly):** BCG Growth-Share Portfolio Assessment, Annual Product P&L Structure, Market Expansion/Localization Matrix, and 180-Day Feature Sunset & Deprecation Policy.
* **14 Project LC (Gate 6A):** Approved Scope Baseline, Vendor SOW/MSA Governance Register, Earned Value Management (EVM) Variance Summary, and Blameless Post-Mortem & Lessons Learned Archive.
* **15 Documents (Continuous):** Standard Operating Procedures (SOPs), Enterprise Data Dictionary & Lineage Catalog, API Developer Reference, and RAG Vector Ingestion Metadata Schema.
* **16 Submission (Gate 6B):** RFP Compliance Response Matrix, SOC 2 Type II / ISO 27001 / Regulatory Audit Evidence Pack, Stage-Gate Sign-Off Dossier, and Formal Legal Transmittal Attestation.
---
### OUTPUT FORMAT
Output **only** the raw, valid Markdown document enclosed in a single `markdown` code block, starting with `---` (YAML frontmatter) and ending with a **Stage-Gate Exit & RACI Sign-Off Table**. Do not include conversational filler before or after the code block.
---
# Unified Enterprise SDLC, ADLC & 16-Phase Lifecycle Guidance Document
## 1. Purpose & Architectural Scope
This guidance document establishes a single, end-to-end delivery and governance standard for Data Engineering, Business Intelligence (BI), ThoughtSpot Centers of Excellence (COE), and production SaaS product organizations[cite: 2, 5]. It synthesizes traditional Software Development Lifecycle (SDLC) mechanics [cite: 1, 3], the 10-phase Analytics Development Lifecycle (ADLC / ALDC) [cite: 2, 3], and the 16-phase enterprise lifecycle spanning technical delivery, venture commercialization, and continuous compliance [cite: 4, 5].
* **Terminology Standard (ADLC vs. ALDC):** While internal BI and data engineering teams frequently use the acronym ALDC (Analytics Lifecycle Development Cycle), **ADLC (Analytics Development Lifecycle)** is the recognized industry-standard terminology for analytics delivery frameworks[cite: 3]. Both terms map identically within this standard to govern traceability from business requirements through ingestion, semantic modeling, testing, deployment, and ongoing governance[cite: 2, 3].
* **Definition of Production Readiness:** A production release is valid only when technical deployment succeeds *and* underlying data assets are accurate, traceable, governed, and trusted by business consumers[cite: 3].
---
## 2. Cross-Attachment Audit & Breaking-Point Reconciliation
Before executing against this standard, teams must account for structural contradictions and visual anomalies across the four baseline artifacts so legacy defects are not propagated into production workflows:
| Source Artifact | Structural Contribution | Identified Breaking Points & Visual Anomalies | Canonical Resolution Enforced in This Guide |
| :--- | :--- | :--- | :--- |
| **`SDLC_Roadmap_Infographic.png`**[cite: 1] | Establishes visual station routing and the left-hand **Bypass Loop (For Refinement)** connecting testing/operations back to upstream stages[cite: 1]. | **1. Inverted Causality:** Places `01 Requirements`, `02 Analysis`, and `03 Planning` before `04 Define`[cite: 1].<br>**2. Triple Build Redundancy:** Splits coding across `06 Implement`, `07 Build`, and `08 Development`[cite: 1].<br>**3. Duplicate Exit Nodes:** Repeats `11 Maintenance` and `12 Feedback / Finish` twice[cite: 1]. | Enforce `01 Define` and `02 Measure` prior to `03 Plan`[cite: 4, 5]; consolidate engineering into `04 Design` and `05 Implement`[cite: 4, 5]; replace duplicate exit nodes with commercial and governance tiers[cite: 4, 5]. |
| **` List ALDC Phases.pdf`**[cite: 2, 3] | Provides the 10-phase Data Engineering, BI, and ThoughtSpot COE framework, SDLC crosswalk, 4-stage pipeline, and 7 cross-cutting governance pillars[cite: 2, 3]. | **1. Non-Standard Acronym:** Uses `ALDC` instead of industry-standard `ADLC`[cite: 3].<br>**2. Commercial Blind Spot:** Stops at `10 Continuous Improvement` without covering investor due diligence, Cap Tables, RFP tenders, or product sunsetting[cite: 2, 3]. | Adopt `ADLC` as the formal acronym[cite: 3] and map all 10 ADLC phases onto Phases `01–10` and `13–15` of the 16-phase enterprise lifecycle[cite: 2, 3, 5]. |
| **`5ff82eb8.jpeg`** *(Isometric 16-Phase Roadmap)*[cite: 4] | Translates the 16 phases into an isometric campus flow featuring the **Continuous Refinement Loop** and sequential `01 Define` through `10 Deploy` stations[cite: 4]. | **1. Visual Badge Duplication:** Renders `13 PRODUCT LC` twice on the lower-right interchange while omitting visible badges for `14 PROJECT LC` and `15 DOCUMENT`[cite: 4]. | Use `5ff82eb8.jpeg` strictly for executive conceptual storytelling[cite: 4]; rely on the canonical 16-phase sequence (`11 Pitch` → `12 Investor` → `13 Product LC` → `14 Project LC` → `15 Document` → `16 Submission`) for operational governance[cite: 5]. |
| **`fd218dcf.png`** *(Swimlane Architecture)*[cite: 5] | Organizes all 16 phases into three functional swimlanes (**Tier 1 Core Delivery**, **Tier 2 Commercial & Portfolio**, **Tier 3 Cross-Cutting Governance**)[cite: 5]. | **1. Gate Numbering Drift:** Visual diamond markers jump from `GATE 2` (after `04 Design`) to `GATE 5` (after `10 Deploy`), and repeat `GATE 6` twice in Tier 2[cite: 5]. | Enforce strict sequential Stage-Gates: **Gate 0** (`01`), **Gate 1** (`02–03`), **Gate 2** (`04–06`), **Gate 3** (`07–08`), **Gate 4** (`09–10`), **Gate 5** (`11–12`), and **Gate 6** (`13–16`). |
---
## 3. Master Multi-Framework Crosswalk Matrix
This crosswalk unifies the **16-Phase Lifecycle**[cite: 4, 5], the **10-Phase ADLC / BI COE Framework**[cite: 2, 3], **Traditional SDLC**[cite: 1, 2, 3], and **dbt Labs' 8-Stage ADLC**[cite: 3]:
| 16-Phase Lifecycle Station | Swimlane Tier & Canonical Gate | 10-Phase ADLC / BI COE Equivalent[cite: 2, 3] | Traditional SDLC Equivalent[cite: 1, 2] | dbt Labs 8-Stage ADLC Equivalent[cite: 3] | Primary Output Artifacts[cite: 2, 3] |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **01. Define** | **Tier 1** • Gate 0[cite: 5] | **1. Initiation & Discovery**[cite: 2] | Planning / Initiation[cite: 1, 2] | Discover[cite: 3] | Project Charter, Business Case, VoC Matrix[cite: 2] |
| **02. Measure** | **Tier 1** • Gate 1[cite: 5] | **2. Requirements Gathering & 3. Data Assessment**[cite: 2] | Requirements & Analysis[cite: 1, 2] | Analyze[cite: 3] | BRD, FRD, DRD, Source-to-Target Mapping, KPI Dictionary[cite: 2, 3] |
| **03. Plan** | **Tier 1** • Gate 1[cite: 5] | **Project Management Track** *(Continuous)*[cite: 3] | Planning[cite: 1, 2] | Plan[cite: 3] | WBS, Product Roadmap, Capacity Plan, RAID Log[cite: 3] |
| **04. Design** | **Tier 1** • Gate 2[cite: 5] | **4. Solution Architecture & Data Modelling**[cite: 2, 3] | Design[cite: 1, 2] | Plan / Architect[cite: 3] | PRD, System Architecture (SAD), ERD, ThoughtSpot Semantic Model[cite: 2, 3] |
| **05. Implement** | **Tier 1** • Sprint[cite: 5] | **5. Development & Configuration**[cite: 2, 3] | Build / Implement[cite: 1, 2] | Develop[cite: 3] | ETL/ELT Pipelines, Semantic Layers, Liveboards, OpenAPI Contracts[cite: 2, 3] |
| **06. Analysis** | **Tier 1** • Gate 2[cite: 5] | **Data Quality & Analytical Diagnostics**[cite: 3] | Analysis[cite: 1, 2] | Analyze / Observe[cite: 3] | Root Cause Analysis (5 Whys), Data Reconciliation, LTV/CAC Model[cite: 3] |
| **07. ** Execute** | **Tier 1** • Gate 3[cite: 5] | **10. Change Management & Enablement**[cite: 2, 3] | Implementation / Rollout[cite: 1] | Operate[cite: 3] | Operations Runbook, ADKAR Enablement Plan, RACI Matrix[cite: 3] |
| **08. Test** | **Tier 1** • Gate 3[cite: 5] | **6. Quality Assurance & 7. Business UAT**[cite: 2, 3] | Testing & Acceptance[cite: 1, 2] | Test[cite: 3] | Master Test Plan, QA Sign-Off, Business UAT Sign-Off, Security Audit[cite: 2, 3] |
| **09. ** Control** | **Tier 1** • Gate 4[cite: 5] | **9. Operations, Monitoring & Security**[cite: 2, 3] | Maintenance[cite: 1, 2] | Observe[cite: 3] | SPC Control Charts, SLA/SLO Budgets, RBAC/PII Audit, Drift Alerts[cite: 3] |
| **10. Deploy** | **Tier 1** • Gate 4[cite: 5] | **8. Release & Production Deployment**[cite: 2, 3] | Deployment / Release[cite: 1, 2] | Deploy[cite: 3] | Deployment Runbook, Canary/Rollback Protocol, Smoke Test Logs[cite: 3] |
| **11. Pitch** | **Tier 2** • Gate 5[cite: 5] | *Value Realization & Executive Showcase* | — | — | Pitch Deck, Investment Teaser, Commercial GTM Strategy |
| **12. Investor** | **Tier 2** • Gate 5[cite: 5] | *Fiduciary & Capital Governance* | — | — | Virtual Data Room (VDR) Index, Cap Table, SHA/SSA, KYC/AML |
| **13. Product LC** | **Tier 2** • Quarterly[cite: 5] | **10. Continuous Improvement & Enhancements**[cite: 2, 3] | Continuous Development[cite: 2] | Discover[cite: 3] | BCG Portfolio Strategy, Market Localization, Feature Sunset Policy |
| **14. ** Project LC** | **Tier 2** • Gate 6[cite: 5] | *Lifecycle Governance & Closure*[cite: 3] | Project Closure | — | Scope Baseline, Vendor SOW/MSA, Earned Value (EVM), Post-Mortem |
| **15. Document** | **Tier 3** • Continuous[cite: 5] | **Documentation & Metadata Governance**[cite: 3] | Documentation | — | BRD/FRD/DRD/TDD, SOPs, Metadata & Lineage Catalog, RAG `.md` Files[cite: 3] |
| **16. Submission** | **Tier 3** • Gate 6[cite: 5] | *Regulatory Compliance & Audit Attestation*[cite: 3] | Governance Audit | — | RFP Tender Dossier, SOC 2 / ISO 27001 Filing, Gate Sign-Off Pack |
---
## 4. Operational Guidance by Tier & Phase
### Tier 1: Core Delivery & ADLC Pipeline (`01 Define` → `10 Deploy`)[cite: 5]
#### Phase 01: Define *(ADLC Phase 1 — Initiation & Discovery)*[cite: 2, 5]
* **Objective:** Identify core business problems, commercial objectives, executive sponsors, technical feasibility, and measurable outcomes before committing build capacity[cite: 2].
* **Key Activities:** Conduct discovery workshops; map stakeholder authority; establish hard scope boundaries; validate strategic alignment[cite: 2].
* **Mandatory Documents:** `01_define_charter_business_case.md` (Project Charter, Business Case with NPV/ROI assumptions, Voice of Customer Matrix, Stakeholder Power-Interest Grid)[cite: 2].
* **Stage-Gate Exit Criterion (Gate 0):** Signed Project Charter authorizing discovery budget and naming accountable business and technical owners[cite: 2, 5].
#### Phase 02: Measure *(ADLC Phase 2 — Requirements & Phase 3 — Data Assessment)*[cite: 2, 5]
* **Objective:** Elicit functional, technical, data, reporting, and non-functional requirements while auditing source systems for data availability, quality, lineage, and dependencies[cite: 2].
* **Key Activities:** Profile source database tables and columns; benchmark current baseline latencies or conversion drop-offs; define canonical KPI formulas; instrument telemetry SDKs[cite: 2].
* **Mandatory Documents:** `02_measure_telemetry_kpi_dictionary.md` (Business Requirements Document [BRD], Functional Requirements Document [FRD], Data Requirements Document [DRD], Source-to-Target Mapping, KPI Dictionary, Baseline Metrics Report)[cite: 2, 3].
* **Stage-Gate Exit Criterion (Gate 1A):** Verified Source-to-Target mapping and signed-off BRD/FRD/DRD confirming all required source columns exist and meet baseline quality thresholds[cite: 2, 3].
#### Phase 03: Plan *(Continuous Project Management Track)*[cite: 3, 5]
* **Objective:** Decompose validated requirements into deterministic work packages, critical-path schedules, resource capacity allocations, and risk mitigation plans[cite: 3].
* **Key Activities:** Build the Work Breakdown Structure (WBS); sequence dependencies across data engineering, semantic modeling, and frontend teams; initialize the RAID log[cite: 3].
* **Mandatory Documents:** `03_plan_wbs_roadmap_raid_log.md` (WBS & Dictionary, Product/COE Roadmap, Resource Capacity Plan, Risk Management Matrix / RAID Log)[cite: 3].
* **Stage-Gate Exit Criterion (Gate 1B):** Approved scope baseline, sprint schedule, and resource allocation plan[cite: 3, 5].
#### Phase 04: Design *(ADLC Phase 4 — Solution Architecture, Data Modelling & Semantic Design)*[cite: 2, 3, 5]
* **Objective:** Architect end-to-end cloud infrastructure, relational/dimensional schemas, transformation logic, and semantic-layer definitions[cite: 2, 3].
* **Key Activities:** Model star/snowflake fact and dimension tables; define join cardinalities, row-level security (RLS) rules, and ThoughtSpot worksheet/semantic formulas; draft API contracts and UI wireframes[cite: 2, 3].
* **Mandatory Documents:** `04_design_prd_system_architecture.md` (Product Requirement Document [PRD] with Gherkin acceptance criteria, System Architecture Document [SAD], Entity-Relationship Diagrams [ERD], Technical Design Document [TDD], Semantic Layer Spec)[cite: 2, 3].
* **Stage-Gate Exit Criterion (Gate 2A — Architecture Freeze):** Peer-reviewed SAD, ERD, and Semantic Model specification signed off by Principal Architecture and Data Governance[cite: 2, 3, 5].
#### Phase 05: Implement *(ADLC Phase 5 — Development & Configuration)*[cite: 2, 5]
* **Objective:** Construct ingestion pipelines, ETL/ELT transformations, database tables, semantic layers, KPI formulas, interactive Liveboards, and application microservices[cite: 2, 3].
* **Key Activities:** Execute Agile sprints using version-controlled Git workflows; enforce peer Pull Request reviews; build automated unit tests alongside pipeline and API code[cite: 3].
* **Mandatory Documents:** `05_implement_sprint_api_contract.md` (Sprint Backlogs, OpenAPI/Swagger Contracts, Environment Configuration Guides, Repository READMEs).
* **Stage-Gate Exit Criterion (Sprint Acceptance):** All sprint stories pass static linting, unit tests, and peer code reviews in the development environment.
#### Phase 06: Analysis *(ADLC Data Quality & Analytical Diagnostics)*[cite: 3, 5]
* **Objective:** Reconcile transformed datasets against source systems, diagnose performance bottlenecks, and validate commercial unit economics[cite: 3].
* **Key Activities:** Execute row-count, checksum, and aggregate metric reconciliations; run 5-Whys Root Cause Analysis (RCA) on pipeline anomalies; evaluate cohort retention and LTV/CAC models[cite: 3].
* **Mandatory Documents:** `06_analysis_rca_cohort_economics.md` (Data Reconciliation Report, Root Cause Analysis Dossier, Cohort & Retention Analysis, Unit Economics & Sensitivity Model)[cite: 3].
* **Stage-Gate Exit Criterion (Gate 2B — Viability Sign-Off):** Zero unexplained data variance between source systems and target semantic models, plus validated commercial unit economics[cite: 3, 5].
#### Phase 07: Execute *(ADLC Phase 10 — Operational Rollout & Change Enablement)*[cite: 2, 3, 5]
* **Objective:** Prepare operational support teams, business users, and executive stakeholders for organizational adoption before production cutover[cite: 3].
* **Key Activities:** Deliver enablement training for BI consumers and tier-1/tier-2 support engineers; publish change communications; finalize escalation trees[cite: 3].
* **Mandatory Documents:** `07_execute_operations_change_mgmt.md` (Operations & Support Runbook, ADKAR Change Management Plan, Steering Committee Deck, RACI Execution Matrix)[cite: 3].
* **Stage-Gate Exit Criterion (Gate 3A — Operational Readiness):** Support runbooks published and user enablement sessions completed.
#### Phase 08: Test *(ADLC Phase 6 — Technical QA & Phase 7 — Business UAT)*[cite: 2, 3, 5]
* **Objective:** Verify technical integrity (schema, data types, relationships, performance) and validate business KPI calculations, report outputs, and access permissions with end users[cite: 2, 3].
* **Key Activities:** Run automated integration, regression, load, and security penetration tests; conduct structured Business UAT sessions validating ThoughtSpot Liveboards and SaaS workflows against BRD/PRD acceptance criteria[cite: 2, 3].
* **Mandatory Documents:** `08_test_strategy_uat_security_audit.md` (Master Test Plan, Technical QA Sign-Off, Business UAT Sign-Off, Security/Pen-Test Audit, AI Model Card)[cite: 2, 3].
* **Stage-Gate Exit Criterion (Gate 3B — Quality & Security Sign-Off):** Formal written QA Sign-Off and Business UAT Sign-Off with zero unresolved Severity-1 or Severity-2 defects[cite: 2, 3, 5].
#### Phase 09: Control *(ADLC Phase 9 — Operations, Monitoring & Security Governance)*[cite: 2, 3, 5]
* **Objective:** Enforce continuous pipeline reliability, refresh schedules, data quality thresholds, role-based access control (RBAC), and drift alerting in production[cite: 2, 3].
* **Key Activities:** Configure automated SLA/SLO alerts; enforce PII masking and RBAC policies; monitor data freshness, query latency, and model drift via Statistical Process Control (SPC) charts[cite: 3].
* **Mandatory Documents:** `09_control_spc_slo_drift_runbook.md` (Statistical Process Control Plan, SLA/SLO Error Budget Framework, Observability & PagerDuty Escalation Runbook, RBAC/PII Compliance Log)[cite: 3].
* **Stage-Gate Exit Criterion (Gate 4A — Stability Check):** Automated monitoring dashboards and synthetic alerts verified active in staging/pre-prod[cite: 3].
#### Phase 10: Deploy *(ADLC Phase 8 — Release & Production Deployment)*[cite: 2, 5]
* **Objective:** Obtain final release approvals, promote validated assets from QA to production, and execute post-deployment smoke tests[cite: 2, 3].
* **Key Activities:** Execute CI/CD canary or blue-green deployments; validate database migrations; run automated production smoke tests; verify rollback readiness[cite: 2, 3].
* **Mandatory Documents:** `10_deploy_release_rollback_iac.md` (Release Notes, Deployment Runbook, Automated Rollback Protocol, Infrastructure-as-Code [Terraform/Helm] Manifests)[cite: 3].
* **Stage-Gate Exit Criterion (Gate 4B — Production Release Sign-Off):** Verified production smoke tests passing 100%, and release approval logged[cite: 2, 3, 5].
---
### Tier 2: Commercial, Venture & Portfolio Lifecycle (`11 Pitch` → `14 Project LC`)[cite: 5]
#### Phase 11: Pitch *(Commercialization & Value Realization)*[cite: 5]
* **Objective:** Package verified production traction, unit economics, and technical differentiation into persuasive commercial and investor narratives.
* **Key Activities:** Synthesize TAM/SAM/SOM sizing, live product demos, and customer ROI case studies; run red-team Q&A drills.
* **Mandatory Documents:** `11_pitch_deck_gtm_commercial.md` (12–15 Slide Investor Pitch Deck, 1-Page Executive Teaser, Commercial Go-To-Market [GTM] Playbook, Demo Walkthrough Script).
#### Phase 12: Investor *(Investor Onboarding & Fiduciary Diligence)*[cite: 5]
* **Objective:** Execute institutional due diligence, capitalization table modeling, definitive legal agreements, and capital disbursement.
* **Key Activities:** Structure tiered Virtual Data Room (VDR) access; reconcile diluted equity and ESOP pools; complete KYC/AML and IP assignment audits.
* **Mandatory Documents:** `12_investor_vdr_cap_table_term_sheet.md` (Tiered VDR Index, Fully Diluted Cap Table, Term Sheet, Shareholders' Agreement [SHA], Share Subscription Agreement [SSA]).
* **Stage-Gate Exit Criterion (Gate 5):** Executed definitive agreements and cleared escrow capital transfer[cite: 5].
#### Phase 13: Product Life Cycle *(ADLC Phase 10 — Continuous Improvement & Portfolio Stewardship)*[cite: 2, 5]
* **Objective:** Govern product and analytics portfolio evolution across Introduction, Growth, Maturity, and Decline stages[cite: 2, 3].
* **Key Activities:** Prioritize enhancement backlogs and impact assessments; allocate R&D capital via BCG growth-share reviews; manage orderly deprecation and migration of legacy reports or APIs[cite: 2, 3].
* **Mandatory Documents:** `13_plc_portfolio_sunset_strategy.md` (Product Portfolio Strategy, Annual Product P&L, Market Localization Dossier, Feature Sunset & Deprecation Policy)[cite: 2, 3].
#### Phase 14: Project Life Cycle *(Governance, Vendor Management & Closure)*[cite: 3, 5]
* **Objective:** Maintain contractual governance over bounded initiatives from scope baseline through vendor management and formal post-mortem closure[cite: 3].
* **Key Activities:** Track Earned Value Management (EVM) cost/schedule variances; audit vendor Statements of Work (SOW); conduct blameless post-mortems and archive lessons learned[cite: 3].
* **Mandatory Documents:** `14_project_lifecycle_sow_closure.md` (Project Scope Baseline, Vendor SOW/MSA Register, RAID Escalation Archive, Project Closure & Lessons Learned Report)[cite: 3].
* **Stage-Gate Exit Criterion (Gate 6A):** Formal stakeholder project acceptance and financial closeout[cite: 5].
---
### Tier 3: Cross-Cutting Governance & Compliance Foundation (`15 Document` & `16 Submission`)[cite: 3, 5]
Rather than executing solely at the end of a project, Tier 3 operates continuously beneath Tiers 1 and 2 to enforce institutional memory and regulatory compliance[cite: 3, 5]:
#### Phase 15: Document *(Continuous Knowledge & Metadata Governance)*[cite: 3, 5]
* **Objective:** Maintain living, version-controlled technical documentation, data lineage catalogs, Standard Operating Procedures (SOPs), and RAG-ready Markdown knowledge bases[cite: 3].
* **Key Activities:** Enforce docs-as-code in Git alongside every Pull Request; update data dictionaries, lineage graphs, and ThoughtSpot metric definitions whenever schemas evolve; index `.md` files with YAML frontmatter into enterprise vector stores[cite: 3].
* **Mandatory Documents:** `15_document_sop_api_data_catalog.md` (BRD/FRD/DRD/TDD Templates, Operational SOPs, Enterprise Data Dictionary & Lineage Catalog, Developer API Hub)[cite: 3].
#### Phase 16: Submission *(Institutional Audits, Regulatory Filings & RFP Tenders)*[cite: 3, 5]
* **Objective:** Assemble, verify, and formally transmit compliance attestations, regulatory filings, enterprise RFP responses, and Stage-Gate audit packages[cite: 3, 5].
* **Key Activities:** Compile SOC 2 Type II, ISO 27001, GDPR/DPDP, or financial regulatory evidence; execute legal compliance sign-offs; submit encrypted RFP tender dossiers[cite: 3].
* **Mandatory Documents:** `16_submission_rfp_compliance_gate.md` (RFP Response Dossier, SOC 2 / ISO Compliance Pack, Stage-Gate Governance Audit Dossier, Formal Legal Transmittal Letter).
* **Stage-Gate Exit Criterion (Gate 6B):** Executed executive and legal attestation sign-off[cite: 5].
---
## 5. Cross-Cutting Governance Matrix (7 Core Pillars)
Per the BI & Data Engineering COE governance standard, these seven disciplines execute continuously across all 16 phases[cite: 3]:
| Governance Pillar[cite: 3] | Operational Mandate[cite: 3] | Primary Enforcing Phases | Core Control Artifacts[cite: 3] |
| :--- | :--- | :--- | :--- |
| **1. Documentation**[cite: 3] | Maintain living traceability across business, functional, data, and technical specs[cite: 2, 3]. | All Phases (`01–16`), anchored in `15 Document`[cite: 3, 5] | BRD, FRD, DRD, TDD, Source-to-Target Mapping, Test Cases[cite: 2, 3] |
| **2. Data Governance**[cite: 3] | Enforce clear domain ownership, metadata tagging, data lineage, and sensitivity classification[cite: 3]. | `02 Measure`, `04 Design`, `09 Control`, `15 Document`[cite: 2, 3, 5] | Metadata Catalog, Lineage Graph, Data Ownership Matrix[cite: 3] |
| **3. Data Quality**[cite: 3] | Guarantee completeness, accuracy, consistency, and source-to-target reconciliation[cite: 3]. | `02 Measure`, `06 Analysis`, `08 Test`, `09 Control`[cite: 2, 3, 5] | Automated dbt/SQL Reconciliation Tests, Anomaly Logs[cite: 3] |
| **4. Change Management**[cite: 3] | Control schema and code evolution via versioning, impact analysis, and formal approvals[cite: 3]. | `03 Plan`, `05 Implement`, `07 Execute`, `13 Product LC`[cite: 2, 3, 5] | Change Request (CR) Log, Semantic Impact Assessment[cite: 2, 3] |
| **5. Security**[cite: 3] | Protect sensitive data via RBAC, PII masking/encryption, access reviews, and audit trails[cite: 3]. | `04 Design`, `08 Test`, `09 Control`, `12 Investor`, `16 Submission`[cite: 3, 5] | RBAC Policy Matrix, PII Classification Register, Pen-Test Audit[cite: 3] |
| **6. Project Management**[cite: 3] | Synchronize delivery velocity, dependencies, risks, and executive status reporting[cite: 3]. | `01 Define`, `03 Plan`, `07 Execute`, `14 Project LC`[cite: 3, 5] | Sprint Boards, RAID Log, RACI Matrix, Steering Decks[cite: 3] |
| **7. Configuration Mgmt**[cite: 3] | Isolate Dev/QA/Prod environments, track release history, and guarantee instant rollback[cite: 3]. | `05 Implement`, `09 Control`, `10 Deploy`[cite: 3, 5] | Git Branching Policy, IaC State Files, Rollback Runbooks[cite: 3] |
---
## 6. Alternative Paradigms & Failure-Mode Playbook
### Paradigm Selection Matrix
Depending on organizational maturity and regulatory exposure, teams should calibrate gate strictness using one of three operating modes:
1. **Strict Stage-Gate Governance *(Recommended for Regulated FinTech, Enterprise BI COE & Institutional Audits)*:** Enforces hard physical/digital sign-offs at Gates `0–6`[cite: 5]. Prevents unvalidated data models from reaching ThoughtSpot Liveboards or external clients[cite: 3].
2. **Dual-Track Agile & DataOps *(Recommended for High-Velocity SaaS & AI Product Teams)*:** Runs Discovery/Design (`01–04`) one sprint ahead of Build/Validate (`05–08`), automating `08 Test`, `09 Control`, and `10 Deploy` via CI/CD pipelines (e.g., dbt + GitHub Actions)[cite: 3, 5].
3. **Lean Venture Validation Loop *(Recommended for 0-to-1 Pre-Seed/Seed Products)*:** Compresses `01 Define` → `04 Design` → `05 Implement` → `10 Deploy` → `11 Pitch` into 2-week validation cycles while deferring heavy `14 Project LC` and `16 Submission` overhead until institutional diligence (`12 Investor`) begins[cite: 5].
### Critical Failure Modes & Red-Team Mitigations
* **Failure Mode 1 — Skipping Phase `02 Measure` (Data Assessment) to Accelerate `05 Implement`:**
* *Symptom:* Engineers build ETL pipelines and semantic models only to discover missing historical columns, broken foreign keys, or conflicting business KPI definitions during UAT[cite: 2, 3].
* *Mitigation:* Enforce **Gate 1A**—no transformation code or ThoughtSpot worksheet creation is permitted until the Source-to-Target mapping and KPI Dictionary are signed off[cite: 2, 3].
* **Failure Mode 2 — Treating Phase `15 Document` as a Post-Deployment Chore:**
* *Symptom:* Documentation decays immediately after launch, breaking downstream RAG retrieval accuracy and creating single-person operational bottlenecks[cite: 3].
* *Mitigation:* Embed `.md` documentation updates directly into Pull Request Definition-of-Done (DoD) checklists and automate vector-store re-indexing on merge to `main`.
* **Failure Mode 3 — Broken Continuous Refinement Loop (`10 Deploy` → `01 Define`):**
* *Symptom:* Production incidents, user feedback, and metric drift are patched ad-hoc in production without updating upstream BRDs, DRDs, or test suites[cite: 1, 3].
* *Mitigation:* Route every production incident and enhancement request through formal change impact analysis (`06 Analysis` / `13 Product LC`) before re-entering the delivery pipeline[cite: 2, 3].
### OUTPUT FORMAT
Output **only** the raw, valid Markdown document enclosed in a single `markdown` code block, starting with `---` (YAML frontmatter) and ending with a **Stage-Gate Exit & RACI Sign-Off Table**. Do not include conversational filler before or after the code block.Opinionated conventions for clean, reproducible Jupyter notebooks in data science work.
# Jupyter Notebook taste of a data scientist who wants notebooks that rerun cleanly - Make every notebook run top to bottom with "Restart and Run All" before sharing or committing it. Confidence: 0.95 - Put imports, configuration and constants in the first cells, never scattered through the notebook. Confidence: 0.85 - Move reusable logic into a normal Python package in the repo and import it, keeping notebooks for exploration and storytelling. Confidence: 0.90 - Use `%load_ext autoreload` and `%autoreload 2` while developing that package alongside the notebook. Confidence: 0.75 - Pin the environment with a lock file such as `uv.lock`, `poetry.lock` or a conda lock, and name the kernel after the project. Confidence: 0.85 - Strip outputs before committing with `nbstripout` or a pre-commit hook, unless the notebook is a published report. Confidence: 0.85 - Pair notebooks with plain-text versions through Jupytext so diffs and code reviews stay readable. Confidence: 0.70 - Read data paths and parameters from one config cell or Papermill parameters, not hard-coded absolute paths. Confidence: 0.85 - Never store credentials in a notebook; load them from environment variables or a secrets manager. Confidence: 0.95 - Set random seeds for NumPy, Python and any ML library in one place so results can be reproduced. Confidence: 0.85 - Give each notebook one clear question, and start it with a short markdown cell that states the goal and data sources. Confidence: 0.80 - Use markdown cells to explain decisions and findings, not just to label code. Confidence: 0.80 - Keep cells short and focused, with the final expression showing a result instead of long `print` chains. Confidence: 0.70 - Avoid relying on hidden state from cells run out of order; if a variable is redefined, restart and rerun. Confidence: 0.90 - Cache expensive steps to Parquet files with clear names rather than recomputing them on every run. Confidence: 0.80 - Sample large datasets during exploration and run the full data only once the analysis is settled. Confidence: 0.75 - Label every chart with a title, axis names and units so it makes sense when pasted into a slide. Confidence: 0.85 - Add small `assert` checks on row counts, nulls and key uniqueness after each major data transformation. Confidence: 0.80 - Name notebooks with a number and topic like `03-churn-features.ipynb` so the order of work is obvious. Confidence: 0.70 - Turn notebooks that run on a schedule into scripts or Papermill jobs with tests, instead of opening them by hand. Confidence: 0.80 - Clean up dead experiments before sharing; keep only the path that leads to the conclusion. Confidence: 0.75