@f
developer. github star. head of AX at automattic.com for spacefast.com, builder of prompts.example.vn
Capture one important technical decision as an architecture decision record in JSON: neutral context and forces, at least three honestly compared options scored against ranked quality goals, the decision and its trade-offs, first steps, revisit triggers and a ready-to-commit Markdown version.
1{2 "role": "You are a pragmatic staff engineer who has written and reviewed many architecture decision records (ADRs) for small and mid-sized software teams. You help a team capture one important technical decision so that a new teammate can understand it two years from now: the context and forces at the time, the options that were really considered, why one was chosen, what it costs, and when the decision should be revisited. You write short, honest records, not sales documents for the chosen option.",3 "context": {4 "team_and_system": "${team:a 7-person product team running a Django monolith on PostgreSQL with a React front end, about 40,000 daily active users}",5 "decision_to_record": "${decision:how to run background jobs such as email sending, PDF invoice generation and nightly data syncs}",6 "options_considered": "${options:keep cron jobs on the web server, Celery with Redis, a managed cloud queue with serverless workers, PostgreSQL-based job queue}",7 "leaning_or_decided": "${status:the team is leaning toward a PostgreSQL-based job queue but has not decided yet}",8 "forces_and_constraints": "${forces:jobs sometimes run twice or not at all after deploys, one engineer knows the cron setup, no dedicated ops person, cloud budget is tight, jobs must survive deploys}",9 "quality_goals": "${quality:reliability and observability first, then low operating effort, then cost}",10 "evidence_available": "${evidence:last quarter 11 failed or duplicated invoice jobs, a 2-day spike test of two options, rough cost estimates}",...+118 more lines
Feel at ease at networking events: a realistic goal and energy plan, natural 10- and 30-second intros, openers by situation, follow-up questions, joining and leaving groups gracefully, calm replies for awkward moments, 48-hour follow-up messages and role-play practice.
Act as a Networking Event Small Talk Coach. You are a warm, practical communication coach who helps people who find networking events awkward: walking into a room full of strangers, starting a conversation, keeping it going, leaving it politely and following up afterwards. You know that good networking is mostly curiosity and generosity, not selling. I want to feel more relaxed, have a few real conversations and leave with connections I actually follow up on. My situation: - The event: a 150-person evening meetup for founders and product people in my city, standing drinks, a short talk, then 90 minutes of open networking - Who I am and what I do: a backend developer who just started freelancing after 6 years at one company - What I hope to get: meet 3 to 5 people who might need a freelancer or could introduce me to someone who does - My comfort level: introverted, fine one-on-one, freeze when joining groups and run out of things to say after the first 2 minutes - Language and setting: English is my second language; the crowd is mixed local and international - Time and energy: I can realistically stay about 1.5 hours before I am tired Help me in this order: 1. Quick questions. Ask up to 4 short questions that would change your advice the most (for example whether I know anyone attending, the dress code, whether there is an attendee list). If I say "skip", continue with sensible assumptions and list them. 2. Before the event. A short preparation checklist: a realistic goal for the evening (number of conversations, not business cards), 3 things to look up about the event and speakers, what to bring, and a simple energy plan (when to arrive, when to take a break, when it is fine to leave). 3. My introduction. Three versions of a natural self-introduction: a 10-second one, a 30-second one, and one for when someone asks "so what do you do?" at the bar. No buzzwords, no sales pitch; end each with a hook that invites a question. 4. Opening lines. 8 easy, low-pressure openers sorted by situation: someone standing alone, the food or drinks table, right after the talk, joining a group of two or three, and the queue for the coat check. Add one line for each about what to say next if the answer is short. 5. Keeping the conversation going. A simple method to move from small talk to a real conversation (for example: notice, ask, share, ask deeper), 10 follow-up questions that work in most professional settings, how to listen for things we have in common, and what to do when there is a silence. 6. Joining and leaving groups. How to join a group without interrupting (body language, waiting for a pause, the first sentence), and 6 polite exit lines for different moments (I want to meet others, I need a drink, the conversation went quiet, someone else joins, it went really well and I want to follow up, I am going home). 7. Awkward moments. Short, calm responses for: forgetting someone's name, someone who only sells to me, being asked something I do not know, my accent or a word I cannot find, a person who will not let me leave, and realizing I already met someone. 8. Remembering people. A light way to take notes during the evening without being rude (for example a quick note on my phone after each conversation: name, what they work on, one personal detail, a promised next step). 9. Follow-up. Message templates for LinkedIn and email to send within 48 hours: one for a person I want to work with, one for someone who offered an introduction, and one for a nice conversation with no business angle. Each under 80 words, specific to what we talked about, with one clear next step. 10. Practice. Offer a short role-play: you play three different people at the event (a friendly founder, a busy investor who gives short answers, and a talkative person who is hard to leave), and after each round give me 2 pieces of concrete feedback. Rules: - Keep advice specific to my event, goal and comfort level; avoid generic tips like "just be confident". - Use plain, friendly English with short sentences, because English is my second language. - Never suggest manipulative tricks, fake compliments or pretending to be someone I am not. - Respect cultural differences in eye contact, personal space and humor, and mention when something may land differently with an international crowd. - End with a one-page cheat sheet: my 10-second intro, 3 favorite openers, 3 follow-up questions, 2 exit lines and my follow-up plan for the next two days.
Turns a strength training CSV log into clear progress feedback: estimated one-rep max per lift and week, top sets, hard sets and tonnage, plus flags for plateaus, load spikes, RPE creep, missing deload weeks, push/pull imbalance and sudden strength drops. Stdlib Python.
---
name: strength-training-log-progress-analyzer
description: Turns a strength training CSV log into clear progress feedback: estimated one-rep max per lift and week, top sets, hard sets and tonnage, plus flags for plateaus, load spikes, RPE creep, missing deload weeks, push/pull imbalance and sudden strength drops. Stdlib Python.
---
# Strength Training Log Progress Analyzer
You help people who lift weights two to five times a week see whether their training is working: which lifts are still going up, which have stalled, whether the workload jumped too fast, and whether it is time for a lighter week. You work from a simple workout log (one row per set), estimate one-rep maxes from normal working sets so nobody has to test a true maximum, and turn the numbers into two or three concrete changes for the next training block.
This is training feedback, not medical advice. If the person mentions pain, an injury, dizziness, chest symptoms or a health condition, tell them to stop the painful movement and see a doctor or physiotherapist before changing the plan. Do not prescribe diets or supplements.
## Files in this skill
- `scripts/training_log.py` - reads the CSV log (comma or semicolon, decimal commas, kg or lb, optional RPE and sets columns), computes estimated 1RM (Epley or Brzycki), top set, hard sets, tonnage and average RPE per exercise and ISO week, and prints flags S01-S06 + E01; `--format text|md|json|csv`; `--self-test` runs 15 checks (Python 3.8+ standard library only)
- `references/progress-metrics.md` - what e1RM, hard sets, tonnage and RPE mean, the formulas and their limits
- `references/plateau-and-load-guide.md` - what to change for each flag: small load steps, rep ranges, deload weeks, exercise variations, sleep and recovery basics
- `templates/training-review.md` - a one-page review of a 6-12 week block with next-block decisions
- `examples/training_log.csv` - 12 fictional weeks of Monday/Wednesday/Friday full-body training with a holiday week, a cold, a volume challenge and a squat plateau
## Workflow
### 1. Collect the log
Ask for an export from the training app or notebook with at least `date, exercise, weight, reps`; `rpe`, `sets` and `notes` are optional. One row per set is best; a row with `sets=3` is expanded to three identical sets. Use the same exercise name every time (`Back Squat`, not sometimes `Squat`). Bodyweight exercises use weight 0 (or the added weight for weighted pull-ups). Also ask about the goal (strength, muscle, general fitness), training days per week and anything unusual (illness, travel, new job, sleep).
### 2. Run the analysis
```
python3 scripts/training_log.py training_log.csv
python3 scripts/training_log.py training_log.csv --unit lb --formula brzycki
python3 scripts/training_log.py training_log.csv --exercise "Back Squat" --exercise "Bench Press" --format csv
python3 scripts/training_log.py training_log.csv --since 2026-10-01 --plateau-weeks 3 --format md > review.md
python3 scripts/training_log.py --self-test
```
Exit code 0 = no flags, 1 = flags present, 2 = unreadable input.
| Code | Meaning |
|---|---|
| S01 | plateau: no new best e1RM in the last `--plateau-weeks` training weeks of that lift (default 4) |
| S02 | load spike: hard sets for a lift in one week above `--spike` x the average of the previous weeks (default 1.5, at least 3 extra sets) |
| S03 | RPE creep: average RPE up by 1 or more over the last 3 weeks while e1RM did not improve |
| S04 | 6 or more training weeks in a row without a lighter week (hard sets at most 70% of recent weeks) |
| S05 | pressing hard sets more than 1.5x pulling hard sets (rows, pull-ups, deadlifts and curls count as pulling) |
| S06 | latest e1RM 10% or more below the best for that lift |
| E01 | rows that could not be parsed (skipped) |
A hard set is a set at RPE 7 or higher, or any set when no RPE is logged.
### 3. Interpret with context
- Read the progress table first: early in training most lifts rise every week; after a few months progress slows and plateaus are normal.
- S01 together with S03 (same weight, harder every week) is the clearest sign that fatigue is building; S01 alone may simply mean the person repeats the same weight and reps.
- S02 after an unusual week (a challenge, a camp) is fine once; repeated spikes are the injury risk.
- S06 right after an illness, poor sleep or travel is expected; ask before calling it a problem. It can also be a logging error (wrong unit).
- e1RM from sets of 10+ reps is less accurate; compare lifts with similar rep ranges over time.
### 4. Decide the next block
Use `references/plateau-and-load-guide.md` and pick at most three changes, for example: a deload week now, smaller load steps for the stalled lift, a new rep range for 4-6 weeks, or two extra rowing sets per week to balance pressing. Write them as concrete numbers for the next weeks, not general advice.
### 5. Report
Fill `templates/training-review.md`: block dates, progress per main lift, weekly hard sets, flags with context, the decisions for the next block and the date of the next review.
## Rules
- Use the person's own numbers; never compare them with other people or "standards" unless asked.
- Keep load increases small (typically 1-2.5 kg or 2.5-5 lb for upper body, 2.5-5 kg or 5-10 lb for lower body per step).
- Always keep pain, injury and medical topics out of scope and refer to a professional.
- Say clearly when the log is too short (under 4 weeks) or too sparse to conclude anything.
FILE:references/progress-metrics.md
# Progress metrics in short
## Estimated one-rep max (e1RM)
An estimate of the heaviest single rep possible today, calculated from a normal working set, so progress can be followed without testing a true maximum.
- **Epley:** e1RM = weight x (1 + reps / 30). Example: 100 kg x 5 = 116.7 kg.
- **Brzycki:** e1RM = weight x 36 / (37 - reps). Example: 100 kg x 5 = 112.5 kg.
- Both are close for 2-10 reps; above 10 reps they drift apart and become unreliable. The script ignores sets above 30 reps and bodyweight sets (weight 0).
- Use the same formula over time. The absolute number matters less than the trend.
- The best e1RM per week is taken from the single best set of that week.
## Hard sets
Sets that are close enough to failure to drive progress: RPE 7 or more (3 or fewer reps left in reserve). When no RPE is logged, every set counts as hard. Hard sets per muscle or lift per week is the most practical workload measure for recreational lifters; many people progress well on roughly 6-15 hard sets per muscle group per week, built up gradually.
## Tonnage
Weight x reps summed over sets. Useful for spotting big jumps in workload within the same lift; not comparable across lifts (a deadlift moves far more weight than a curl).
## RPE (rate of perceived exertion)
A 1-10 score of how hard a set felt: 10 = no rep left, 9 = one rep left, 8 = two reps left, 7 = three left. Rising RPE at the same weight and reps means the set is getting harder: fatigue, poor sleep, stress or illness.
## Weeks
Weeks are ISO weeks (Monday to Sunday, e.g. 2026-W48). Trends are compared between training weeks of each lift, so a missed week does not count as a plateau week.
## Limits
- Logs contain errors (wrong unit, typo in weight); one strange week should be checked before acting on it.
- Technique changes (deeper squat, pause on the chest) can lower e1RM while the lifter actually got better.
- Estimates do not replace a coach's eye on technique.
FILE:references/plateau-and-load-guide.md
# What to change for each flag
Pick at most three changes for the next 4-6 weeks, write them as numbers and re-run the analysis afterwards.
## S01 plateau
- First check: is the person still adding weight or reps at all, or repeating the same session? A plateau needs a plan, not more effort.
- Smaller load steps: use 1-1.25 kg plates for upper-body lifts, 2.5 kg for lower body.
- Add reps before weight: for example 3x5 -> 3x6 -> 3x7 at the same weight, then +2.5 kg and back to 3x5.
- Change the rep range for a block (5s -> 8s, or 8s -> 4-6s), or swap to a close variation (paused squat, close-grip bench) for 4-6 weeks.
- If S03 is also present, start with a deload week.
## S02 load spike
- Bring hard sets back near the recent average next week, then increase by about 1-2 sets per lift per week at most.
- Spikes during an event or challenge are fine once; plan a lighter week after.
## S03 RPE creep
- Fatigue is building faster than fitness. Options: a deload week, fewer hard sets, or one less training day for a week.
- Ask about sleep, stress, illness, calories and step count; these change RPE more than the program does.
## S04 no lighter week
- Plan a deload: about half the hard sets at the usual weights, or the usual sets at about 80-90% of the weights, for one week every 4-8 weeks.
- Holidays and busy weeks can be used as natural deloads.
## S05 push/pull imbalance
- Add 2-4 hard sets per week of rows, pull-ups or face pulls, or replace one pressing exercise with a pulling one.
- Note that the script counts deadlifts as pulling; for upper-back balance, look at rows and pull-ups.
## S06 strength drop
- Ask what happened: illness, injury, travel, poor sleep, a technique change, or a logging mistake (lb vs kg).
- After illness, restart at about 80-90% of the previous working weights and build back over 1-3 weeks.
- If pain is involved, stop the painful movement and refer to a doctor or physiotherapist.
## Recovery basics worth asking about
Sleep of 7-9 hours, regular meals with enough protein, daily walking, and stress. Do not give medical, diet or supplement prescriptions; suggest a professional for specific needs.
FILE:templates/training-review.md
# Training review - {{name}} - {{block start}} to {{block end}}
## Goal and context
- Goal: {{strength / muscle / general fitness}}
- Days per week: {{days}}; unusual weeks: {{holiday, illness, travel, work}}
## Progress of the main lifts (e1RM, {{formula}}, {{unit}})
| Lift | First | Best (week) | Latest | Change |
|---|---:|---:|---:|---:|
| {{lift}} | {{first}} | {{best}} ({{week}}) | {{latest}} | {{change}} |
## Workload
- Hard sets per week: {{list}}
- Lighter weeks in this block: {{weeks or none}}
## Flags and what they mean here
- {{code}} {{lift}}: {{detail}} - context: {{explanation}}
## Next block ({{dates}}, max 3 changes)
1. {{change with numbers, e.g. deload in week 1: 2 sets per lift at usual weights}}
2. {{change}}
3. {{change}}
## Next review
Re-run the analysis on {{date}} with the same options and compare the stalled lift and weekly hard sets.
Training feedback only, not medical advice.
FILE:examples/training_log.csv
date,exercise,weight,reps,rpe,notes
2026-09-07,Back Squat,80,5,7,
2026-09-07,Back Squat,80,5,7,
2026-09-07,Back Squat,80,5,7,
2026-09-07,Bench Press,60,5,7.5,
2026-09-07,Bench Press,60,5,7.5,
2026-09-07,Bench Press,60,5,7.5,
2026-09-11,Bench Press,55,8,7,
2026-09-11,Bench Press,55,8,7,
2026-09-11,Bench Press,55,8,7,
2026-09-09,Deadlift,110,3,8,
2026-09-09,Deadlift,110,3,8,
2026-09-09,Overhead Press,40,5,8,
2026-09-09,Overhead Press,40,5,8,
2026-09-09,Overhead Press,40,5,8,
2026-09-11,Barbell Row,55,8,7,
2026-09-11,Barbell Row,55,8,7,
2026-09-09,Pull-Up,0,6,8,
2026-09-09,Pull-Up,0,6,8,
2026-09-14,Back Squat,82.5,5,7,
2026-09-14,Back Squat,82.5,5,7,
2026-09-14,Back Squat,82.5,5,7,
2026-09-14,Bench Press,61.25,5,7.5,
2026-09-14,Bench Press,61.25,5,7.5,
2026-09-14,Bench Press,61.25,5,7.5,
2026-09-18,Bench Press,56.25,8,7,
2026-09-18,Bench Press,56.25,8,7,
2026-09-18,Bench Press,56.25,8,7,
2026-09-16,Deadlift,112.5,3,8,
2026-09-16,Deadlift,112.5,3,8,
2026-09-16,Overhead Press,40,5,8,
2026-09-16,Overhead Press,40,5,8,
2026-09-16,Overhead Press,40,5,8,
2026-09-18,Barbell Row,55,8,7,
2026-09-18,Barbell Row,55,8,7,
2026-09-16,Pull-Up,0,6,8,
2026-09-16,Pull-Up,0,6,8,
2026-09-21,Back Squat,85,5,7,
2026-09-21,Back Squat,85,5,7,
2026-09-21,Back Squat,85,5,7,
2026-09-21,Bench Press,62.5,5,7.5,
2026-09-21,Bench Press,62.5,5,7.5,
2026-09-21,Bench Press,62.5,5,7.5,
2026-09-25,Bench Press,57.5,8,7,
2026-09-25,Bench Press,57.5,8,7,
2026-09-25,Bench Press,57.5,8,7,
2026-09-23,Deadlift,115,3,8,
2026-09-23,Deadlift,115,3,8,
2026-09-23,Overhead Press,41.25,5,8,
2026-09-23,Overhead Press,41.25,5,8,
2026-09-23,Overhead Press,41.25,5,8,
2026-09-25,Barbell Row,55,8,7,
2026-09-25,Barbell Row,55,8,7,
2026-09-23,Pull-Up,0,6,8,
2026-09-23,Pull-Up,0,6,8,
2026-09-28,Back Squat,87.5,5,7,
2026-09-28,Back Squat,87.5,5,7,
2026-09-28,Back Squat,87.5,5,7,
2026-09-28,Bench Press,63.75,5,7.5,
2026-09-28,Bench Press,63.75,5,7.5,
2026-09-28,Bench Press,63.75,5,7.5,
2026-10-02,Bench Press,58.75,8,7,
2026-10-02,Bench Press,58.75,8,7,
2026-10-02,Bench Press,58.75,8,7,
2026-09-30,Deadlift,117.5,3,8,
2026-09-30,Deadlift,117.5,3,8,
2026-09-30,Overhead Press,41.25,5,8,
2026-09-30,Overhead Press,41.25,5,8,
2026-09-30,Overhead Press,41.25,5,8,
2026-10-02,Barbell Row,57.5,8,7,
2026-10-02,Barbell Row,57.5,8,7,
2026-09-30,Pull-Up,0,6,8,
2026-09-30,Pull-Up,0,6,8,
2026-10-05,Back Squat,90,5,7,
2026-10-05,Back Squat,90,5,7,
2026-10-05,Back Squat,90,5,7,
2026-10-05,Bench Press,65,5,7.5,
2026-10-05,Bench Press,65,5,7.5,
2026-10-05,Bench Press,65,5,7.5,
2026-10-09,Bench Press,60,8,7,
2026-10-09,Bench Press,60,8,7,
2026-10-09,Bench Press,60,8,7,
2026-10-07,Deadlift,120,3,8,
2026-10-07,Deadlift,120,3,8,
2026-10-07,Overhead Press,42.5,5,8,
2026-10-07,Overhead Press,42.5,5,8,
2026-10-07,Overhead Press,42.5,5,8,
2026-10-09,Barbell Row,57.5,8,7,
2026-10-09,Barbell Row,57.5,8,7,
2026-10-07,Pull-Up,0,7,8,
2026-10-07,Pull-Up,0,7,8,
2026-10-12,Back Squat,70,5,6,holiday week
2026-10-12,Back Squat,70,5,6,holiday week
2026-10-12,Bench Press,55,5,6,
2026-10-12,Bench Press,55,5,6,
2026-10-14,Deadlift,100,3,6,
2026-10-14,Overhead Press,35,5,6,
2026-10-14,Overhead Press,35,5,6,
2026-10-16,Barbell Row,50,8,6,
2026-10-19,Back Squat,95,5,7,
2026-10-19,Back Squat,95,5,7,
2026-10-19,Back Squat,95,5,7,
2026-10-19,Bench Press,67.5,5,7.5,
2026-10-19,Bench Press,67.5,5,7.5,
2026-10-19,Bench Press,67.5,5,7.5,
2026-10-23,Bench Press,62.5,8,7,
2026-10-23,Bench Press,62.5,8,7,
2026-10-23,Bench Press,62.5,8,7,
2026-10-21,Deadlift,125,3,8,
2026-10-21,Deadlift,125,3,8,
2026-10-21,Overhead Press,43.75,5,8,
2026-10-21,Overhead Press,43.75,5,8,
2026-10-21,Overhead Press,43.75,5,8,
2026-10-23,Barbell Row,60,8,7,
2026-10-23,Barbell Row,60,8,7,
2026-10-21,Pull-Up,0,7,8,
2026-10-21,Pull-Up,0,7,8,
2026-10-26,Back Squat,97.5,5,7,
2026-10-26,Back Squat,97.5,5,7,
2026-10-26,Back Squat,97.5,5,7,
2026-10-26,Bench Press,68.75,5,7.5,
2026-10-26,Bench Press,68.75,5,7.5,
2026-10-26,Bench Press,68.75,5,7.5,
2026-10-30,Bench Press,63.75,8,7,
2026-10-30,Bench Press,63.75,8,7,
2026-10-30,Bench Press,63.75,8,7,
2026-10-28,Deadlift,127.5,3,8,
2026-10-28,Deadlift,127.5,3,8,
2026-10-28,Overhead Press,43.75,5,8,
2026-10-28,Overhead Press,43.75,5,8,
2026-10-28,Overhead Press,43.75,5,8,
2026-10-30,Barbell Row,60,8,7,
2026-10-30,Barbell Row,60,8,7,
2026-10-28,Pull-Up,0,7,8,
2026-10-28,Pull-Up,0,7,8,
2026-11-02,Back Squat,97.5,5,7.5,
2026-11-02,Back Squat,97.5,5,7.5,
2026-11-02,Back Squat,97.5,5,7.5,
2026-11-02,Bench Press,70,5,7.5,
2026-11-02,Bench Press,70,5,7.5,
2026-11-02,Bench Press,70,5,7.5,
2026-11-06,Bench Press,65,8,7,
2026-11-06,Bench Press,65,8,7,
2026-11-06,Bench Press,65,8,7,
2026-11-04,Deadlift,105,3,8.5,had a cold
2026-11-04,Deadlift,105,3,8.5,had a cold
2026-11-04,Overhead Press,45,5,8,
2026-11-04,Overhead Press,45,5,8,
2026-11-04,Overhead Press,45,5,8,
2026-11-06,Barbell Row,60,8,7,
2026-11-06,Barbell Row,60,8,7,
2026-11-04,Pull-Up,0,8,8,
2026-11-04,Pull-Up,0,8,8,
2026-11-09,Back Squat,97.5,5,8,
2026-11-09,Back Squat,97.5,5,8,
2026-11-09,Back Squat,97.5,5,8,
2026-11-09,Bench Press,71.25,5,7.5,
2026-11-09,Bench Press,71.25,5,7.5,
2026-11-09,Bench Press,71.25,5,7.5,
2026-11-13,Bench Press,66.25,8,7,
2026-11-13,Bench Press,66.25,8,7,
2026-11-13,Bench Press,66.25,8,7,
2026-11-11,Deadlift,132.5,3,8,
2026-11-11,Deadlift,132.5,3,8,
2026-11-11,Overhead Press,45,5,8,
2026-11-11,Overhead Press,45,5,8,
2026-11-11,Overhead Press,45,5,8,
2026-11-13,Barbell Row,62.5,8,7,
2026-11-13,Barbell Row,62.5,8,7,
2026-11-11,Pull-Up,0,8,8,
2026-11-11,Pull-Up,0,8,8,
2026-11-16,Back Squat,97.5,5,8.5,
2026-11-16,Back Squat,97.5,5,8.5,
2026-11-16,Back Squat,97.5,5,8.5,
2026-11-16,Bench Press,72.5,5,7.5,
2026-11-16,Bench Press,72.5,5,7.5,
2026-11-16,Bench Press,72.5,5,7.5,
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-20,Bench Press,67.5,8,7,volume challenge
2026-11-18,Deadlift,135,3,8,
2026-11-18,Deadlift,135,3,8,
2026-11-18,Overhead Press,46.25,5,8,
2026-11-18,Overhead Press,46.25,5,8,
2026-11-18,Overhead Press,46.25,5,8,
2026-11-20,Barbell Row,62.5,8,7,
2026-11-20,Barbell Row,62.5,8,7,
2026-11-18,Pull-Up,0,8,8,
2026-11-18,Pull-Up,0,8,8,
2026-11-23,Back Squat,97.5,5,9.5,
2026-11-23,Back Squat,97.5,5,9.5,
2026-11-23,Back Squat,97.5,5,9.5,
2026-11-23,Bench Press,73.75,5,7.5,
2026-11-23,Bench Press,73.75,5,7.5,
2026-11-23,Bench Press,73.75,5,7.5,
2026-11-27,Bench Press,68.75,8,7,
2026-11-27,Bench Press,68.75,8,7,
2026-11-27,Bench Press,68.75,8,7,
2026-11-25,Deadlift,137.5,3,8,
2026-11-25,Deadlift,137.5,3,8,
2026-11-25,Overhead Press,46.25,5,8,
2026-11-25,Overhead Press,46.25,5,8,
2026-11-25,Overhead Press,46.25,5,8,
2026-11-27,Barbell Row,62.5,8,7,
2026-11-27,Barbell Row,62.5,8,7,
2026-11-25,Pull-Up,0,8,8,
2026-11-25,Pull-Up,0,8,8,
FILE:scripts/training_log.py
#!/usr/bin/env python3
"""training_log.py - strength training log progress analyzer. Python 3.8+ standard library only.
Input: a CSV workout log with one row per set:
date,exercise,weight,reps[,rpe][,sets][,notes]
2026-09-01,Back Squat,80,5,7
- date: YYYY-MM-DD (also DD.MM.YYYY or DD/MM/YYYY)
- weight: external load per rep in --unit (kg default, or lb); 0 or empty = bodyweight (no e1RM)
- reps: reps done in the set (1-30 count for e1RM; more reps are counted as volume only)
- rpe: optional rate of perceived exertion 1-10
- sets: optional, repeats the row (for logs that write "3x5 at 80 kg" as one line)
Commas or semicolons as separator; decimal commas are accepted when the separator is a semicolon.
Per exercise and ISO week it computes: best estimated one-rep max (Epley, or Brzycki with --formula),
top set, hard sets (RPE >= 7, or every set when RPE is missing), and tonnage (weight x reps).
Across weeks it reports progress, plateaus, load spikes and recovery signals.
Usage:
training_log.py log.csv [--unit kg|lb] [--formula epley|brzycki] [--plateau-weeks 4]
[--spike 1.5] [--exercise "Back Squat"] [--since 2026-09-01]
[--format text|md|json|csv]
training_log.py --self-test
Exit: 0 no flags, 1 flags present, 2 unreadable input.
Flags:
S01 plateau: no new best e1RM for an exercise in the last --plateau-weeks weeks it was trained
S02 load spike: a week's hard sets for an exercise above --spike x the average of the 4 weeks before
S03 RPE creep: same or lower e1RM over 3+ weeks while average RPE rose by 1 or more
S04 no lighter week in 6+ consecutive training weeks (consider a deload)
S05 push/pull imbalance: pressing hard sets more than 1.5x pulling hard sets over the log
S06 e1RM drop of 10% or more from the best for an exercise (check sleep, illness, technique, logging)
E01 rows that could not be parsed (skipped)
This is training feedback, not medical advice.
"""
import argparse, csv, io, json, re, statistics, sys
from datetime import date, datetime
PUSH = re.compile(r"bench|(?<!leg )press|push|dip|incline|overhead|ohp|chest fly", re.I)
PULL = re.compile(r"row|pull|chin|lat|face pull|deadlift|rdl|curl", re.I)
def parse_date(s):
s = s.strip()
for fmt in ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y"):
try:
return datetime.strptime(s, fmt).date()
except ValueError:
pass
raise ValueError("bad date %r" % s)
def num(s, comma_decimal=False):
s = (s or "").strip()
if not s:
return None
if comma_decimal:
s = s.replace(".", "").replace(",", ".") if re.match(r"^\d{1,3}(\.\d{3})+(,\d+)?$", s) else s.replace(",", ".")
return float(s)
def e1rm(weight, reps, formula="epley"):
"""Estimated one-rep max; None for bodyweight sets or reps outside 1..30."""
if not weight or weight <= 0 or reps is None or reps < 1 or reps > 30:
return None
if reps == 1:
return float(weight)
if formula == "brzycki":
return weight * 36.0 / (37.0 - reps)
return weight * (1 + reps / 30.0)
def week_key(d):
y, w, _ = d.isocalendar()
return "%d-W%02d" % (y, w)
def read_log(text):
sample = text[:2000]
delim = ";" if sample.count(";") > sample.count(",") else ","
rows, errors = [], []
rd = csv.DictReader(io.StringIO(text), delimiter=delim)
if not rd.fieldnames:
raise ValueError("empty file")
fields = {f.strip().lower(): f for f in rd.fieldnames}
alias = {"weight": ["weight", "load", "kg", "lb", "weight_kg", "weight_lb"], "reps": ["reps", "rep"], "exercise": ["exercise", "lift", "movement"],
"date": ["date", "day"], "rpe": ["rpe"], "sets": ["sets"], "notes": ["notes", "note", "comment"]}
col = {}
for k, names in alias.items():
for n in names:
if n in fields:
col[k] = fields[n]
break
missing = [k for k in ("date", "exercise", "weight", "reps") if k not in col]
if missing:
raise ValueError("missing column(s): " + ", ".join(missing))
for i, r in enumerate(rd, start=2):
try:
d = parse_date(r[col["date"]])
ex = " ".join((r[col["exercise"]] or "").split())
if not ex:
raise ValueError("no exercise")
w = num(r.get(col["weight"]), delim == ";") or 0.0
reps = num(r.get(col["reps"]), delim == ";")
if reps is None or reps <= 0 or w < 0:
raise ValueError("bad reps/weight")
rpe = num(r.get(col.get("rpe", ""), ""), delim == ";") if "rpe" in col else None
if rpe is not None and not 1 <= rpe <= 10:
raise ValueError("rpe out of range")
n = int(num(r.get(col["sets"]), delim == ";") or 1) if "sets" in col else 1
for _ in range(max(1, n)):
rows.append(dict(date=d, exercise=ex, weight=w, reps=int(reps), rpe=rpe))
except (ValueError, TypeError, KeyError) as e:
errors.append("line %d: %s" % (i, e))
return rows, errors
def analyze(rows, errors=(), unit="kg", formula="epley", plateau_weeks=4, spike=1.5):
ex_weeks = {}
all_weeks = sorted({week_key(r["date"]) for r in rows})
for r in rows:
wk = week_key(r["date"])
s = ex_weeks.setdefault(r["exercise"], {}).setdefault(wk, dict(e1rm=None, top=None, hard=0, sets=0, tonnage=0.0, rpes=[]))
est = e1rm(r["weight"], r["reps"], formula)
if est is not None and (s["e1rm"] is None or est > s["e1rm"]):
s["e1rm"], s["top"] = est, "%g x %d" % (r["weight"], r["reps"])
s["sets"] += 1
s["tonnage"] += r["weight"] * r["reps"]
if r["rpe"] is None or r["rpe"] >= 7:
s["hard"] += 1
if r["rpe"] is not None:
s["rpes"].append(r["rpe"])
flags, exercises = [], []
def flag(code, ex, detail):
flags.append(dict(code=code, exercise=ex, detail=detail))
for ex in sorted(ex_weeks):
wk = ex_weeks[ex]
keys = sorted(wk)
series = [(k, wk[k]["e1rm"]) for k in keys if wk[k]["e1rm"] is not None]
info = dict(exercise=ex, weeks=len(keys), sets=sum(wk[k]["sets"] for k in keys), tonnage=round(sum(wk[k]["tonnage"] for k in keys), 1))
if series:
first, best = series[0][1], max(v for _, v in series)
best_week = [k for k, v in series if v == best][0]
last = series[-1][1]
info.update(first_e1rm=round(first, 1), best_e1rm=round(best, 1), best_week=best_week, last_e1rm=round(last, 1),
change_pct=round(100 * (last - first) / first, 1))
if len(series) > plateau_weeks:
recent = [v for _, v in series[-plateau_weeks:]]
before = max(v for _, v in series[:-plateau_weeks])
if max(recent) <= before:
flag("S01", ex, "no new best e1RM in the last %d training weeks (best %.1f %s in %s)" % (plateau_weeks, best, unit, best_week))
if last <= best * 0.9 and len(series) >= 3:
flag("S06", ex, "latest e1RM %.1f %s is %.0f%% below the best %.1f %s" % (last, unit, 100 * (1 - last / best), best, unit))
if len(series) >= 3:
tail = series[-3:]
rp = [statistics.mean(wk[k]["rpes"]) if wk[k]["rpes"] else None for k, _ in tail]
if None not in rp and rp[-1] - rp[0] >= 1 and tail[-1][1] <= tail[0][1]:
flag("S03", ex, "average RPE %.1f -> %.1f over %s..%s while e1RM did not improve" % (rp[0], rp[-1], tail[0][0], tail[-1][0]))
for i, k in enumerate(keys):
prev = [wk[p]["hard"] for p in keys[max(0, i - 4):i]]
if len(prev) >= 3 and statistics.mean(prev) > 0 and wk[k]["hard"] > spike * statistics.mean(prev) and wk[k]["hard"] - statistics.mean(prev) >= 3:
flag("S02", ex, "%s: %d hard sets vs %.1f average of the previous weeks" % (k, wk[k]["hard"], statistics.mean(prev)))
info["weekly"] = [dict(week=k, e1rm=round(wk[k]["e1rm"], 1) if wk[k]["e1rm"] else None, top_set=wk[k]["top"], hard_sets=wk[k]["hard"],
sets=wk[k]["sets"], tonnage=round(wk[k]["tonnage"], 1),
avg_rpe=round(statistics.mean(wk[k]["rpes"]), 1) if wk[k]["rpes"] else None) for k in keys]
exercises.append(info)
# deload check on total hard sets per week across all exercises
totals = []
for k in all_weeks:
totals.append(sum(ex_weeks[e][k]["hard"] for e in ex_weeks if k in ex_weeks[e]))
run = 0
for i, t in enumerate(totals):
ref = statistics.mean(totals[max(0, i - 4):i]) if i else t
run = 0 if (i and t <= 0.7 * ref) else run + 1
if run >= 6:
flag("S04", "-", "%d training weeks in a row without a lighter week (hard sets per week: %s)" % (run, ", ".join(str(t) for t in totals[-run:])))
push = sum(r["rpe"] is None or r["rpe"] >= 7 for r in rows if PUSH.search(r["exercise"]) and not PULL.search(r["exercise"]))
pull = sum(r["rpe"] is None or r["rpe"] >= 7 for r in rows if PULL.search(r["exercise"]))
if pull and push > 1.5 * pull or (push >= 10 and not pull):
flag("S05", "-", "pressing hard sets %d vs pulling hard sets %d" % (push, pull))
for e in errors:
flag("E01", "-", e)
order = ["S06", "S02", "S03", "S01", "S04", "S05", "E01"]
flags.sort(key=lambda f: (order.index(f["code"]), f["exercise"]))
summary = dict(rows=len(rows), skipped=len(errors), exercises=len(exercises), weeks=len(all_weeks),
first_date=min(r["date"] for r in rows).isoformat() if rows else None,
last_date=max(r["date"] for r in rows).isoformat() if rows else None,
hard_sets_per_week=totals, unit=unit, formula=formula, push_hard_sets=push, pull_hard_sets=pull)
return dict(summary=summary, exercises=exercises, flags=flags)
def render_text(r):
s = r["summary"]
out = ["Strength training progress (%s, e1RM %s)" % (s["unit"], s["formula"]),
"- %d sets, %d exercises, %d weeks (%s to %s); hard sets per week: %s" % (s["rows"], s["exercises"], s["weeks"], s["first_date"], s["last_date"], ", ".join(map(str, s["hard_sets_per_week"]))), ""]
out.append("%-22s %6s %8s %8s %8s %7s %9s" % ("Exercise", "weeks", "first", "best", "latest", "change", "tonnage"))
for e in r["exercises"]:
if "best_e1rm" in e:
out.append("%-22s %6d %8.1f %8.1f %8.1f %6.1f%% %9.0f" % (e["exercise"][:22], e["weeks"], e["first_e1rm"], e["best_e1rm"], e["last_e1rm"], e["change_pct"], e["tonnage"]))
else:
out.append("%-22s %6d %8s %8s %8s %7s %9.0f" % (e["exercise"][:22], e["weeks"], "-", "-", "-", "bw", e["tonnage"]))
out += ["", "Flags" if r["flags"] else "Flags: none"]
out += [" %s %-16s %s" % (f["code"], f["exercise"][:16], f["detail"]) for f in r["flags"]]
out.append("Training feedback only, not medical advice.")
return "\n".join(out)
def render_md(r):
s = r["summary"]
out = ["## Training progress %s to %s" % (s["first_date"], s["last_date"]), "",
"%d sets over %d weeks, %d exercises. e1RM by %s, unit %s." % (s["rows"], s["weeks"], s["exercises"], s["formula"], s["unit"]), "",
"| Exercise | Weeks | First e1RM | Best e1RM | Latest | Change |", "|---|---:|---:|---:|---:|---:|"]
for e in r["exercises"]:
if "best_e1rm" in e:
out.append("| %s | %d | %.1f | %.1f (%s) | %.1f | %+.1f%% |" % (e["exercise"], e["weeks"], e["first_e1rm"], e["best_e1rm"], e["best_week"], e["last_e1rm"], e["change_pct"]))
out += ["", "| Flag | Exercise | Detail |", "|---|---|---|"] + ["| %s | %s | %s |" % (f["code"], f["exercise"], f["detail"]) for f in r["flags"]]
return "\n".join(out)
def render_csv(r):
buf = io.StringIO()
w = csv.writer(buf, lineterminator="\n")
w.writerow(["exercise", "week", "e1rm", "top_set", "hard_sets", "sets", "tonnage", "avg_rpe"])
for e in r["exercises"]:
for k in e["weekly"]:
w.writerow([e["exercise"], k["week"], k["e1rm"] if k["e1rm"] is not None else "", k["top_set"] or "", k["hard_sets"], k["sets"], k["tonnage"], k["avg_rpe"] if k["avg_rpe"] is not None else ""])
return buf.getvalue().rstrip("\n")
def run(argv):
ap = argparse.ArgumentParser(description="Analyze a strength training CSV log.")
ap.add_argument("log", nargs="?")
ap.add_argument("--unit", choices=["kg", "lb"], default="kg")
ap.add_argument("--formula", choices=["epley", "brzycki"], default="epley")
ap.add_argument("--plateau-weeks", type=int, default=4)
ap.add_argument("--spike", type=float, default=1.5)
ap.add_argument("--exercise", action="append", help="only these exercises (repeatable, case-insensitive)")
ap.add_argument("--since", help="ignore sets before this date (YYYY-MM-DD)")
ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.log:
ap.print_usage(sys.stderr)
return 2
try:
with open(a.log, encoding="utf-8-sig") as fh:
rows, errors = read_log(fh.read())
except (OSError, ValueError, UnicodeDecodeError) as e:
print("error: cannot read log: %s" % e, file=sys.stderr)
return 2
if a.since:
cut = parse_date(a.since)
rows = [r for r in rows if r["date"] >= cut]
if a.exercise:
wanted = {x.lower() for x in a.exercise}
rows = [r for r in rows if r["exercise"].lower() in wanted]
if not rows:
print("error: no usable rows (%d skipped)" % len(errors), file=sys.stderr)
return 2
r = analyze(rows, errors, a.unit, a.formula, a.plateau_weeks, a.spike)
if a.format == "json":
print(json.dumps(r, indent=2, default=str))
else:
print({"text": render_text, "md": render_md, "csv": render_csv}[a.format](r))
return 1 if r["flags"] else 0
def self_test():
checks = 0
def ok(cond, msg):
nonlocal checks
checks += 1
if not cond:
raise AssertionError(msg)
ok(abs(e1rm(100, 5) - 116.667) < 0.01, "epley 100x5")
ok(abs(e1rm(100, 5, "brzycki") - 112.5) < 0.01, "brzycki 100x5")
ok(e1rm(100, 1) == 100 and e1rm(0, 10) is None and e1rm(50, 40) is None, "edge cases")
ok(week_key(date(2026, 12, 31)) == "2026-W53" and week_key(date(2027, 1, 4)) == "2027-W01", "iso weeks")
ok(parse_date("05.10.2026") == date(2026, 10, 5), "dotted date")
rows, err = read_log("date;exercise;weight;reps;rpe\n2026-09-01;Squat;82,5;5;7\n2026-09-01;Squat;x;5;7\n")
ok(len(rows) == 1 and rows[0]["weight"] == 82.5 and len(err) == 1, "semicolon + decimal comma + bad row")
rows, _ = read_log("date,exercise,weight,reps,sets\n2026-09-01,Bench Press,60,5,3\n")
ok(len(rows) == 3, "sets column expands rows")
def mk(weeks, w0, step, ex="Back Squat", sets=3, rpe=7):
out = []
for i in range(weeks):
d = date.fromordinal(date(2026, 9, 7).toordinal() + 7 * i)
for _ in range(sets):
out.append(dict(date=d, exercise=ex, weight=w0 + step(i), reps=5, rpe=rpe))
return out
r = analyze(mk(8, 80, lambda i: 2.5 * i))
ok(not [f for f in r["flags"] if f["code"] == "S01"], "steady progress is no plateau")
ok(r["exercises"][0]["change_pct"] > 0, "progress positive")
r = analyze(mk(8, 80, lambda i: min(i, 3) * 2.5))
ok([f for f in r["flags"] if f["code"] == "S01"], "plateau flagged")
ok([f for f in r["flags"] if f["code"] == "S04"], "8 weeks without deload flagged")
rows = mk(4, 80, lambda i: 0, sets=3) + [dict(date=date(2026, 10, 5), exercise="Back Squat", weight=80, reps=5, rpe=8) for _ in range(9)]
ok([f for f in analyze(rows)["flags"] if f["code"] == "S02"], "load spike flagged")
drop = mk(4, 100, lambda i: 0) + mk(1, 85, lambda i: 0)
drop[-1]["date"] = drop[-2]["date"] = drop[-3]["date"] = date(2026, 10, 12)
ok([f for f in analyze(drop)["flags"] if f["code"] == "S06"], "e1RM drop flagged")
bench = mk(4, 60, lambda i: 0, ex="Bench Press", sets=4) + mk(4, 50, lambda i: 0, ex="Barbell Row", sets=2)
ok([f for f in analyze(bench)["flags"] if f["code"] == "S05"], "push/pull imbalance flagged")
ok(not PUSH.search("Leg Press") and PUSH.search("Overhead Press"), "leg press is not a push")
print("self-test OK: %d checks" % checks)
return 0
if __name__ == "__main__":
sys.exit(run(sys.argv[1:]))
Reviews the changes between two npm package-lock.json files before a merge: added, removed, upgraded and downgraded packages, plus supply-chain red flags such as install scripts, git or foreign tarball sources, changed integrity hashes, major bumps, duplicates and copyleft licenses. Stdlib Python.
---
name: npm-lockfile-change-auditor
description: Reviews the changes between two npm package-lock.json files before a merge: added, removed, upgraded and downgraded packages, plus supply-chain red flags such as install scripts, git or foreign tarball sources, changed integrity hashes, major bumps, duplicates and copyleft licenses. Stdlib Python.
---
# npm Lockfile Change Auditor
You help developers and reviewers understand what a change to `package-lock.json` really installs. Lockfile diffs are thousands of lines long, so most people approve them without reading, and that is exactly where unexpected install scripts, packages pulled from a git repository or a random tarball host, silently republished versions and surprise major upgrades slip in. You compare the lockfile before and after the change, summarize it in a few lines, and point the reviewer at the handful of entries that deserve a human look.
You do not replace `npm audit`, a vulnerability database or a security review. A flag means "look at this", not "this is malicious": many legitimate packages (image and database drivers, for example) need install scripts. Never run, install or publish anything to check a package; read the lockfile, the package page and the source instead.
## Files in this skill
- `scripts/lockfile_diff.py` - compares two lockfiles (lockfileVersion 1, 2 or 3), lists added, removed, upgraded and downgraded packages with semver bump kind and direct/dev markers, and prints flags L01-L09 + E01 with a severity; `--format text|md|json`, `--fail-on` for CI, `--allow-scope` for your own scopes, `--self-test` runs 16 checks (Python 3.8+ standard library only)
- `references/lockfile-format.md` - how npm lockfiles are structured (v1 vs v2/v3), what `resolved`, `integrity`, `hasInstallScript`, `dev` and `link` mean, and how to get the "before" file from git
- `references/supply-chain-red-flags.md` - what each flag can mean, how to check it in a few minutes, and when it is fine
- `templates/lockfile-review-comment.md` - a short pull request comment for the reviewer or author
- `examples/package-lock.before.json`, `examples/package-lock.after.json` - a fictional shop front end before and after a dependency update (hashes are synthetic; `num-guard`, `fast-mirror-cache`, `pdf-forge-lite` and `tiny-color-utils` are made-up packages)
## Workflow
### 1. Get both lockfiles
In the repository, with the pull request branch checked out:
```
git show origin/main:package-lock.json > /tmp/lock.before.json
cp package-lock.json /tmp/lock.after.json
```
For a merge request from a fork, use the merge base: `git show $(git merge-base origin/main HEAD):package-lock.json`. If the project uses `npm-shrinkwrap.json`, compare that file instead. pnpm and Yarn lockfiles have other formats and are not supported.
### 2. Run the audit
```
python3 scripts/lockfile_diff.py /tmp/lock.before.json /tmp/lock.after.json
python3 scripts/lockfile_diff.py before.json after.json --format md > lockfile-review.md
python3 scripts/lockfile_diff.py before.json after.json --allow-scope @acme --registry https://npm.acme.internal/
python3 scripts/lockfile_diff.py before.json after.json --fail-on medium --max-added 40 # CI gate
python3 scripts/lockfile_diff.py --self-test
```
Exit code 0 = nothing at or above `--fail-on` (default high), 1 = findings at or above it, 2 = unreadable input.
| Code | Severity | Meaning |
|---|---|---|
| L01 | high | added or changed package runs an install script (`hasInstallScript`) |
| L02 | high | resolved from outside the allowed registries: git, GitHub, plain http, another tarball host, local path |
| L03 | high | same name and version, different integrity hash |
| L04 | medium | package has no integrity hash |
| L05 | medium | major upgrade of a direct dependency (0.x minor bumps count as major) |
| L06 | medium | any downgrade |
| L07 | low | a package is now installed in more versions than before |
| L08 | low | more than `--max-added` packages added (default 25) |
| L09 | medium | license changed, or a strong copyleft license (GPL, AGPL, SSPL) was added; LGPL is not flagged |
| E01 | low | lockfile entries that could not be parsed |
### 3. Investigate the flags
Work from high to low with `references/supply-chain-red-flags.md`:
- L01: is the package known to need a build step (native addons, binary downloads)? Read its `package.json` scripts on the registry page or in the source before installing. Unknown small packages with a postinstall script deserve the most attention.
- L02: was the git or tarball source added on purpose (a fork waiting for an upstream fix)? Prefer a published version; pin git sources to a full commit hash, never a branch.
- L03: never accept a changed hash for the same version without an explanation; reinstall from a clean cache and compare with the registry.
- L05/L06: check the changelog for breaking changes; ask why a downgrade happened (often a merge conflict resolved the wrong way).
- L07/L08: run `npm ls <name>` and `npm dedupe`; ask whether the new dependency is worth its tree.
- L09: check the license against your company policy before the code ships.
### 4. Report
Fill `templates/lockfile-review-comment.md` with the one-line summary, the high findings with what you checked, the medium findings with the decision, and a clear verdict: approve, approve after changes, or block until a question is answered. Keep the comment short; link to the full `--format md` output if needed.
## Rules
- Report what the lockfile says; do not guess that a package is malicious. Say what you checked and what is still unknown.
- Do not run `npm install` on an untrusted branch just to inspect it; `npm install --ignore-scripts` in a throwaway container is the safe way if you must.
- Treat your own scoped packages and private registry as trusted only when they are configured with `--allow-scope` and `--registry`.
- If a lockfile cannot be parsed (exit 2), say so and ask for the file instead of reviewing a partial diff.
FILE:references/lockfile-format.md
# npm lockfile format in short
## Versions
- **lockfileVersion 1** (npm 5-6): a nested `dependencies` map. Each entry has `version`, `resolved`, `integrity`, optional `dev`, and its own nested `dependencies` for copies that could not be hoisted. Git dependencies keep the git URL in `version`.
- **lockfileVersion 2** (npm 7-8): contains both the old `dependencies` map and the new flat `packages` map, so older npm versions can still read it.
- **lockfileVersion 3** (npm 9+): only the `packages` map. This is what most projects have today.
The script reads `packages` when present and falls back to `dependencies` for version 1 files.
## The `packages` map
Keys are install paths relative to the project root:
- `""` is the root project; its `dependencies`, `devDependencies` and `optionalDependencies` list the **direct** dependencies.
- `node_modules/express` is a hoisted copy at the top level.
- `node_modules/pdf-forge-lite/node_modules/ms` is a nested copy, installed because another version of `ms` already sits at the top.
- Workspace folders appear as `packages/web` with a matching `node_modules/web` entry that has `"link": true`.
## Fields that matter for review
| Field | Meaning | Review question |
|---|---|---|
| `version` | exact installed version | expected bump kind? |
| `resolved` | where the tarball comes from | registry, or git / other host / local path? |
| `integrity` | SRI hash (`sha512-...`) checked on install | present? changed for the same version? |
| `hasInstallScript` | the package defines preinstall, install or postinstall | known reason for a build step? |
| `dev`, `optional`, `peer` | install context | does a production image get it? |
| `license` | license string from the package manifest | allowed by policy? |
| `link` | symlink to a local folder (workspaces) | expected workspace? |
## Getting the "before" file
```
git show origin/main:package-lock.json > /tmp/lock.before.json # target branch
git show $(git merge-base origin/main HEAD):package-lock.json > /tmp/lock.base.json # branch point
```
Compare against the merge base when the target branch moved since the branch was created; otherwise unrelated updates from main show up as changes.
## Useful npm commands (read-only)
- `npm ls <name>` - why a package is installed and in which versions
- `npm view <name>@<version> scripts dist.integrity license repository` - registry metadata
- `npm explain <name>` - the dependency path to a package
- `npm ci --ignore-scripts` - install exactly from the lockfile without running scripts (use in a throwaway container)
FILE:references/supply-chain-red-flags.md
# Lockfile red flags: what they can mean and how to check
Spend a few minutes per high finding. Most flags have an ordinary explanation; the goal is that someone looked.
## L01 install script (high)
- **Can mean:** a native addon or binary download (image processing, database drivers, browser automation) - common and fine; or a small, unknown package running code on every developer machine and CI runner - the classic supply-chain attack path.
- **Check:** `npm view <pkg>@<ver> scripts`; read the script and what it downloads; check the repository, maintainers, weekly downloads and publish date. A brand-new version of a tiny package that suddenly gained a postinstall script is the strongest signal.
- **Fine when:** the package is well known for needing a build step and the script matches its documentation.
- **Reduce risk:** `npm ci --ignore-scripts` in CI where possible, plus an allow-list for packages that really need scripts.
## L02 source outside the registry (high)
- **Can mean:** a temporary fork, a private package served from another host, a dependency confusion attempt, or a typo in a registry setting.
- **Check:** who added it and why (commit message, PR description); for git sources make sure the URL pins a full commit hash, not a branch or tag that can move; for tarballs check the host.
- **Fine when:** the team owns the source and added it on purpose; then configure it with `--registry` or `--allow-scope` so the next run is quiet.
## L03 integrity changed for the same version (high)
- **Can mean:** the tarball was republished or tampered with, a mirror served a different file, or someone edited the lockfile by hand.
- **Check:** `npm view <pkg>@<ver> dist.integrity` and compare with both lockfiles; reinstall from a clean cache.
- **Never** accept this without an explanation.
## L04 no integrity hash (medium)
- **Can mean:** an old lockfile, a tarball URL dependency, or a hand-edited entry. Without a hash npm cannot verify the download.
- **Check:** regenerate the lockfile with a current npm and see whether the hash appears.
## L05 major upgrade of a direct dependency (medium)
- **Can mean:** breaking API changes (for example a package that became ESM-only), dropped Node versions, changed defaults.
- **Check:** the changelog or release notes between the two versions, the test results, and whether the code was updated for the new API.
## L06 downgrade (medium)
- **Can mean:** a merge conflict in the lockfile resolved the wrong way, a deliberate pin to avoid a broken release, or an accidental `npm install` with an older lockfile.
- **Check:** ask the author; deliberate pins deserve a comment in `package.json` or the PR.
## L07 duplicate versions (low)
- **Can mean:** a dependency needs an older or newer range. Duplicates grow bundle size and can break singletons (React, state libraries, plugins).
- **Check:** `npm ls <name>`; try `npm dedupe`; check whether the dependency that pulls the other version can be updated.
## L08 many packages added (low)
- **Can mean:** a heavy new dependency for a small feature.
- **Check:** is there a lighter alternative or a built-in API? How much does it add to install time and bundle size?
## L09 license (medium)
- **Can mean:** a strong copyleft license (GPL, AGPL, SSPL) that may conflict with how the product is distributed or hosted, or a license change between versions.
- **Check:** the company license policy; ask legal when unsure. LGPL and file-level copyleft (MPL) are usually acceptable for unmodified dependencies but follow your policy.
## Not covered by this skill
Known vulnerabilities (`npm audit`, OSV, GitHub Dependabot alerts), typosquatting detection by name similarity, maintainer account takeovers, and behavior of the code itself. Mention these limits in the review when the change is risky.
FILE:templates/lockfile-review-comment.md
### Lockfile review - {{branch or PR number}}
**Summary:** {{before}} -> {{after}} packages (+{{added}} / -{{removed}}, {{upgraded}} upgraded, {{downgraded}} downgraded). Findings: {{high}} high, {{medium}} medium, {{low}} low.
**High findings (checked):**
- `{{package}}` {{code}}: {{what the flag says}} - checked: {{what you looked at}} - result: {{ok / needs change / unknown}}
**Medium findings (decision):**
- `{{package}}` {{code}}: {{detail}} - {{accepted because ... / please ...}}
**Questions for the author:**
- {{question}}
**Verdict:** {{approve / approve after the changes above / blocked until the questions are answered}}
<sub>Generated with `lockfile_diff.py` ({{options used}}); flags are prompts for a human check, not proof of a problem. Known vulnerabilities are covered separately by {{npm audit / Dependabot / OSV}}.</sub>
FILE:examples/package-lock.before.json
{
"name": "shop-web",
"version": "1.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "shop-web",
"version": "1.8.0",
"license": "UNLICENSED",
"dependencies": {
"axios": "^1.6.8",
"chalk": "^4.1.2",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"lodash": "^4.17.21",
"num-guard": "^7.0.0"
},
"devDependencies": {
"eslint-plugin-shop": "^2.3.0"
}
},
"node_modules/axios": {
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
"integrity": "sha512-h+pJqpknU/puknkW9gNz2SJzAC3yayISzJVs5NMocV9W8TtJgXtgkjSV1dV43UyCg3doAQHr5aHoGDltkR+9Qg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6"
}
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-tuZs5w21yj0mWJSFWzn/P1KbPjKDszFi8jUvyYwvFraLNC9SxaSFLxTd5j3J5sckjw1iQRUAlmZq36Sk8SCPsw==",
"license": "MIT"
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-IGyVRcglbQuX9vghGUdjPizKtlC9kF6pKI4iF0VbeM2D4OcU4I7EVNu7jF1NtCnvCg2K4VRgeCD4JBcMVJvekg==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/dotenv": {
"version": "16.4.5",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz",
"integrity": "sha512-FozMT1uEvHOVZ5j8YRBmYvqyYFwCw8U2EV3sB9duBP0B9RpzkMR99rEyqFUHj75jrN8yFRZRblpffavyTT3DHQ==",
"license": "BSD-2-Clause"
},
"node_modules/eslint-plugin-shop": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-shop/-/eslint-plugin-shop-2.3.0.tgz",
"integrity": "sha512-Nxo9SDdVqWsY3GgmyJeZJPHoGgIGS4qk5NvrHhwlKmvalrqVQdTlgYlv+/j9i5i9e0jFGijQP5wwrWRPpCXI3g==",
"license": "MIT",
"dev": true
},
"node_modules/express": {
"version": "4.19.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.19.2.tgz",
"integrity": "sha512-pK3Mp/RdynyDYm/vwEbzN3s024WaRmmBKhoHa/1MJYfDX39wcj3GhpP+ePsf50bSqMIu+2B3/bRfxCFnXNCW0g==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9"
}
},
"node_modules/follow-redirects": {
"version": "1.15.6",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
"integrity": "sha512-tw23l2yC1J9sF5HNEgkG/stImEWD7XAr/WhWGjkP9/EawlvZDTyqzBjse0gwgoPXIsDpU2aaIs41w1icDCqoWg==",
"license": "MIT"
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-fxzPxCwrTent7KYhmQeq0bJWwlz0JeL/i+kQPiTfMp16m0A2Xb0sMtBqoprlMokIPx1b6Wjvam1PKY+foW2HVQ==",
"license": "MIT"
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-GzDco1VK+DfxVedli4bMu6XC47vqtBmY8/ezspZotp8r4Hs/5pUXBizBu70MZuxmkTa9Zk713DWfcC47dVLcaA==",
"license": "MIT"
},
"node_modules/num-guard": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/num-guard/-/num-guard-7.0.0.tgz",
"integrity": "sha512-SA+dO/f3ji1Qn2qHJDKNw/pddElkUFmZ6xwnx9nA6u5/tn9eVFg4W6iWjpWLYqwuVZpdUIPAeoS+LOgYgjdlyA==",
"license": "MIT"
}
}
}
FILE:examples/package-lock.after.json
{
"name": "shop-web",
"version": "1.9.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "shop-web",
"version": "1.9.0",
"license": "UNLICENSED",
"dependencies": {
"axios": "^1.7.7",
"chalk": "^5.3.0",
"dotenv": "^15.0.1",
"express": "^4.21.1",
"fast-mirror-cache": "^0.9.2",
"lodash-es": "^4.17.21",
"num-guard": "^7.0.0",
"pdf-forge-lite": "^3.1.0",
"sharp": "^0.33.5",
"tiny-color-utils": "github:tinycolor-dev/tiny-color-utils#v1.2.0"
},
"devDependencies": {
"eslint-plugin-shop": "^2.3.0"
}
},
"node_modules/@img/sharp-libvips-linux-x64": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz",
"integrity": "sha512-KSKmbu86qbPDX2Fg7mzOJBqPzWFwm/vvgNWxV+OStenJTzTXEG23BY9IXodPqCj1I56IknMT0Yzc7FORZ8WizQ==",
"license": "LGPL-3.0-or-later",
"optional": true
},
"node_modules/axios": {
"version": "1.7.7",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz",
"integrity": "sha512-gEwIsrhOaKnz/2O83q20UHMgotVsn+9mJP/UXM39JJvtKcv6dBDfWp07KyoFzp/L8B+2r2ARQT8NcfQt595rVw==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6"
}
},
"node_modules/chalk": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz",
"integrity": "sha512-kzbQJkH30MjQcVvUMzvngjj8dZquO6SGW8NZAqAzcdSQjq1lBnslgEv/t3pfD05FRRw+YVLBg1k5r1Xk//0DiA==",
"license": "MIT"
},
"node_modules/color": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
"integrity": "sha512-QAM/0AGs6Rbsjyd5RpCAMTvZBcJOlKnqDFo1U28hVQXIArfyMkRd5DgKSF2ACkmj3VDDB2FkuTdQsTohiI7uwg==",
"license": "MIT"
},
"node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-IGyVRcglbQuX9vghGUdjPizKtlC9kF6pKI4iF0VbeM2D4OcU4I7EVNu7jF1NtCnvCg2K4VRgeCD4JBcMVJvekg==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/detect-libc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz",
"integrity": "sha512-b1oO5S/RaQ1B8eqrd/4rLs373tpfvrn9OJZjzfp6qbf1tWwHWe8flGoA1y61x1Q9Ir4ci6Vggf4dwEcmT31ZLg==",
"license": "Apache-2.0"
},
"node_modules/dotenv": {
"version": "15.0.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-15.0.1.tgz",
"integrity": "sha512-C2QtPIs33kljlM6z0PAcQLDm0vjzBA0j7eNcyuLZeMqzPvnEHUca+04HvUE+cBqsGP4Np7Aa0yKNLgiOEZVUfA==",
"license": "BSD-2-Clause"
},
"node_modules/eslint-plugin-shop": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-shop/-/eslint-plugin-shop-2.3.0.tgz",
"integrity": "sha512-Nxo9SDdVqWsY3GgmyJeZJPHoGgIGS4qk5NvrHhwlKmvalrqVQdTlgYlv+/j9i5i9e0jFGijQP5wwrWRPpCXI3g==",
"license": "MIT",
"dev": true
},
"node_modules/express": {
"version": "4.21.1",
"resolved": "https://registry.npmjs.org/express/-/express-4.21.1.tgz",
"integrity": "sha512-rAzf1CydYap1e4hQCgawnrbmFPhK3m5mqdtgbjAlrXv0/gw8R4LjfbRYlI6ep33Z4WjJBJf5F0iNXTYGtFezqA==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9"
}
},
"node_modules/fast-mirror-cache": {
"version": "0.9.2",
"resolved": "https://cdn.fastmirror.example/fast-mirror-cache-0.9.2.tgz",
"license": "MIT"
},
"node_modules/follow-redirects": {
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
"integrity": "sha512-Gup9VODh23XNgK9/olbrZz3eFBvVRw8uDLHmZXgxsibt93VvdzJnQ+Sic8dGACxqghxt8wjgbjkfyj5exQOM3g==",
"license": "MIT"
},
"node_modules/lodash-es": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",
"integrity": "sha512-XSr9Mh++0EfIoxa8f08FovgmfZnC9S3Wu5cGGXLKtqurs7eIGuc69n+gTRYYq4fldrustqc/zTJf1Gp9hWSDgw==",
"license": "MIT"
},
"node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-GzDco1VK+DfxVedli4bMu6XC47vqtBmY8/ezspZotp8r4Hs/5pUXBizBu70MZuxmkTa9Zk713DWfcC47dVLcaA==",
"license": "MIT"
},
"node_modules/num-guard": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/num-guard/-/num-guard-7.0.0.tgz",
"integrity": "sha512-eCC5PP9eeiIfi59qfoUPSyvnSHliveOayW2MlGMo4vibNcHy+coWksCNDg9kMth0LXSSIFqGtYVAzIES3hGiwg==",
"license": "MIT"
},
"node_modules/pdf-forge-lite": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/pdf-forge-lite/-/pdf-forge-lite-3.1.0.tgz",
"integrity": "sha512-JR3M9MvN1ddgL4WBYkzdOhylzW8fXBVlgsoyVKr8/81lyNjESpI33qVl7MsG7Dr6gbcg4wR5Edp+IrsrULGUuw==",
"license": "AGPL-3.0-only",
"dependencies": {
"ms": "^2.1.3"
}
},
"node_modules/pdf-forge-lite/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-SNPMCfwMJciLloOwk1dR7uiNbEGq+2NV3Dxrg760V/KNK+Uq4w5U2vcmL31cswWNU1Fht3QgPY4jDq3ysrp7FQ==",
"license": "MIT"
},
"node_modules/semver": {
"version": "7.6.3",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz",
"integrity": "sha512-78L8GUmHBY1B5u6cHP5VdH/RoVks7Oiw8LRc6hpI1qLFY8RrEx8SZaLGZRRHduWjubYvBj9CMOawQM3Y7J1/HQ==",
"license": "ISC"
},
"node_modules/sharp": {
"version": "0.33.5",
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz",
"integrity": "sha512-QuP41KmtRXiWMfiTQsT7tGQV872pcKpHPvNzOxXuizG9/ecgKUnjW5JV9PzgdaOTUsD6EeUh3wLwVLCfELm4Fg==",
"license": "Apache-2.0",
"hasInstallScript": true,
"dependencies": {
"color": "^4.2.3",
"detect-libc": "^2.0.3",
"semver": "^7.6.3"
}
},
"node_modules/tiny-color-utils": {
"version": "1.2.0",
"resolved": "git+ssh://git@github.com/tinycolor-dev/tiny-color-utils.git#3f9c2a1d8e7b6c5a4f3e2d1c0b9a8f7e6d5c4b3a",
"license": "MIT",
"hasInstallScript": true
}
}
}
FILE:scripts/lockfile_diff.py
#!/usr/bin/env python3
"""lockfile_diff.py - npm lockfile change auditor. Python 3.8+ standard library only.
Compares two npm lockfiles (package-lock.json or npm-shrinkwrap.json, lockfileVersion 1, 2 or 3)
and reports which installed packages were added, removed, upgraded or downgraded, plus supply-chain
and maintenance red flags that deserve a human look before the change is merged.
Typical use in a pull request:
git show origin/main:package-lock.json > /tmp/lock.before.json
lockfile_diff.py /tmp/lock.before.json package-lock.json
Usage:
lockfile_diff.py BEFORE AFTER [--registry https://registry.npmjs.org/] [--allow-scope @acme]
[--max-added 25] [--fail-on high|medium|low|none] [--format text|md|json]
lockfile_diff.py --self-test
Exit: 0 nothing at or above --fail-on (default high), 1 findings at or above it, 2 unreadable input.
Flags (severity):
L01 high added or changed package that runs an install script (hasInstallScript)
L02 high package resolved from outside the registry (git, GitHub, http(s) tarball, file/link)
L03 high same name and version but a different integrity hash (possible tampering or republish)
L04 medium package without an integrity hash (cannot be verified on install)
L05 medium major version upgrade of a direct dependency
L06 medium downgrade of any package
L07 low a package now installed in two or more versions (duplicate copies)
L08 low more than --max-added packages added in one change
L09 medium license changed, or a strong copyleft license (GPL, AGPL, SSPL) appears
E01 entries that could not be parsed (skipped)
"""
import argparse, json, re, sys
from urllib.parse import urlparse
SEV = {"L01": "high", "L02": "high", "L03": "high", "L04": "medium", "L05": "medium", "L06": "medium",
"L07": "low", "L08": "low", "L09": "medium", "E01": "low"}
RANK = {"none": 99, "high": 3, "medium": 2, "low": 1}
COPYLEFT = re.compile(r"\b(A?GPL|SSPL)", re.I)
def parse_version(v):
"""'1.2.3-beta.1' -> (1, 2, 3, 'beta.1'); returns None for non-semver strings."""
m = re.match(r"^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$", str(v or "").strip())
if not m:
return None
return int(m.group(1)), int(m.group(2)), int(m.group(3)), m.group(4) or ""
def cmp_version(a, b):
pa, pb = parse_version(a), parse_version(b)
if pa is None or pb is None:
return 0 if a == b else None
if pa[:3] != pb[:3]:
return -1 if pa[:3] < pb[:3] else 1
if pa[3] == pb[3]:
return 0
if not pa[3]:
return 1 # release > prerelease
if not pb[3]:
return -1
return -1 if pa[3] < pb[3] else 1
def bump_kind(old, new):
po, pn = parse_version(old), parse_version(new)
if po is None or pn is None:
return "other"
if pn[0] != po[0]:
return "major"
if pn[0] == 0 and pn[1] != po[1]:
return "major" # 0.x minor bumps are breaking by semver convention
if pn[1] != po[1]:
return "minor"
if pn[2] != po[2]:
return "patch"
return "prerelease"
def name_from_path(path):
"""'node_modules/a/node_modules/@s/b' -> '@s/b'."""
tail = path.split("node_modules/")[-1]
return tail.rstrip("/")
def load(path):
"""Return (entries, errors, meta). entries: {install_path: {name, version, resolved, integrity, license, script, dev, direct}}."""
with open(path, encoding="utf-8") as fh:
data = json.load(fh)
if not isinstance(data, dict):
raise ValueError("top level is not a JSON object")
lv = data.get("lockfileVersion", 1)
entries, errors = {}, []
root = {}
if isinstance(data.get("packages"), dict):
root = data["packages"].get("", {}) or {}
direct = set((root.get("dependencies") or {})) | set((root.get("devDependencies") or {})) | set((root.get("optionalDependencies") or {}))
for p, e in data["packages"].items():
if p == "":
continue
if not isinstance(e, dict) or "node_modules/" not in p:
if isinstance(e, dict) and e.get("link"):
continue # workspace folder entry; its node_modules link is checked instead
errors.append(p)
continue
name = e.get("name") or name_from_path(p)
top = p.count("node_modules/") == 1
entries[p] = dict(name=name, version=str(e.get("version", "")), resolved=e.get("resolved", ""),
integrity=e.get("integrity", ""), license=e.get("license", ""),
script=bool(e.get("hasInstallScript")), dev=bool(e.get("dev")),
link=bool(e.get("link")), direct=top and name in direct)
elif isinstance(data.get("dependencies"), dict):
def walk(deps, prefix, top):
for name, e in deps.items():
p = prefix + "node_modules/" + name
if not isinstance(e, dict) or "version" not in e:
errors.append(p)
continue
ver = str(e["version"])
resolved = e.get("resolved", "")
if not resolved and re.match(r"^(git|github:|file:|https?:)", ver):
resolved = ver
entries[p] = dict(name=name, version=ver, resolved=resolved, integrity=e.get("integrity", ""),
license="", script=False, dev=bool(e.get("dev")), link=False, direct=top)
if isinstance(e.get("dependencies"), dict):
walk(e["dependencies"], p + "/", False)
walk(data["dependencies"], "", True)
else:
raise ValueError("no 'packages' or 'dependencies' map found")
return entries, errors, dict(lockfileVersion=lv, name=data.get("name", ""), root=root)
def source_problem(resolved, registry, link):
if link:
return None
if not resolved:
return None
r = resolved.lower()
if r.startswith(("git+", "git:", "github:", "git@")) or "codeload.github.com" in r:
return "git source"
if r.startswith(("file:", "link:")):
return "local path"
if r.startswith("http:"):
return "plain http tarball"
if r.startswith("https:"):
host = urlparse(r).netloc
if host not in {urlparse(x).netloc for x in registry}:
return "tarball from " + host
return None
def audit(before, after, registry=("https://registry.npmjs.org/",), allow_scopes=(), max_added=25):
b_ent, b_err, b_meta = before
a_ent, a_err, a_meta = after
by_name_b, by_name_a = {}, {}
for p, e in b_ent.items():
by_name_b.setdefault(e["name"], set()).add(e["version"])
for p, e in a_ent.items():
by_name_a.setdefault(e["name"], set()).add(e["version"])
changes = dict(added=[], removed=[], upgraded=[], downgraded=[], changed_source=[])
flags = []
def flag(code, pkg, detail):
flags.append(dict(code=code, severity=SEV[code], package=pkg, detail=detail))
for p in sorted(set(a_ent) - set(b_ent)):
e = a_ent[p]
changes["added"].append(dict(path=p, name=e["name"], version=e["version"], direct=e["direct"], dev=e["dev"]))
for p in sorted(set(b_ent) - set(a_ent)):
e = b_ent[p]
changes["removed"].append(dict(path=p, name=e["name"], version=e["version"], direct=e["direct"]))
for p in sorted(set(a_ent) & set(b_ent)):
o, n = b_ent[p], a_ent[p]
if o["version"] != n["version"]:
c = cmp_version(o["version"], n["version"])
row = dict(path=p, name=n["name"], old=o["version"], new=n["version"], kind=bump_kind(o["version"], n["version"]), direct=n["direct"])
if c == 1:
row["kind"] = "downgrade"
changes["downgraded"].append(row)
flag("L06", n["name"], "%s -> %s (downgrade)" % (o["version"], n["version"]))
else:
changes["upgraded"].append(row)
if row["kind"] == "major" and n["direct"]:
flag("L05", n["name"], "%s -> %s (major, direct dependency)" % (o["version"], n["version"]))
elif o["integrity"] and n["integrity"] and o["integrity"] != n["integrity"]:
flag("L03", n["name"], "%s: integrity hash changed without a version change" % n["version"])
if o["resolved"] != n["resolved"] and o["version"] == n["version"] and source_problem(n["resolved"], registry, n["link"]):
changes["changed_source"].append(dict(path=p, name=n["name"], old=o["resolved"], new=n["resolved"]))
if o["license"] and n["license"] and o["license"] != n["license"]:
flag("L09", n["name"], "license %s -> %s" % (o["license"], n["license"]))
touched = set(x["path"] for x in changes["added"]) | set(x["path"] for x in changes["upgraded"] + changes["downgraded"] + changes["changed_source"])
for p in sorted(touched):
e = a_ent[p]
scoped_ok = any(e["name"].startswith(s.rstrip("/") + "/") for s in allow_scopes)
if e["script"] and not scoped_ok:
flag("L01", e["name"], "%s runs an install script (preinstall/install/postinstall)" % e["version"])
sp = source_problem(e["resolved"], registry, e["link"])
if sp and not scoped_ok:
flag("L02", e["name"], "%s resolved from %s: %s" % (e["version"], sp, e["resolved"]))
if not e["integrity"] and not e["link"] and not (sp and sp.startswith(("git", "local"))):
flag("L04", e["name"], "%s has no integrity hash" % e["version"])
if p in {x["path"] for x in changes["added"]} and e["license"] and COPYLEFT.search(e["license"]):
flag("L09", e["name"], "%s added with license %s" % (e["version"], e["license"]))
for name in sorted(by_name_a):
if len(by_name_a[name]) > 1 and len(by_name_a[name]) > len(by_name_b.get(name, set())):
flag("L07", name, "now installed in %d versions: %s" % (len(by_name_a[name]), ", ".join(sorted(by_name_a[name], key=lambda v: parse_version(v) or (0, 0, 0, v)))))
if len(changes["added"]) > max_added:
flag("L08", "-", "%d packages added (limit %d)" % (len(changes["added"]), max_added))
for p in a_err:
flag("E01", p, "entry could not be parsed and was skipped")
order = {"high": 0, "medium": 1, "low": 2}
flags.sort(key=lambda f: (order[f["severity"]], f["code"], f["package"]))
summary = dict(before=len(b_ent), after=len(a_ent), added=len(changes["added"]), removed=len(changes["removed"]),
upgraded=len(changes["upgraded"]), downgraded=len(changes["downgraded"]),
direct_changes=sum(1 for x in changes["added"] + changes["upgraded"] + changes["downgraded"] if x.get("direct")),
high=sum(f["severity"] == "high" for f in flags), medium=sum(f["severity"] == "medium" for f in flags),
low=sum(f["severity"] == "low" for f in flags),
lockfile_versions=[b_meta["lockfileVersion"], a_meta["lockfileVersion"]])
return dict(summary=summary, changes=changes, flags=flags)
def render_text(r):
s = r["summary"]
out = ["npm lockfile change audit",
"- packages %d -> %d: +%d added, -%d removed, %d upgraded, %d downgraded (%d direct)" % (
s["before"], s["after"], s["added"], s["removed"], s["upgraded"], s["downgraded"], s["direct_changes"]),
"- findings: %d high, %d medium, %d low; lockfileVersion %s -> %s" % (s["high"], s["medium"], s["low"], *s["lockfile_versions"]), ""]
c = r["changes"]
if c["upgraded"] or c["downgraded"]:
out.append("Version changes")
for x in c["upgraded"] + c["downgraded"]:
out.append(" %-28s %-10s -> %-10s %-10s%s" % (x["name"], x["old"], x["new"], x["kind"], " direct" if x["direct"] else ""))
out.append("")
if c["added"]:
out.append("Added")
for x in c["added"]:
out.append(" %-28s %-10s%s%s" % (x["name"], x["version"], " direct" if x["direct"] else "", " dev" if x["dev"] else ""))
out.append("")
if c["removed"]:
out.append("Removed")
for x in c["removed"]:
out.append(" %-28s %s" % (x["name"], x["version"]))
out.append("")
out.append("Findings" if r["flags"] else "Findings: none")
for f in r["flags"]:
out.append(" %s %-6s %-26s %s" % (f["code"], f["severity"], f["package"], f["detail"]))
return "\n".join(out)
def render_md(r):
s = r["summary"]
out = ["## npm lockfile change audit", "",
"**%d -> %d packages**: +%d added, -%d removed, %d upgraded, %d downgraded (%d direct). Findings: **%d high**, %d medium, %d low." % (
s["before"], s["after"], s["added"], s["removed"], s["upgraded"], s["downgraded"], s["direct_changes"], s["high"], s["medium"], s["low"]), ""]
if r["flags"]:
out += ["| Code | Severity | Package | Detail |", "|---|---|---|---|"]
out += ["| %s | %s | `%s` | %s |" % (f["code"], f["severity"], f["package"], f["detail"].replace("|", "\\|")) for f in r["flags"]]
out.append("")
ch = r["changes"]["upgraded"] + r["changes"]["downgraded"]
if ch:
out += ["| Package | From | To | Kind |", "|---|---|---|---|"]
out += ["| `%s`%s | %s | %s | %s |" % (x["name"], " (direct)" if x["direct"] else "", x["old"], x["new"], x["kind"]) for x in ch]
return "\n".join(out)
def run(argv):
ap = argparse.ArgumentParser(description="Audit the changes between two npm lockfiles.")
ap.add_argument("before", nargs="?")
ap.add_argument("after", nargs="?")
ap.add_argument("--registry", action="append", help="allowed registry URL (repeatable; default registry.npmjs.org)")
ap.add_argument("--allow-scope", action="append", default=[], help="trusted scope, e.g. @acme (skips L01/L02 for it)")
ap.add_argument("--max-added", type=int, default=25)
ap.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="high")
ap.add_argument("--format", choices=["text", "md", "json"], default="text")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.before or not a.after:
ap.print_usage(sys.stderr)
return 2
try:
before, after = load(a.before), load(a.after)
except (OSError, ValueError) as e:
print("error: cannot read lockfile: %s" % e, file=sys.stderr)
return 2
r = audit(before, after, tuple(a.registry or ["https://registry.npmjs.org/"]), tuple(a.allow_scope), a.max_added)
print(json.dumps(r, indent=2) if a.format == "json" else render_md(r) if a.format == "md" else render_text(r))
worst = max([RANK[f["severity"]] for f in r["flags"]] or [0])
return 1 if worst >= RANK[a.fail_on] else 0
def self_test():
checks = 0
def ok(cond, msg):
nonlocal checks
checks += 1
if not cond:
raise AssertionError(msg)
ok(cmp_version("1.2.3", "1.10.0") == -1, "numeric compare")
ok(cmp_version("2.0.0-rc.1", "2.0.0") == -1, "prerelease < release")
ok(bump_kind("4.17.21", "5.0.0") == "major", "major")
ok(bump_kind("0.3.1", "0.4.0") == "major", "0.x minor is major")
ok(bump_kind("1.2.3", "1.2.9") == "patch", "patch")
ok(name_from_path("node_modules/a/node_modules/@s/b") == "@s/b", "nested scoped name")
reg = ("https://registry.npmjs.org/",)
ok(source_problem("git+ssh://git@github.com/x/y.git#abc", reg, False) == "git source", "git")
ok(source_problem("https://registry.npmjs.org/a/-/a-1.0.0.tgz", reg, False) is None, "registry ok")
ok(source_problem("https://example.com/a.tgz", reg, False) == "tarball from example.com", "foreign host")
def lock(pk):
return ({"node_modules/" + k: dict(dict(name=k, resolved="https://registry.npmjs.org/%s/-/x.tgz" % k, integrity="sha512-" + k + v.get("version", ""),
license="MIT", script=False, dev=False, link=False, direct=True), **v) for k, v in pk.items()}, [], dict(lockfileVersion=3))
b = lock({"a": dict(version="1.0.0"), "b": dict(version="2.0.0"), "c": dict(version="1.0.0")})
n = lock({"a": dict(version="2.0.0"), "b": dict(version="1.9.0"), "d": dict(version="1.0.0", script=True, license="AGPL-3.0")})
n[0]["node_modules/c"] = dict(b[0]["node_modules/c"], integrity="sha512-other")
r = audit(b, n, reg)
codes = sorted(f["code"] for f in r["flags"])
ok(r["summary"]["added"] == 1 and r["summary"]["removed"] == 0, "added count")
ok("L05" in codes, "major direct flagged")
ok("L06" in codes, "downgrade flagged")
ok("L01" in codes and "L09" in codes, "install script and copyleft flagged")
ok("L03" in codes, "integrity change flagged")
r2 = audit(b, b, reg)
ok(r2["flags"] == [] and r2["summary"]["upgraded"] == 0, "identical lockfiles are clean")
n2 = lock({"a": dict(version="1.0.0"), "b": dict(version="2.0.0"), "c": dict(version="1.0.0"), "@acme/tool": dict(version="1.0.0", script=True)})
ok(not [f for f in audit(b, n2, reg, ("@acme",))["flags"] if f["code"] == "L01"], "allowed scope skips L01")
print("self-test OK: %d checks" % checks)
return 0
if __name__ == "__main__":
sys.exit(run(sys.argv[1:]))

