prompts.example.vnprompts.example.vnprompts.example.vn
TeamsBotsSkillsPromptsPromptmasters
BookFor KidsDevelopers
Login
CC0 2026 prompts.example.vn
DeepWikiHow to...DocsAPIPrivacyTermsSupportAboutGitHub
All Tags

Tracking Prompts

5 prompts12 bots
Support Ticket SLA Breach Analyzer
Skill

Measures support SLAs from a helpdesk ticket export in business hours: first response and resolution times, attainment by priority, agent, channel and week, open tickets breached or about to breach, reopen rate and data gaps, plus a weekly review for support leads and founders. Stdlib Python.

---
name: support-ticket-sla-breach-analyzer
description: Measures support SLAs from a helpdesk ticket export in business hours: first response and resolution times, attainment by priority, agent, channel and week, open tickets breached or about to breach, reopen rate and data gaps, plus a weekly review for support leads and founders. Stdlib Python.
---

# Support Ticket SLA Breach Analyzer

You help support leads, operations managers and founders of small companies see whether they keep the promises they make to customers about response and resolution times. Helpdesk dashboards often show a single average, count nights and weekends as waiting time, or hide which priority, channel or week is slipping. You take a plain ticket export and the team's SLA policy, measure every ticket in business hours, and turn the result into a short, fair review: where the team is on track, where it misses, which open tickets need attention today, and what to change in staffing, routing or the policy itself.

SLA numbers describe a system, not a person. Slow agents usually have the hardest queue, too many channels or no cover. Always look at workload and routing before drawing conclusions about individuals, and never suggest using the report for discipline without context.

## Files in this skill

- `scripts/sla_report.py` - reads a ticket CSV and an SLA policy JSON, computes business minutes (per-weekday hours, holidays, optional 24/7 "calendar hours" for urgent tickets), first-response and resolution breaches, attainment by priority, agent, channel and ISO week, median and p90 first response, open tickets breached or at risk, and flags T01-T08 + E01; `--now`, `--since/--until`, `--risk-share`, `--format text|md|json|csv`, `--fail-on`, `--self-test` runs 21 checks (Python 3.8+ standard library only)
- `references/sla-metrics.md` - what first response, resolution, attainment, median and p90 mean, and which numbers to show to whom
- `references/business-hours-and-policies.md` - how business-hours clocks work, pausing, time zones, and how to set realistic targets
- `templates/weekly-sla-review.md` - a one-page weekly review for a support lead or founder
- `examples/tickets.csv` - two weeks of fictional tickets for a small SaaS team (4 agents, email, chat and phone), with open tickets, one typo row and one ticket closed by automation
- `examples/sla_policy.json` - Mon-Fri 09:00-18:00, holidays, targets for urgent (24/7), high, normal and low

## Workflow

### 1. Get the export and the policy
Ask for a CSV export of the period (two to four weeks is ideal) with these columns; most helpdesks can export them or a spreadsheet can rename them:
```
ticket_id,priority,channel,customer_tier,agent,created_at,first_response_at,resolved_at,status,reopened
T-1043,normal,email,business,dev,2026-11-16 12:20,2026-11-16 15:16,2026-11-18 09:45,solved,0
```
- Required: `ticket_id`, `priority`, `created_at`. Times as `YYYY-MM-DD HH:MM` in the team's local time (convert UTC exports first).
- `first_response_at` = first public reply by a human (not the auto-acknowledgement); empty if none yet.
- `resolved_at` empty for open tickets; `reopened` = 1 if the customer reopened it.
Then write the policy JSON like `examples/sla_policy.json`: business hours, holidays, an `attainment_goal_pct` and, per priority, `first_response_min` and `resolution_min` in business minutes. Add `"calendar_hours": true` to a priority that is covered 24/7.

### 2. Run the analysis
```
python3 scripts/sla_report.py tickets.csv --policy sla_policy.json --now "2026-11-27 17:00"
python3 scripts/sla_report.py tickets.csv --policy sla_policy.json --format md > sla-review.md
python3 scripts/sla_report.py tickets.csv --policy sla_policy.json --since 2026-11-23 --until 2026-11-27
python3 scripts/sla_report.py tickets.csv --policy sla_policy.json --format csv > tickets-sla.csv   # per ticket
python3 scripts/sla_report.py --self-test
```
`--now` is the moment open tickets are measured against (default: the latest timestamp in the file). Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable file, bad policy or missing columns.

| Code | Severity | Finding |
|---|---|---|
| T01 | medium / high | a priority's first-response or resolution attainment is below the goal (high for urgent/high priority or 20+ points below) |
| T02 | medium / high | an open ticket has already breached its first-response or resolution target |
| T03 | medium | an open ticket has `--risk-share` (default 25%) or less of its target left |
| T04 | low | an agent's first-response attainment is 15+ points below the team (5+ tickets) |
| T05 | low | more than 10% of tickets were reopened |
| T06 | info | a ticket was solved without a recorded first response |
| T07 | medium | tickets with a priority that has no target in the policy |
| T08 | info | fewer than 20 tickets; percentages are rough |
| E01 | medium | rows that could not be read (line number and reason shown) |

### 3. Act on today first
Start with T02 and T03: list the open tickets that need a reply or an update now, highest priority first, with the owner. A short, honest update to a customer whose ticket is late is better than silence.

### 4. Find the pattern
Use `references/sla-metrics.md` to read the tables. Compare priorities, channels, weeks and agents. Typical causes and fixes:
- Misses cluster on Monday mornings or after holidays: backlog from the weekend; stagger shifts or add a Monday triage hour.
- Email misses but chat is fine: agents are pulled into live channels; protect email time blocks or set separate owners.
- One agent's numbers are low (T04): check their queue (priority mix, enterprise customers, hard product areas), hours and cover before anything else.
- Urgent first response is slow outside hours: the 24/7 promise has no on-call; either add an on-call rota or change the policy.
- High reopen rate (T05): tickets are closed too early; add a "confirm it works" step.
- Targets missed by a few minutes everywhere: the targets may be unrealistic for the staffing; see `references/business-hours-and-policies.md`.

### 5. Report
Fill `templates/weekly-sla-review.md`. Lead with the customer impact (how many customers waited too long, which tiers), then the numbers, then two or three concrete changes with an owner and a date. Repeat the analysis next week with the same policy and compare.

## Rules
- Measure with the policy the customer was promised; if contracts differ by tier, run the report per tier or add tier-specific priorities.
- Use business minutes consistently; say clearly when a priority uses calendar hours.
- Median and p90 tell more than the average; one ticket that waited a week should not hide or dominate the picture.
- Do not rank or shame individual agents; discuss T04 privately and with workload context.
- Customer names, emails and ticket text are personal data; work from IDs and keep exports out of shared chats.
- Auto-replies and bot answers are not a first response unless the policy explicitly says so.

FILE:references/sla-metrics.md
# SLA metrics in plain words

## First response time (FRT)
Time from ticket creation to the first public reply by a person, counted in business minutes. It tells customers "someone has seen my problem". Automatic acknowledgements do not count. Internal notes do not count.

## Resolution time
Time from creation to the moment the ticket is solved. Most helpdesks can pause this clock while waiting for the customer ("pending"); this script uses the raw times from the export, so if your team pauses the clock, export the helpdesk's own "business resolution time" or treat the numbers as an upper bound.

## Attainment (SLA met %)
The share of measured tickets that met the target: tickets met / tickets with a measured time. Open tickets without a first response are not in the first-response attainment until they get one; they appear as breached (T02) or at risk (T03) instead. A typical goal is 90-95% per priority.

## Median and p90
- Median: half of tickets got a first response faster than this. A good picture of the normal customer experience.
- p90: 9 out of 10 tickets were faster than this. Shows how bad the slow tail is; most complaints come from the tail.
- Averages are easily pulled up by a few very old tickets; prefer median and p90 in reports.

## Reopen rate
The share of solved tickets that the customer reopened. Above about 10% usually means tickets are closed before the problem is really fixed, or the answer was unclear.

## Backlog and at-risk tickets
Open tickets measured at `--now`. "Breached" means the target is already missed; "at risk" means only `--risk-share` (default 25%) of the target is left. This is the list a support lead uses at the start of a shift.

## Who needs which number
- Customers and contracts: attainment per priority and tier, against the promised targets.
- Support lead: open breached and at-risk tickets today, p90 per channel, Monday and post-holiday patterns.
- Founder or manager: weekly attainment trend, reopen rate, and whether staffing matches demand.
- Individual agents: their own queue and workload, discussed one to one, never a public leaderboard.

FILE:references/business-hours-and-policies.md
# Business hours, clocks and realistic targets

## How the business-hours clock works
Only time inside open hours counts. A ticket created Friday at 17:30 in a 09:00-18:00 Monday-Friday team has used 30 minutes by Friday evening and continues Monday at 09:00. Tickets created before opening start counting at opening time. Holidays listed in the policy count as closed days.

Example from the policy in `examples/`: a normal ticket created Monday 12:20 and solved Wednesday 09:45 used 340 + 540 + 45 = 925 business minutes, well inside the 1,620-minute (3 business days) resolution target.

## Calendar hours (24/7)
For priorities that promise round-the-clock cover (often "urgent" for outages), set `"calendar_hours": true`. Then every minute counts, nights and weekends included. Only promise this if someone is really on call.

## Time zones
Convert all timestamps to the team's local time before running the script (most helpdesks export UTC). Teams in several time zones can either use one "follow the sun" calendar with longer hours or run the report per team with its own policy.