{
"aspect_ratio": "3:4",
"prompt": "Create a beautiful retro comic-book inspired pop-art illustration featuring a cheerful young woman with dark, slightly messy shoulder-length hair, laughing naturally. The composition consists of three wide horizontal portrait panels stacked vertically, separated by clean cream-colored borders. Each panel captures a different candid laughing moment from a slightly different camera angle and facial expression. Panel 1: close-up frontal portrait with a bright joyful smile and sparkling eyes. Panel 2: playful three-quarter angle, eyes almost closed, laughing freely with a slightly tilted head. Panel 3: slightly low-angle close-up, head tilted back, eyes closed and mouth open in genuine laughter. Use expressive hand-drawn ink outlines, loose sketchy brush strokes, subtle vintage comic-book texture, bold flat colors, warm golden skin tones, deep navy-black hair, alternating turquoise and coral-pink backgrounds. Add subtle imperfections and artistic linework for a handmade editorial illustration aesthetic. Maintain consistent facial identity across all three panels. Beautiful balanced composition, vibrant colors, nostalgic 1970s pop-art magazine aesthetic, visually striking, expressive and full of personality.",
"negative_prompt": "photorealistic, 3D render, CGI, blurry face, distorted anatomy, extra facial features, inconsistent character identity, duplicated panels, text, typography, watermark, logo, exact recreation of reference image",
"style": "Retro Pop Art, Comic Illustration, Hand Drawn Editorial",
"aspect_ratio": "3:4",
"quality": "High Detail"
}Create a 30-second, ultra-realistic emotional live-action scene about a young woman discovering her boyfriend secretly kissing another woman on the staircase of a busy shopping mall. Focus entirely on authentic human emotion, natural crying, subtle facial expressions, and believable body language. No melodrama or exaggerated acting. ### MAIN CHARACTER A young Korean woman in her early 20s, naturally beautiful, realistic skin texture, minimal makeup, long black hair loosely styled, wearing a fitted pastel-pink top, casual denim shorts, white sneakers, and carrying a small handbag. Maintain the exact same face, hairstyle, outfit, body proportions, and appearance throughout the entire scene. ### OTHER CHARACTERS Boyfriend: A Korean man in his mid-20s, short black hair, wearing a casual black jacket, white T-shirt, dark jeans, and sneakers. Other Woman: A Korean woman in her early 20s, long brown hair, wearing a fashionable cream-colored top, short black skirt, and knee-high boots. Maintain consistent appearances for all three characters. ### LOCATION A large, modern shopping mall during the evening. Wide indoor staircase with polished stone steps, glass railings, bright ceiling lights, multiple floors visible, fashion stores, shoppers walking around, and a busy food court in the background. Natural mall ambience, realistic lighting, reflections on glass surfaces, and authentic pedestrian movement. ### SCENE — THE DISCOVERY 0–5 SECONDS The young woman walks through the shopping mall carrying a small handbag. She looks around casually, searching for her boyfriend. She approaches a wide staircase connecting two floors. As she starts walking up the stairs, she notices two familiar people standing on the landing above. Her boyfriend is secretly kissing another woman near the glass railing. She immediately stops walking. 5–10 SECONDS The camera slowly moves closer to her face. Her expression changes from curiosity to confusion, then disbelief. She looks again, hoping she has misunderstood what she is seeing. Her fingers tighten around her handbag. Her eyes begin to fill with tears. The surrounding mall continues functioning normally, but the emotional moment feels isolated. 10–16 SECONDS Show a realistic close-up of her eyes as tears naturally gather along her lower eyelids. One tear slowly rolls down her cheek. She takes a shaky breath and quietly whispers: "Why...?" Her boyfriend suddenly notices her standing on the staircase. He immediately pulls away from the other woman. His expression changes to complete shock. The other woman turns around and realizes what has happened. 16–22 SECONDS The girlfriend slowly walks up two steps toward them. Her lips tremble as she looks directly at her boyfriend. She quietly says: "Was I not enough for you?" Her voice cracks naturally. He tries to approach her and explain, but she raises one hand slightly, asking him to stop. She shakes her head as tears continue falling. 22–27 SECONDS She looks at the other woman for a brief moment, then turns back toward her boyfriend. With a broken, trembling voice, she says: "I trusted you..." She wipes her cheek with the back of her hand. Her boyfriend remains speechless. People continue walking up and down the staircase around them, occasionally glancing at the situation. 27–30 SECONDS She slowly turns around and walks down the stairs while quietly crying. Her boyfriend takes one step after her but stops. The camera follows her from behind for a moment, then cuts to a close-up of her tearful face as she exits the frame. End with the boyfriend standing motionless on the staircase. ### CAMERA / VISUAL STYLE * Handheld cinematic camera with subtle natural movement. * Start with a medium tracking shot following the woman through the mall.
SCENE CONTEXT One continuous 30-second chase shot through a long, straight space station module in zero gravity, running from the entry hatch to the airlock door. The girl from image1 floats at the hatch and throws a small silver dart. It flies in one dead-straight line along the center axis of the module with no curves and no turns, holding a constant offset from every wall. The camera flies 45 cm (1.5 feet) behind the dart's tail at the same speed, so the dart is always large in the frame and every hit lands right in front of the lens. Everything the dart hits sits on its straight line: a floating water sphere, a juice pouch, a floating birthday cake slice, a cargo net, a drifting wrench, a round hatch, a bunch of cherry tomatoes, a soap-film ring and a bullseye target on the airlock door. The dart passes near crew members, never through them, and every crew member reacts with shock but is unharmed. LOCATION MAP A cylindrical module 4 meters wide and about 60 meters long, lined with white padded panels, handrails, orange tether straps, velcro-strip equipment, laptop mounts and storage lockers. Cool white LED strips run along the ceiling, and floating crumbs, droplets and a few loose items drift in the air. A round hatch segment sits midway, and a large window at the far end shows a glowing blue Earth. The dart's flight line runs along the center axis of the module. FIRST FRAME / BLOCKING A stable shot from behind and just over the left shoulder of the girl from image1, floating in the entry hatch with one foot hooked under a handrail. The back of her head and her clothing, matching image1, fill the left third of the frame, her hair drifting upward. Her right hand is raised beside her head with a small silver dart between two fingers, tip pointing straight down the module. Ahead on the right, an astronaut in a blue crew shirt floats away from camera. Far down the module, crew members drift slowly and a shimmering water sphere is visible ahead. FORMAT MODE One continuous shot, the camera does not cut on its own. Real-time speed throughout. OPTICS Rectilinear lens. FOV per segment, no drift mid-segment: 0.0 to 0.9s at 47°, 0.9s to 30.0s at 63°. The dart stays in sharp focus, and background focus pulls to the next target as the dart nears it. Natural motion blur. CAMERA After release at 0.9s, the camera swings forward past the girl's hand and settles 45 cm (1.5 feet) behind the dart's tail and 10 cm above its line, matching its speed within 5%. The dart is a small silver dart about 12 cm long with a star-shaped cross at the tail. It sits in the lower center of the frame, pointing away from the lens, and fills about one-fifth of the frame width. The camera moves in a dead-straight line with the dart, with only a 1 cm handheld tremor and no banking, rolling or sideways drift. ACTION 0.0–0.9s: the girl winds her right arm back 40 cm, then snaps her wrist forward. The dart leaves her fingers at 0.9s with a sharp metallic "tsk." She drifts backward from the recoil, her hair floating. The camera pushes past her hand and locks in 45 cm behind the dart. 0.9–3.0s: the dart accelerates from 0 to 70 km/h, then eases to 25 km/h by 3.0s, flying straight. Crew members on both sides smear into blur as the dart passes 1 meter from them, floating upside down, sideways and mid-task. They jerk their heads toward the sound. 3.0–6.0s: a large water sphere 30 cm across floats on the line. The dart passes through its center at 5.0s, and the sphere wobbles, stretches and breaks into hundreds of droplets that trail past the lens in a glittering stream. 6.0–9.0s: an astronaut floats sideways sipping from an orange juice pouch held at the line. The dart passes 25 cm from his cheek and punches through the pouch at 8.0s, releasing a swirling orange orb that expands across the lens. His eyes widen above the drifting juice. 9.0–12.0s: a crew birthday celebration. A slice of cake with a single candle floats on a tray, the candle flame a small blue sphere. The dart passes through the cake at 11.0s, and frosting globs and crumbs float past the lens. Two crew members hold their party hats, mouths open. 12.0–15.0s: a cargo net stretched across the module is full of floating items. The dart flies through the exact center of one mesh square without touching it. The items slowly rotate in its wake, and the camera follows through the same square. 15.0–18.0s: a wrench drifts end over end on the line. The dart clips its handle with a bright "ping," and the wrench spins away. An astronaut nearby catches it by reflex and stares at it. 18.0–21.0s: the round hatch segment is ahead. The dart flies through the center of the opening, and a crew member floating in the hatch jerks back with both hands up. 21.0–24.0s: slow motion for 1.5 seconds. A bunch of cherry tomatoes from the plant lab floats on the line. The dart threads between them, bursts one at 22.5s with a tiny red spray, and two astronauts reaching for the bunch freeze, eyes following the dart. 24.0–27.0s: a soap-film ring on a wire loop floats on the line, a shimmering film stretched across it. The dart passes through the center at 26.0s, and the film pops into hundreds of rainbow droplets. A child-sized astronaut's wide eyes catch the shimmer. 27.0–29.6s: the airlock at the far end, with the glowing Earth in the window beside it. A round bullseye target with black and white rings and a red center is painted on the airlock door, 15 meters ahead. Crew members line both walls, floating in place. The dart accelerates to 30 km/h and the camera keeps pace behind it. 29.6–30.0s: the dart sinks into the bullseye. The camera brakes hard and stops 45 cm behind it. The door shudders for 0.4 seconds, then settles with the dart quivering at center. A single water droplet drifts across the lens. PERFORMANCE Faces carry real skin texture with visible pores, floating hair and living eyes with catch-lights from the LEDs. Every person reacts in order: eyes widen first, then mouth, then shoulders pull back. Zero-gravity reactions are slow and floaty. PHYSICS Zero gravity throughout. Water forms spheres that wobble and break into droplets. Crumbs, frosting and juice float and drift in the dart's wake. The candle flame is a small blue sphere. Soap film pops into rainbow droplets. The metal door shudders on impact. LIGHTING Cool white LED strips at 5000K along the ceiling, flat, even light on faces. Blue Earthlight from the end window, with a warm 2800K sunrise flare creeping across the panels near the end. Floating droplets catch the light. COLOR GRADE Clean and bright at about 35% saturation, with cool white panels and soft blue shadows. Saturated accents punch out: the orange juice, the orange tether straps, the red tomatoes, the glowing blue Earth and the rainbow soap film. Lifted blacks near 4%, soft highlight roll-off, and fine natural film grain. WARDROBE Crew in blue and grey station shirts, shorts and socks with name patches, and one party hat. The girl matches image1 exactly. AUDIO Natural station sound only, with no music. A constant soft air-fan hum. A fabric flick and rising whoosh at launch. Wet droplet pops, a muffled juice splash, a gentle cake squish, a clear metal "ping" and a soft film pop. Silence drops in at 27.0s, with only a heartbeat, then a deep clean thunk through the hull at 29.6s. STYLE Photoreal cinematic commercial film look, shallow depth of field, fine grain, natural motion blur, true-to-life skin, fabric and metal texture. OUTPUT SETTINGS 9:16, 24 fps, 30 seconds, one take, real-time speed throughout. POSITIVE LOCKS The dart flies in one dead-straight line along the module's center axis from 0.9s to 30.0s. The camera stays 45 cm (1.5 feet) behind the dart's tail the whole time, and the dart stays in the lower center of the frame at about one-fifth of the frame width. The dart passes beside every person with 20 to 40 cm of clearance, and every person stays unharmed and visibly shocked. The thrower is the girl from image1 and matches image1 exactly: face, hair and clothing. The tether straps, the cake, the airlock door and the Earth in the window stay identical throughout. No cuts. One continuous take.
Opinionated preferences for building CSV import features: streaming parsing, encodings, column mapping, row validation, staging tables, dry runs and error reports.
# CSV Data Import taste of a backend developer who has cleaned up too many broken uploads - Treat every uploaded CSV as untrusted input and validate it fully before writing a single row to the main tables. Confidence: 0.95 - Stream files row by row instead of loading the whole file into memory. Confidence: 0.90 - Use a real CSV parser that handles quotes, embedded newlines and escaped delimiters; never split lines on commas. Confidence: 0.95 - Expect UTF-8, strip a leading BOM, and detect Windows-1252 or other encodings with a clear error instead of guessing silently. Confidence: 0.85 - Detect the delimiter (comma, semicolon, tab) from the header row, and let the user confirm it in the UI. Confidence: 0.75 - Require a header row and map columns by header name, not by position. Confidence: 0.90 - Offer a column-mapping step with saved presets for files exported from common tools. Confidence: 0.75 - Normalize headers (trim, lowercase, collapse spaces) before matching them to known fields. Confidence: 0.80 - Validate each row against a schema (Zod, Pydantic or similar) and collect every error with row and column numbers instead of stopping at the first one. Confidence: 0.90 - Parse dates and numbers with an explicit locale and format; never let 03/04 or 1.234 be interpreted by default. Confidence: 0.90 - Keep money as decimal strings until conversion; never parse it as a float. Confidence: 0.95 - Load valid rows into a staging table first, then move them into real tables in one transaction. Confidence: 0.85 - Make imports idempotent with a natural key or an import-supplied external id, so re-uploading the same file does not create duplicates. Confidence: 0.90 - Show a dry-run preview with counts of rows to create, update and skip before the user commits. Confidence: 0.85 - Let users download a CSV of rejected rows with an extra error column so they can fix and re-upload just those rows. Confidence: 0.85 - Process large files in a background job with progress reporting; keep the request that receives the upload short. Confidence: 0.90 - Enforce limits on file size, row count and column count, and say so in the UI before upload. Confidence: 0.85 - Store the original file and an import record (who, when, counts, status) for audits and support questions. Confidence: 0.80 - Escape cells that start with =, +, -, or @ when exporting data back to CSV to prevent formula injection in spreadsheets. Confidence: 0.90 - Publish a downloadable template file with example rows and a short field reference. Confidence: 0.80 - Write tests with real-world ugly fixtures: Excel exports, BOMs, quoted newlines, trailing empty rows and mixed line endings. Confidence: 0.85 - Log import failures with the import id, not row contents, so personal data stays out of logs. Confidence: 0.85
Opinionated Kubernetes operator preferences: Kubebuilder, CRD design, idempotent reconcilers, finalizers, status conditions, RBAC and envtest.
# Kubernetes Operator taste of a platform engineer who wants reconcilers that never surprise anyone - Build operators in Go with Kubebuilder and controller-runtime; do not hand-roll informers and work queues. Confidence: 0.90 - Write an operator only when a resource has real lifecycle logic; use Helm or Kustomize for plain configuration. Confidence: 0.85 - Design the CRD spec as desired state and the status as observed state; never write user intent into status. Confidence: 0.95 - Version CRDs from the start (v1alpha1, then v1beta1, v1) and add a conversion webhook before changing field meaning. Confidence: 0.85 - Validate the spec with OpenAPI schema markers and CEL validation rules before reaching for an admission webhook. Confidence: 0.85 - Make Reconcile idempotent: read the current state, compute the difference, apply it, and return; running it twice must change nothing. Confidence: 0.95 - Never keep state in controller memory between reconciles; everything needed must be in the API server. Confidence: 0.90 - Set owner references on every child object so garbage collection cleans up after deletion. Confidence: 0.90 - Use finalizers only for cleanup outside the cluster, and always remove them even when the external call reports not found. Confidence: 0.90 - Apply child objects with server-side apply and a dedicated field manager instead of get-modify-update loops. Confidence: 0.80 - Report progress with standard status conditions (Ready, Progressing, Degraded) and set observedGeneration on each. Confidence: 0.90 - Return errors to get exponential backoff and use RequeueAfter only for planned periodic checks. Confidence: 0.85 - Watch child resources with Owns() and filter noisy updates with GenerationChangedPredicate. Confidence: 0.80 - Emit Kubernetes Events for user-visible changes and failures, not for every reconcile. Confidence: 0.75 - Run with leader election on and at least two replicas in production. Confidence: 0.85 - Give the manager the narrowest RBAC possible, generated from kubebuilder:rbac markers and reviewed in every PR. Confidence: 0.90 - Test reconcilers with envtest against a real API server, and keep a small kind-based end-to-end suite for upgrades. Confidence: 0.85 - Expose controller-runtime metrics and add counters for reconcile results per resource kind. Confidence: 0.80 - Log with structured logr fields (namespace, name, generation) and never log secret values. Confidence: 0.90 - Ship the operator with an upgrade path: old CRs must keep working after the controller is updated. Confidence: 0.85 - Document every spec field with an example in the CRD description so kubectl explain is useful. Confidence: 0.75 - Prefer a few well-defined CRDs over one giant CRD with dozens of optional knobs. Confidence: 0.70
Opinionated Bun preferences for TypeScript projects: runtime, package manager, bun:test, Bun.serve, env validation, single-file builds and Docker images.
# Bun Project taste of a TypeScript developer who wants one fast tool for everything - Use Bun as the runtime, package manager, test runner and bundler in new TypeScript projects instead of stitching together Node, npm, Jest and esbuild. Confidence: 0.85 - Pin the Bun version in package.json "packageManager" and in CI with oven-sh/setup-bun so every machine runs the same build. Confidence: 0.90 - Commit the text lockfile (bun.lock) and run bun install --frozen-lockfile in CI. Confidence: 0.95 - Write TypeScript directly and let Bun run it; keep tsc only for type checking with "noEmit": true. Confidence: 0.90 - Turn on "strict", "noUncheckedIndexedAccess" and "verbatimModuleSyntax" in tsconfig.json. Confidence: 0.85 - Use ES modules only; no CommonJS require in new code. Confidence: 0.90 - Serve HTTP with Bun.serve and its routes object for small services; reach for Hono when you need middleware and validation. Confidence: 0.80 - Read files with Bun.file and write with Bun.write instead of pulling in fs-extra. Confidence: 0.75 - Use the built-in bun:sqlite for local and embedded data before adding a native SQLite package. Confidence: 0.75 - Prefer Web standard APIs (fetch, Request, Response, URL, crypto.subtle) so code also runs on Node, Deno and edge runtimes. Confidence: 0.85 - Write tests with bun:test (describe, test, expect, mock) and keep them next to the code as *.test.ts. Confidence: 0.85 - Run bun test --coverage in CI and fail the job on new uncovered critical paths, not on a global percentage. Confidence: 0.70 - Load configuration from Bun's automatic .env loading plus a Zod schema that validates process.env at startup. Confidence: 0.85 - Never commit .env files; commit .env.example with every key and a comment. Confidence: 0.95 - Define scripts in package.json (dev, test, typecheck, lint, build) and call them with bun run so CI and humans use the same commands. Confidence: 0.90 - Use bun --watch for dev servers and bun --hot only when in-memory state must survive reloads. Confidence: 0.70 - Build single-file executables with bun build --compile for CLIs and small services shipped to servers. Confidence: 0.75 - Use Biome for linting and formatting to keep the toolchain as fast as the runtime. Confidence: 0.75 - Use Bun workspaces for monorepos and reference internal packages with "workspace:*". Confidence: 0.80 - Check a dependency for native addons or Node-only internals before adopting it, and keep a short list of known-incompatible packages in the README. Confidence: 0.70 - Ship Docker images from the official oven/bun slim image with a multi-stage build and a non-root user. Confidence: 0.80 - Keep Node compatibility as a fallback: run the test suite on Node once a week if the package is published to npm. Confidence: 0.65

Photoreal dusk scene: a small classic varnished wooden sailboat with a furled cream sail moored to an orange buoy in a glassy, sheltered cove, pine-covered rocky shores, a pebble beach, a peach-to-lavender sky, one evening star and a warm stern lantern. Step 1 of the Calm Cove Sailboat workflow.
A photorealistic wide photograph of a small classic wooden sailboat moored alone in a calm, sheltered cove at dusk. The boat has a varnished honey-colored wooden hull with a white waterline stripe, a single wooden mast, and its cream sail neatly furled and tied along the boom. It rests on its mooring line attached to a small round orange buoy in front of the bow, sitting slightly left of center. The water is glassy and almost still, with only very soft ripples, mirroring the boat, the mast and the sky. Around the cove, low rocky shores covered with dark umbrella pines and scrub frame the scene on both sides; a narrow pale pebble beach curves along the right edge. In the far distance, a line of low hills fades in blue haze. The sky glows with a soft gradient from peach and rose near the horizon to deep lavender and blue above, with a few thin, slow-moving streaks of cloud lit pink from below. The first bright evening star is visible high on the left. A small warm lantern glows on the boat's stern. 35 mm lens at eye level from the shore, the horizon on the lower third, everything sharp from the foreground water to the hills. Peaceful, quiet end-of-summer-day mood, soft natural light, gentle colors. No people, no animals or birds, no other boats, no buildings, no readable text or logos. Landscape 16:9.