## Pausing
Many helpdesks pause the resolution clock while a ticket waits for the customer. If you need paused times, export the helpdesk's own SLA fields; the script cannot see status history in a flat export.

## Setting realistic targets
1. Measure first: run the report with generous targets and look at the median and p90 per priority and channel.
2. Set first-response targets that the team meets 90-95% of the time with current staffing, then tighten slowly.
3. Keep few priorities (3-4) with clear definitions customers understand: urgent = service down or data at risk, high = a key feature blocked, normal = a question or a problem with a workaround, low = feedback or how-to.
4. Match channels to expectations: chat and phone need minutes, email hours.
5. Write down what happens on breach: who is alerted, when the customer gets an update, and whether service credits apply.
6. Review targets every quarter; when attainment is always 100%, the promise may be too loose to be useful.

## Rough staffing check
Tickets per week x average handling minutes / (agents x focused minutes per week) should stay well below 1. If it is close to 1, no process change will fix breaches; the team needs more people, fewer tickets (better docs, product fixes) or looser targets.

FILE:templates/weekly-sla-review.md
# Weekly support SLA review - {{week, e.g. 2026-W48}}

**Period:** {{from}} to {{to}} | **Policy:** {{policy name}} | **Goal:** {{90}}% per priority

## Customer impact
- {{N}} customers waited longer than promised for a first reply ({{tiers affected}}).
- {{N}} open tickets are breached right now; {{N}} more will breach today.

## Numbers
| Priority | Tickets | First response met | Resolution met | FR median | FR p90 |
|---|---|---|---|---|---|
| urgent | {{}} | {{}} | {{}} | {{}} | {{}} |
| high | {{}} | {{}} | {{}} | {{}} | {{}} |
| normal | {{}} | {{}} | {{}} | {{}} | {{}} |
| low | {{}} | {{}} | {{}} | {{}} | {{}} |

Trend vs last week: {{better / same / worse, one sentence}}. Reopen rate: {{x}}%.

## What we see
1. {{pattern, e.g. email first responses slip on Monday mornings}}
2. {{pattern}}
3. {{data gap, e.g. 1 unreadable row, 1 ticket closed by automation}}

## Today
| Ticket | Priority | State | Owner | Next step |
|---|---|---|---|---|
| {{id}} | {{}} | {{breached / at risk}} | {{}} | {{reply / update customer / escalate}} |

## Changes for next week
| Change | Owner | By |
|---|---|---|
| {{e.g. Monday 09:00-10:00 triage hour for the email backlog}} | {{}} | {{date}} |
| {{e.g. on-call rota for urgent phone tickets after 18:00}} | {{}} | {{date}} |

_Numbers describe the system, not individual people. Agent-level details are discussed one to one._

FILE:examples/tickets.csv
ticket_id,priority,channel,customer_tier,agent,created_at,first_response_at,resolved_at,status,reopened
T-1041,urgent,phone,enterprise,ben,2026-11-16 08:40,2026-11-16 09:27,2026-11-16 11:08,solved,0
T-1042,low,email,pro,dev,2026-11-16 11:00,2026-11-17 10:36,2026-11-24 10:19,solved,0
T-1043,normal,email,business,dev,2026-11-16 12:20,2026-11-16 15:16,2026-11-18 09:45,solved,0
T-1044,low,email,business,dev,2026-11-16 13:12,2026-11-16 16:45,2026-11-18 15:43,solved,0
T-1045,normal,chat,business,ana,2026-11-16 18:05,2026-11-17 10:33,2026-11-18 15:49,solved,0
T-1046,normal,email,enterprise,chloe,2026-11-16 18:12,2026-11-17 11:51,2026-11-19 16:22,solved,0
T-1047,normal,chat,business,dev,2026-11-17 15:48,2026-11-18 10:21,2026-11-20 13:42,solved,0
T-1048,normal,email,enterprise,ben,2026-11-17 19:00,2026-11-18 15:06,2026-11-24 10:19,solved,1
T-1049,low,chat,business,chloe,2026-11-18 08:33,2026-11-19 09:39,2026-11-20 15:14,solved,0
T-1050,low,email,business,dev,2026-11-18 09:05,2026-11-18 17:46,2026-11-24 16:46,solved,0
T-1051,normal,email,pro,chloe,2026-11-18 09:41,2026-11-18 11:15,2026-11-20 09:47,solved,0
T-1052,normal,email,pro,ben,2026-11-18 14:00,2026-11-19 15:00,2026-11-23 15:42,solved,0
T-1053,high,chat,free,ben,2026-11-18 15:41,2026-11-18 16:38,2026-11-19 10:56,solved,0
T-1054,high,chat,pro,dev,2026-11-19 14:33,2026-11-19 14:48,2026-11-20 15:11,solved,0
T-1055,normal,email,free,ben,2026-11-20 07:20,2026-11-20 13:18,2026-11-25 10:22,solved,0
T-1056,low,email,pro,ana,2026-11-20 09:12,2026-11-23 09:58,2026-11-25 13:32,solved,0
T-1057,normal,chat,pro,dev,2026-11-20 13:55,2026-11-23 09:26,2026-11-24 17:21,solved,0
T-1058,low,phone,pro,chloe,2026-11-20 16:20,2026-11-23 13:31,2026-11-24 15:29,solved,0
T-1059,normal,chat,pro,dev,2026-11-23 07:55,2026-11-23 10:26,2026-11-24 12:10,solved,0
T-1060,normal,email,pro,chloe,2026-11-23 09:12,2026-11-23 14:35,,open,0
T-1061,high,email,free,ana,2026-11-23 17:12,2026-11-24 09:06,2026-11-25 09:23,solved,0
T-1062,urgent,phone,enterprise,ana,2026-11-23 21:05,2026-11-23 21:36,2026-11-23 23:22,solved,1
T-1063,normal,chat,business,dev,2026-11-24 07:41,2026-11-24 14:03,2026-11-25 12:31,solved,0
T-1064,normal,phone,free,chloe,2026-11-24 08:48,2026-11-24 11:57,2026-11-27 16:11,solved,0
T-1065,high,email,enterprise,ben,2026-11-24 10:20,2026-11-24 11:03,2026-11-24 14:30,solved,0
T-1066,normal,email,pro,dev,2026-11-24 12:00,2026-11-24 14:08,,open,0
T-1067,low,email,pro,chloe,2026-11-24 18:33,2026-11-25 16:06,,open,0
T-1068,normal,phone,pro,ana,2026-11-24 18:41,2026-11-25 10:04,,open,0
T-1069,urgent,phone,free,ana,2026-11-25 13:05,2026-11-25 13:19,2026-11-25 16:34,solved,0
T-1070,normal,email,business,chloe,2026-11-25 17:48,2026-11-27 13:31,,open,0
T-1071,high,phone,pro,dev,2026-11-26 16:20,2026-11-27 09:46,2026-11-27 14:11,solved,0
T-1072,normal,email,pro,ana,2026-11-27 11:05,2026-11-27 13:47,,open,0
T-1073,normal,email,business,ana,2026-11-27 11:05,2026-11-27 12:17,,open,0
T-1074,normal,email,pro,chloe,2026-11-27 13:55,,,new,0
T-1075,high,phone,enterprise,ana,2026-11-27 15:20,2026-11-27 16:04,,open,0
T-1076,normal,email,business,chloe,2026-11-27 17:00,,,new,0
T-1077,low,chat,enterprise,ana,2026-11-27 17:12,,,new,0
T-1078,high,email,free,ana,2026-11-27 18:20,,,new,0
T-1079,high,chat,enterprise,dev,2026-11-27 16:10,,,new,0
T-1080,normal,email,pro,ben,2026-11-27 09:40,,,new,0
T-1081,normal,email,business,chloe,2026-11-24 10:15,2026-11-24 11:02,,open,0
T-1082,low,email,free,ana,2026-11-27 11:30,,,new,0
T-1083,normal,chat,pro,ana,2026-11-25 14:05,2026-11-25 14:40,,pending,0
T-1084,normal,email,pro,chloe,2026-11-31 10:00,,,new,0
T-1085,low,email,free,(bot),2026-11-20 12:00,,2026-11-20 12:01,solved,0

FILE:examples/sla_policy.json
{
  "name": "Example SaaS support policy",
  "business_hours": {"days": ["mon", "tue", "wed", "thu", "fri"], "start": "09:00", "end": "18:00"},
  "holidays": ["2026-11-26", "2026-12-25", "2026-12-31"],
  "attainment_goal_pct": 90,
  "targets": {
    "urgent": {"first_response_min": 30, "resolution_min": 240, "calendar_hours": true},
    "high": {"first_response_min": 60, "resolution_min": 540},
    "normal": {"first_response_min": 240, "resolution_min": 1620},
    "low": {"first_response_min": 540, "resolution_min": 2700}
  }
}

FILE:scripts/sla_report.py
#!/usr/bin/env python3
"""sla_report.py - measure support SLA attainment from a ticket export, in business hours.

Reads a ticket CSV (Zendesk, Freshdesk, Help Scout, Intercom, Jira Service Management or a
spreadsheet export with the columns below) and an SLA policy JSON (business hours, holidays and
first-response / resolution targets per priority). Computes elapsed business minutes per ticket,
breaches, attainment by priority, agent, channel and week, open tickets already breached or at
risk, and flags T01-T08 + E01.

Required columns: ticket_id, priority, created_at
Optional columns: first_response_at, resolved_at, status, agent, channel, customer_tier, reopened
Datetimes: "YYYY-MM-DD HH:MM" (or with seconds / a T), all in the policy's local time.

Usage:
  sla_report.py TICKETS.csv --policy POLICY.json [--now "YYYY-MM-DD HH:MM"] [--since DATE] [--until DATE]
                [--format text|md|json|csv] [--risk-share 0.25] [--fail-on none|info|low|medium|high]
  sla_report.py --self-test
Exit: 0 ok, 1 flags at or above --fail-on, 2 unreadable input. Python 3.8+, standard library only.
"""
import argparse, csv, io, json, statistics, sys
from datetime import date, datetime, time, timedelta