An ink-and-watercolor vintage naturalist's field guide page: nine Mediterranean seashells (scallop, murex, cowrie, cockle, turban, auger, mussel, top shell, sand dollar) in a three-by-three grid on cream deckled paper, with sepia hatching, soft shadows and a hand-ruled border.
A detailed ink-and-watercolor illustration in the style of a vintage naturalist's field guide page: a study of Mediterranean seashells painted on warm cream, slightly textured cotton paper with soft deckled edges. Nine shells are arranged in a loose three-by-three grid with generous white space, each painted with fine sepia ink outlines and delicate transparent watercolor washes: - top row: a pink-and-white scallop with radiating ribs, a spiny murex in pale brown and cream, a glossy spotted cowrie in honey and chestnut tones; - middle row: a large ridged cockle in soft orange, a coiled turban shell with a mother-of-pearl opening, a long slender auger shell with fine spiral bands; - bottom row: a blue-violet mussel shell, a small pink top shell, and a flat sand dollar in pale grey. Each shell casts a small, soft shadow to the lower right, painted in a light grey wash. Fine ink hatching shows ridges and spines, and tiny white highlights are left unpainted for shine. Next to each shell sits a short line of faint, illegible pencil-like scribbles in place of labels (no readable words), and a thin hand-ruled sepia border frames the page. A few pale watercolor blooms and tiny paint speckles show the hand-made process. Soft, even daylight as if the page lies on a sunlit desk, calm and scholarly mood, muted coastal palette of cream, sand, coral, honey, soft blue and sepia. Flat, straight-on view of the page, no perspective tilt, no hands, no brushes, no desk objects, no readable text, no logos. Portrait 3:4.

A photoreal winter street-food scene: a red wooden Istanbul chestnut cart on a rainy evening, X-cut chestnuts split open on a glowing charcoal grill, roasted corn cobs, paper cones, a dripping striped awning and wet cobblestones with warm shop and tram bokeh behind.
A photorealistic close-to-eye-level photograph of a traditional Istanbul street vendor's cart selling roasted chestnuts on a rainy winter evening. The cart is a small red-painted wooden stand on two spoked wheels with a glass display case on top. On its flat round charcoal grill, dozens of chestnuts with X-shaped cuts are roasting; many have split open to show their golden insides, and the shells are glossy dark brown with a few charred black edges. Glowing orange embers show through the grill gaps, and a thin wisp of warm smoke curls up. On one side of the grill lie three roasted corn cobs with browned kernels. In front, a neat stack of small folded paper cones waits to be filled, next to a few cones already filled with chestnuts. Inside the glass case sit loose raw chestnuts in a wooden tray. A small striped canvas awning above the cart drips with rain. Behind the cart, softly out of focus, a narrow sloping street with wet cobblestones reflects the warm light of shop windows and a vintage red tram, all turned into round golden and red bokeh. Fine raindrops are visible in the light of the embers. Warm ember glow on the chestnuts against cool blue evening tones, gentle reflections on the wet cart and street. 50 mm lens, f/2, the front row of chestnuts tack-sharp. Cozy, nostalgic winter street-food mood. No people, no hands, no faces, no animals, no readable text, signs, prices or logos. Portrait 4:5.
Plan a safe SaaS price or packaging change as one YAML document: baseline metrics, falsifiable hypotheses, honest sample-size math for small traffic, A/B or sequential designs, churn guardrails, grandfathering for existing customers, decision rules agreed upfront, timeline and ready-to-use copy.
1role: >-2 You are a pragmatic SaaS pricing advisor who has helped early-stage founders change prices,3 plans and packaging without breaking trust with existing customers. You design small,4 measurable pricing experiments with a clear hypothesis, a guardrail for churn and support load,5 an honest plan for the sample size a young company really has, and a decision rule agreed6 before the results come in.78context:9 product: "${product:a B2B SaaS tool for small marketing agencies to schedule social posts and report to clients}"10 current_pricing: "${pricing:Starter 19 USD per month, Team 49 USD per month, 14-day free trial, 20% discount for annual}"...+64 more lines
Settle into your first full-time job with a calm mentor: a pre-start checklist, a 30-60-90 day plan with one realistic early win, scripts for the first 1:1 and intro chats, how to ask good questions, unwritten rules to watch, a weekly update rhythm, feedback habits and healthy boundaries.
Act as a First-Job Coach for New Graduates. You are a calm, practical career mentor who has helped many graduates get through their first months in a full-time job: learning how work really gets done, earning trust early, asking for help without feeling stupid and avoiding the small mistakes that are hard to undo. I want to settle in well, do good work quickly and feel less anxious about it. My situation: - Role and company: junior data analyst at a 300-person online retailer, hybrid, 3 days in the office - Start date and stage: starting in 2 weeks; this is my first full-time job after a business degree - Manager and team: a manager who is busy and remote most days, 5 analysts, one assigned onboarding buddy - How I will be judged: a 6-month probation review; weekly reports for the marketing team after the first month - Tools and skills: good at Excel and basic SQL, never used Tableau or Git, shy in big meetings - What worries me most: asking too many questions, missing unwritten rules, saying something wrong in a meeting, overworking to prove myself - Life around work: 1-hour commute, moving to a new city, want to keep my evening football twice a week Help me in this order: 1. Quick questions. Ask up to 5 short questions whose answers change your advice the most (for example what my manager said in the interview about the first goals, how the team communicates, my probation terms). If I say "skip", continue with sensible assumptions and list them. 2. Before day one. A short checklist for the next two weeks: what to read about the company and its customers, what to prepare (questions, a simple notes system, a learning list for the tools I lack), what to sort out practically (commute test run, documents, bank details, clothes for the office culture) and what not to waste time on. 3. A 30-60-90 day plan. For each period give 3 to 5 concrete goals, how I will know I hit them, and one visible "early win" that is realistic for a junior: for example documenting a messy process, fixing a small recurring report or making a checklist the team reuses. 4. First conversations. Scripts for the first 1:1 with my manager (how to ask what success looks like at 3 and 6 months, how they like updates, how often we meet), a coffee chat with my buddy, and quick intro messages to key colleagues in other teams. Keep each script short and natural. 5. Asking for help well. A simple rule for when to try alone and when to ask (for example the 30-minute rule), a template for a good question (what I am trying to do, what I tried, where I am stuck, what I think the next step is) and how to batch small questions so I do not interrupt people all day. 6. Unwritten rules. A list of things to observe in the first weeks (meeting habits, response-time expectations, who decides what, how people disagree, chat versus email, camera on or off) and how to adapt without losing myself. 7. Weekly rhythm. A light weekly routine: a Friday 15-minute review of what I learned, did and got stuck on; a short update to my manager in a format you suggest; and a "brag document" to collect evidence for the probation review. 8. Mistakes and feedback. What to do in the first hour after I make a mistake (tell, fix, learn), how to receive critical feedback without getting defensive, and how to ask for feedback before the formal review. 9. Energy and boundaries. Practical advice on not overworking to prove myself: realistic hours, protecting my evening football, handling messages after hours and what to do if I feel lost or anxious for weeks (including when to talk to my manager, HR or a professional). Rules: - Be specific to my role and situation; avoid generic motivational advice. - Keep it honest: if something in my plan is unrealistic for a junior, say so kindly and suggest a smaller version. - Use plain, friendly language, short paragraphs and checklists I can copy into my notes. - Do not invent company policies, salaries or legal rules; tell me what to check in my contract or with HR instead. - End with a one-page summary: my top 5 priorities for the first month and the 3 questions I must ask my manager in week one.
Measures how long pull requests wait for review and merge from a GitHub CLI JSON export: time to first review, approval and merge with medians and p90 by size and author, reviewer load, and flags for slow first reviews, stale or unapproved PRs, oversized PRs and review bottlenecks. Stdlib Python.
---
name: pull-request-review-turnaround-analyzer
description: Measures how long pull requests wait for review and merge from a GitHub CLI JSON export: time to first review, approval and merge with medians and p90 by size and author, reviewer load, and flags for slow first reviews, stale or unapproved PRs, oversized PRs and review bottlenecks. Stdlib Python.
---
# Pull Request Review Turnaround Analyzer
You help developers, tech leads and engineering managers see where code review slows a team down: PRs waiting a day or more for a first look, large PRs that sit for a week, approvals that land on one person, and merges that skipped review. You work from a JSON export of the team's pull requests, report medians and p90 instead of averages, and turn the numbers into a few agreed team habits, not a ranking of people.
Use the numbers to improve the process, never to score individuals. Do not share per-person tables outside the team without the team's agreement, and remember that review time depends on time zones, on-call duty, holidays and PR size.
## Files in this skill
- `scripts/pr_turnaround.py` - reads `gh pr list --json ...` output, ignores self-reviews, measures time to first review, first approval and merge (optionally without weekends), size buckets (XS-XL), per-author and per-size medians and p90, reviewer load, and prints flags R01-R06 + E01; `--format text|md|json`; `--self-test` runs 14 checks (Python 3.8+ standard library only)
- `references/review-metrics.md` - what each metric means, healthy ranges for small teams, how to export data from GitHub (and GitLab via conversion), and the main pitfalls
- `references/improvement-playbook.md` - team habits and settings that fix each flag (review slots, PR size limits, CODEOWNERS rotation, draft PRs, branch protection)
- `templates/review-health-report.md` - a short retro or monthly engineering note
- `examples/prs.json` - 13 fictional PRs from a two-week sprint of a small shop team, with a huge refactor, a bot PR, an unreviewed hotfix, a stale PR and one overloaded reviewer
## Workflow
### 1. Export the data
Agree the window (a sprint, a month) and the repository. Then run, in the repository:
```
gh pr list --state all --limit 300 --search "created:>=2026-11-01" \
--json number,title,author,createdAt,mergedAt,closedAt,isDraft,additions,deletions,reviews,url > prs.json
```
For several repositories export each one and analyze them separately first (different teams, different norms). Agree the targets with the team: first review within 24 working hours (default), PRs under 400 changed lines, nothing open without review for more than 3 days.
### 2. Run the analysis
```
python3 scripts/pr_turnaround.py prs.json
python3 scripts/pr_turnaround.py prs.json --exclude-weekends --ignore-bots
python3 scripts/pr_turnaround.py prs.json --first-review-hours 8 --stale-days 2 --large-lines 300
python3 scripts/pr_turnaround.py prs.json --since 2026-11-16 --format md > review-health.md
python3 scripts/pr_turnaround.py prs.json --now 2026-11-27T17:00:00Z # reproducible ages for open PRs
python3 scripts/pr_turnaround.py --self-test
```
Exit code 0 = no flags, 1 = flags present, 2 = unreadable input.
| Code | Meaning |
|---|---|
| R01 | first review took longer than `--first-review-hours` |
| R02 | open, non-draft PR without any review for more than `--stale-days` |
| R03 | merged without an approval from someone other than the author |
| R04 | large PR (at least `--large-lines` changed lines, default 400) |
| R05 | one reviewer wrote at least half of all reviews (10+ reviews in the window) |
| R06 | changes were requested and nothing happened for more than `--stale-days` |
| E01 | PR entries that could not be parsed |
### 3. Interpret
- Look at the size table first: if L and XL PRs take days while XS and S take hours, the fix is smaller PRs, not faster reviewers.
- First review time is the main waiting cost; time to merge also includes the author's rework and CI.
- Use `--exclude-weekends` for teams that do not work weekends, otherwise Friday PRs look slow.
- Bot PRs (Renovate, Dependabot) follow other rules; analyze with and without `--ignore-bots`.
- R03 is not always wrong (an emergency hotfix), but each case should have a follow-up review.
- R05 is a bus-factor and burnout signal: one person approves most changes.
### 4. Act
Pick at most two habits from `references/improvement-playbook.md` that match the biggest flags, agree them in a retro, and re-run on the next sprint with the same options to compare.
### 5. Report
Fill `templates/review-health-report.md`: window, overall medians and p90, size table, reviewer load, flags, the agreed habits and the date of the next check.
FILE:references/review-metrics.md
# Review metrics
## Definitions (as computed by scripts/pr_turnaround.py)
- Time to first review: PR creation to the first submitted review (approve, comment or request changes) by someone other than the author. Self-reviews and pending reviews are ignored. Comments that are not part of a review are not counted.
- Time to first approval: creation to the first APPROVED review by someone else.
- Time to merge: creation to merge. Includes waiting, rework, CI and merge queues.
- Size: additions + deletions. Buckets: XS <50, S 50-199, M 200-399, L 400-999, XL 1000+.
- Median and p90: half of the PRs are faster than the median; 9 out of 10 are faster than p90. Averages hide the slow tail, so they are not used.
- Weekends: with --exclude-weekends, Saturday and Sunday in UTC do not count. Teams far from UTC should keep this in mind.
## Healthy ranges for small product teams (rules of thumb)
- First review median: a few working hours; p90 within one working day.
- Merge median: within one or two working days for S and M PRs.
- Most PRs in XS-M; L and XL should be rare and announced.
- No single reviewer above about 40% of reviews in a team of four or more.
These are starting points to discuss, not targets to enforce.
## Exporting data
GitHub CLI (in the repository folder):
gh pr list --state all --limit 300 --search "created:>=2026-11-01" \
--json number,title,author,createdAt,mergedAt,closedAt,isDraft,additions,deletions,reviews,url > prs.json
- --limit must cover the window; raise it for busy repositories.
- Reviews in the export do not include the time a reviewer was requested; the script measures from PR creation.
- PRs opened as drafts and marked ready later look slower than they were; count draft time separately or exclude them with --since.
GitLab: export merge requests with the API and map fields to the same names: iid -> number, author.username -> author.login, created_at -> createdAt, merged_at -> mergedAt, closed_at -> closedAt, draft -> isDraft, approvals -> reviews with state APPROVED and submittedAt. Line counts need the changes endpoint.
## Pitfalls
- Do not compare people: authors who take the hardest work naturally have slower PRs.
- Time zones and on-call duty change first-review times a lot.
- Small samples: with fewer than about 10 PRs per group, treat medians as anecdotes.
- Holidays and code freezes distort a window; note them in the report.
FILE:references/improvement-playbook.md
# Improvement playbook: from flag to habit
Pick at most two changes per retro. Re-run the analysis after one sprint to see if they helped.
## R01 slow first reviews
- Review slots: everyone checks open PRs twice a day (for example after stand-up and after lunch) before starting new work.
- A shared rule: first look within one working day, even if it is only "I will review this afternoon".
- Turn on review request notifications in chat for the team channel, not only email.
- Use CODEOWNERS or auto-assignment with round-robin so a PR always has a named reviewer.
## R02 stale PRs without review
- A daily or weekly "PRs waiting" list in chat (gh pr list --search "review:none draft:false").
- Authors ping a specific person after one day instead of the whole channel.
- If a PR is not needed any more, close it; open PRs cost attention.
## R03 merged without approval
- Branch protection: require at least one approval and passing checks on the main branch.
- Allow an emergency path for hotfixes, but add a follow-up review issue within one working day.
- Check whether admins bypass protection by default.
## R04 large PRs
- Agree a soft limit (for example 400 changed lines) and split by layers or behind feature flags.
- Stacked PRs or a short design note before a big refactor.
- Exclude generated files and lockfiles from the diff with .gitattributes linguist-generated, so size reflects real review work.
## R05 one reviewer does most reviews
- Rotate reviewer duty weekly; pair a newer teammate with the main reviewer to spread knowledge.
- Widen CODEOWNERS to a team instead of one person.
- Protect focus time: the main reviewer should not be the default for every PR.
## R06 changes requested, then silence
- Authors answer review comments within one working day, even if only to say when they will fix them.
- Reviewers mark comments as blocking or optional (for example a "nit:" prefix) so authors know what really must change.
- Close or convert to draft if the work is paused.
FILE:templates/review-health-report.md
# Code review health - {{team or repository}} - {{window}}
## Numbers
- PRs: {{prs}} (merged {{merged}}, open or draft {{open}})
- First review: median {{first_review_median}}, p90 {{first_review_p90}} (target {{target}})
- Merge: median {{merge_median}}, p90 {{merge_p90}}
- Options used: {{for example --exclude-weekends --ignore-bots}}
## By size
| Size | PRs | First review median | Merge median |
|---|---:|---:|---:|
| {{bucket}} | {{n}} | {{first_review}} | {{merge}} |
## Reviewer load
- {{reviewer}}: {{reviews}} reviews ({{share}})
## Flags and context
- {{code}} {{where}}: {{detail}} - context: {{holiday, incident, hotfix, on-call}}
## Habits we agreed (max 2)
1. {{habit}} - owner {{name}}
2. {{habit}} - owner {{name}}
## Next check
Re-run on {{date}} with the same options and compare the first review p90 and the size table.
FILE:examples/prs.json
[
{
"number": 412,
"title": "Add invoice PDF export",
"author": {
"login": "maya"
},
"createdAt": "2026-11-16T09:10:00Z",
"mergedAt": "2026-11-17T15:30:00Z",
"closedAt": "2026-11-17T15:30:00Z",
"isDraft": false,
"additions": 180,
"deletions": 40,
"reviews": [
{
"author": {
"login": "deniz"
},
"submittedAt": "2026-11-16T13:05:00Z",
"state": "COMMENTED"
},
{
"author": {
"login": "deniz"
},
"submittedAt": "2026-11-17T10:20:00Z",
"state": "APPROVED"
}
],
"url": "https://github.com/example-shop/storefront/pull/412"
},
{
"number": 413,
"title": "Fix timezone in reminder emails",
"author": {
"login": "ali"
},
"createdAt": "2026-11-16T11:00:00Z",
"mergedAt": "2026-11-16T16:45:00Z",
"closedAt": "2026-11-16T16:45:00Z",
"isDraft": false,
"additions": 22,
"deletions": 6,
"reviews": [
{
"author": {
"login": "maya"
},
"submittedAt": "2026-11-16T12:10:00Z",
"state": "APPROVED"
}
],
"url": "https://github.com/example-shop/storefront/pull/413"
},
{
"number": 414,
"title": "Refactor billing service into modules",
"author": {
"login": "deniz"
},
"createdAt": "2026-11-17T08:30:00Z",
"mergedAt": "2026-11-21T17:00:00Z",
"closedAt": "2026-11-21T17:00:00Z",
"isDraft": false,
"additions": 1640,
"deletions": 1210,
"reviews": [
{
"author": {
"login": "selin"
},
"submittedAt": "2026-11-19T16:00:00Z",
"state": "CHANGES_REQUESTED"
},
{
"author": {
"login": "selin"
},
"submittedAt": "2026-11-21T11:30:00Z",
"state": "APPROVED"
}
],
"url": "https://github.com/example-shop/storefront/pull/414"
},
{
"number": 415,
"title": "Bump eslint to v9",
"author": {
"login": "renovate[bot]"
},
"createdAt": "2026-11-17T06:00:00Z",
"mergedAt": "2026-11-18T09:00:00Z",
"closedAt": "2026-11-18T09:00:00Z",
"isDraft": false,
"additions": 35,
"deletions": 30,
"reviews": [
{
"author": {
"login": "deniz"
},
"submittedAt": "2026-11-18T08:40:00Z",
"state": "APPROVED"
}
],
"url": "https://github.com/example-shop/storefront/pull/415"
},
{
"number": 416,
"title": "Add rate limit to public API",
"author": {
"login": "selin"
},
"createdAt": "2026-11-18T10:00:00Z",
"mergedAt": "2026-11-19T12:00:00Z",
"closedAt": "2026-11-19T12:00:00Z",
"isDraft": false,
"additions": 260,
"deletions": 20,
"reviews": [
{
"author": {
"login": "deniz"
},
"submittedAt": "2026-11-18T14:30:00Z",
"state": "APPROVED"
}
],
"url": "https://github.com/example-shop/storefront/pull/416"
},
{
"number": 417,
"title": "Hotfix: null check in checkout",
"author": {
"login": "ali"
},
"createdAt": "2026-11-19T18:20:00Z",
"mergedAt": "2026-11-19T18:35:00Z",
"closedAt": "2026-11-19T18:35:00Z",
"isDraft": false,
"additions": 4,
"deletions": 1,
"reviews": [],
"url": "https://github.com/example-shop/storefront/pull/417"
},
{
"number": 418,
"title": "Dark mode for settings page",
"author": {
"login": "maya"
},
"createdAt": "2026-11-20T15:00:00Z",
"mergedAt": "2026-11-24T10:00:00Z",
"closedAt": "2026-11-24T10:00:00Z",
"isDraft": false,
"additions": 320,
"deletions": 90,
"reviews": [
{
"author": {
"login": "deniz"
},
"submittedAt": "2026-11-23T09:00:00Z",
"state": "APPROVED"
}
],
"url": "https://github.com/example-shop/storefront/pull/418"
},
{
"number": 419,
"title": "Migrate cron jobs to queue workers",
"author": {
"login": "ali"
},
"createdAt": "2026-11-21T16:30:00Z",
"mergedAt": null,
"closedAt": null,
"isDraft": false,
"additions": 540,
"deletions": 210,
"reviews": [
{
"author": {
"login": "deniz"
},
"submittedAt": "2026-11-24T10:15:00Z",
"state": "CHANGES_REQUESTED"
}
],
"url": "https://github.com/example-shop/storefront/pull/419"
},
{
"number": 420,
"title": "Update onboarding copy",
"author": {
"login": "selin"
},
"createdAt": "2026-11-24T09:00:00Z",
"mergedAt": "2026-11-24T11:00:00Z",
"closedAt": "2026-11-24T11:00:00Z",
"isDraft": false,
"additions": 12,
"deletions": 12,
"reviews": [
{
"author": {
"login": "deniz"
},
"submittedAt": "2026-11-24T10:30:00Z",
"state": "APPROVED"
}
],
"url": "https://github.com/example-shop/storefront/pull/420"
},
{
"number": 421,
"title": "Experiment: new search ranking",
"author": {
"login": "deniz"
},
"createdAt": "2026-11-24T13:00:00Z",
"mergedAt": null,
"closedAt": "2026-11-26T09:00:00Z",
"isDraft": false,
"additions": 410,
"deletions": 60,
"reviews": [
{
"author": {
"login": "maya"
},
"submittedAt": "2026-11-25T09:30:00Z",
"state": "COMMENTED"
}
],
"url": "https://github.com/example-shop/storefront/pull/421"
},
{
"number": 422,
"title": "Add audit log table",
"author": {
"login": "maya"
},
"createdAt": "2026-11-24T08:00:00Z",
"mergedAt": null,
"closedAt": null,
"isDraft": false,
"additions": 150,
"deletions": 10,
"reviews": [],
"url": "https://github.com/example-shop/storefront/pull/422"
},
{
"number": 423,
"title": "WIP: mobile push notifications",
"author": {
"login": "ali"
},
"createdAt": "2026-11-26T14:00:00Z",
"mergedAt": null,
"closedAt": null,
"isDraft": true,
"additions": 700,
"deletions": 40,
"reviews": [],
"url": "https://github.com/example-shop/storefront/pull/423"
},
{
"number": 424,
"title": "Cache product list responses",
"author": {
"login": "selin"
},
"createdAt": "2026-11-26T08:00:00Z",
"mergedAt": "2026-11-26T15:20:00Z",
"closedAt": "2026-11-26T15:20:00Z",
"isDraft": false,
"additions": 95,
"deletions": 15,
"reviews": [
{
"author": {
"login": "deniz"
},
"submittedAt": "2026-11-26T09:10:00Z",
"state": "APPROVED"
}
],
"url": "https://github.com/example-shop/storefront/pull/424"
}
]
FILE:scripts/pr_turnaround.py
#!/usr/bin/env python3
"""pr_turnaround.py - pull request review turnaround analyzer. Python 3.8+ standard library only.
Input: JSON from the GitHub CLI, for example
gh pr list --state all --limit 300 --json number,title,author,createdAt,mergedAt,closedAt,isDraft,additions,deletions,reviews,url > prs.json
(a list of PR objects; reviews = [{author:{login}, submittedAt, state}]). GitLab or other exports work
if converted to the same keys.
Per PR it measures: time to first review by someone other than the author, time to first approval,
time to merge, and size (additions + deletions). It summarizes medians and p90 overall, by size
bucket and by author, shows reviewer load, and flags process problems.
Usage:
pr_turnaround.py prs.json [--now 2026-11-27T17:00:00Z] [--since 2026-11-01] [--exclude-weekends]
[--first-review-hours 24] [--stale-days 3] [--large-lines 400] [--ignore-bots]
[--format text|md|json]
pr_turnaround.py --self-test
Exit: 0 no flags, 1 flags present, 2 unreadable input.
Flags:
R01 first review took longer than --first-review-hours
R02 open, non-draft PR without any review older than --stale-days
R03 merged without an approval from someone other than the author
R04 large PR (>= --large-lines changed lines): slower and riskier to review
R05 reviewer concentration: one person wrote >= 50% of all reviews (10+ reviews)
R06 open PR waiting on the author after CHANGES_REQUESTED for longer than --stale-days
E01 entries that could not be parsed
"""
import argparse, json, statistics, sys
from datetime import datetime, timedelta, timezone
BUCKETS = [(50, "XS <50"), (200, "S 50-199"), (400, "M 200-399"), (1000, "L 400-999"), (10 ** 12, "XL 1000+")]
def ts(x):
if not x:
return None
return datetime.fromisoformat(x.replace("Z", "+00:00")).astimezone(timezone.utc)
def hours(a, b, exclude_weekends=False):
"""Hours from a to b; with exclude_weekends, Saturday and Sunday (UTC) do not count."""
if a is None or b is None:
return None
if b < a:
return 0.0
if not exclude_weekends:
return (b - a).total_seconds() / 3600
total, cur = 0.0, a
while cur < b:
nxt = min(b, (cur + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0))
if cur.weekday() < 5:
total += (nxt - cur).total_seconds()
cur = nxt
return total / 3600
def pct(vals, p):
vals = sorted(v for v in vals if v is not None)
if not vals:
return None
k = (len(vals) - 1) * p / 100
lo, hi = int(k), min(int(k) + 1, len(vals) - 1)
return vals[lo] + (vals[hi] - vals[lo]) * (k - lo)
def bucket(n):
for lim, name in BUCKETS:
if n < lim:
return name
def is_bot(login):
return login.endswith("[bot]") or login.endswith("-bot") or login in ("dependabot", "renovate")
def analyze(prs, now, since=None, exclude_weekends=False, first_review_hours=24.0, stale_days=3.0, large_lines=400, ignore_bots=False):
rows, flags = [], []
for i, p in enumerate(prs):
try:
author = (p.get("author") or {}).get("login") or "unknown"
created = ts(p["createdAt"])
if since and created < since:
continue
if ignore_bots and is_bot(author):
continue
merged, closed = ts(p.get("mergedAt")), ts(p.get("closedAt"))
revs = sorted([(ts(r["submittedAt"]), (r.get("author") or {}).get("login") or "unknown", (r.get("state") or "").upper())
for r in p.get("reviews") or [] if r.get("submittedAt")], key=lambda x: x[0])
revs = [r for r in revs if r[1] != author and r[2] != "PENDING"]
first = revs[0][0] if revs else None
appr = next((r[0] for r in revs if r[2] == "APPROVED"), None)
size = int(p.get("additions") or 0) + int(p.get("deletions") or 0)
state = "merged" if merged else ("closed" if closed else ("draft" if p.get("isDraft") else "open"))
rows.append(dict(number=p.get("number"), title=p.get("title", ""), author=author, state=state, size=size,
bucket=bucket(size), reviewers=sorted({r[1] for r in revs}), reviews=revs,
first_review_h=hours(created, first, exclude_weekends),
approval_h=hours(created, appr, exclude_weekends),
merge_h=hours(created, merged, exclude_weekends),
age_h=hours(created, now, exclude_weekends), created=created, url=p.get("url", "")))
except Exception as e: # noqa: BLE001
flags.append(dict(code="E01", where="entry %d" % i, detail=str(e)))
stale_h = stale_days * 24
for r in rows:
ref = "#%s %s" % (r["number"], r["title"][:48])
if r["first_review_h"] is not None and r["first_review_h"] > first_review_hours:
flags.append(dict(code="R01", where=ref, detail="first review after %.1f h (target %g h)" % (r["first_review_h"], first_review_hours)))
if r["state"] == "open" and not r["reviews"] and r["age_h"] > stale_h:
flags.append(dict(code="R02", where=ref, detail="open %.1f h without any review" % r["age_h"]))
if r["state"] == "merged" and r["approval_h"] is None:
flags.append(dict(code="R03", where=ref, detail="merged without an approval from another person"))
if r["size"] >= large_lines and r["state"] != "closed":
flags.append(dict(code="R04", where=ref, detail="%d changed lines (%s)" % (r["size"], r["bucket"])))
if r["state"] == "open" and r["reviews"] and r["reviews"][-1][2] == "CHANGES_REQUESTED":
waited = hours(r["reviews"][-1][0], now, exclude_weekends)
if waited > stale_h:
flags.append(dict(code="R06", where=ref, detail="changes requested %.1f h ago, no new review since" % waited))
load = {}
for r in rows:
for _, who, _s in r["reviews"]:
load[who] = load.get(who, 0) + 1
total_reviews = sum(load.values())
if total_reviews >= 10:
top, n = max(load.items(), key=lambda kv: kv[1])
if n / total_reviews >= 0.5:
flags.append(dict(code="R05", where=top, detail="%d of %d reviews (%.0f%%): review knowledge and load sit with one person" % (n, total_reviews, 100 * n / total_reviews)))
def stats(sel):
f = [r["first_review_h"] for r in sel]; m = [r["merge_h"] for r in sel]
return dict(prs=len(sel), first_review_median_h=pct(f, 50), first_review_p90_h=pct(f, 90),
merge_median_h=pct(m, 50), merge_p90_h=pct(m, 90),
merged=sum(r["state"] == "merged" for r in sel), open=sum(r["state"] in ("open", "draft") for r in sel))
by_size = [dict(bucket=b, **stats([r for r in rows if r["bucket"] == b])) for _, b in BUCKETS if any(r["bucket"] == b for r in rows)]
by_author = [dict(author=a, **stats([r for r in rows if r["author"] == a])) for a in sorted({r["author"] for r in rows})]
reviewers = [dict(reviewer=k, reviews=v, share=round(v / total_reviews, 3)) for k, v in sorted(load.items(), key=lambda kv: -kv[1])]
return dict(summary=stats(rows), by_size=by_size, by_author=by_author, reviewers=reviewers, flags=flags,
prs=[{k: v for k, v in r.items() if k not in ("reviews", "created")} for r in rows])
def fh(x):
return "-" if x is None else ("%.1f h" % x if x < 48 else "%.1f d" % (x / 24))
def render(res, fmt):
if fmt == "json":
return json.dumps(res, indent=1, default=str)
md, out, s = fmt == "md", [], res["summary"]
H = (lambda t, l=2: "#" * l + " " + t) if md else (lambda t, l=2: t)
out.append(H("PR review turnaround"))
out.append("- PRs %d (merged %d, open/draft %d); first review median %s, p90 %s; merge median %s, p90 %s" % (
s["prs"], s["merged"], s["open"], fh(s["first_review_median_h"]), fh(s["first_review_p90_h"]), fh(s["merge_median_h"]), fh(s["merge_p90_h"])))
for title, key, name in (("By size (changed lines)", "by_size", "bucket"), ("By author", "by_author", "author")):
out += ["", H(title, 3)]
if md:
out += ["| %s | PRs | first review median | merge median | merge p90 |" % name, "|---|---:|---:|---:|---:|"]
for g in res[key]:
c = (g[name], str(g["prs"]), fh(g["first_review_median_h"]), fh(g["merge_median_h"]), fh(g["merge_p90_h"]))
out.append("| %s |" % " | ".join(c) if md else " %-12s %3s PRs first review %8s merge %8s p90 %8s" % c)
out += ["", H("Reviewer load", 3)]
for r in res["reviewers"]:
out.append("%s%s: %d reviews (%.0f%%)" % ("- " if md else " ", r["reviewer"], r["reviews"], 100 * r["share"]))
out += ["", H("Flags (%d)" % len(res["flags"]), 3)]
for f in res["flags"]:
out.append("%s%s %s: %s" % ("- " if md else " ", f["code"], f["where"], f["detail"]))
if not res["flags"]:
out.append(" none")
return "\n".join(out)
def self_test():
ok = 0
def check(c, name):
nonlocal ok
if not c:
raise SystemExit("FAIL " + name)
ok += 1
U = lambda s: ts(s)
check(abs(hours(U("2026-11-27T12:00:00Z"), U("2026-11-30T12:00:00Z")) - 72) < 1e-9, "calendar hours")
check(abs(hours(U("2026-11-27T12:00:00Z"), U("2026-11-30T12:00:00Z"), True) - 24) < 1e-9, "weekend excluded (Fri 12:00 -> Mon 12:00 = 24 h)")
check(hours(U("2026-11-28T10:00:00Z"), U("2026-11-29T10:00:00Z"), True) == 0, "weekend only = 0")
check(pct([1, 2, 3, 4], 50) == 2.5 and pct([], 50) is None, "percentile")
check(bucket(49) == "XS <50" and bucket(400) == "L 400-999" and bucket(5000) == "XL 1000+", "buckets")
rv = lambda who, t, st: {"author": {"login": who}, "submittedAt": t, "state": st}
base = lambda n, **k: dict(dict(number=n, title="pr%d" % n, author={"login": "a"}, createdAt="2026-11-23T09:00:00Z", mergedAt=None, closedAt=None, isDraft=False, additions=10, deletions=0, reviews=[]), **k)
now = U("2026-11-27T09:00:00Z")
prs = [base(1, mergedAt="2026-11-23T15:00:00Z", reviews=[rv("b", "2026-11-23T11:00:00Z", "APPROVED")]),
base(2, mergedAt="2026-11-25T09:00:00Z", reviews=[rv("b", "2026-11-24T21:00:00Z", "APPROVED")]),
base(3, mergedAt="2026-11-23T10:00:00Z", reviews=[rv("a", "2026-11-23T09:30:00Z", "APPROVED")]),
base(4),
base(5, isDraft=True),
base(6, additions=500, reviews=[rv("b", "2026-11-23T10:00:00Z", "CHANGES_REQUESTED")])]
r = analyze(prs, now)
codes = sorted(f["code"] + str(f["where"]).split()[0] for f in r["flags"])
check(codes == ["R01#2", "R02#4", "R03#3", "R04#6", "R06#6"], "flags %s" % codes)
check(r["prs"][2]["first_review_h"] is None, "self review ignored")
check(abs(r["summary"]["first_review_median_h"] - 2.0) < 1e-9, "first review median 2 h (PRs 1, 2, 6)")
check(r["summary"]["merged"] == 3 and r["summary"]["open"] == 3, "state counts")
check(len(analyze(prs, now, since=U("2026-11-24T00:00:00Z"))["prs"]) == 0, "since filter")
bots = [base(7, author={"login": "renovate[bot]"})]
check(len(analyze(bots, now, ignore_bots=True)["prs"]) == 0 and len(analyze(bots, now)["prs"]) == 1, "ignore bots")
many = [base(10 + i, mergedAt="2026-11-23T12:00:00Z", reviews=[rv("b" if i < 8 else "c", "2026-11-23T10:00:00Z", "APPROVED")]) for i in range(10)]
check([f["code"] for f in analyze(many, now)["flags"]] == ["R05"], "reviewer concentration")
e = analyze([{"number": 1}], now)
check([f["code"] for f in e["flags"]] == ["E01"], "bad entry E01")
check("first review" in render(r, "text") and render(r, "md").startswith("## ") and json.loads(render(r, "json"))["summary"]["prs"] == 6, "renderers")
print("self-test OK: %d checks" % ok)
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("file", nargs="?")
ap.add_argument("--now", help="ISO time used as 'now' for open PR ages (default: current UTC time)")
ap.add_argument("--since", help="only PRs created on or after this date (YYYY-MM-DD)")
ap.add_argument("--exclude-weekends", action="store_true", help="do not count Saturday and Sunday (UTC)")
ap.add_argument("--first-review-hours", type=float, default=24.0)
ap.add_argument("--stale-days", type=float, default=3.0)
ap.add_argument("--large-lines", type=int, default=400)
ap.add_argument("--ignore-bots", action="store_true")
ap.add_argument("--format", choices=["text", "md", "json"], default="text")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.file:
ap.error("give a JSON file or --self-test")
try:
with open(a.file, encoding="utf-8") as fh_:
prs = json.load(fh_)
if not isinstance(prs, list):
raise ValueError("expected a JSON list of pull requests")
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr); sys.exit(2)
now = ts(a.now) if a.now else datetime.now(timezone.utc)
since = ts(a.since + "T00:00:00Z") if a.since else None
res = analyze(prs, now, since, a.exclude_weekends, a.first_review_hours, a.stale_days, a.large_lines, a.ignore_bots)
print(render(res, a.format))
sys.exit(1 if res["flags"] else 0)
if __name__ == "__main__":
main()
Turns a car fuel log CSV into honest numbers: fill-to-fill consumption in L/100km or mpg that handles partial top-ups, cost per km, monthly spend, and flags for consumption spikes, overpriced fills, odometer typos and missing entries, with a checklist of likely causes. Stdlib Python.
---
name: car-fuel-log-consumption-and-cost-analyzer
description: Turns a car fuel log CSV into honest numbers: fill-to-fill consumption in L/100km or mpg that handles partial top-ups, cost per km, monthly spend, and flags for consumption spikes, overpriced fills, odometer typos and missing entries, with a checklist of likely causes. Stdlib Python.
---
# Car Fuel Log Consumption and Cost Analyzer
You help drivers answer three everyday questions from their own fuel receipts: how much fuel does my car really use, what does each kilometer cost me, and is something wrong when the numbers change? You work from a simple fuel log (a CSV from a spreadsheet, a notes app or a fuel-tracking app export), measure consumption the correct way (full tank to full tank), and explain changes in plain language before anyone spends money at a garage.
You only read the log the user gives you. You are not a mechanic: when the numbers suggest a mechanical problem (a sudden lasting jump in consumption, a fuel smell, warning lights), say so clearly and recommend a check at a garage instead of guessing a diagnosis.
## Files in this skill
- `scripts/fuel_log.py` - reads the CSV, sorts by date, builds full-to-full segments (partial top-ups are added to the next full fill), computes L/100km, mpg, cost per km, monthly spend and summary numbers, and prints flags F01-F06 + E01; `--units km|mi`, `--gallons us|uk`, `--format text|md|csv|json`; `--self-test` runs 20 checks (Python 3.8+ standard library only)
- `references/fuel-economy-basics.md` - how to log fill-ups so the numbers are trustworthy, the full-to-full method, unit conversions and what a normal spread looks like
- `references/consumption-red-flags.md` - likely causes behind each flag (season, tires, driving mix, loads, a mechanical issue) and what to check first, cheapest first
- `templates/fuel-report.md` - a short monthly or yearly car cost note
- `examples/fuel_log.csv` - a fictional four-month log with a partial top-up, a winter-tire change, an expensive motorway station and a trailing top-up
## Workflow
### 1. Get a usable log
Ask for a CSV with one row per fill-up: `date` (YYYY-MM-DD), `odometer_km` (or `odometer_mi` with `--units mi`), `liters` (or gallons with `--gallons us|uk`), `price_per_liter` or `total_cost`, and `full_tank` (yes/no). `station` and `notes` are optional but very useful (trips, tire changes, roof box, heavy loads). If the user has only receipts, help them type the rows; if they never noted whether the tank was full, assume yes and say that partial fills will make single segments noisy. Semicolon-separated files with decimal commas (46,20), common in European spreadsheet exports, are detected automatically; a full_tank value that is not yes/no is reported as E01 instead of being guessed.
### 2. Run the analysis
```
python3 scripts/fuel_log.py fuel_log.csv
python3 scripts/fuel_log.py fuel_log.csv --format md > fuel-report.md
python3 scripts/fuel_log.py fuel_log.csv --format csv > segments.csv
python3 scripts/fuel_log.py us_log.csv --units mi --gallons us # US log in miles and gallons
python3 scripts/fuel_log.py fuel_log.csv --spike-pct 15 --price-pct 5 # stricter flags
python3 scripts/fuel_log.py --self-test
```
Exit code 0 = no flags, 1 = flags present, 2 = unreadable file or fewer than 2 usable rows.
| Code | Meaning |
|---|---|
| F01 | odometer did not increase (typo, wrong order, a different car in the same log) |
| F02 | a segment uses at least `--spike-pct` (default 20%) more fuel than the median |
| F03 | a segment is far below the median: usually a fill-up that was never logged |
| F04 | a fill cost at least `--price-pct` (default 6%) more per liter than the nearby fills |
| F05 | more than `--gap` km (default 1500) between two fills: likely a missing entry |
| F06 | partial fills after the last full tank are not measured yet (normal at the end of a log) |
| E01 | rows that could not be parsed (date format, empty liters) |
### 3. Interpret
- Trust the median and the trend over a single segment; one short segment with a partial fill is noisy.
- Compare like with like: winter versus summer, city weeks versus motorway trips. A 10-20% rise in cold months is normal (winter fuel, tires, heating, short trips).
- A spike that comes back to normal after one segment usually has a reason in the notes (a loaded trip, traffic, a roof box). A rise that lasts three or more segments without a reason is worth a check (tire pressure first, then a garage).
- F03 and F05 often point at a missing receipt rather than an amazing tank; fix the log before celebrating.
- Price flags show where money leaks: motorway stations and premium fuel the car does not need. Check the owner's manual for the required octane before switching grades.
### 4. Act
Use `references/consumption-red-flags.md` to go from a flag to the cheapest next check. Suggest concrete savings with numbers from the log (for example "skipping motorway stations would have saved about 229 on that fill"). Re-run after the next few fills to confirm a fix.
### 5. Report
Fill `templates/fuel-report.md`: period, distance, average and median consumption, cost per km, monthly spend, flags with causes, and one or two actions.
FILE:references/fuel-economy-basics.md
# Fuel economy basics
## Log every fill-up the same way
1. Fill until the pump clicks off the first time; do not top up further. This makes "full" mean the same level each time.
2. Write down the date, odometer, liters, price per liter (or the total) and whether the tank was full.
3. Add a short note for anything unusual: a long trip, a roof box or trailer, new tires, a heat wave or a cold snap, a different fuel grade.
4. Never skip a receipt, even a small top-up. A missing fill makes the next segment look far too efficient (flag F03) and the distance gap may trigger F05.
## Full-to-full method
Consumption is only measurable between two full tanks: liters added after full tank A up to and including full tank B, divided by the distance from A to B.
L/100km = 100 x liters added between two full tanks / km driven between them
Partial top-ups between the two full tanks are added to the liters of that segment. Fuel added after the last full tank (flag F06) cannot be measured until the next full fill.
## Units
- L/100km: lower is better. mpg: higher is better.
- mpg (US) = 235.215 / L/100km. mpg (UK) = 282.481 / L/100km.
- 1 US gallon = 3.785 L, 1 UK gallon = 4.546 L, 1 mile = 1.609 km.
- The script converts a miles/gallons log to km and liters internally (`--units mi --gallons us|uk`).
## What normal looks like
- Single segments vary by 5-10% even with identical driving: pumps click off at slightly different levels.
- City driving and short trips use 20-40% more than steady motorway driving at moderate speed.
- Very high motorway speeds raise consumption sharply (air resistance grows with the square of speed).
- Cold months typically add 10-20%: engines take longer to warm up, winter tires roll heavier and winter fuel blends contain a little less energy.
- The official figure from the brochure is usually lower than real-world driving.
## Cost per km
Cost per km = fuel spend of the measured segments / measured distance. It covers fuel only; insurance, tax, maintenance, tires and depreciation come on top. For a full car cost picture add those per year and divide by yearly distance.
FILE:references/consumption-red-flags.md
# Consumption red flags: likely causes and first checks
Go from cheapest and most likely to most expensive. Always check the log itself first.
## F02 consumption spike
Likely causes, in order:
1. Driving mix: more short trips, city traffic, cold starts, a long motorway trip at high speed. Look at the notes and the dates.
2. Season: winter tires fitted, cold mornings, heating, defrosting, idling to warm up.
3. Load and drag: roof box or bike rack, trailer, heavy luggage, open windows at speed.
4. Tire pressure too low: check all four when cold against the label in the door frame. Cheap and common.
5. Logging error: a fill marked full that was not really full, or a skipped receipt in the previous segment.
6. Mechanical: dragging brake, clogged air filter, a failing sensor or thermostat. Suspect these when the rise lasts three or more segments with normal driving, or comes with a warning light, a smell, noise or a pull to one side. Recommend a garage check; do not diagnose.
## F03 suspiciously good segment
Almost always a missing fill-up entry or a full tank that was really a partial one. Ask the user to look for a missing receipt or card statement in that period before trusting the number.
## F04 expensive fill
Motorway or premium stations, premium fuel grades the car does not need, or paying by a card with fees. Show the extra cost of that fill. Check the owner's manual or the fuel-filler flap for the minimum octane before recommending a cheaper grade.
## F05 big distance gap
A missing entry, a long trip with a fill abroad that was not logged, or an odometer typo. Ask for the missing receipt; until then, the segment over the gap is not reliable.
## F01 odometer not increasing
Typo (an extra or missing digit), rows in the wrong order, or two cars mixed in one log. Fix the row and run again.
## F06 trailing partial fills
Normal at the end of a log: wait for the next full tank. Nothing to fix.
## E01 unreadable rows
Date not in YYYY-MM-DD, empty liters or odometer, a summary row from a spreadsheet. Fix or remove the row.
## When to recommend a garage
- consumption up 15% or more for three or more segments with unchanged driving and season,
- any warning light, fuel smell, rough idle, smoke or a noticeable loss of power,
- the car pulls to one side or a wheel gets hot after driving (possible dragging brake).
FILE:templates/fuel-report.md
# Car fuel report - {{car}} - {{period}}
## Numbers
- Distance: {{distance_km}} km ({{measured_km}} km measured full to full)
- Average consumption: {{avg_l100}} L/100km ({{mpg}} mpg), median {{median_l100}}, range {{best_l100}} - {{worst_l100}}
- Fuel spend: {{total_spend}} {{currency}}, cost per km {{cost_per_km}} {{currency}}
- Average price per liter: {{avg_price}} {{currency}}
## Monthly spend
| Month | Fills | Liters | Spend |
|---|---:|---:|---:|
| {{month}} | {{fills}} | {{liters}} | {{cost}} |
## What changed and why
- {{flag code}} {{where}}: {{detail}} - likely cause: {{cause}} - check: {{check}}
## Actions
1. {{action with expected saving}}
2. {{action}}
## Next check
Re-run after {{n}} more fill-ups (around {{date}}) and compare the median.
FILE:examples/fuel_log.csv
date,odometer_km,liters,price_per_liter,full_tank,station,notes
2026-08-02,48210,52.4,46.20,yes,Shell Beykoz,start of log
2026-08-14,48890,49.8,46.50,yes,Opet Kavacik,commute week
2026-08-27,49540,47.1,46.90,yes,Shell Beykoz,
2026-09-05,50310,50.6,47.30,yes,BP Sile road,weekend trip to Sile
2026-09-16,50720,20.0,47.80,no,Opet Kavacik,half tank top-up
2026-09-21,51010,38.9,47.60,yes,Shell Beykoz,
2026-10-03,51620,58.3,48.10,yes,Shell Beykoz,winter tires fitted
2026-10-15,52240,55.0,48.40,yes,Total Umraniye,city traffic
2026-10-28,52900,53.9,52.90,yes,Motorway services,expensive motorway station
2026-11-09,53440,57.6,48.90,yes,Opet Kavacik,cold mornings
2026-11-22,54010,49.5,49.20,yes,Shell Beykoz,
2026-11-28,54320,25.0,49.40,no,BP Sile road,top-up before trip
FILE:scripts/fuel_log.py
#!/usr/bin/env python3
"""fuel_log.py - fuel consumption and cost analyzer for a car fuel log (CSV). Python 3.8+ standard library only.
Consumption is measured fill-to-fill: liters are summed from the fill after one full tank up to and
including the next full tank, and divided by the distance between the two full fills. Partial
top-ups are therefore counted correctly instead of producing fake very low or very high values.
CSV columns (header names, case-insensitive): date, odometer (odometer_km / odometer_mi / odometer),
liters (or litres, gallons with --gallons), price_per_liter (or price, or total_cost), full_tank
(yes/no, true/false, 1/0; missing = yes), station and notes optional. Comma or semicolon
separated (semicolon files may use decimal commas such as 46,20).
Usage:
fuel_log.py fuel_log.csv [--units km|mi] [--gallons us|uk] [--spike-pct 20] [--price-pct 6]
[--gap 1500] [--format text|md|csv|json]
fuel_log.py --self-test
Exit: 0 no flags, 1 flags present, 2 unreadable file or no usable rows.
Flags:
F01 odometer not increasing (typo, wrong order or a replaced odometer)
F02 consumption spike: a fill-to-fill segment at least --spike-pct above the median
F03 unusually low segment (below median by --spike-pct x 1.5): often a missed fill-up entry
F04 price per liter at least --price-pct above the median of the surrounding fills
F05 distance between two fills above --gap (a missing entry is likely)
F06 trailing partial fills: liters after the last full tank are not in any segment yet
E01 rows that could not be parsed
"""
import argparse, csv, json, statistics, sys
from datetime import date
GAL = {"us": 3.785411784, "uk": 4.54609}
KM_PER_MI = 1.609344
def _f(x):
x = (x or "").strip().replace(" ", "")
if not x:
return None
if "," in x and "." not in x:
x = x.replace(",", ".")
return float(x.replace(",", ""))
def _yes(x):
x = (x or "").strip().lower()
if x in ("", "y", "yes", "true", "1", "full", "f"):
return True
if x in ("n", "no", "false", "0", "partial", "p"):
return False
raise ValueError("full_tank value %r is not yes/no" % x)
def load(path, units="km", gallons=None):
rows, errors = [], []
with open(path, newline="", encoding="utf-8-sig") as fh:
head = fh.readline(); fh.seek(0)
delim = ";" if head.count(";") > head.count(",") else "," # European exports often use ; with decimal commas
rd = csv.DictReader(fh, delimiter=delim)
if not rd.fieldnames:
raise ValueError("empty file")
cols = {c.strip().lower(): c for c in rd.fieldnames}
def col(*names):
for n in names:
if n in cols:
return cols[n]
return None
c_date = col("date", "day")
c_odo = col("odometer_km", "odometer_mi", "odometer", "odo", "mileage")
c_vol = col("liters", "litres", "liter", "volume", "gallons")
c_ppl = col("price_per_liter", "price_per_litre", "price", "price_per_gallon")
c_tot = col("total_cost", "total", "cost", "amount")
c_full = col("full_tank", "full", "is_full")
if not (c_date and c_odo and c_vol):
raise ValueError("need columns date, odometer and liters; found %s" % ", ".join(rd.fieldnames))
for i, r in enumerate(rd, start=2):
try:
d = date.fromisoformat(r[c_date].strip())
odo = _f(r[c_odo]); vol = _f(r[c_vol])
if odo is None or vol is None or vol <= 0:
raise ValueError("missing odometer or volume")
if units == "mi":
odo *= KM_PER_MI
if gallons:
vol *= GAL[gallons]
ppl = _f(r.get(c_ppl)) if c_ppl else None
tot = _f(r.get(c_tot)) if c_tot else None
if ppl is not None and gallons:
ppl /= GAL[gallons]
if tot is None and ppl is not None:
tot = ppl * vol
if ppl is None and tot is not None:
ppl = tot / vol
rows.append(dict(line=i, date=d, odo=odo, liters=vol, ppl=ppl, cost=tot,
full=_yes(r.get(c_full)) if c_full else True,
station=(r.get(col("station")) or "").strip() if col("station") else "",
notes=(r.get(col("notes")) or "").strip() if col("notes") else ""))
except Exception as e: # noqa: BLE001
errors.append((i, str(e)))
return rows, errors
def analyze(rows, errors, spike_pct=20.0, price_pct=6.0, gap=1500.0):
flags = [dict(code="E01", where="line %d" % ln, detail=msg) for ln, msg in errors]
rows = sorted(rows, key=lambda r: (r["date"], r["odo"]))
for a, b in zip(rows, rows[1:]):
if b["odo"] <= a["odo"]:
flags.append(dict(code="F01", where="line %d" % b["line"], detail="odometer %.0f after %.0f" % (b["odo"], a["odo"])))
elif b["odo"] - a["odo"] > gap:
flags.append(dict(code="F05", where="lines %d-%d" % (a["line"], b["line"]), detail="%.0f km between fills" % (b["odo"] - a["odo"])))
segs, start, acc, cost_acc, parts = [], None, 0.0, 0.0, 0
for r in rows:
if start is None:
if r["full"]:
start = r
continue
acc += r["liters"]; parts += 1
cost_acc += r["cost"] or 0.0
if r["full"]:
dist = r["odo"] - start["odo"]
if dist > 0:
segs.append(dict(start=start["date"].isoformat(), end=r["date"].isoformat(), km=dist, liters=acc,
l100=100.0 * acc / dist, cost=cost_acc, cost_km=cost_acc / dist if cost_acc else None,
fills=parts, line=r["line"], notes=r["notes"]))
start, acc, cost_acc, parts = r, 0.0, 0.0, 0
trailing = acc
if trailing > 0:
flags.append(dict(code="F06", where="after %s" % start["date"].isoformat(), detail="%.1f L in partial fills not measured yet" % trailing))
med = statistics.median([s["l100"] for s in segs]) if segs else None
for s in segs:
if med and s["l100"] >= med * (1 + spike_pct / 100):
flags.append(dict(code="F02", where="%s..%s" % (s["start"], s["end"]), detail="%.1f L/100km vs median %.1f (+%.0f%%)%s" % (s["l100"], med, 100 * (s["l100"] / med - 1), "; note: " + s["notes"] if s["notes"] else "")))
elif med and s["l100"] <= med * (1 - 1.5 * spike_pct / 100):
flags.append(dict(code="F03", where="%s..%s" % (s["start"], s["end"]), detail="%.1f L/100km vs median %.1f: check for a missed fill-up entry" % (s["l100"], med)))
prices = [r for r in rows if r["ppl"]]
for i, r in enumerate(prices):
near = [p["ppl"] for j, p in enumerate(prices) if j != i and abs(j - i) <= 3]
if len(near) >= 2:
m = statistics.median(near)
if r["ppl"] >= m * (1 + price_pct / 100):
flags.append(dict(code="F04", where="line %d %s" % (r["line"], r["station"]), detail="%.2f per liter vs %.2f nearby (+%.0f%%), extra %.2f on this fill" % (r["ppl"], m, 100 * (r["ppl"] / m - 1), (r["ppl"] - m) * r["liters"])))
total_km = sum(s["km"] for s in segs)
total_l = sum(s["liters"] for s in segs)
spend = sum(r["cost"] or 0 for r in rows)
months = {}
for r in rows:
k = r["date"].strftime("%Y-%m"); m = months.setdefault(k, dict(month=k, fills=0, liters=0.0, cost=0.0))
m["fills"] += 1; m["liters"] += r["liters"]; m["cost"] += r["cost"] or 0
span_km = rows[-1]["odo"] - rows[0]["odo"] if len(rows) > 1 else 0
summary = dict(fills=len(rows), segments=len(segs), distance_km=round(span_km, 1), measured_km=round(total_km, 1),
avg_l100=round(100 * total_l / total_km, 2) if total_km else None,
median_l100=round(med, 2) if med else None,
best_l100=round(min(s["l100"] for s in segs), 2) if segs else None,
worst_l100=round(max(s["l100"] for s in segs), 2) if segs else None,
total_spend=round(spend, 2),
cost_per_km=round(sum(s["cost"] for s in segs) / total_km, 3) if total_km else None,
avg_price=round(spend / sum(r["liters"] for r in rows if r["cost"]), 3) if any(r["cost"] for r in rows) else None)
return dict(summary=summary, segments=segs, months=list(months.values()), flags=flags)
def render(res, fmt, units="km"):
s, out = res["summary"], []
if fmt == "json":
return json.dumps(res, indent=1, default=str)
if fmt == "csv":
out.append("start,end,km,liters,l_per_100km,cost,cost_per_km,fills")
for g in res["segments"]:
out.append("%s,%s,%.0f,%.2f,%.2f,%.2f,%s,%d" % (g["start"], g["end"], g["km"], g["liters"], g["l100"], g["cost"], "%.3f" % g["cost_km"] if g["cost_km"] else "", g["fills"]))
return "\n".join(out)
md = fmt == "md"
mpg = lambda l100: 235.214583 / l100 if l100 else 0
out.append(("## " if md else "") + "Fuel log summary")
out.append("- fills %d, measured segments %d, distance %.0f km (measured %.0f km)" % (s["fills"], s["segments"], s["distance_km"], s["measured_km"]))
if s["avg_l100"]:
out.append("- average %.2f L/100km (%.1f mpg US), median %.2f, best %.2f, worst %.2f" % (s["avg_l100"], mpg(s["avg_l100"]), s["median_l100"], s["best_l100"], s["worst_l100"]))
out.append("- total spend %.2f, cost per km %s, average price per liter %s" % (s["total_spend"], s["cost_per_km"], s["avg_price"]))
out.append("")
out.append(("### " if md else "") + "Segments (full tank to full tank)")
if md:
out += ["| start | end | km | liters | L/100km | cost/km | fills |", "|---|---|---:|---:|---:|---:|---:|"]
for g in res["segments"]:
cells = (g["start"], g["end"], "%.0f" % g["km"], "%.1f" % g["liters"], "%.2f" % g["l100"], "%.3f" % g["cost_km"] if g["cost_km"] else "-", str(g["fills"]))
out.append("| " + " | ".join(cells) + " |" if md else " %s .. %s %5s km %5s L %6s L/100km %s/km %s fill(s)" % cells)
out.append("")
out.append(("### " if md else "") + "Monthly spend")
for m in res["months"]:
out.append("%s%s: %d fills, %.1f L, %.2f" % ("- " if md else " ", m["month"], m["fills"], m["liters"], m["cost"]))
out.append("")
out.append(("### " if md else "") + "Flags (%d)" % len(res["flags"]))
for f in res["flags"]:
out.append("%s%s %s: %s" % ("- " if md else " ", f["code"], f["where"], f["detail"]))
if not res["flags"]:
out.append(" none")
return "\n".join(out)
def self_test():
import os, tempfile
ok = 0
def check(cond, name):
nonlocal ok
if not cond:
raise SystemExit("FAIL " + name)
ok += 1
def run(text, **kw):
fd, p = tempfile.mkstemp(suffix=".csv"); os.write(fd, text.encode()); os.close(fd)
try:
rows, err = load(p, **{k: v for k, v in kw.items() if k in ("units", "gallons")})
return analyze(rows, err, **{k: v for k, v in kw.items() if k not in ("units", "gallons")})
finally:
os.remove(p)
base = "date,odometer_km,liters,price_per_liter,full_tank\n2026-01-01,1000,40,2.0,yes\n2026-01-10,1500,30,2.0,yes\n2026-01-20,2000,30,2.0,yes\n"
r = run(base)
check(r["summary"]["segments"] == 2, "two segments")
check(abs(r["summary"]["avg_l100"] - 6.0) < 1e-9, "avg 6.0")
check(r["flags"] == [], "no flags on clean data")
check(abs(r["summary"]["cost_per_km"] - 0.12) < 1e-9, "cost per km")
check(abs(r["summary"]["total_spend"] - 200.0) < 1e-9, "total spend includes first fill")
p = run("date,odometer_km,liters,price_per_liter,full_tank\n2026-01-01,1000,40,2,yes\n2026-01-05,1200,10,2,no\n2026-01-10,1500,20,2,yes\n")
check(p["summary"]["segments"] == 1 and abs(p["segments"][0]["l100"] - 6.0) < 1e-9, "partial fill merged")
check(p["segments"][0]["fills"] == 2, "segment counts 2 fills")
t = run(base + "2026-01-25,2100,10,2.0,no\n")
check([f["code"] for f in t["flags"]] == ["F06"], "trailing partial F06")
b = run(base + "2026-01-25,1900,30,2.0,yes\n")
check("F01" in [f["code"] for f in b["flags"]], "odometer backwards F01")
s = run(base + "2026-01-30,2500,45,2.0,yes\n2026-02-08,3000,30,2.0,yes\n")
check("F02" in [f["code"] for f in s["flags"]], "spike F02")
g = run(base + "2026-02-20,4000,60,2.0,yes\n")
codes = [f["code"] for f in g["flags"]]
check("F05" in codes and "F03" in codes, "gap F05 and low F03")
pr = run("date,odometer_km,liters,price_per_liter,full_tank\n2026-01-01,1000,40,2.0,yes\n2026-01-10,1500,30,2.0,yes\n2026-01-20,2000,30,2.3,yes\n2026-01-30,2500,30,2.0,yes\n")
check([f["code"] for f in pr["flags"]] == ["F04"], "price F04")
tc = run("date,odometer,litres,total_cost,full\n2026-01-01,1000,40,80,y\n2026-01-10,1500,30,60,y\n")
check(abs(tc["summary"]["cost_per_km"] - 0.12) < 1e-9 and abs(tc["summary"]["avg_price"] - 2.0) < 1e-9, "total_cost column")
mi = run("date,odometer_mi,gallons,price_per_gallon,full_tank\n2026-01-01,1000,10,3.5,yes\n2026-01-10,1300,10,3.5,yes\n", units="mi", gallons="us")
check(abs(235.214583 / mi["summary"]["avg_l100"] - 30.0) < 0.05, "30 mpg round trip")
e = run(base + "not-a-date,1,1,1,yes\n")
check([f["code"] for f in e["flags"]] == ["E01"], "bad row E01")
check(_f("46,20") == 46.2 and _f("1,234.5") == 1234.5, "number parsing")
check(_yes("") and _yes("Yes") and not _yes("no") and not _yes("0"), "full tank parsing")
sc = run("date;odometer;litres;price;full\n2026-01-01;1000;40,0;2,00;ja\n")
check([f["code"] for f in sc["flags"]] == ["E01"], "unknown full_tank value is E01, not silently partial")
eu = run("date;odometer;litres;price;full\n2026-01-01;1000;40,0;2,00;yes\n2026-01-10;1500;30,0;2,00;yes\n")
check(abs(eu["summary"]["avg_l100"] - 6.0) < 1e-9 and eu["flags"] == [], "semicolon CSV with decimal commas")
check("L/100km" in render(r, "text") and render(r, "csv").count("\n") == 2 and json.loads(render(r, "json"))["summary"]["segments"] == 2, "renderers")
print("self-test OK: %d checks" % ok)
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("file", nargs="?")
ap.add_argument("--units", choices=["km", "mi"], default="km", help="odometer unit (results are always per km)")
ap.add_argument("--gallons", choices=["us", "uk"], help="volume and price columns are in gallons")
ap.add_argument("--spike-pct", type=float, default=20.0)
ap.add_argument("--price-pct", type=float, default=6.0)
ap.add_argument("--gap", type=float, default=1500.0, help="km between fills that suggests a missing entry")
ap.add_argument("--format", choices=["text", "md", "csv", "json"], default="text")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.file:
ap.error("give a CSV file or --self-test")
try:
rows, errors = load(a.file, a.units, a.gallons)
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr); sys.exit(2)
if len(rows) < 2:
print("error: need at least 2 usable fill-ups (%d parsed, %d errors)" % (len(rows), len(errors)), file=sys.stderr); sys.exit(2)
res = analyze(rows, errors, a.spike_pct, a.price_pct, a.gap)
print(render(res, a.format, a.units))
sys.exit(1 if res["flags"] else 0)
if __name__ == "__main__":
main()
The viral dart-chase trend in snowy Paris: one continuous take that follows a thrown dart from just behind its tail through balloons, a city bus, a fire hoop, a taxi and a Christmas market to a perfect bullseye. Upload a reference image of your character.
Create a photorealistic 30-second cinematic video in snowy Paris at blue dusk. Use the lady from the reference image exactly, preserving her face, hair, body and outfit. She throws a small silver dart straight down a snow-covered Paris street. At 0.9 seconds, the camera moves behind the dart and follows it from exactly 45 cm behind its tail. Keep the dart in the lower centre of the frame, flying in one perfectly straight line at a constant height of 1.15 metres. ACTION SEQUENCE: - 0–3s: The dart launches as pedestrians react in surprise. - 3–7s: Pops a red balloon held by a little girl in a yellow winter jacket. - 7–11s: Flies straight through the windows of a moving Paris city bus. - 11–15s: Passes through the centre of a street performer's glowing fire hoop. - 15–19s: Travels through the open windows of a black Paris taxi, narrowly missing the driver. - 19–23s: Tears through hanging paper snowflakes at a winter flower market and pops a pink balloon. - 23–27s: Pops an orange balloon outside a Christmas market. - 27–30s: Hits the exact centre of a red bullseye on a wooden target in a narrow snowy street. The camera stops 45 cm behind the dart as it quivers. VISUALS: Beautiful snow-covered Paris streets, falling snowflakes, warm café lights, Christmas decorations, wet cobblestones, frosted windows and cinematic blue-and-gold winter lighting. Realistic snow, glass, fire and balloon physics. CAMERA: One continuous take, no cuts, realistic tracking, natural motion blur. The dart never changes direction. AUDIO: Natural winter street ambience, footsteps in snow, wind, dart whoosh, balloon pops, bus and taxi engines, fire crackling and final wooden impact. No music. POSITIVE LOCKS: The lady must match the reference image exactly. Maintain the dart's straight trajectory, constant height and camera distance. All obstacles appear in the specified order. Nobody is touched or injured. Consistent snowfall and character appearance. OUTPUT: 9:16, 24 FPS, 30 seconds, photorealistic cinematic quality.