SEV = {"info": 0, "low": 1, "medium": 2, "high": 3}
FMT = ("%Y-%m-%d %H:%M", "%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M", "%Y-%m-%dT%H:%M:%S")
DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]


def parse_dt(s):
    s = (s or "").strip()
    if not s:
        return None
    s = s.replace("Z", "")
    for f in FMT:
        try:
            return datetime.strptime(s[:19] if "T" in s or s.count(":") == 2 else s, f)
        except ValueError:
            continue
    raise ValueError("bad datetime %r" % s)


def parse_hm(s):
    h, m = s.split(":")
    return time(int(h), int(m))


class Calendar:
    """Business hours: per-weekday open/close times and a set of holiday dates."""

    def __init__(self, policy):
        bh = policy.get("business_hours", {})
        days = [d.lower()[:3] for d in bh.get("days", ["mon", "tue", "wed", "thu", "fri"])]
        start, end = parse_hm(bh.get("start", "09:00")), parse_hm(bh.get("end", "17:00"))
        if end <= start:
            raise ValueError("business_hours end must be after start")
        self.hours = {DAYS.index(d): (start, end) for d in days}
        self.holidays = {date.fromisoformat(h) for h in policy.get("holidays", [])}

    def open_window(self, d):
        if d in self.holidays or d.weekday() not in self.hours:
            return None
        s, e = self.hours[d.weekday()]
        return datetime.combine(d, s), datetime.combine(d, e)

    def minutes(self, a, b):
        """Business minutes between datetimes a and b (0 if b <= a)."""
        if b <= a:
            return 0
        total, d = 0.0, a.date()
        while d <= b.date():
            w = self.open_window(d)
            if w:
                lo, hi = max(a, w[0]), min(b, w[1])
                if hi > lo:
                    total += (hi - lo).total_seconds() / 60
            d += timedelta(days=1)
        return int(round(total))


def load_policy(path):
    with open(path, encoding="utf-8") as fh:
        p = json.load(fh)
    if "targets" not in p or not isinstance(p["targets"], dict):
        raise ValueError("policy needs a 'targets' object keyed by priority")
    for k, t in p["targets"].items():
        if "first_response_min" not in t or "resolution_min" not in t:
            raise ValueError("target %r needs first_response_min and resolution_min" % k)
    return p


def read_tickets(text):
    rows, errors = [], []
    rd = csv.DictReader(io.StringIO(text))
    cols = {c.strip().lower() for c in (rd.fieldnames or [])}
    missing = {"ticket_id", "priority", "created_at"} - cols
    if missing:
        raise ValueError("missing columns: %s" % ", ".join(sorted(missing)))
    for i, raw in enumerate(rd, start=2):
        r = {k.strip().lower(): (v or "").strip() for k, v in raw.items() if k}
        try:
            created = parse_dt(r["created_at"])
            if created is None:
                raise ValueError("empty created_at")
            fr = parse_dt(r.get("first_response_at"))
            res = parse_dt(r.get("resolved_at"))
            if fr and fr < created:
                raise ValueError("first_response_at before created_at")
            if res and res < created:
                raise ValueError("resolved_at before created_at")
        except ValueError as e:
            errors.append(dict(line=i, ticket=r.get("ticket_id", ""), reason=str(e)))
            continue
        status = (r.get("status") or ("solved" if res else "open")).lower()
        rows.append(dict(id=r["ticket_id"], priority=r["priority"].lower(), created=created, first_response=fr,
                         resolved=res, status=status, agent=r.get("agent") or "(unassigned)",
                         channel=(r.get("channel") or "unknown").lower(), tier=r.get("customer_tier") or "",
                         reopened=(r.get("reopened") or "0").strip().lower() in ("1", "yes", "true", "y")))
    return rows, errors


def evaluate(tickets, policy, now, risk_share=0.25):
    cal = Calendar(policy)
    out = []
    for t in tickets:
        tg = policy["targets"].get(t["priority"])
        if tg is None:
            out.append(dict(t, known_priority=False)); continue
        mins = (lambda a, b: max(0, int(round((b - a).total_seconds() / 60)))) if tg.get("calendar_hours") else cal.minutes
        e = dict(t, known_priority=True, fr_target=tg["first_response_min"], res_target=tg["resolution_min"])
        e["fr_min"] = mins(t["created"], t["first_response"]) if t["first_response"] else None
        e["fr_breach"] = (e["fr_min"] > tg["first_response_min"]) if e["fr_min"] is not None else None
        e["res_min"] = mins(t["created"], t["resolved"]) if t["resolved"] else None
        e["res_breach"] = (e["res_min"] > tg["resolution_min"]) if e["res_min"] is not None else None
        e["open"] = t["resolved"] is None and t["status"] not in ("solved", "closed", "resolved")
        e["open_state"] = None
        if e["open"]:
            elapsed_res = mins(t["created"], now)
            waiting_fr = t["first_response"] is None
            elapsed_fr = mins(t["created"], now) if waiting_fr else None
            e["elapsed_open_min"] = elapsed_res
            if waiting_fr and elapsed_fr > tg["first_response_min"]:
                e["open_state"] = "breached_first_response"
            elif elapsed_res > tg["resolution_min"]:
                e["open_state"] = "breached_resolution"
            elif waiting_fr and tg["first_response_min"] - elapsed_fr <= risk_share * tg["first_response_min"]:
                e["open_state"] = "at_risk_first_response"; e["minutes_left"] = tg["first_response_min"] - elapsed_fr
            elif tg["resolution_min"] - elapsed_res <= risk_share * tg["resolution_min"]:
                e["open_state"] = "at_risk_resolution"; e["minutes_left"] = tg["resolution_min"] - elapsed_res
        out.append(e)
    return out


def rate(items, key):
    vals = [x[key] for x in items if x.get(key) is not None]
    if not vals:
        return None, 0
    return round(100.0 * sum(1 for v in vals if not v) / len(vals), 1), len(vals)


def pctl(vals, p):
    if not vals:
        return None
    v = sorted(vals)
    k = max(0, min(len(v) - 1, int(round(p / 100.0 * (len(v) - 1)))))
    return v[k]


def group(ev, key):
    g = {}
    for e in ev:
        if e.get("known_priority"):
            g.setdefault(e[key], []).append(e)
    rows = []
    for k, items in sorted(g.items()):
        fr, nfr = rate(items, "fr_breach"); rs, nrs = rate(items, "res_breach")
        frs = [x["fr_min"] for x in items if x.get("fr_min") is not None]
        rows.append(dict(key=k, tickets=len(items), fr_met_pct=fr, fr_measured=nfr, res_met_pct=rs, res_measured=nrs,
                         fr_median=statistics.median(frs) if frs else None, fr_p90=pctl(frs, 90),
                         reopened=sum(1 for x in items if x["reopened"])))
    return rows


def week_of(d):
    y, w, _ = d.isocalendar()
    return "%d-W%02d" % (y, w)