Turn any travel photo into bold, flat, hand-painted acrylic travel art that keeps the landmark recognizable and adds elegant country and city lettering. Upload your reference photo and replace [COUNTRY NAME] and [CITY / REGION / LANDMARK NAME].
Transform the uploaded reference photograph into a beautiful, vibrant, hand-painted acrylic artwork while preserving the original location, architectural identity, composition and recognizable details. 1. ARTISTIC STYLE Bold, flat acrylic painting with solid, vibrant blocks of colour. Simplified shapes and clean, expressive forms. Visible hand-painted brushstrokes and subtle canvas texture. Imperfect outlines, slightly wobbly edges and an organic handmade appearance. Minimal details, artistic and visually striking. 2. COLOUR & PAINTING Use a rich, harmonious palette inspired by the actual location. Represent buildings, landscapes, water, sky and vegetation using distinct solid colours. No gradients, realistic shading, artificial lighting or cast shadows. Avoid photorealism, 3D effects and glossy digital finishes. 3. PRESERVE THE LANDMARK Keep the main landmark recognizable and architecturally accurate. Preserve its original silhouette, proportions, structure and distinctive features. Retain the important surrounding scenery from the reference photograph. Simplify details artistically without changing the identity of the place. 4. LOCATION TYPOGRAPHY Add elegant, clearly readable typography within the composition: [COUNTRY NAME] — large, beautiful lettering. [CITY / REGION / LANDMARK NAME] — smaller subtitle underneath. Integrate the text naturally into the artwork like a premium illustrated travel poster. 5. FINAL FINISH Create a visually rich, vibrant, handcrafted acrylic painting with bold colour separation, expressive brush textures and simplified forms. The final result should look like an original piece of hand-painted travel art, not an AI-generated photograph. Maintain the original reference’s aspect ratio and make the artwork beautifully composed.
Opinionated React Router v7 framework-mode preferences: loaders and actions, typed routes, progressive forms, server-only modules, error boundaries and URL state.
# React Router App taste of a full-stack developer who wants routes to own their data
- Use React Router v7 in framework mode with Vite and TypeScript for new apps, not the old data-router setup by hand. Confidence: 0.90
- Define routes in app/routes.ts with explicit route() and layout() calls instead of relying only on file-name magic. Confidence: 0.75
- Load data in route loaders and mutate in route actions; never fetch page data in useEffect. Confidence: 0.95
- Use the generated Route types (./+types/route-name) for loaderData, actionData and params in every route module. Confidence: 0.90
- Render on the server by default and switch a route to prerender or SPA mode only when there is a clear reason. Confidence: 0.80
- Use <Form> and useFetcher for mutations so the app works before JavaScript loads and revalidates automatically. Confidence: 0.90
- Validate form data and params in actions with Zod and return field errors with data(..., { status: 400 }). Confidence: 0.85
- Throw redirect() after a successful POST to avoid double submits on refresh. Confidence: 0.90
- Keep server-only code in .server.ts files so secrets and database clients never reach the client bundle. Confidence: 0.95
- Read the session in a shared helper used by loaders and actions; protect routes with a parent layout loader that redirects. Confidence: 0.80
- Export an ErrorBoundary from the root and from risky routes, and throw data() responses for 404 and 403. Confidence: 0.85
- Use URL search params as state for filters, sorting and pagination so views are shareable and back-button safe. Confidence: 0.90
- Show pending UI with useNavigation and fetcher.state, and add optimistic UI for quick actions like toggles. Confidence: 0.80
- Return promises from loaders for slow, non-critical data and render them with Suspense and Await. Confidence: 0.70
- Set cache headers per route with the headers export instead of one global policy. Confidence: 0.75
- Define meta and links exports per route for titles, descriptions and preloaded assets. Confidence: 0.75
- Keep a thin route module and move business logic into plain functions in app/lib that are easy to unit test. Confidence: 0.85
- Do not add a client data cache library by default; the router's revalidation is enough for most apps. Confidence: 0.70
- Use nested routes and <Outlet /> for shared layouts instead of repeating headers and sidebars. Confidence: 0.85
- Prefetch likely next pages with <Link prefetch="intent">. Confidence: 0.75
- Test loaders and actions as functions with Vitest, and cover the main flows with Playwright against a built server. Confidence: 0.80
- Deploy with an official adapter for the target (Node, Vercel, Cloudflare) and keep environment access behind one typed config module. Confidence: 0.75Opinionated ClickHouse preferences for fast analytics: MergeTree table design, batch ingestion, materialized view rollups, TTLs, quotas and monitoring.
# ClickHouse Analytics taste of a data engineer who wants dashboards under one second - Use ClickHouse for append-heavy analytical events and keep transactional data in Postgres; do not treat it as an OLTP store. Confidence: 0.95 - Default to the MergeTree family and choose the engine on purpose: ReplacingMergeTree for upserts, AggregatingMergeTree for rollups. Confidence: 0.90 - Pick ORDER BY from the most common filters, low cardinality first (tenant_id, event_type, toDate(ts), ts). Confidence: 0.90 - Partition by month (toYYYYMM) or not at all; never partition by high-cardinality keys like user_id. Confidence: 0.90 - Use LowCardinality(String) for repeated values like country, plan and event name. Confidence: 0.85 - Use the smallest fitting numeric types and DateTime64 in UTC; avoid Nullable unless null really means something. Confidence: 0.85 - Insert in batches of thousands to hundreds of thousands of rows, or turn on async_insert; never insert row by row. Confidence: 0.95 - Ingest from Kafka through a Kafka engine table plus a materialized view into the real MergeTree table. Confidence: 0.80 - Build materialized views into AggregatingMergeTree tables with -State functions and read them with -Merge functions. Confidence: 0.85 - Do not rely on FINAL for every query on ReplacingMergeTree; design queries with argMax or accept eventual merges. Confidence: 0.75 - Select only the columns you need; SELECT * on a wide table defeats the columnar format. Confidence: 0.90 - Use uniq or uniqCombined for distinct counts on dashboards and keep uniqExact for billing-grade numbers. Confidence: 0.80 - Add data-skipping indexes (minmax, bloom_filter) only after EXPLAIN shows wasted granules, not up front. Confidence: 0.75 - Put the smaller table on the right side of a JOIN, or replace dimension joins with dictionaries. Confidence: 0.85 - Set TTL rules to delete or move old raw data to cheaper storage, and keep rollups longer than raw events. Confidence: 0.85 - Manage schema with versioned migration files in git, using ON CLUSTER statements when running a cluster. Confidence: 0.80 - Give each consumer a separate user with settings profiles and quotas (max_memory_usage, max_execution_time). Confidence: 0.85 - Watch system.query_log, system.parts and merge activity; alert on too many parts per partition. Confidence: 0.85 - Avoid lightweight DELETE and ALTER UPDATE for routine work; model changes as new rows instead. Confidence: 0.80 - Back up with BACKUP TO S3 or clickhouse-backup on a schedule and test a restore every quarter. Confidence: 0.75 - Run integration tests against a real ClickHouse container with sample data, not an SQLite stand-in. Confidence: 0.75 - Prefer ClickHouse Cloud or a managed service for small teams; self-host only when someone owns operations. Confidence: 0.65
Opinionated Pydantic v2 preferences for validating data at the edges of Python backends: separate input and output models, strict settings, discriminated unions and safe serialization.
# Pydantic Models taste of a Python backend developer who wants data checked at the edges - Use Pydantic v2 only and write new code against its API (model_validate, model_dump, field_validator), never the v1 compatibility layer. Confidence: 0.95 - Validate data at the boundaries (HTTP requests, queue messages, config, third-party responses) and pass typed models inward. Confidence: 0.90 - Keep separate models for input, output and storage (UserCreate, UserRead, UserRow) instead of one model with optional fields. Confidence: 0.90 - Set model_config = ConfigDict(extra="forbid") on request models so typos in payloads fail loudly. Confidence: 0.85 - Make value objects and events immutable with frozen=True. Confidence: 0.80 - Prefer precise types over plain str: EmailStr, HttpUrl, UUID, PositiveInt, constr with a pattern, Literal for small enums. Confidence: 0.85 - Use Annotated types with Field constraints and reuse them as named aliases (Slug = Annotated[str, Field(pattern=...)]). Confidence: 0.80 - Put single-field rules in field_validator and cross-field rules in model_validator(mode="after"); keep validators pure with no I/O. Confidence: 0.90 - Model variants with discriminated unions on a type field instead of trying each model in order. Confidence: 0.85 - Use timezone-aware datetimes only (AwareDatetime) and reject naive ones at the boundary. Confidence: 0.85 - Store money as Decimal with fixed places, never float. Confidence: 0.95 - Load settings with pydantic-settings from environment variables, with a prefix per service and SecretStr for secrets. Confidence: 0.90 - Never return ORM objects from an API directly; convert with model_validate(obj, from_attributes=True) into a response model. Confidence: 0.85 - Keep strict mode on for internal messages and allow lax coercion only on user-facing form input. Confidence: 0.70 - Use alias_generator with to_camel when the wire format is camelCase, and keep snake_case attributes in Python. Confidence: 0.80 - Serialize with model_dump(mode="json", exclude_none=True) for APIs so dates and decimals become stable strings. Confidence: 0.75 - Use TypeAdapter for validating plain lists, dicts and unions without wrapping them in a dummy model. Confidence: 0.80 - Export JSON Schema with model_json_schema and commit it, so API clients and docs stay in sync. Confidence: 0.70 - Return validation errors as a list of field paths and messages; never leak the raw exception text to clients. Confidence: 0.85 - Avoid heavy business logic and database calls inside models; models describe shape, services do work. Confidence: 0.85 - Test models with table-driven pytest cases for valid and invalid payloads, plus a few Hypothesis property tests for parsers. Confidence: 0.70 - Run mypy or pyright with the Pydantic plugin in CI so model fields and call sites are type-checked. Confidence: 0.80

Photoreal sunrise over a calm lotus pond: one large open pink lotus with a yellow seed pod, closed buds on tall stems, round green leaves beaded with droplets, mirror-still water, a thin layer of low mist and warm golden backlight. Step 1 of the Misty Lotus Pond workflow.
A photorealistic wide photograph of a calm lotus pond at sunrise. In the foreground, one large pink lotus flower is fully open, its pale pink petals with deeper pink tips around a yellow seed pod and golden stamens. Around it stand a few closed pink buds on tall, slender stems and large round green leaves, some flat on the water, some raised and slightly cupped, with clear water droplets beading on their surface. The still, dark water reflects the flowers, the leaves and the warm sky. A thin, low layer of mist lies over the pond and softens the middle distance, where more lotus leaves and flowers fade into the haze. Far behind, a soft silhouette of trees. The sun is low behind the mist, giving warm golden backlight that makes the petals glow at their edges and the mist shine, while the shadows stay cool blue-green. 70 mm lens at water level, the foreground flower and nearest leaves sharp, the background gently blurred. Peaceful, quiet early-morning mood with soft pink, gold and green tones. No people, no animals, no insects, no boats, no buildings, no readable text or logos. Wide 16:9.

A photoreal macro still of a hand-thrown celadon tea bowl repaired with kintsugi: pale sea-green crackle glaze, branching gold lacquer seams and a gold-filled chip at the rim, on dark slate beside folded linen and a leaf, lit by low window light that makes the gold glow.
A photorealistic close-up studio photograph of a handmade celadon tea bowl repaired with kintsugi. The bowl has a soft, pale sea-green glaze with a fine crackle pattern and a slightly uneven, hand-thrown rim. It was broken into several pieces and joined again with bright gold lacquer seams that branch across the side like rivers on a map; one small missing chip at the rim is filled entirely with smooth gold. The bowl stands slightly off center on a dark, matte slate board, next to a folded piece of undyed linen and a single dark green leaf. The background is a deep charcoal wall that fades into shadow. Low, soft window light from the left makes the gold seams glow and catch small highlights, shows the depth of the crackled glaze and casts a long, gentle shadow to the right. 100 mm macro lens at a slight downward angle, shallow depth of field: the front seams tack-sharp, the back rim and the linen gently blurred. Calm, minimal, contemplative mood with a palette of sea green, gold, charcoal and warm linen. No people, no hands, no steam, no readable text or logos. Square 1:1.