def analyze(tickets, errors, policy, now, risk_share=0.25):
    ev = evaluate(tickets, policy, now, risk_share)
    for e in ev:
        e["week"] = week_of(e["created"])
    known = [e for e in ev if e.get("known_priority")]
    goal = float(policy.get("attainment_goal_pct", 90))
    fr, nfr = rate(known, "fr_breach"); rs, nrs = rate(known, "res_breach")
    summary = dict(tickets=len(ev), from_=min((e["created"] for e in ev), default=None), to=max((e["created"] for e in ev), default=None),
                   fr_met_pct=fr, fr_measured=nfr, res_met_pct=rs, res_measured=nrs, goal_pct=goal,
                   open=sum(1 for e in known if e["open"]), reopened=sum(1 for e in known if e["reopened"]))
    by_priority, by_agent = group(ev, "priority"), group(ev, "agent")
    by_channel, by_week = group(ev, "channel"), group(ev, "week")
    flags = []

    def flag(code, sev, msg, ref=None):
        flags.append(dict(code=code, severity=sev, ref=ref, message=msg))

    for r in by_priority:
        for kind, label in (("fr", "first response"), ("res", "resolution")):
            v, n = r[kind + "_met_pct"], r[kind + "_measured"]
            if v is not None and n >= 3 and v < goal:
                sev = "high" if r["key"] in ("urgent", "high") or v < goal - 20 else "medium"
                flag("T01", sev, "%s SLA met %.1f%% of %d tickets (goal %.0f%%)" % (label, v, n, goal), r["key"])
    for e in known:
        if e["open_state"] and e["open_state"].startswith("breached"):
            flag("T02", "high" if e["priority"] in ("urgent", "high") else "medium",
                 "open ticket already breached (%s, %s, %d business min open)" % (e["open_state"].replace("breached_", "").replace("_", " "), e["priority"], e["elapsed_open_min"]), e["id"])
        elif e["open_state"]:
            flag("T03", "medium", "open ticket at risk: %d min left for %s (%s)" % (e["minutes_left"], e["open_state"].replace("at_risk_", "").replace("_", " "), e["priority"]), e["id"])
    team_fr = summary["fr_met_pct"]
    for r in by_agent:
        if r["fr_measured"] >= 5 and team_fr is not None and r["fr_met_pct"] is not None and r["fr_met_pct"] < team_fr - 15:
            flag("T04", "low", "first response met %.1f%% vs team %.1f%%; check workload and queue routing before judging the person" % (r["fr_met_pct"], team_fr), r["key"])
    if known and summary["reopened"] / float(len(known)) > 0.10:
        flag("T05", "low", "%d of %d tickets were reopened (%.0f%%); fast closes may hide unsolved problems" % (summary["reopened"], len(known), 100.0 * summary["reopened"] / len(known)))
    for e in known:
        if e["resolved"] and not e["first_response"]:
            flag("T06", "info", "solved without a recorded first response (data gap or solved by a macro/automation)", e["id"])
    unknown = sorted({e["priority"] for e in ev if not e.get("known_priority")})
    if unknown:
        flag("T07", "medium", "priorities without an SLA target: %s (%d tickets ignored)" % (", ".join(unknown), sum(1 for e in ev if not e.get("known_priority"))))
    if len(known) < 20:
        flag("T08", "info", "only %d tickets with a known priority; percentages are rough" % len(known))
    for er in errors:
        flag("E01", "medium", "line %d (%s): %s" % (er["line"], er["ticket"] or "?", er["reason"]))
    flags.sort(key=lambda f: (-SEV[f["severity"]], f["code"], str(f["ref"] or "")))
    worst = sorted([e for e in known if e.get("fr_min") is not None and e["fr_breach"]], key=lambda e: e["fr_min"] - e["fr_target"], reverse=True)[:5]
    return dict(summary=summary, by_priority=by_priority, by_agent=by_agent, by_channel=by_channel, by_week=by_week,
                open=[e for e in known if e["open_state"]], worst_first_response=worst, tickets=ev, flags=flags, errors=errors)


def hm(m):
    if m is None:
        return "-"
    m = int(round(m))
    return "%dh%02d" % (m // 60, m % 60) if m >= 60 else "%dm" % m


def p(v):
    return "  -  " if v is None else "%5.1f%%" % v


def table(rows, title, width=14):
    out = [title, "  %-*s %7s %9s %9s %9s %9s %8s" % (width, "", "tickets", "FR met", "Res met", "FR med", "FR p90", "reopen")]
    for r in rows:
        out.append("  %-*s %7d %9s %9s %9s %9s %8d" % (width, str(r["key"])[:width], r["tickets"], p(r["fr_met_pct"]), p(r["res_met_pct"]), hm(r["fr_median"]), hm(r["fr_p90"]), r["reopened"]))
    return out


def render_text(res):
    s = res["summary"]; out = ["Support SLA report"]
    out.append("  Tickets              %d (created %s to %s), %d open, %d reopened" % (s["tickets"], s["from_"].strftime("%Y-%m-%d") if s["from_"] else "-", s["to"].strftime("%Y-%m-%d") if s["to"] else "-", s["open"], s["reopened"]))
    out.append("  First response met   %s of %d measured (goal %.0f%%)" % (p(s["fr_met_pct"]).strip(), s["fr_measured"], s["goal_pct"]))
    out.append("  Resolution met       %s of %d measured" % (p(s["res_met_pct"]).strip(), s["res_measured"]))
    out.append("")
    out += table(res["by_priority"], "By priority"); out.append("")
    out += table(res["by_agent"], "By agent"); out.append("")
    out += table(res["by_channel"], "By channel"); out.append("")
    out += table(res["by_week"], "By week")
    out.append("")
    out.append("Open tickets breached or at risk (%d)" % len(res["open"]))
    for e in res["open"]:
        out.append("  %-8s %-7s %-12s %-26s open %s" % (e["id"], e["priority"], e["agent"][:12], e["open_state"], hm(e["elapsed_open_min"])))
    out.append("")
    out.append("Slowest first responses over target")
    for e in res["worst_first_response"]:
        out.append("  %-8s %-7s %-8s %s vs target %s" % (e["id"], e["priority"], e["channel"], hm(e["fr_min"]), hm(e["fr_target"])))
    out.append("")
    out.append("Findings (%d)" % len(res["flags"]))
    for f in res["flags"]:
        out.append("  [%s %s] %s%s" % (f["code"], f["severity"], (str(f["ref"]) + ": ") if f["ref"] else "", f["message"]))
    if not res["flags"]:
        out.append("  none")
    return "\n".join(out)


def render_md(res):
    s = res["summary"]; out = ["# Support SLA report", ""]
    out.append("**%d tickets**, %d open, %d reopened. First response met **%s** (goal %.0f%%), resolution met **%s**." % (s["tickets"], s["open"], s["reopened"], p(s["fr_met_pct"]).strip(), s["goal_pct"], p(s["res_met_pct"]).strip()))
    for title, rows in (("By priority", res["by_priority"]), ("By agent", res["by_agent"]), ("By channel", res["by_channel"]), ("By week", res["by_week"])):
        out += ["", "## " + title, "", "| | Tickets | FR met | Resolution met | FR median | FR p90 | Reopened |", "|---|---|---|---|---|---|---|"]
        out += ["| %s | %d | %s | %s | %s | %s | %d |" % (r["key"], r["tickets"], p(r["fr_met_pct"]).strip(), p(r["res_met_pct"]).strip(), hm(r["fr_median"]), hm(r["fr_p90"]), r["reopened"]) for r in rows]
    out += ["", "## Open tickets breached or at risk", ""]
    out += ["- `%s` %s, %s, %s, open %s" % (e["id"], e["priority"], e["agent"], e["open_state"].replace("_", " "), hm(e["elapsed_open_min"])) for e in res["open"]] or ["- none"]
    out += ["", "## Findings", ""]
    out += ["- **%s** (%s) %s%s" % (f["code"], f["severity"], ("`%s`: " % f["ref"]) if f["ref"] else "", f["message"]) for f in res["flags"]] or ["- none"]
    return "\n".join(out)


def render_csv(res):
    buf = io.StringIO(); w = csv.writer(buf, lineterminator="\n")
    w.writerow(["ticket_id", "priority", "agent", "channel", "week", "fr_business_min", "fr_target_min", "fr_breach", "res_business_min", "res_target_min", "res_breach", "open_state"])
    for e in res["tickets"]:
        if not e.get("known_priority"):
            continue
        b = lambda v: "" if v is None else ("yes" if v else "no")
        w.writerow([e["id"], e["priority"], e["agent"], e["channel"], e["week"], "" if e["fr_min"] is None else e["fr_min"], e["fr_target"], b(e["fr_breach"]),
                    "" if e["res_min"] is None else e["res_min"], e["res_target"], b(e["res_breach"]), e["open_state"] or ""])
    return buf.getvalue().rstrip("\n")


def to_json(res):
    def conv(o):
        if isinstance(o, (datetime, date)):
            return o.isoformat(sep=" ") if isinstance(o, datetime) else o.isoformat()
        raise TypeError(type(o))
    r = {k: v for k, v in res.items() if k != "tickets"}
    r["summary"] = dict(res["summary"]); r["summary"]["from"] = r["summary"].pop("from_")
    return json.dumps(r, indent=2, default=conv)


TEST_POLICY = {"business_hours": {"days": ["mon", "tue", "wed", "thu", "fri"], "start": "09:00", "end": "17:00"},
               "holidays": ["2026-12-25"], "attainment_goal_pct": 90,
               "targets": {"urgent": {"first_response_min": 30, "resolution_min": 240, "calendar_hours": True},
                           "normal": {"first_response_min": 240, "resolution_min": 1440}}}


def self_test():
    checks = []

    def ok(name, cond):
        checks.append((name, bool(cond)))

    cal = Calendar(TEST_POLICY)
    D = lambda s: datetime.strptime(s, "%Y-%m-%d %H:%M")
    ok("same day minutes", cal.minutes(D("2026-11-30 10:00"), D("2026-11-30 11:30")) == 90)
    ok("before opening counts from 09:00", cal.minutes(D("2026-11-30 07:00"), D("2026-11-30 09:45")) == 45)
    ok("overnight skips closed hours", cal.minutes(D("2026-11-30 16:30"), D("2026-12-01 09:30")) == 60)
    ok("weekend skipped", cal.minutes(D("2026-12-04 16:00"), D("2026-12-07 10:00")) == 120)
    ok("holiday skipped", cal.minutes(D("2026-12-24 16:00"), D("2026-12-28 09:30")) == 60 + 30)
    ok("reverse is zero", cal.minutes(D("2026-12-01 10:00"), D("2026-12-01 09:00")) == 0)
    csv_text = ("ticket_id,priority,created_at,first_response_at,resolved_at,status,agent,channel,reopened\n"
                "A,normal,2026-11-30 10:00,2026-11-30 11:00,2026-11-30 15:00,solved,ana,email,0\n"
                "B,normal,2026-11-30 16:00,2026-12-01 13:30,2026-12-03 10:00,solved,ben,email,1\n"
                "C,urgent,2026-12-05 23:00,2026-12-05 23:20,2026-12-06 01:00,solved,ana,phone,0\n"
                "D,normal,2026-12-01 09:00,,,open,ben,chat,0\n"
                "E,low,2026-12-01 09:00,,,open,ben,chat,0\n"
                "F,normal,2026-12-01 10:00,2026-12-01 09:00,,open,ana,chat,0\n"
                "G,normal,2026-12-01 13:30,,,open,ana,chat,0\n")
    rows, errs = read_tickets(csv_text)
    ok("bad row reported", len(errs) == 1 and errs[0]["ticket"] == "F" and errs[0]["line"] == 7)
    res = analyze(rows, errs, TEST_POLICY, D("2026-12-01 17:00"))
    t = {e["id"]: e for e in res["tickets"]}
    ok("A first response 60 min met", t["A"]["fr_min"] == 60 and t["A"]["fr_breach"] is False)
    ok("B overnight first response 330 min breached", t["B"]["fr_min"] == 330 and t["B"]["fr_breach"] is True)
    ok("C urgent uses calendar hours", t["C"]["fr_min"] == 20 and t["C"]["res_min"] == 120)
    ok("D open breached first response", t["D"]["open_state"] == "breached_first_response")
    ok("G open at risk", t["G"]["open_state"] == "at_risk_first_response" and t["G"]["minutes_left"] == 30)
    codes = {f["code"] for f in res["flags"]}
    ok("T07 unknown priority", "T07" in codes)
    ok("T02 and T03 present", {"T02", "T03"} <= codes)
    ok("T05 reopened", "T05" in codes)
    ok("E01 present", "E01" in codes)
    ok("fr met pct", res["summary"]["fr_met_pct"] == round(100 * 2 / 3, 1))
    ok("csv rows", len(render_csv(res).splitlines()) == 1 + 5)
    ok("json loads", json.loads(to_json(res))["summary"]["tickets"] == 6)
    try:
        read_tickets("id,prio\n1,2\n"); ok("missing columns rejected", False)
    except ValueError:
        ok("missing columns rejected", True)
    ok("iso T datetime", parse_dt("2026-12-01T09:05:00") == D("2026-12-01 09:05"))
    bad = [n for n, c in checks if not c]
    if bad:
        print("self-test FAILED: " + ", ".join(bad)); return 1
    print("self-test OK: %d checks" % len(checks)); return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("tickets", nargs="?")
    ap.add_argument("--policy")
    ap.add_argument("--now", help="reference time for open tickets (default: latest timestamp in the file)")
    ap.add_argument("--since"); ap.add_argument("--until")
    ap.add_argument("--risk-share", type=float, default=0.25, help="open ticket is at risk when this share of the target is left")
    ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
    ap.add_argument("--fail-on", choices=["none"] + list(SEV), default="none")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.tickets or not a.policy:
        ap.print_usage(sys.stderr); print("error: TICKETS.csv and --policy are required", file=sys.stderr); return 2
    try:
        policy = load_policy(a.policy)
        Calendar(policy)
        with open(a.tickets, encoding="utf-8-sig") as fh:
            rows, errors = read_tickets(fh.read())
        if a.since:
            rows = [r for r in rows if r["created"].date() >= date.fromisoformat(a.since)]
        if a.until:
            rows = [r for r in rows if r["created"].date() <= date.fromisoformat(a.until)]
        now = parse_dt(a.now) if a.now else max([x for r in rows for x in (r["created"], r["first_response"], r["resolved"]) if x], default=datetime.now())
    except (OSError, ValueError, json.JSONDecodeError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    res = analyze(rows, errors, policy, now, a.risk_share)
    print({"text": render_text, "md": render_md, "json": to_json, "csv": render_csv}[a.format](res))
    if a.fail_on != "none" and any(SEV[f["severity"]] >= SEV[a.fail_on] for f in res["flags"]):
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
TrackingReportBusiness+4
F@f
0
Sleep Diary Pattern Analyzer
Skill

Turns a nightly sleep diary CSV into clear numbers and patterns: total sleep, time in bed, sleep efficiency, time to fall asleep, regularity, social jet lag between workdays and free days, weekly trends, and flags for late caffeine, long naps, alcohol nights and very short nights. Stdlib Python.

---
name: sleep-diary-pattern-analyzer
description: Turns a nightly sleep diary CSV into clear numbers and patterns: total sleep, time in bed, sleep efficiency, time to fall asleep, regularity, social jet lag between workdays and free days, weekly trends, and flags for late caffeine, long naps, alcohol nights and very short nights. Stdlib Python.
---

# Sleep Diary Pattern Analyzer

You help people who feel they sleep badly look at their own sleep with real numbers instead of impressions. Most people only remember the worst nights. A two- or three-week sleep diary shows what is actually going on: how long they sleep, how much time they lie awake, how much their schedule moves between workdays and weekends, and whether things like late coffee, evening drinks or long naps line up with worse nights. You read the diary, explain the numbers in plain words and suggest a few small, realistic experiments.

You are not a doctor and this is not a diagnosis. A sleep diary is a self-help and conversation tool; sleep clinicians use the same kind of diary, but they combine it with an interview and sometimes tests. Always point people to `references/when-to-get-help.md` when the diary or their description shows warning signs.

## Files in this skill

- `scripts/sleep_diary.py` - reads the diary CSV (times in HH:MM, nights crossing midnight handled automatically), computes per-night time in bed, total sleep, efficiency and sleep midpoint, a summary, a weekly table and flags S01-S10 + E01; `--format text|md|json|csv`, `--since/--until`, `--target-hours`, `--fail-on`, `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/sleep-metrics.md` - what each number means, how it is calculated and typical ranges for adults
- `references/when-to-get-help.md` - warning signs that need a doctor or sleep specialist instead of a spreadsheet, and limits of a diary
- `templates/two-week-sleep-review.md` - a short, friendly review with numbers, patterns and 2-3 experiments
- `examples/sleep_diary.csv` - 3 fictional weeks of an office worker who goes to bed late, drinks coffee in the afternoon on some days and sleeps in on weekends (one row has a typo on purpose)

## Workflow

### 1. Get a diary
If the person has no diary yet, give them the CSV header and ask them to fill one row every morning for at least 14 nights (7 is the minimum for patterns):
```
date,bedtime,sleep_latency_min,awakenings,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type
2026-11-09,23:55,10,2,14,06:50,07:05,0,11:30,0,4,work
```
- `date` = the evening they went to bed (a 00:20 bedtime still belongs to the previous date)
- `bedtime` = when they turned the lights off to sleep; `out_of_bed` = when they actually got up (defaults to `wake_time`)
- `sleep_latency_min` and `awake_min` are guesses, not measurements; rough numbers are fine
- `caffeine_last` = time of the last coffee, tea, cola or energy drink; `quality` = 1 (very bad) to 5 (very good)
- `day_type` = whether the NEXT day is a `work` or `free` day
Data from a sleep tracker or watch works too: export bedtime and wake time and fill the rest by hand.

### 2. Run the analysis
```
python3 scripts/sleep_diary.py sleep_diary.csv
python3 scripts/sleep_diary.py sleep_diary.csv --format md > sleep-review.md
python3 scripts/sleep_diary.py sleep_diary.csv --since 2026-11-16 --target-hours 8
python3 scripts/sleep_diary.py sleep_diary.csv --format csv      # per-night table for a spreadsheet
python3 scripts/sleep_diary.py --self-test
```
Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable file or missing columns.

| Code | Severity | Pattern |
|---|---|---|
| S01 | medium | average sleep efficiency below 85% |
| S02 | medium / high | average total sleep below 7 h / below 6 h |
| S03 | medium | wake-up time varies by more than 60 min (standard deviation) |
| S04 | low / medium | social jet lag of 1 h+ / 2 h+ (free-day sleep midpoint later than on workdays) |
| S05 | medium | average time to fall asleep over 30 min |
| S06 | low | nights with caffeine after 14:00 took 10+ min longer to fall asleep |
| S07 | low | naps over 30 min on 3+ days |
| S08 | low | nights after alcohol had 15+ min more time awake |
| S09 | info | fewer than 7 nights or gaps of 2+ missing nights |
| S10 | medium | 2+ nights with less than 5 h of sleep |
| E01 | medium | rows that could not be read (the line number and reason are shown) |

### 3. Explain and suggest
Use `references/sleep-metrics.md` to explain the numbers in one or two sentences each. Then pick at most three experiments for the next two weeks, linked to the flags, for example:
- S03/S04: the same wake-up time every day, weekends included, within 30-60 minutes; morning daylight soon after waking.
- S06: last caffeine before 14:00 for two weeks, then compare `--since` the start date.
- S07: naps under 30 minutes and before 15:00.
- S01/S05: get up after about 20 minutes awake in bed, do something calm in dim light, return when sleepy.
- S08: compare a few alcohol-free evenings.
The "consistent schedule idea" in the output uses the median workday wake time and `--target-hours`; present it as a starting point, not a rule, and never suggest less than 7 hours in bed on their own.

### 4. Report
Fill `templates/two-week-sleep-review.md`. Keep it kind and concrete; say what went well, too. Repeat the analysis after the experiment period and compare.

## Rules
- Never diagnose (insomnia, sleep apnea, depression, etc.) and never recommend medication, supplements or doses. Refer to a doctor when `when-to-get-help.md` applies.
- Do not recommend strict sleep restriction (shortening time in bed below current sleep) without a clinician; it is a treatment step that needs supervision.
- Diary values are estimates. Talk about patterns over several nights, never about one night.
- Correlation is not cause: "nights with late coffee took longer" is a hint for an experiment, not proof.
- Keep the diary private; it is health data. Do not ask for names or share it outside the conversation.

FILE:references/sleep-metrics.md
# Sleep diary metrics

All values come from the diary, so they are estimates. Look at averages and patterns over at least 7, ideally 14 or more nights.

| Metric | How it is calculated | Typical adult range / meaning |
|---|---|---|
| Time in bed (TIB) | `out_of_bed - bedtime` | Should be close to the sleep you need plus 15-30 min. Much more than that often means lying awake. |
| Time to fall asleep (sleep onset latency) | `sleep_latency_min` | 10-20 min is typical. Regularly over 30 min is a sign of trouble falling asleep (S05). Under 5 min every night can mean sleep debt. |
| Time awake at night (WASO) | `awake_min` | Short awakenings are normal; people rarely remember those under a few minutes. 30+ min per night on average is worth noting. |
| Total sleep time (TST) | `wake_time - (bedtime + latency) - awake_min` | Most adults need 7-9 hours (American Academy of Sleep Medicine, National Sleep Foundation). Below 7 h on average: S02. |
| Sleep efficiency (SE) | `TST / TIB x 100` | 85% or more is usually considered good; below 85% (S01) means a lot of time in bed awake. |
| Sleep midpoint | halfway between falling asleep and waking | A marker of the body clock. Later midpoints = later chronotype or a shifted schedule. |
| Social jet lag | free-day midpoint minus workday midpoint | Like flying one or two time zones every weekend. 1 h+ is common (S04 low), 2 h+ makes Monday mornings much harder (S04 medium). |
| Regularity | standard deviation of bedtime and wake time | Wake time matters most. A spread over 60 min (S03) makes the body clock drift. |
| Quality | the person's 1-5 rating | Subjective, but useful: compare quality with the other numbers. |

## Reading the numbers together
- Short sleep + high efficiency + very short latency: probably not enough time in bed (going to bed too late or getting up very early). Experiment: earlier lights out.
- Normal sleep time + low efficiency + long latency: lots of time awake in bed. Experiments: consistent wake time, get up when awake for long, avoid long naps and late caffeine.
- Good weekday numbers + big social jet lag: the weekend schedule pulls the body clock later; Monday and Tuesday nights then start badly.
- Worse nights after alcohol: alcohol helps people fall asleep but often causes more awakenings in the second half of the night.

## Caffeine and naps
Caffeine has an average half-life of about 5 hours (it varies a lot between people, from about 2 to 10 hours), so an afternoon coffee is still partly active at bedtime. Short naps (10-30 min) before mid-afternoon refresh most people without hurting night sleep; longer or later naps reduce sleep pressure in the evening.

## The "consistent schedule idea"
The script suggests a fixed wake time (the median workday wake time) and a lights-out time that gives `--target-hours` of sleep plus a typical time to fall asleep. It is a starting point for a conversation. Keeping the same wake time every day is the single most useful habit for a regular body clock.

FILE:references/when-to-get-help.md
# When a sleep diary is not enough

A diary helps people notice patterns and try small habit changes. Some situations need a doctor, ideally a general practitioner first, who can refer to a sleep specialist. Recommend getting help, kindly and clearly, when any of these apply:

## See a doctor soon
- Loud snoring with pauses in breathing, gasping or choking at night (noticed by a partner), especially with morning headaches or high blood pressure: possible sleep apnea.
- Strong sleepiness during the day: falling asleep while driving, in meetings or in conversations, even after enough hours in bed.
- Trouble falling or staying asleep at least 3 nights a week for 3 months or more, affecting the day: chronic insomnia has effective treatments, especially cognitive behavioral therapy for insomnia (CBT-I).
- An urge to move the legs in the evening with uncomfortable feelings that get better with movement.
- Acting out dreams, sudden muscle weakness with laughter or strong emotions, or sleep attacks.
- Sleep problems together with low mood, loss of interest, strong anxiety or thoughts of self-harm. If someone mentions thoughts of self-harm, encourage them to contact local emergency services or a crisis line right away.
- Sleep problems that started with a new medication, or that come with pain, breathing problems at night or frequent urination.
- Pregnancy, shift work with accidents or near misses, or a child or teenager with persistent sleep problems: get specific professional advice.

## Never do in this skill
- Diagnose a sleep disorder or rule one out.
- Recommend sleeping pills, melatonin doses, supplements or stopping a prescribed medication.
- Tell someone to drive or work in a safety-critical job when they report strong sleepiness.

## Limits of a diary
- Times are estimates; people often overestimate time awake and underestimate sleep, especially on bad nights.
- Wearable trackers estimate sleep from movement and heart rate; they are fine for bedtime and wake time but not exact for sleep stages.
- A few weeks show habits, not health. Bring the diary and the script's summary to the doctor; clinicians find a filled diary useful.

FILE:templates/two-week-sleep-review.md
# Your sleep review: {{from}} to {{to}} ({{N}} nights)

## The short version
{{2-3 sentences in plain words: how much you sleep, how regular it is, the main pattern, one thing that is already good}}

## Your numbers
| | Your average | Typical range |
|---|---|---|
| Sleep per night | {{6h38}} | 7-9 h |
| Time in bed | {{7h38}} | sleep + 15-30 min |
| Sleep efficiency | {{87%}} | 85% or more |
| Time to fall asleep | {{25 min}} | 10-20 min |
| Wake-up time variation | {{73 min}} | under 60 min |
| Social jet lag | {{1h49}} | under 1 h |

## Patterns we noticed
- {{e.g. On the 7 nights with coffee after 14:00 you needed about 42 minutes to fall asleep, compared with 16 minutes on other nights.}}
- {{...}}

## Experiments for the next two weeks (pick 2-3)
1. {{e.g. Wake up at 06:50 every day, also on weekends (within 30-60 minutes), and get daylight within an hour.}}
2. {{e.g. Last coffee before 14:00.}}
3. {{e.g. Keep naps under 30 minutes and before 15:00.}}

Keep filling the diary, then run the analysis again from {{start date}} and compare.

## Please talk to a doctor if
{{Only if relevant: the warning signs from when-to-get-help.md that apply, written kindly. Otherwise: "Nothing in your diary suggests you need medical help right now, but see a doctor if ..."}}

_This review is based on your own diary estimates and is not medical advice._

FILE:examples/sleep_diary.csv
date,bedtime,sleep_latency_min,awakenings,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type
2026-11-09,23:55,10,2,14,06:50,07:05,0,11:30,0,4,work
2026-11-10,23:10,50,2,14,06:50,07:00,0,16:30,0,2,work
2026-11-11,00:20,15,1,7,06:45,07:00,0,10:00,0,4,work
2026-11-12,23:25,50,1,7,06:50,06:55,40,16:00,0,3,work
2026-11-13,00:55,20,3,50,09:20,09:40,40,08:30,2,3,free
2026-11-14,00:55,10,3,55,09:20,10:00,40,,2,2,free
2026-11-15,00:20,15,2,14,06:45,07:00,0,08:30,0,4,work
2026-11-16,00:20,20,0,0,06:50,07:00,0,,0,4,work
2026-11-17,23:10,40,1,7,06:45,07:00,0,16:30,0,3,work
2026-11-18,23:40,40,1,7,06:45,06:55,0,16:00,0,3,work
2026-11-19,00:20,35,2,14,07:00,07:15,50,16:00,0,2,work
2026-11-20,00:40,10,2,35,09:20,10:00,40,,2,2,free
2026-11-22,23:25,10,2,14,06:45,07:00,0,11:30,0,4,work
2026-11-23,23:40,20,2,14,06:50,07:00,0,08:30,0,4,work
2026-11-24,00:50,40,2,60,06:45,06:55,0,16:30,0,1,work
2026-11-25,01:05,30,1,7,06:45,06:55,0,11:30,0,4,work
2026-11-26,23:25,40,1,7,07:00,07:05,0,16:30,0,2,work
2026-11-27,00:40,20,1,25,10:10,10:30,40,10:00,2,2,free
2026-11-28,01:30,10,3,55,10:10,10:40,50,08:30,2,3,free
2026-11-29,23:40,15,1,7,07:00,07:10,0,10:00,0,4,work
2026-11-30,23:30,15,,10,7:05,,0,,0,,work
2026-12-01,23:15,,1,abc,06:50,07:00,0,09:00,0,4,work

FILE:scripts/sleep_diary.py
#!/usr/bin/env python3
"""sleep_diary.py - turn a simple sleep diary CSV into clear sleep metrics and pattern flags.

One row per night. Required columns: date, bedtime, wake_time. Optional: sleep_latency_min,
awake_min, awakenings, out_of_bed, nap_min, caffeine_last, alcohol_drinks, quality, day_type.
Times are HH:MM (24 h); a night that crosses midnight is handled automatically. date is the
evening you went to bed (YYYY-MM-DD or DD.MM.YYYY). day_type is the NEXT day: work or free.

Per night: time in bed, sleep onset, total sleep time, sleep efficiency, sleep midpoint.
Summary: averages, regularity, workday vs free-day comparison (social jet lag), weekly table,
and flags S01-S10 + E01. Not a medical tool; see references/when-to-get-help.md.

Python 3.8+ standard library only.
Usage:
  sleep_diary.py DIARY.csv [--format text|md|json|csv] [--since YYYY-MM-DD] [--until YYYY-MM-DD]
                 [--target-hours 7.5] [--fail-on high|medium|low|none]
  sleep_diary.py --self-test
Exit codes: 0 = no flags at or above --fail-on (default none), 1 = flags at or above it, 2 = bad input.
"""
import argparse, csv, datetime, io, json, statistics, sys

FLAGS = {
    "S01": "average sleep efficiency below 85% (a lot of time in bed awake)",
    "S02": "average total sleep below the healthy adult range (7 h); below 6 h is high",
    "S03": "wake-up time varies a lot (standard deviation over 60 min)",
    "S04": "social jet lag: sleep midpoint on free days is 1 h or more later than on workdays (2 h+ is medium)",
    "S05": "average time to fall asleep over 30 min",
    "S06": "nights with caffeine after 14:00 took clearly longer to fall asleep (10 min+ on average)",
    "S07": "long daytime naps (over 30 min) on 3 or more days",
    "S08": "nights after alcohol had clearly more time awake (15 min+ on average)",
    "S09": "fewer than 7 nights logged, or gaps of 2+ missing nights; patterns are less reliable",
    "S10": "2 or more very short nights (under 5 h of sleep)",
    "E01": "rows that could not be read",
}
SEV_ORDER = {"high": 3, "medium": 2, "low": 1, "info": 0}


def parse_date(s):
    s = (s or "").strip()
    for fmt in ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y"):
        try:
            return datetime.datetime.strptime(s, fmt).date()
        except ValueError:
            pass
    raise ValueError("bad date %r" % s)


def parse_clock(s):
    s = (s or "").strip().replace(".", ":")
    h, _, m = s.partition(":")
    h, m = int(h), int(m or 0)
    if not (0 <= h <= 23 and 0 <= m <= 59):
        raise ValueError("bad time %r" % s)
    return h * 60 + m


def since_noon(clock_min):
    """Minutes since 12:00 on the diary date: 23:30 -> 690, 00:30 -> 750, 07:00 -> 1140.
    Assumes bedtimes after 12:00 belong to the evening and times before 12:00 to the next morning."""
    return clock_min - 720 if clock_min >= 720 else clock_min + 720


def num(row, key, default=0.0):
    v = (row.get(key) or "").strip().replace(",", ".")
    try:
        return float(v) if v else default
    except ValueError:
        raise ValueError("bad number %r in %s" % (v, key))


def fmt_clock(m_since_noon):
    m = int(round(m_since_noon + 720)) % 1440
    return "%02d:%02d" % (m // 60, m % 60)


def hm(minutes):
    minutes = int(round(minutes))
    sign = "-" if minutes < 0 else ""
    minutes = abs(minutes)
    return "%s%dh%02d" % (sign, minutes // 60, minutes % 60)


def read_nights(text, since=None, until=None):
    nights, errors = [], []
    rdr = csv.DictReader(io.StringIO(text))
    if not rdr.fieldnames:
        raise ValueError("empty file")
    cols = {c.strip().lower() for c in rdr.fieldnames if c}
    missing = {"date", "bedtime", "wake_time"} - cols
    if missing:
        raise ValueError("missing required column(s): " + ", ".join(sorted(missing)))
    for i, raw in enumerate(rdr, 2):
        row = {(k or "").strip().lower(): (v or "").strip() for k, v in raw.items()}
        if not any(row.values()):
            continue
        try:
            d = parse_date(row["date"])
            if (since and d < since) or (until and d > until):
                continue
            bed = since_noon(parse_clock(row["bedtime"]))
            wake = since_noon(parse_clock(row["wake_time"]))
            oob = since_noon(parse_clock(row["out_of_bed"])) if row.get("out_of_bed") else wake
            lat, awake = num(row, "sleep_latency_min"), num(row, "awake_min")
            onset = bed + lat
            if not (bed < wake <= oob) or onset >= wake:
                raise ValueError("times out of order (bed %s, wake %s, out of bed %s)" % (row["bedtime"], row["wake_time"], row.get("out_of_bed") or "-"))
            tib = oob - bed
            tst = wake - onset - awake
            if tst <= 0 or tib > 20 * 60:
                raise ValueError("implausible night (sleep %.0f min, in bed %.0f min)" % (tst, tib))
            caf = row.get("caffeine_last", "")
            q = row.get("quality", "")
            nights.append({
                "date": d.isoformat(), "bedtime": row["bedtime"], "wake_time": row["wake_time"],
                "tib_min": tib, "tst_min": tst, "latency_min": lat, "awake_min": awake,
                "awakenings": num(row, "awakenings", 0), "efficiency": round(100.0 * tst / tib, 1),
                "midpoint": onset + (wake - onset) / 2.0, "wake": wake, "bed": bed,
                "nap_min": num(row, "nap_min"), "late_caffeine": bool(caf) and parse_clock(caf) >= 14 * 60,
                "alcohol": num(row, "alcohol_drinks") > 0, "quality": int(q) if q else None,
                "day_type": (row.get("day_type") or "").lower() or None})
        except (ValueError, KeyError) as e:
            errors.append({"line": i, "error": str(e)})
    nights.sort(key=lambda n: n["date"])
    return nights, errors


def mean(xs):
    xs = [x for x in xs if x is not None]
    return sum(xs) / len(xs) if xs else None


def analyze(nights, errors, target_hours=7.5):
    flags = []

    def add(code, sev, detail):
        flags.append({"code": code, "severity": sev, "detail": detail})
    if errors:
        add("E01", "medium", "%d row(s): %s" % (len(errors), "; ".join("line %d %s" % (e["line"], e["error"]) for e in errors[:3])))
    if not nights:
        return {"summary": {"nights": 0}, "nights": [], "weekly": [], "flags": flags}
    tst = mean(n["tst_min"] for n in nights)
    eff = mean(n["efficiency"] for n in nights)
    lat = mean(n["latency_min"] for n in nights)
    wake_sd = statistics.pstdev([n["wake"] for n in nights]) if len(nights) > 1 else 0.0
    bed_sd = statistics.pstdev([n["bed"] for n in nights]) if len(nights) > 1 else 0.0
    work = [n for n in nights if n["day_type"] == "work"]
    free = [n for n in nights if n["day_type"] == "free"]
    sjl = (mean(n["midpoint"] for n in free) - mean(n["midpoint"] for n in work)) if work and free else None
    if eff < 85:
        add("S01", "medium", "average efficiency %.1f%%" % eff)
    if tst < 360:
        add("S02", "high", "average sleep %s" % hm(tst))
    elif tst < 420:
        add("S02", "medium", "average sleep %s" % hm(tst))
    if wake_sd > 60:
        add("S03", "medium", "wake time SD %d min" % round(wake_sd))
    if sjl is not None and sjl >= 60:
        add("S04", "medium" if sjl >= 120 else "low", "free-day midpoint %s later than workdays" % hm(sjl))
    if lat > 30:
        add("S05", "medium", "average %d min to fall asleep" % round(lat))
    lc = [n["latency_min"] for n in nights if n["late_caffeine"]]
    nc = [n["latency_min"] for n in nights if not n["late_caffeine"]]
    if len(lc) >= 2 and len(nc) >= 2 and mean(lc) - mean(nc) >= 10:
        add("S06", "low", "%d min vs %d min to fall asleep (%d late-caffeine nights)" % (round(mean(lc)), round(mean(nc)), len(lc)))
    longnaps = [n for n in nights if n["nap_min"] > 30]
    if len(longnaps) >= 3:
        add("S07", "low", "%d days with naps over 30 min" % len(longnaps))
    al = [n["awake_min"] for n in nights if n["alcohol"]]
    na = [n["awake_min"] for n in nights if not n["alcohol"]]
    if len(al) >= 2 and len(na) >= 2 and mean(al) - mean(na) >= 15:
        add("S08", "low", "%d min vs %d min awake at night (%d alcohol nights)" % (round(mean(al)), round(mean(na)), len(al)))
    dates = [datetime.date.fromisoformat(n["date"]) for n in nights]
    gaps = [(a, b) for a, b in zip(dates, dates[1:]) if (b - a).days >= 3]
    if len(nights) < 7 or gaps:
        add("S09", "info", "%d nights logged%s" % (len(nights), ("; gaps after " + ", ".join(a.isoformat() for a, _ in gaps)) if gaps else ""))
    short = [n for n in nights if n["tst_min"] < 300]
    if len(short) >= 2:
        add("S10", "medium", "%d nights under 5 h: %s" % (len(short), ", ".join(n["date"] for n in short)))
    flags.sort(key=lambda f: (-SEV_ORDER[f["severity"]], f["code"]))
    weeks = {}
    for n in nights:
        y, w, _ = datetime.date.fromisoformat(n["date"]).isocalendar()
        weeks.setdefault("%d-W%02d" % (y, w), []).append(n)
    weekly = [{"week": k, "nights": len(v), "avg_sleep": hm(mean(x["tst_min"] for x in v)),
               "avg_efficiency": round(mean(x["efficiency"] for x in v), 1),
               "avg_quality": (round(mean(x["quality"] for x in v), 1) if any(x["quality"] for x in v) else None)}
              for k, v in sorted(weeks.items())]
    wake_ref = statistics.median([n["wake"] for n in (work or nights)])
    summary = {
        "nights": len(nights), "from": nights[0]["date"], "to": nights[-1]["date"],
        "avg_sleep": hm(tst), "avg_time_in_bed": hm(mean(n["tib_min"] for n in nights)),
        "avg_efficiency_pct": round(eff, 1), "avg_latency_min": round(lat), "avg_awake_min": round(mean(n["awake_min"] for n in nights)),
        "avg_bedtime": fmt_clock(mean(n["bed"] for n in nights)), "avg_wake_time": fmt_clock(mean(n["wake"] for n in nights)),
        "bedtime_sd_min": round(bed_sd), "wake_sd_min": round(wake_sd),
        "workday_midpoint": fmt_clock(mean(n["midpoint"] for n in work)) if work else None,
        "free_day_midpoint": fmt_clock(mean(n["midpoint"] for n in free)) if free else None,
        "social_jet_lag": hm(sjl) if sjl is not None else None,
        "avg_quality": round(mean(n["quality"] for n in nights), 1) if any(n["quality"] for n in nights) else None,
        "anchor_wake_time": fmt_clock(wake_ref),
        "suggested_lights_out": fmt_clock(wake_ref - target_hours * 60 - max(15, min(lat, 30))),
        "target_hours": target_hours,
    }
    return {"summary": summary, "nights": nights, "weekly": weekly, "flags": flags}


def render(res, fmt):
    s = res["summary"]
    if fmt == "json":
        return json.dumps(res, indent=2, default=str)
    if fmt == "csv":
        b = io.StringIO(); w = csv.writer(b, lineterminator="\n")
        w.writerow(["date", "bedtime", "wake_time", "time_in_bed", "sleep", "efficiency_pct", "latency_min", "awake_min", "midpoint", "day_type", "quality"])
        for n in res["nights"]:
            w.writerow([n["date"], n["bedtime"], n["wake_time"], hm(n["tib_min"]), hm(n["tst_min"]), n["efficiency"], int(n["latency_min"]), int(n["awake_min"]), fmt_clock(n["midpoint"]), n["day_type"] or "", n["quality"] or ""])
        return b.getvalue().rstrip("\n")
    if not s.get("nights"):
        return "No readable nights.\n" + "\n".join("  %s %s" % (f["code"], f["detail"]) for f in res["flags"])
    lines = [
        ("Nights", "%d (%s to %s)" % (s["nights"], s["from"], s["to"])),
        ("Average sleep", "%s of %s in bed (efficiency %.1f%%)" % (s["avg_sleep"], s["avg_time_in_bed"], s["avg_efficiency_pct"])),
        ("Falling asleep", "%d min on average; %d min awake during the night" % (s["avg_latency_min"], s["avg_awake_min"])),
        ("Bedtime / wake time", "%s / %s (variation %d / %d min SD)" % (s["avg_bedtime"], s["avg_wake_time"], s["bedtime_sd_min"], s["wake_sd_min"])),
        ("Sleep midpoint", "workdays %s, free days %s, social jet lag %s" % (s["workday_midpoint"] or "-", s["free_day_midpoint"] or "-", s["social_jet_lag"] or "-")),
        ("Quality (1-5)", str(s["avg_quality"] or "-")),
        ("Consistent schedule idea", "wake at %s every day; lights out around %s for %.1f h of sleep" % (s["anchor_wake_time"], s["suggested_lights_out"], s["target_hours"])),
    ]
    if fmt == "md":
        out = ["## Sleep diary summary", "", "| Metric | Value |", "|---|---|"] + ["| %s | %s |" % l for l in lines]
        out += ["", "### Weekly", "", "| Week | Nights | Avg sleep | Efficiency | Quality |", "|---|---|---|---|---|"]
        out += ["| %s | %d | %s | %.1f%% | %s |" % (w["week"], w["nights"], w["avg_sleep"], w["avg_efficiency"], w["avg_quality"] or "-") for w in res["weekly"]]
        out += ["", "### Patterns", ""] + (["- **%s %s** %s - %s" % (f["severity"], f["code"], FLAGS[f["code"]], f["detail"]) for f in res["flags"]] or ["- none"])
        out += ["", "_Not medical advice. See when-to-get-help before changing sleep on purpose._"]
        return "\n".join(out)
    out = ["Sleep diary summary"] + ["  %-25s %s" % l for l in lines] + ["", "Weekly"]
    out += ["  %-9s %d night%s  sleep %s  efficiency %5.1f%%  quality %s" % (w["week"], w["nights"], "" if w["nights"] == 1 else "s", w["avg_sleep"], w["avg_efficiency"], w["avg_quality"] or "-") for w in res["weekly"]]
    out += ["", "Patterns"] + (["  %-6s %s  %s" % (f["severity"].upper(), f["code"], f["detail"]) for f in res["flags"]] or ["  none"])
    out += ["", "Not medical advice; see references/when-to-get-help.md."]
    return "\n".join(out)


def self_test():
    head = "date,bedtime,sleep_latency_min,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type\n"
    rows = [
        "2026-11-02,23:30,10,10,07:00,07:10,0,09:00,0,4,work",
        "2026-11-03,23:45,40,20,07:00,07:15,0,16:30,0,3,work",
        "2026-11-04,00:15,15,40,07:00,07:20,45,10:00,2,2,work",
        "2026-11-05,23:30,45,15,07:00,07:30,40,17:00,0,3,work",
        "2026-11-06,01:30,10,45,09:30,10:00,0,11:00,3,2,free",
        "2026-11-07,02:00,10,10,10:30,10:45,60,,0,4,free",
        "2026-11-08,23:00,20,10,07:00,07:05,0,08:30,0,4,work",
        "2026-11-09,bad,10,10,07:00,,,,,,work",
    ]
    nights, errs = read_nights(head + "\n".join(rows) + "\n")
    r = analyze(nights, errs, 7.5)
    codes = {f["code"] for f in r["flags"]}
    n0 = nights[0]
    checks = [
        ("7 nights read", len(nights) == 7), ("1 error row", len(errs) == 1 and errs[0]["line"] == 9),
        ("midnight crossing tib", n0["tib_min"] == 460), ("tst", n0["tst_min"] == 430),
        ("efficiency", n0["efficiency"] == round(100 * 430 / 460, 1)),
        ("after-midnight bedtime", nights[2]["bed"] == 735 and nights[2]["tst_min"] == 350),
        ("S04 social jet lag", "S04" in codes), ("S06 late caffeine", "S06" in codes),
        ("S07 naps", "S07" in codes), ("S08 alcohol", "S08" in codes), ("E01", "E01" in codes),
        ("S03 wake variation", "S03" in codes), ("no S10", "S10" not in codes),
        ("clock format", fmt_clock(750) == "00:30" and fmt_clock(1140) == "07:00"),
        ("hm", hm(430) == "7h10" and hm(-75) == "-1h15"),
        ("dd.mm.yyyy", parse_date("03.12.2026") == datetime.date(2026, 12, 3)),
        ("out of order rejected", read_nights(head + "2026-11-02,07:00,10,0,06:00,,,,,,\n")[1] != []),
        ("md render", render(r, "md").startswith("## Sleep diary summary")),
        ("csv render", render(r, "csv").count("\n") == 7),
    ]
    bad = [n for n, ok in checks if not ok]
    if bad:
        print("self-test FAILED:", ", ".join(bad)); print(sorted(codes)); return 1
    print("self-test OK: %d checks" % len(checks)); return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description="Analyze a sleep diary CSV (stdlib only).")
    ap.add_argument("diary", nargs="?")
    ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
    ap.add_argument("--since"); ap.add_argument("--until")
    ap.add_argument("--target-hours", type=float, default=7.5)
    ap.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="none")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.diary:
        ap.error("give a diary CSV (or --self-test)")
    try:
        text = sys.stdin.read() if a.diary == "-" else open(a.diary, encoding="utf-8-sig").read()
        nights, errors = read_nights(text, parse_date(a.since) if a.since else None, parse_date(a.until) if a.until else None)
    except (OSError, ValueError) as e:
        print("error: %s" % e, file=sys.stderr); return 2
    if not 4 <= a.target_hours <= 10:
        print("error: --target-hours must be between 4 and 10", file=sys.stderr); return 2
    res = analyze(nights, errors, a.target_hours)
    print(render(res, a.format))
    if a.fail_on == "none":
        return 0
    return 1 if any(SEV_ORDER[f["severity"]] >= SEV_ORDER[a.fail_on] for f in res["flags"]) else 0


if __name__ == "__main__":
    sys.exit(main())
TrackingDaily RoutineData Analysis+4
F@f
0
Strength Training Log Progress Analyzer
Skill

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:]))
TrackingTrainingData Analysis+5
F@f
0
Car Fuel Log Consumption and Cost Analyzer
Skill

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()
TrackingCostBudgeting+5
F@f
0
Household Product Recall Check and Registration Tracker (JSON)
Text

Build a JSON tracker for recall checks on the products in your home: normalize brands and models, find label locations, rank priority (car seats, cribs, heaters, batteries first), list official sources to check without inventing recalls, plan product registration, act on a known recall, flag secondhand items, and set a review schedule.

1You are a careful household product safety assistant. Help me build and maintain a recall check and product registration tracker for the products in my home, then return the result as JSON only, matching the schema below exactly.
2
3My inputs (fill in what you know; leave blank if unknown):
4- Country or region: [e.g., United States, United Kingdom, EU country, Canada, Australia]
5- Household notes: [e.g., baby or toddler at home, older adults, pets, renter or owner]
6- Product list, one per line: [category | brand | model name or number | approximate purchase date | where bought | serial or batch number if known | registered with maker? yes/no]
7 Example: Car seat | BrandX | Model 300 | 2025-03 | online store | SN unknown | no
8
9Instructions:
101. Normalize each product: category, brand, model, purchase date, retailer, and which identifiers I still need to find (model number, serial, batch or lot code, date code). Tell me exactly where such labels usually are for that kind of product (base, back panel, inside the door, under the seat, on the battery, on the packaging).
...+55 more lines
JSONTrackingSafety+3
F@f
0