Measures meeting load and focus time from an .ics calendar export: expands recurring meetings, drops declined, free and cancelled events, and reports weekly meeting share, focus blocks, back-to-back chains, double bookings, late meetings, no-lunch days and costly series. Stdlib Python.
---
name: calendar-meeting-load-and-focus-time-analyzer
description: Measures meeting load and focus time from an .ics calendar export: expands recurring meetings, drops declined, free and cancelled events, and reports weekly meeting share, focus blocks, back-to-back chains, double bookings, late meetings, no-lunch days and costly series. Stdlib Python.
---
# Calendar Meeting Load and Focus Time Analyzer
You help managers, founders and busy individual contributors see where their working week really goes. Most people feel that they "have too many meetings" but cannot say how many hours, which series cost the most, or why there is never a two-hour block left for deep work. You take a plain calendar export, measure it honestly, and turn the numbers into a short calendar reset plan: what to cut, shorten, merge, move to async, or protect.
A calendar shows invitations, not how valuable each meeting is. Some heavy weeks are right (planning, hiring, a launch). Use the numbers to start a conversation about trade-offs, never to judge a person or a team, and always ask what the person wants more time for before recommending cuts.
## Files in this skill
- `scripts/meeting_load.py` - reads an iCalendar (.ics) export, unfolds lines, converts time zones (TZID, UTC, Windows zone names), expands recurring meetings (RRULE DAILY/WEEKLY/MONTHLY with INTERVAL, COUNT, UNTIL, BYDAY incl. "1TH"/"-1FR", BYMONTHDAY, EXDATE, moved or cancelled instances via RECURRENCE-ID), skips cancelled, declined (with `--me`), free/transparent and all-day events, treats all-day "Out of office" or "Vacation" events as days off, and reports per day and ISO week: meeting hours and load, focus blocks, fragmented time, back-to-back chains, double bookings, meetings outside working hours, days without lunch, and series ranked by person-hours and cost; flags M01-M09; `--format text|md|json|csv`, `--fail-on`, `--self-test` runs 30 checks (Python 3.9+ standard library only)
- `references/meeting-load-metrics.md` - what each number means, sensible ranges, and how to read them for managers and makers
- `references/calendar-export-and-ics-notes.md` - how to export from Google Calendar, Outlook and Apple Calendar, and the ICS details that change the numbers
- `templates/calendar-reset-plan.md` - a one-page plan: numbers, decisions per series, protected focus time and a check-in date
- `examples/head-of-product.ics` - two fictional weeks of a head of product at a 60-person startup (standup, 1:1s, leadership sync, biweekly product review, monthly all-hands, a moved 1:1, a declined demo, a cancelled sync, a day off and an evening call with a US partner)
## Workflow
### 1. Get the export and the person's goals
Ask for an .ics export of the last 2-4 normal working weeks (see `references/calendar-export-and-ics-notes.md`) and the person's email address as it appears in invitations. Then ask three questions: what are your working hours and time zone, what do you need more time for (deep work, customers, coaching the team, thinking), and which meetings do you think are most and least valuable?
### 2. Run the analysis
```
python3 scripts/meeting_load.py calendar.ics --me you@company.com --since 2026-11-23 --until 2026-12-04
python3 scripts/meeting_load.py calendar.ics --me you@company.com --workday 08:30-17:30 --tz Europe/Istanbul
python3 scripts/meeting_load.py calendar.ics --me you@company.com --hourly-cost 75 --format md > meeting-load.md
python3 scripts/meeting_load.py calendar.ics --me you@company.com --focus-min 90 --max-load 50 # maker vs manager settings
python3 scripts/meeting_load.py calendar.ics --format csv > meetings.csv # one row per meeting
python3 scripts/meeting_load.py calendar.ics --me you@company.com --fail-on medium # e.g. a weekly reminder job
python3 scripts/meeting_load.py --self-test
```
Without `--since/--until` the window runs from the first to the last one-off (non-recurring) meeting in the file, because a series can start months earlier and open-ended series never end; pass both dates for exact periods. Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable file or bad option.
| Code | Severity | Signal |
|---|---|---|
| M01 | medium / high | weekly meetings take `--max-load` (default 40%) or more of working time (high at 1.5x) |
| M02 | medium | fewer than `--min-focus-blocks` (default 3) free blocks of `--focus-min` (default 120) minutes in a week |
| M03 | low | a chain of 3+ meetings with less than 5 minutes between them |
| M04 | medium | two accepted meetings overlap (double booking) |
| M05 | low / medium | a meeting before or after working hours (medium on a day off or non-working day) |
| M06 | low | a recurring meeting with `--large` (default 8) or more people, with its person-hours and cost |
| M07 | low | a recurring meeting of 30+ minutes that you organize without an agenda in the invite |
| M08 | info | something the script could not read exactly (unsupported rule, unknown time zone, bad line) |
| M09 | low | a working day with meetings and no free 30 minutes in the `--lunch` window |
### 3. Read the numbers with the person
Use `references/meeting-load-metrics.md`. Start with the week view (load and focus blocks), then the top series by person-hours: a few recurring meetings usually explain most of the load. Check the flags for quick wins: double bookings, meetings on days off, evening calls that could rotate, missing agendas.
### 4. Decide per series
For each of the top 5-8 series agree one decision: keep, shorten (60 -> 45 or 30 -> 25), lower the frequency, make attendance optional for some people, replace with an async update, merge with another meeting, or end it. Protect at least 2-3 focus blocks per week as real calendar events, and move recurring meetings to cluster on fewer days if possible.
### 5. Write the plan and check again
Fill `templates/calendar-reset-plan.md` with the numbers before and the target after, the decision per series, the protected focus blocks and who needs to be told. Run the script again after 2-4 weeks with the same settings and compare.
## Rules
- Never share someone's calendar details beyond the person who asked; summaries for a team use series names and totals, not private event titles.
- Person-hours and cost are rough estimates; say so and never present them as exact.
- A meeting that looks expensive can be the most valuable hour of the week; ask before recommending a cut.
- Recommend changes the person can make themselves first (their own meetings, declining, shortening); for meetings owned by others, suggest how to raise it.
- Use the same settings when comparing periods; changing working hours or `--focus-min` changes every number.
- Mention any M08 note, because unsupported rules or unknown time zones can make the numbers too low or too high.
FILE:references/meeting-load-metrics.md
# Meeting load metrics
## The core numbers
- **Meeting hours** - the time inside working hours covered by at least one accepted, busy meeting. Overlapping meetings are counted once (you can only be in one place), and double bookings are reported separately.
- **Load** - meeting hours divided by available working hours (working days only; days off from all-day "Out of office" events are removed). This is the number most people underestimate.
- **Focus block** - a free stretch of at least `--focus-min` minutes (default 120) inside working hours. Two hours is the usual minimum for writing, design, analysis or coding; use 90 for people whose work comes in shorter pieces.
- **Fragmented time** - free gaps shorter than 30 minutes between meetings. It looks free on the calendar but is rarely usable.
- **Back-to-back chain** - three or more meetings with less than 5 minutes between them: no break, no notes, late starts.
- **Person-hours** - duration times the number of people who did not decline. A 90-minute weekly meeting with 10 people costs 15 person-hours a week. Multiply by an average loaded hourly cost for a rough money figure.
- **Recurring share** - how much meeting time comes from recurring series. High shares (over 60%) mean the calendar runs on autopilot: the best place to cut.
## Rough ranges (adapt to the role)
| Role | Typical load | Focus blocks per week |
|---|---|---|
| Individual contributor (engineer, designer, analyst) | 10-25% | 6-10 |
| Team lead / senior IC | 25-40% | 4-6 |
| Manager of managers, head of function | 40-60% | 2-4 |
| Founder / CEO in a small company | 40-70% (spiky) | 2-3, protected on purpose |
Above about 60% for several weeks almost everyone loses the time to prepare, follow up and think; work moves into evenings.
## How to read the week
1. Load and focus blocks together: a 45% load with 4 focus blocks is fine; a 35% load with 0 focus blocks means the meetings are spread badly.
2. Top series by person-hours: usually 3-5 series explain half the load.
3. Flags for quick wins: double bookings, meetings on days off, missing agendas, evening calls that could rotate between time zones.
4. Days without lunch and long chains: small fixes (25/50-minute defaults, a lunch hold) make a big difference.
## What the numbers cannot tell
- Whether a meeting was useful, or what would happen without it.
- Work done outside the calendar (chat, email, reviews) and meetings that never made it into the calendar.
- Private events and events from other calendars that were not exported.
FILE:references/calendar-export-and-ics-notes.md
# Calendar export and ICS notes
## Exporting
- **Google Calendar** (web): Settings -> Settings for my calendars -> choose the calendar -> "Export calendar" downloads a zip with one .ics per calendar. Or Settings -> Import & export -> Export for all calendars.
- **Outlook** (desktop, Windows): File -> Save Calendar -> choose a date range and "Full details" -> .ics. Outlook on the web: Settings -> Calendar -> Shared calendars -> Publish a calendar, then download the ICS link.
- **Apple Calendar** (macOS): select the calendar in the sidebar -> File -> Export -> Export...
- **Fastmail, Proton, Nextcloud**: calendar settings -> export or the CalDAV/ICS link.
Export the work calendar only, and remove private calendars before sharing the file with anyone.
## Details that change the numbers
- **Time zones**: events carry `TZID=...`, UTC times end in `Z`, and Outlook may use Windows names such as "Turkey Standard Time". The script converts everything to `--tz` (default: the file's `X-WR-TIMEZONE`). Pass `--tz` explicitly if you travel or the file has no calendar time zone.
- **Recurring meetings**: a series is one VEVENT with an `RRULE`; skipped dates are `EXDATE`; a moved or cancelled single meeting is a second VEVENT with the same `UID` and a `RECURRENCE-ID`. Supported: DAILY, WEEKLY, MONTHLY with INTERVAL, COUNT, UNTIL, BYDAY (also "1TH", "-1FR") and BYMONTHDAY. Anything else (for example YEARLY or BYSETPOS) is counted once and reported as M08.
- **Declined meetings**: only visible when `--me` is your address as it appears in the ATTENDEE lines; otherwise declined meetings are counted as busy.
- **Free vs busy**: events marked "Free" (`TRANSP:TRANSPARENT`) are not counted. Many focus-time tools create busy events; those are counted as meetings, which is usually what you want to see - or exclude them by marking them free.
- **All-day events** are never counted as meetings. All-day events named like "Out of office", "OOO", "Vacation", "Holiday", "Day off", "Leave" or "Sick" make that day a day off.
- **Attendees**: rooms and resources (`CUTYPE=ROOM/RESOURCE`) and people who declined are not counted for person-hours. Large distribution lists appear as one attendee, so all-hands costs are often too low.
- **Exports from someone else's calendar** may hide titles ("Busy") and attendees; load numbers still work, series names and costs do not.
FILE:templates/calendar-reset-plan.md
# Calendar reset plan: {{name}}, {{role}}
**Period measured:** {{from}} to {{to}} ({{N}} working days, working hours {{09:00-18:00}}, {{time zone}})
**What I want more time for:** {{e.g. product strategy, customer conversations, coaching the team}}
## Numbers now and target
| Metric | Now | Target in 4 weeks |
|---|---|---|
| Meeting load (share of working time) | {{42%}} | {{30-35%}} |
| Focus blocks of 2+ hours per week | {{4}} | {{6}} |
| Back-to-back chains per week | {{2}} | {{0-1}} |
| Days without a lunch break | {{2}} | {{0}} |
| Meetings outside working hours per week | {{1}} | {{0-1, rotating}} |
## Decisions per series
| Series | People | h/week | Decision | Owner | Told by |
|---|---|---|---|---|---|
| {{Leadership sync}} | {{10}} | {{1.75}} | {{shorten 90 -> 60, written pre-read}} | {{CEO}} | {{date}} |
| {{Daily standup}} | {{9}} | {{1.25}} | {{3x per week + async updates}} | {{eng lead}} | {{date}} |
| {{Product review}} | {{12}} | {{0.75}} | {{agenda in invite, optional for 4 people}} | {{me}} | {{date}} |
## Protected time
- Focus blocks: {{Tue 09:45-12:00, Thu 13:00-16:00, Fri 13:00-17:00}} as busy events named "Focus"
- Lunch: {{12:30-13:15 daily hold}}
- Meeting-light day: {{Friday}}
## Defaults from now on
- New meetings 25 or 50 minutes, agenda in the invite, decision owner named.
- Recurring meetings reviewed every quarter; any series without a clear purpose ends.
- Evening calls across time zones rotate between the two sides.
## Check-in
Re-run the analysis on {{date}} with the same settings and compare with the numbers above.
FILE:examples/head-of-product.ics
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp//Calendar Export//EN
CALSCALE:GREGORIAN
METHOD:PUBLISH
X-WR-CALNAME:Alex Morgan
X-WR-TIMEZONE:Europe/Istanbul
BEGIN:VTIMEZONE
TZID:Europe/Istanbul
BEGIN:STANDARD
DTSTART:19700101T000000
TZOFFSETFROM:+0300
TZOFFSETTO:+0300
TZNAME:+03
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
UID:standup@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261123T093000
DTEND;TZID=Europe/Istanbul:20261123T094500
RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR
EXDATE;TZID=Europe/Istanbul:20261204T093000
SUMMARY:Daily standup
ORGANIZER;CN=Jonas:mailto:jonas@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
END:VEVENT
BEGIN:VEVENT
UID:one-on-one-sam@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261123T100000
DTEND;TZID=Europe/Istanbul:20261123T103000
RRULE:FREQ=WEEKLY;BYDAY=MO
SUMMARY:1:1 Alex / Sam
DESCRIPTION:Shared agenda doc: wins, blockers, career goals, feedback both
ways.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
END:VEVENT
BEGIN:VEVENT
UID:one-on-one-sam@example.com
DTSTAMP:20261205T080000Z
RECURRENCE-ID;TZID=Europe/Istanbul:20261130T100000
DTSTART;TZID=Europe/Istanbul:20261201T160000
DTEND;TZID=Europe/Istanbul:20261201T163000
SUMMARY:1:1 Alex / Sam (moved)
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
END:VEVENT
BEGIN:VEVENT
UID:one-on-one-priya@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261125T100000
DTEND;TZID=Europe/Istanbul:20261125T103000
RRULE:FREQ=WEEKLY;BYDAY=WE
SUMMARY:1:1 Alex / Priya
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
END:VEVENT
BEGIN:VEVENT
UID:ceo-1on1@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261126T110000
DTEND;TZID=Europe/Istanbul:20261126T114500
RRULE:FREQ=WEEKLY;BYDAY=TH
SUMMARY:1:1 with CEO
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
END:VEVENT
BEGIN:VEVENT
UID:leadership-sync@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261124T140000
DTEND;TZID=Europe/Istanbul:20261124T153000
RRULE:FREQ=WEEKLY;BYDAY=TU
SUMMARY:Leadership sync
DESCRIPTION:Standing agenda: metrics, hiring, top risks, decisions needed
this week.
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
END:VEVENT
BEGIN:VEVENT
UID:product-review@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261118T150000
DTEND;TZID=Europe/Istanbul:20261118T163000
RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=WE
SUMMARY:Product review
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
END:VEVENT
BEGIN:VEVENT
UID:design-critique@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261126T140000
DTEND;TZID=Europe/Istanbul:20261126T150000
RRULE:FREQ=WEEKLY;BYDAY=TH
SUMMARY:Design critique
DESCRIPTION:Bring 1-2 designs in progress; 15 minutes each; decisions go i
nto the design log.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
END:VEVENT
BEGIN:VEVENT
UID:all-hands@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261106T170000
DTEND;TZID=Europe/Istanbul:20261106T180000
RRULE:FREQ=MONTHLY;BYDAY=1TH
SUMMARY:All-hands
DESCRIPTION:Company update, team demos and open Q&A.
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
END:VEVENT
BEGIN:VEVENT
UID:us-partner@example.com
DTSTAMP:20261205T080000Z
DTSTART:20261123T153000Z
DTEND:20261123T161500Z
RRULE:FREQ=WEEKLY;BYDAY=MO
SUMMARY:US partner sync
ORGANIZER;CN=Partner.Lead:mailto:partner.lead@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Partner.Lead;PARTSTAT=ACCEPTED:mailto:partner.lead@example.com
END:VEVENT
BEGIN:VEVENT
UID:sprint-planning@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261123T130000
DTEND;TZID=Europe/Istanbul:20261123T143000
RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=MO
SUMMARY:Sprint planning
DESCRIPTION:Sprint goal, capacity, top backlog items, risks.
ORGANIZER;CN=Jonas:mailto:jonas@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-012@example.com
DTSTAMP:20261205T080000Z
DTSTART:20261123T080000Z
DTEND:20261123T090000Z
SUMMARY:Customer call: Northwind
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Customer.Ops;PARTSTAT=ACCEPTED:mailto:customer.ops@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-013@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261123T120000
DTEND;TZID=Europe/Istanbul:20261123T130000
SUMMARY:Pricing workshop
DESCRIPTION:Decide the 2027 price list proposal.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-014@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261124T100000
DTEND;TZID=Europe/Istanbul:20261124T120000
SUMMARY:Roadmap offsite prep
DESCRIPTION:Draft the H1 roadmap themes for the offsite.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-015@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261124T153000
DTEND;TZID=Europe/Istanbul:20261124T160000
SUMMARY:Vendor demo: analytics tool
ORGANIZER;CN=Vendor:mailto:vendor@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=DECLINED:mailto:alex@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-016@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261124T160000
DTEND;TZID=Europe/Istanbul:20261124T170000
SUMMARY:Interview: Senior PM
ORGANIZER;CN=Nina:mailto:nina@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-017@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261125T110000
DTEND;TZID=Europe/Istanbul:20261125T120000
SUMMARY:Customer advisory call
ORGANIZER;CN=Carlos:mailto:carlos@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-018@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261125T130000
DTEND;TZID=Europe/Istanbul:20261125T140000
SUMMARY:Analytics deep dive
DESCRIPTION:Activation funnel drop in week 47.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-019@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261125T163000
DTEND;TZID=Europe/Istanbul:20261125T173000
SUMMARY:Interview: Product Designer
ORGANIZER;CN=Nina:mailto:nina@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-020@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261126T130000
DTEND;TZID=Europe/Istanbul:20261126T140000
SUMMARY:Focus time
TRANSP:TRANSPARENT
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-021@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261126T143000
DTEND;TZID=Europe/Istanbul:20261126T150000
SUMMARY:Pricing page review
ORGANIZER;CN=Yuki:mailto:yuki@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-022@example.com
DTSTAMP:20261205T080000Z
DTSTART;VALUE=DATE:20261127
DTEND;VALUE=DATE:20261128
SUMMARY:Out of office
END:VEVENT
BEGIN:VEVENT
UID:evt-023@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261130T110000
DTEND;TZID=Europe/Istanbul:20261130T120000
SUMMARY:Board deck review
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-024@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261130T143000
DTEND;TZID=Europe/Istanbul:20261130T160000
SUMMARY:Quarterly planning
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Nina;PARTSTAT=ACCEPTED:mailto:nina@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-025@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261201T100000
DTEND;TZID=Europe/Istanbul:20261201T110000
SUMMARY:Customer interview 1
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Customer.A;PARTSTAT=ACCEPTED:mailto:customer.a@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-026@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261201T110000
DTEND;TZID=Europe/Istanbul:20261201T120000
SUMMARY:Customer interview 2
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Customer.B;PARTSTAT=ACCEPTED:mailto:customer.b@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-027@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261201T120000
DTEND;TZID=Europe/Istanbul:20261201T123000
SUMMARY:Sales handoff: Acme
ORGANIZER;CN=Carlos:mailto:carlos@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-028@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261202T110000
DTEND;TZID=Europe/Istanbul:20261202T120000
SUMMARY:Engineering estimate session
ORGANIZER;CN=Jonas:mailto:jonas@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-029@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261202T120000
DTEND;TZID=Europe/Istanbul:20261202T130000
SUMMARY:Lunch and learn: AI in support
ORGANIZER;CN=Lena:mailto:lena@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
ATTENDEE;CN=Tom;PARTSTAT=ACCEPTED:mailto:tom@example.com
ATTENDEE;CN=Ece;PARTSTAT=ACCEPTED:mailto:ece@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-030@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261202T130000
DTEND;TZID=Europe/Istanbul:20261202T140000
SUMMARY:Partner call: Globex
ORGANIZER;CN=Carlos:mailto:carlos@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Partner.B;PARTSTAT=ACCEPTED:mailto:partner.b@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-031@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261203T090000
DTEND;TZID=Europe/Istanbul:20261203T093000
SUMMARY:Investor update prep
ORGANIZER;CN=Ada:mailto:ada@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-032@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261203T120000
DTEND;TZID=Europe/Istanbul:20261203T130000
SUMMARY:Customer QBR: Initech
ORGANIZER;CN=Carlos:mailto:carlos@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Carlos;PARTSTAT=ACCEPTED:mailto:carlos@example.com
ATTENDEE;CN=Yuki;PARTSTAT=ACCEPTED:mailto:yuki@example.com
ATTENDEE;CN=Customer.C;PARTSTAT=ACCEPTED:mailto:customer.c@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-033@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261204T100000
DTEND;TZID=Europe/Istanbul:20261204T110000
SUMMARY:Weekly metrics review
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Ravi;PARTSTAT=ACCEPTED:mailto:ravi@example.com
ATTENDEE;CN=Ada;PARTSTAT=ACCEPTED:mailto:ada@example.com
ATTENDEE;CN=Ben;PARTSTAT=ACCEPTED:mailto:ben@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-034@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261204T150000
DTEND;TZID=Europe/Istanbul:20261204T153000
SUMMARY:Feature flag cleanup sync
STATUS:CANCELLED
ORGANIZER;CN=Jonas:mailto:jonas@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Jonas;PARTSTAT=ACCEPTED:mailto:jonas@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
END:VEVENT
BEGIN:VEVENT
UID:evt-035@example.com
DTSTAMP:20261205T080000Z
DTSTART;TZID=Europe/Istanbul:20261204T160000
DTEND;TZID=Europe/Istanbul:20261204T170000
SUMMARY:Team retro
DESCRIPTION:What went well, what to change, one experiment for next sprint.
ORGANIZER;CN=Alex:mailto:alex@example.com
ATTENDEE;CN=Alex Morgan;PARTSTAT=ACCEPTED:mailto:alex@example.com
ATTENDEE;CN=Sam;PARTSTAT=ACCEPTED:mailto:sam@example.com
ATTENDEE;CN=Priya;PARTSTAT=ACCEPTED:mailto:priya@example.com
ATTENDEE;CN=Mei;PARTSTAT=ACCEPTED:mailto:mei@example.com
ATTENDEE;CN=Omar;PARTSTAT=ACCEPTED:mailto:omar@example.com
ATTENDEE;CN=Lena;PARTSTAT=ACCEPTED:mailto:lena@example.com
END:VEVENT
END:VCALENDAR
FILE:scripts/meeting_load.py
#!/usr/bin/env python3
"""meeting_load.py - measure meeting load and focus time from an iCalendar (.ics) export.
Reads one person's calendar export (Google Calendar, Outlook, Apple Calendar, Fastmail ...),
expands recurring meetings (RRULE DAILY/WEEKLY/MONTHLY with INTERVAL, COUNT, UNTIL, BYDAY,
BYMONTHDAY, EXDATE and moved or cancelled instances via RECURRENCE-ID), drops cancelled,
declined, free (transparent) and all-day events, and measures, per day and ISO week inside
working hours: meeting hours and share of the working week, focus blocks, fragmented time,
back-to-back chains, double bookings, meetings outside working hours, days without a lunch
break, and the recurring series that cost the most person-hours. Flags M01-M09 + E01.
Usage:
meeting_load.py CALENDAR.ics [--me EMAIL] [--tz Europe/Istanbul] [--since YYYY-MM-DD] [--until YYYY-MM-DD]
[--workday 09:00-18:00] [--workdays mon-fri] [--focus-min 120] [--max-load 40]
[--min-focus-blocks 3] [--large 8] [--hourly-cost 0] [--lunch 11:30-14:00]
[--format text|md|json|csv] [--fail-on none|info|low|medium|high]
meeting_load.py --self-test
Exit: 0 ok, 1 flags at or above --fail-on, 2 unreadable input. Python 3.9+ (zoneinfo), standard library only.
"""
import argparse, csv, io, json, re, sys
from datetime import date, datetime, timedelta, timezone
try:
from zoneinfo import ZoneInfo
except ImportError: # pragma: no cover
ZoneInfo = None
SEV = {"info": 0, "low": 1, "medium": 2, "high": 3}
DAYS = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"]
WIN_TZ = {"Turkey Standard Time": "Europe/Istanbul", "W. Europe Standard Time": "Europe/Berlin",
"GMT Standard Time": "Europe/London", "Romance Standard Time": "Europe/Paris",
"Eastern Standard Time": "America/New_York", "Pacific Standard Time": "America/Los_Angeles",
"Central Standard Time": "America/Chicago", "UTC": "UTC"}
# ---------------------------------------------------------------- ICS parsing
def unfold(text):
return re.sub(r"\r?\n[ \t]", "", text).replace("\r\n", "\n").split("\n")
def parse_prop(line):
"""'DTSTART;TZID=Europe/Istanbul:20261124T100000' -> ('DTSTART', {'TZID': 'Europe/Istanbul'}, '20261124T100000')"""
m = re.match(r'^([A-Za-z0-9-]+)((?:;[^:;]+=(?:"[^"]*"|[^:;]*))*):(.*)$', line)
if not m:
return None
params = {}
for p in re.findall(r';([^=;]+)=("[^"]*"|[^:;]*)', m.group(2)):
params[p[0].upper()] = p[1].strip('"')
return m.group(1).upper(), params, m.group(3)
def unescape(v):
return v.replace("\\n", "\n").replace("\\N", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")
def get_zone(name, notes):
if not name:
return None
name = WIN_TZ.get(name, name)
if name.upper() in ("UTC", "Z", "GMT"):
return timezone.utc
if ZoneInfo:
try:
return ZoneInfo(name)
except Exception:
pass
notes.add("unknown time zone %r, treated as the analysis time zone" % name)
return None
def parse_dt(value, params, default_tz, notes):
"""Returns (aware datetime or date, is_all_day)."""
v = value.strip()
if params.get("VALUE") == "DATE" or re.fullmatch(r"\d{8}", v):
return date(int(v[:4]), int(v[4:6]), int(v[6:8])), True
m = re.fullmatch(r"(\d{8})T(\d{6})(Z?)", v)
if not m:
raise ValueError("bad date-time %r" % value)
dt = datetime.strptime(m.group(1) + m.group(2), "%Y%m%d%H%M%S")
if m.group(3) == "Z":
return dt.replace(tzinfo=timezone.utc), False
tz = get_zone(params.get("TZID"), notes) or default_tz
return dt.replace(tzinfo=tz), False
def parse_duration(v):
m = re.fullmatch(r"([+-])?P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?", v.strip())
if not m:
raise ValueError("bad duration %r" % v)
sign = -1 if m.group(1) == "-" else 1
w, d, h, mi, s = (int(x or 0) for x in m.groups()[1:])
return sign * timedelta(weeks=w, days=d, hours=h, minutes=mi, seconds=s)
def parse_ics(text, default_tz, notes):
events, cur, depth = [], None, []
cal_tz = None
for line in unfold(text):
if not line.strip():
continue
p = parse_prop(line)
if not p:
notes.add("skipped an unreadable line: %s" % line[:60])
continue
name, params, value = p
if name == "BEGIN":
depth.append(value.upper())
if value.upper() == "VEVENT":
cur = {"attendees": [], "exdates": [], "raw": {}}
continue
if name == "END":
if depth and depth[-1] == "VEVENT" and cur is not None:
events.append(cur); cur = None
if depth:
depth.pop()
continue
if name == "X-WR-TIMEZONE" and not cal_tz:
cal_tz = value.strip()
if cur is None or depth[-1] != "VEVENT":
continue
cur["raw"][name] = (params, value)
if name == "ATTENDEE":
cur["attendees"].append({"email": value.lower().replace("mailto:", "").strip(),
"partstat": params.get("PARTSTAT", "NEEDS-ACTION").upper(),
"role": params.get("ROLE", "REQ-PARTICIPANT").upper(),
"cutype": params.get("CUTYPE", "INDIVIDUAL").upper()})
elif name == "EXDATE":
cur["exdates"] += [(params, x) for x in value.split(",")]
return events, cal_tz
def parse_rrule(v):
r = {}
for part in v.split(";"):
if "=" in part:
k, val = part.split("=", 1); r[k.upper()] = val
return r
def expand(start, rule, window_start, window_end, notes, uid):
"""Yield instance starts (aware datetimes) for a supported RRULE."""
freq = rule.get("FREQ", "").upper()
interval = int(rule.get("INTERVAL", "1") or 1)
count = int(rule["COUNT"]) if "COUNT" in rule else None
until = None
if "UNTIL" in rule:
u = rule["UNTIL"]
until = datetime.strptime(u[:15], "%Y%m%dT%H%M%S").replace(tzinfo=timezone.utc) if "T" in u else \
datetime(int(u[:4]), int(u[4:6]), int(u[6:8]), 23, 59, 59, tzinfo=start.tzinfo)
unsupported = set(rule) - {"FREQ", "INTERVAL", "COUNT", "UNTIL", "BYDAY", "BYMONTHDAY", "WKST"}
if freq not in ("DAILY", "WEEKLY", "MONTHLY") or unsupported:
notes.add("recurring event %s uses an unsupported rule (%s); only its first instance is counted" % (uid, ";".join("%s=%s" % kv for kv in rule.items())))
yield start
return
byday = [d.strip() for d in rule.get("BYDAY", "").split(",") if d.strip()]
produced = 0
limit = window_end + timedelta(days=1)
def emit(dt):
nonlocal produced
if until and dt > until:
return False
if count is not None and produced >= count:
return False
produced += 1
return True
if freq == "DAILY":
d = start
while d <= limit:
if not byday or DAYS[d.weekday()] in byday:
if not emit(d): return
yield d
d = d + timedelta(days=interval)
elif freq == "WEEKLY":
days = sorted(DAYS.index(x[-2:]) for x in byday) if byday else [start.weekday()]
week0 = start - timedelta(days=start.weekday())
k = 0
while True:
wk = week0 + timedelta(weeks=k * interval)
if wk > limit:
return
for wd in days:
d = wk + timedelta(days=wd)
if d < start:
continue
if d > limit:
return
if not emit(d): return
yield d
k += 1
else: # MONTHLY
y, m = start.year, start.month
while True:
first = start.replace(year=y, month=m, day=1)
if first > limit:
return
cands = []
if "BYMONTHDAY" in rule:
for md in rule["BYMONTHDAY"].split(","):
try:
cands.append(first.replace(day=int(md)))
except ValueError:
pass
elif byday:
for bd in byday:
mm = re.fullmatch(r"([+-]?\d)?([A-Z]{2})", bd)
n, wd = int(mm.group(1) or 0), DAYS.index(mm.group(2))
days_in = [first + timedelta(days=i) for i in range(31) if (first + timedelta(days=i)).month == m]
match = [d for d in days_in if d.weekday() == wd]
if n == 0:
cands += match
elif -len(match) <= n <= len(match) and n != 0:
cands.append(match[n - 1] if n > 0 else match[n])
else:
try:
cands.append(first.replace(day=start.day))
except ValueError:
pass
for d in sorted(cands):
if d < start:
continue
if d > limit:
return
if not emit(d): return
yield d
m += interval
while m > 12:
m -= 12; y += 1
def build_instances(events, tz, window_start, window_end, me, notes):
"""Returns (instances, skipped_counts, all_day_off_dates)."""
insts, skipped, days_off = {}, {"cancelled": 0, "declined": 0, "free": 0, "all_day": 0}, set()
overrides = {}
masters = []
for ev in events:
raw = ev["raw"]
if "DTSTART" not in raw:
notes.add("event without DTSTART skipped"); continue
try:
st, allday = parse_dt(raw["DTSTART"][1], raw["DTSTART"][0], tz, notes)
if "DTEND" in raw:
en, _ = parse_dt(raw["DTEND"][1], raw["DTEND"][0], tz, notes)
elif "DURATION" in raw:
en = st + parse_duration(raw["DURATION"][1])
else:
en = st + (timedelta(days=1) if allday else timedelta(0))
except ValueError as e:
notes.add("event %s skipped: %s" % (raw.get("UID", ({}, "?"))[1], e)); continue
ev["start"], ev["end"], ev["allday"] = st, en, allday
ev["uid"] = raw.get("UID", ({}, "no-uid-%d" % id(ev)))[1].strip()
ev["summary"] = unescape(raw.get("SUMMARY", ({}, "(no title)"))[1]).strip()
ev["status"] = raw.get("STATUS", ({}, "CONFIRMED"))[1].strip().upper()
ev["transp"] = raw.get("TRANSP", ({}, "OPAQUE"))[1].strip().upper()
ev["description"] = unescape(raw.get("DESCRIPTION", ({}, ""))[1]).strip()
org = raw.get("ORGANIZER", ({}, ""))[1].lower().replace("mailto:", "").strip()
ev["organizer"] = org
if "RECURRENCE-ID" in raw:
rid, _ = parse_dt(raw["RECURRENCE-ID"][1], raw["RECURRENCE-ID"][0], tz, notes)
overrides[(ev["uid"], rid)] = ev
else:
masters.append(ev)
def keep(ev, st):
if ev["status"] == "CANCELLED":
skipped["cancelled"] += 1; return False
if ev["allday"]:
skipped["all_day"] += 1
if ev["transp"] != "TRANSPARENT" and re.search(r"out of office|\booo\b|vacation|holiday|day off|leave|sick", ev["summary"], re.I):
d = st
while d < ev["end"]:
days_off.add(d); d += timedelta(days=1)
return False
if ev["transp"] == "TRANSPARENT":
skipped["free"] += 1; return False
mine = [a for a in ev["attendees"] if me and a["email"] == me]
if mine and mine[0]["partstat"] == "DECLINED":
skipped["declined"] += 1; return False
return True
def add(ev, st):
en = st + (ev["end"] - ev["start"])
if isinstance(st, datetime):
st, en = st.astimezone(tz), en.astimezone(tz)
if en <= window_start or st >= window_end + timedelta(days=1):
return
elif not (window_start.date() <= st <= window_end.date()):
return
if not keep(ev, st):
return
people = [a for a in ev["attendees"] if a["cutype"] not in ("ROOM", "RESOURCE") and a["partstat"] != "DECLINED"]
n = max(len(people), 1)
insts[(ev["uid"], st)] = {"uid": ev["uid"], "summary": ev["summary"], "start": st, "end": en,
"attendees": n, "recurring": "RRULE" in ev["raw"] or ev.get("_override_of_series", False),
"organizer_is_me": bool(me) and ev["organizer"] == me, "has_agenda": len(ev["description"]) >= 20}
for ev in masters:
st = ev["start"]
if "RRULE" in ev["raw"] and not ev["allday"]:
ex = set()
for params, x in ev["exdates"]:
try:
ex.add(parse_dt(x, params, tz, notes)[0])
except ValueError:
pass
for s in expand(st, parse_rrule(ev["raw"]["RRULE"][1]), window_start, window_end, notes, ev["uid"]):
if s in ex:
continue
ov = overrides.pop((ev["uid"], s), None)
if ov is not None:
ov["_override_of_series"] = True
ov["raw"].setdefault("RRULE", ev["raw"]["RRULE"])
if not ov["attendees"]:
ov["attendees"] = ev["attendees"]
if not ov["description"]:
ov["description"] = ev["description"]
add(ov, ov["start"])
else:
add(ev, s)
else:
add(ev, st)
for (uid, rid), ov in overrides.items(): # overrides whose master was outside the file
add(ov, ov["start"])
return sorted(insts.values(), key=lambda i: (i["start"], i["end"])), skipped, days_off
# ---------------------------------------------------------------- analysis
def hm(s):
h, m = s.split(":"); return int(h) * 60 + int(m)
def parse_workdays(s):
s = s.lower().replace(" ", "")
names = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
if "-" in s and "," not in s:
a, b = s.split("-"); return set(range(names.index(a[:3]), names.index(b[:3]) + 1))
return {names.index(x[:3]) for x in s.split(",")}
def analyze(text, me=None, tzname=None, since=None, until=None, workday="09:00-18:00", workdays="mon-fri",
focus_min=120, max_load=40.0, min_focus_blocks=3, large=8, hourly_cost=0.0, lunch="11:30-14:00"):
notes = set()
me = (me or "").lower() or None
m = re.search(r"^X-WR-TIMEZONE:(.+)$", text, re.M)
tzname = tzname or (m.group(1).strip() if m else "UTC")
tz = get_zone(tzname, notes) or timezone.utc
events, _ = parse_ics(text, tz, notes)
if not events:
raise ValueError("no VEVENT found; is this an .ics calendar export?")
w0, w1 = [hm(x) for x in workday.split("-")]
l0, l1 = [hm(x) for x in lunch.split("-")]
wdays = parse_workdays(workdays)
# window: default = first .. last non-recurring timed event (a series' first DTSTART can be months old,
# and open-ended series would run forever); without one-off events: first timed event + 13 days
starts, singles = [], []
for ev in events:
if "DTSTART" in ev["raw"]:
try:
st, ad = parse_dt(ev["raw"]["DTSTART"][1], ev["raw"]["DTSTART"][0], tz, notes)
except ValueError:
continue
if not ad:
starts.append(st.astimezone(tz))
if "RRULE" not in ev["raw"]:
singles.append(st.astimezone(tz))
if (not since or not until) and not starts:
raise ValueError("no timed events; pass --since and --until")
midnight = lambda dt: dt.replace(hour=0, minute=0, second=0, microsecond=0)
ws = datetime.strptime(since, "%Y-%m-%d").replace(tzinfo=tz) if since else midnight(min(singles or starts))
if until:
we = datetime.strptime(until, "%Y-%m-%d").replace(tzinfo=tz)
else:
we = midnight(max(singles)) if singles else ws + timedelta(days=13)
if we < ws:
raise ValueError("--until is before --since")
insts, skipped, days_off = build_instances(events, tz, ws, we, me, notes)
days = {}
d = ws.date()
while d <= we.date():
days[d] = {"date": d, "work": d.weekday() in wdays and d not in days_off, "off": d in days_off, "meetings": []}
d += timedelta(days=1)
for i in insts:
if i["start"].date() in days:
days[i["start"].date()]["meetings"].append(i)
flags = []
def flag(code, sev, msg, when=""):
flags.append({"code": code, "severity": sev, "message": msg, "when": when})
day_rows, weeks = [], {}
overlaps_total, b2b_total, outside_total, no_lunch_days = 0, 0, 0, []
for d, info in sorted(days.items()):
ms = info["meetings"]
mins = lambda dt: dt.hour * 60 + dt.minute
# clip to the day
ivs = []
for i in ms:
a = mins(i["start"]); b = mins(i["end"]) if i["end"].date() == d else 24 * 60
ivs.append((a, b, i))
outside = [i for a, b, i in ivs if not info["work"] or a < w0 or b > w1]
outside_total += len(outside)
for i in outside:
where = "outside working hours" if info["work"] else ("on a day off" if info["off"] else "on a non-working day")
flag("M05", "low" if info["work"] else "medium", "%s %s-%s %s: %s" % (
d.isoformat(), i["start"].strftime("%H:%M"), i["end"].strftime("%H:%M"), where, i["summary"]), d.isoformat())
# overlaps
srt = sorted(ivs, key=lambda x: x[0])
for k in range(1, len(srt)):
for j in range(k):
if srt[j][1] > srt[k][0]:
overlaps_total += 1
flag("M04", "medium", "%s double-booked: %s and %s" % (d.isoformat(), srt[j][2]["summary"], srt[k][2]["summary"]), d.isoformat())
# merged busy time within working hours
busy = []
for a, b, _ in srt:
a, b = max(a, w0), min(b, w1)
if b <= a:
continue
if busy and a <= busy[-1][1]:
busy[-1][1] = max(busy[-1][1], b)
else:
busy.append([a, b])
meet_min = sum(b - a for a, b in busy)
avail = (w1 - w0) if info["work"] else 0
gaps, cur = [], w0
for a, b in busy:
if a > cur: gaps.append((cur, a))
cur = max(cur, b)
if cur < w1: gaps.append((cur, w1))
if not info["work"]:
gaps = []
focus = [g for g in gaps if g[1] - g[0] >= focus_min]
frag = [g for g in gaps if g[1] - g[0] < 30]
# back-to-back chains: 3+ meetings with < 5 min between them
chains, run = 0, 1
for k in range(1, len(srt)):
if srt[k][0] - srt[k - 1][1] < 5 and srt[k][0] >= srt[k - 1][0]:
run += 1
else:
chains += run >= 3; run = 1
chains += run >= 3
b2b_total += chains
if chains:
flag("M03", "low", "%s has %d back-to-back chain(s) of 3+ meetings without a break" % (d.isoformat(), chains), d.isoformat())
lunch_free = any(min(b, l1) - max(a, l0) >= 30 for a, b in gaps)
if info["work"] and ms and not lunch_free:
no_lunch_days.append(d.isoformat())
flag("M09", "low", "%s has no free 30 minutes between %s and %s for lunch" % (d.isoformat(), lunch.split("-")[0], lunch.split("-")[1]), d.isoformat())
row = {"date": d.isoformat(), "weekday": d.strftime("%a"), "workday": info["work"], "day_off": info["off"],
"meetings": len(ms), "meeting_min": meet_min, "available_min": avail,
"focus_blocks": len(focus), "focus_min": sum(b - a for a, b in focus),
"fragmented_min": sum(b - a for a, b in frag), "b2b_chains": chains, "outside_hours": len(outside)}
day_rows.append(row)
iso = d.isocalendar()
wk = weeks.setdefault("%d-W%02d" % (iso[0], iso[1]), {"week": "%d-W%02d" % (iso[0], iso[1]), "meetings": 0, "meeting_min": 0,
"available_min": 0, "focus_blocks": 0, "focus_min": 0, "fragmented_min": 0,
"b2b_chains": 0, "outside_hours": 0, "workdays": 0})
for k in ("meetings", "meeting_min", "available_min", "focus_blocks", "focus_min", "fragmented_min", "b2b_chains", "outside_hours"):
wk[k] += row[k]
wk["workdays"] += info["work"]
for wk in weeks.values():
wk["load_pct"] = round(100.0 * wk["meeting_min"] / wk["available_min"], 1) if wk["available_min"] else 0.0
if wk["workdays"] >= 3:
if wk["load_pct"] >= max_load * 1.5:
flag("M01", "high", "%s meeting load %.1f%% of working time (limit %.0f%%)" % (wk["week"], wk["load_pct"], max_load), wk["week"])
elif wk["load_pct"] >= max_load:
flag("M01", "medium", "%s meeting load %.1f%% of working time (limit %.0f%%)" % (wk["week"], wk["load_pct"], max_load), wk["week"])
if wk["focus_blocks"] < min_focus_blocks:
flag("M02", "medium", "%s only %d focus block(s) of %d+ min (goal %d per week)" % (wk["week"], wk["focus_blocks"], focus_min, min_focus_blocks), wk["week"])
# series
series = {}
for i in insts:
key = i["uid"] if i["recurring"] else "one-off:" + i["summary"]
s = series.setdefault(key, {"title": i["summary"], "recurring": i["recurring"], "instances": 0, "minutes": 0,
"attendees": 0, "person_hours": 0.0, "organizer_is_me": i["organizer_is_me"], "has_agenda": i["has_agenda"]})
dur = (i["end"] - i["start"]).total_seconds() / 60
s["instances"] += 1; s["minutes"] += dur; s["attendees"] = max(s["attendees"], i["attendees"])
s["person_hours"] += dur / 60 * i["attendees"]
n_weeks = max(1.0, len(days) / 7.0)
for s in series.values():
s["hours_per_week"] = round(s["minutes"] / 60 / n_weeks, 2)
s["person_hours"] = round(s["person_hours"], 1)
s["cost"] = round(s["person_hours"] * hourly_cost, 2) if hourly_cost else None
if s["recurring"] and s["attendees"] >= large:
flag("M06", "low", "large recurring meeting '%s': %d people, %.1f person-hours in the period%s" % (
s["title"], s["attendees"], s["person_hours"], (", about %.0f in cost" % s["cost"]) if s["cost"] else ""))
if s["recurring"] and s["organizer_is_me"] and not s["has_agenda"] and s["minutes"] / max(s["instances"], 1) >= 30:
flag("M07", "low", "recurring meeting you organize without an agenda in the invite: '%s'" % s["title"])
for n in sorted(notes):
flag("M08", "info", n)
total_meet = sum(r["meeting_min"] for r in day_rows); total_avail = sum(r["available_min"] for r in day_rows)
summary = {"calendar_tz": tzname, "from": ws.date().isoformat(), "to": we.date().isoformat(), "me": me,
"meetings": len(insts), "meeting_hours": round(total_meet / 60, 1), "available_hours": round(total_avail / 60, 1),
"load_pct": round(100.0 * total_meet / total_avail, 1) if total_avail else 0.0,
"focus_blocks": sum(r["focus_blocks"] for r in day_rows), "focus_hours": round(sum(r["focus_min"] for r in day_rows) / 60, 1),
"fragmented_hours": round(sum(r["fragmented_min"] for r in day_rows) / 60, 1),
"double_bookings": overlaps_total, "b2b_chains": b2b_total, "outside_hours_meetings": outside_total,
"days_without_lunch": len(no_lunch_days), "days_off": sorted(x.isoformat() for x in days_off), "skipped": skipped,
"recurring_share_pct": round(100.0 * sum((i["end"] - i["start"]).total_seconds() for i in insts if i["recurring"]) /
max(1, sum((i["end"] - i["start"]).total_seconds() for i in insts)), 1)}
flags.sort(key=lambda f: (-SEV[f["severity"]], f["code"], f["when"]))
top = sorted(series.values(), key=lambda s: -s["person_hours"])
return {"summary": summary, "weeks": [weeks[k] for k in sorted(weeks)], "days": day_rows, "series": top, "flags": flags,
"events": [{"date": i["start"].date().isoformat(), "start": i["start"].strftime("%H:%M"), "end": i["end"].strftime("%H:%M"),
"minutes": int((i["end"] - i["start"]).total_seconds() // 60), "title": i["summary"], "attendees": i["attendees"],
"recurring": i["recurring"]} for i in insts]}
# ---------------------------------------------------------------- output
def render(res, fmt, top=8):
s = res["summary"]
if fmt == "json":
return json.dumps(res, indent=2, default=str)
if fmt == "csv":
out = io.StringIO(); w = csv.writer(out)
w.writerow(["date", "start", "end", "minutes", "title", "attendees", "recurring"])
for e in res["events"]:
w.writerow([e["date"], e["start"], e["end"], e["minutes"], e["title"], e["attendees"], int(e["recurring"])])
return out.getvalue().rstrip("\n")
md = fmt == "md"
L = ["## Meeting load %s to %s" % (s["from"], s["to"]) if md else "Meeting load %s to %s (%s)" % (s["from"], s["to"], s["calendar_tz"])]
L.append("%d meetings, %.1f h of %.1f h working time = %.1f%% load; %d focus blocks (%.1f h); %.1f h fragmented; recurring %.1f%% of meeting time" % (
s["meetings"], s["meeting_hours"], s["available_hours"], s["load_pct"], s["focus_blocks"], s["focus_hours"], s["fragmented_hours"], s["recurring_share_pct"]))
sk = s["skipped"]
L.append("Skipped: %d cancelled, %d declined, %d free/transparent, %d all-day%s" % (sk["cancelled"], sk["declined"], sk["free"], sk["all_day"],
("; days off: " + ", ".join(s["days_off"])) if s["days_off"] else ""))
L.append("")
if md:
L += ["| Week | Meetings | Meeting h | Load | Focus blocks | Focus h | Fragmented h | B2B chains | Outside hours |", "|---|---|---|---|---|---|---|---|---|"]
for w in res["weeks"]:
L.append("| %s | %d | %.1f | %.1f%% | %d | %.1f | %.1f | %d | %d |" % (w["week"], w["meetings"], w["meeting_min"] / 60, w["load_pct"], w["focus_blocks"],
w["focus_min"] / 60, w["fragmented_min"] / 60, w["b2b_chains"], w["outside_hours"]))
L += ["", "| Series | Recurring | People | h/week | Person-hours |" + (" Cost |" if res["series"] and res["series"][0]["cost"] is not None else ""),
"|---|---|---|---|---|" + ("---|" if res["series"] and res["series"][0]["cost"] is not None else "")]
for x in res["series"][:top]:
L.append("| %s | %s | %d | %.2f | %.1f |%s" % (x["title"], "yes" if x["recurring"] else "no", x["attendees"], x["hours_per_week"], x["person_hours"],
(" %.0f |" % x["cost"]) if x["cost"] is not None else ""))
L += ["", "| Code | Severity | Finding |", "|---|---|---|"] + ["| %s | %s | %s |" % (f["code"], f["severity"], f["message"]) for f in res["flags"]]
else:
L.append("By week meetings meet h load focus blocks focus h frag h b2b outside")
for w in res["weeks"]:
L.append(" %-14s %8d %7.1f %5.1f%% %13d %8.1f %7.1f %4d %8d" % (w["week"], w["meetings"], w["meeting_min"] / 60, w["load_pct"],
w["focus_blocks"], w["focus_min"] / 60, w["fragmented_min"] / 60, w["b2b_chains"], w["outside_hours"]))
L += ["", "By day"]
for r in res["days"]:
if r["workday"] or r["meetings"]:
L.append(" %s %s %2d meetings %5.1f h meetings, %d focus block(s)%s" % (r["date"], r["weekday"], r["meetings"], r["meeting_min"] / 60,
r["focus_blocks"], " (day off)" if r["day_off"] else ""))
L += ["", "Top series by person-hours"]
for x in res["series"][:top]:
L.append(" %-34s %-9s %3d people %5.2f h/week %6.1f person-h%s" % (x["title"][:34], "recurring" if x["recurring"] else "one-off", x["attendees"],
x["hours_per_week"], x["person_hours"], (" cost %.0f" % x["cost"]) if x["cost"] is not None else ""))
L += ["", "Flags"] + ([" %s %-6s %s" % (f["code"], f["severity"], f["message"]) for f in res["flags"]] or [" none"])
return "\n".join(L)
# ---------------------------------------------------------------- self-test
def self_test():
checks = []
def ok(n, c): checks.append((n, bool(c)))
ok("unfold", unfold("SUMMARY:Long\r\n title\r\nX:1") == ["SUMMARY:Long title", "X:1"])
ok("prop params", parse_prop('ATTENDEE;CN="Doe, Jane";PARTSTAT=DECLINED:mailto:j@x.io') == ("ATTENDEE", {"CN": "Doe, Jane", "PARTSTAT": "DECLINED"}, "mailto:j@x.io"))
ok("duration", parse_duration("PT1H30M") == timedelta(minutes=90) and parse_duration("P1D") == timedelta(days=1))
n = set(); utc = timezone.utc
ok("dt utc", parse_dt("20261124T070000Z", {}, utc, n)[0].hour == 7)
ist = get_zone("Europe/Istanbul", n)
ok("dt tzid to utc", parse_dt("20261124T100000", {"TZID": "Europe/Istanbul"}, utc, n)[0].astimezone(utc).hour == 7)
ok("windows tz name", get_zone("Turkey Standard Time", n) is not None)
ok("all-day", parse_dt("20261127", {"VALUE": "DATE"}, utc, n)[1] is True)
st = datetime(2026, 11, 23, 9, 30, tzinfo=ist)
W0, W1 = datetime(2026, 11, 23, tzinfo=ist), datetime(2026, 12, 4, tzinfo=ist)
daily = list(expand(st, parse_rrule("FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR"), W0, W1, n, "u"))
ok("daily weekdays", len(daily) == 10 and all(d.weekday() < 5 for d in daily))
ok("weekly interval 2", [d.day for d in expand(st, parse_rrule("FREQ=WEEKLY;INTERVAL=2;BYDAY=WE"), W0, W1 + timedelta(days=14), n, "u")] == [25, 9])
ok("count", len(list(expand(st, parse_rrule("FREQ=DAILY;COUNT=3"), W0, W1, n, "u"))) == 3)
ok("until", [d.day for d in expand(st, parse_rrule("FREQ=WEEKLY;UNTIL=20261201T000000Z"), W0, W1, n, "u")] == [23, 30])
ok("monthly 1st thursday", [d.day for d in expand(datetime(2026, 11, 5, 16, 0, tzinfo=ist), parse_rrule("FREQ=MONTHLY;BYDAY=1TH"), W0, W1, n, "u")][:2] == [5, 3])
ok("monthly last friday", [d.day for d in expand(datetime(2026, 11, 27, 16, 0, tzinfo=ist), parse_rrule("FREQ=MONTHLY;BYDAY=-1FR"), W0, W1 + timedelta(days=30), n, "u")] == [27, 25])
n2 = set(); list(expand(st, parse_rrule("FREQ=YEARLY"), W0, W1, n2, "y"))
ok("unsupported noted", any("unsupported" in x for x in n2))
cal = "\n".join([
"BEGIN:VCALENDAR", "X-WR-TIMEZONE:Europe/Istanbul",
"BEGIN:VEVENT", "UID:standup", "SUMMARY:Standup", "DTSTART;TZID=Europe/Istanbul:20261123T093000", "DTEND;TZID=Europe/Istanbul:20261123T094500",
"RRULE:FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR", "EXDATE;TZID=Europe/Istanbul:20261125T093000", "ORGANIZER:mailto:me@x.io",
"ATTENDEE;PARTSTAT=ACCEPTED:mailto:me@x.io"] + ["ATTENDEE;PARTSTAT=ACCEPTED:mailto:p%d@x.io" % i for i in range(8)] + ["END:VEVENT",
"BEGIN:VEVENT", "UID:standup", "RECURRENCE-ID;TZID=Europe/Istanbul:20261126T093000", "SUMMARY:Standup", "STATUS:CANCELLED",
"DTSTART;TZID=Europe/Istanbul:20261126T093000", "DTEND;TZID=Europe/Istanbul:20261126T094500", "END:VEVENT",
"BEGIN:VEVENT", "UID:a", "SUMMARY:Planning", "DTSTART:20261123T070000Z", "DTEND:20261123T090000Z", "END:VEVENT",
"BEGIN:VEVENT", "UID:b", "SUMMARY:Review", "DTSTART;TZID=Europe/Istanbul:20261123T110000", "DURATION:PT1H", "END:VEVENT",
"BEGIN:VEVENT", "UID:c", "SUMMARY:Sync", "DTSTART;TZID=Europe/Istanbul:20261123T113000", "DTEND;TZID=Europe/Istanbul:20261123T123000", "END:VEVENT",
"BEGIN:VEVENT", "UID:d", "SUMMARY:Lunch talk", "DTSTART;TZID=Europe/Istanbul:20261123T123000", "DTEND;TZID=Europe/Istanbul:20261123T140000", "END:VEVENT",
"BEGIN:VEVENT", "UID:e", "SUMMARY:US call", "DTSTART;TZID=Europe/Istanbul:20261124T190000", "DTEND;TZID=Europe/Istanbul:20261124T200000", "END:VEVENT",
"BEGIN:VEVENT", "UID:f", "SUMMARY:Declined thing", "DTSTART;TZID=Europe/Istanbul:20261124T100000", "DTEND;TZID=Europe/Istanbul:20261124T110000",
"ATTENDEE;PARTSTAT=DECLINED:mailto:me@x.io", "END:VEVENT",
"BEGIN:VEVENT", "UID:g", "SUMMARY:Focus", "TRANSP:TRANSPARENT", "DTSTART;TZID=Europe/Istanbul:20261124T140000", "DTEND;TZID=Europe/Istanbul:20261124T160000", "END:VEVENT",
"BEGIN:VEVENT", "UID:h", "SUMMARY:Out of office", "DTSTART;VALUE=DATE:20261127", "DTEND;VALUE=DATE:20261128", "END:VEVENT",
"BEGIN:VEVENT", "UID:z", "SUMMARY:End marker", "DTSTART;TZID=Europe/Istanbul:20261127T100000", "DTEND;TZID=Europe/Istanbul:20261127T101500", "END:VEVENT",
"END:VCALENDAR"])
r = analyze(cal, me="me@x.io")
sm = r["summary"]; codes = {f["code"] for f in r["flags"]}
by = {d["date"]: d for d in r["days"]}
ok("standup exdate + cancelled override", sum(1 for e in r["events"] if e["title"] == "Standup") == 3)
ok("skipped counts", sm["skipped"]["declined"] == 1 and sm["skipped"]["free"] == 1 and sm["skipped"]["cancelled"] == 1 and sm["skipped"]["all_day"] == 1)
ok("utc converted", any(e["title"] == "Planning" and e["start"] == "10:00" for e in r["events"]))
ok("double booking (3 overlapping pairs)", "M04" in codes and sm["double_bookings"] == 3)
ok("merged meeting minutes (overlaps counted once)", by["2026-11-23"]["meeting_min"] == 15 + 240)
ok("b2b chain", by["2026-11-23"]["b2b_chains"] == 1 and "M03" in codes)
ok("no lunch", "M09" in codes)
ok("outside hours + day off", sm["outside_hours_meetings"] == 3 and any(f["code"] == "M05" and "day off" in f["message"] for f in r["flags"]))
ok("day off", "2026-11-27" in sm["days_off"] and by["2026-11-27"]["workday"] is False)
ok("large recurring", "M06" in codes)
ok("no agenda organizer", "M07" not in codes) # standup is 15 min
ok("focus block monday afternoon", by["2026-11-23"]["focus_blocks"] == 1 and by["2026-11-23"]["focus_min"] == 240)
ok("window from events", sm["from"] == "2026-11-23" and sm["to"] == "2026-11-27")
ok("csv", render(r, "csv").splitlines()[0].startswith("date,start,end"))
ok("md", "| Week |" in render(r, "md"))
try:
analyze("hello"); ok("no events error", False)
except ValueError:
ok("no events error", True)
bad = [x for x, 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="Meeting load and focus time from an .ics calendar export.")
ap.add_argument("calendar", nargs="?")
ap.add_argument("--me", help="your email address, to drop meetings you declined and find the ones you organize")
ap.add_argument("--tz", help="analysis time zone (default: X-WR-TIMEZONE of the file, else UTC)")
ap.add_argument("--since"); ap.add_argument("--until")
ap.add_argument("--workday", default="09:00-18:00"); ap.add_argument("--workdays", default="mon-fri")
ap.add_argument("--focus-min", type=int, default=120, help="minimum free minutes that count as a focus block")
ap.add_argument("--max-load", type=float, default=40.0, help="weekly meeting share of working time that raises M01")
ap.add_argument("--min-focus-blocks", type=int, default=3)
ap.add_argument("--large", type=int, default=8, help="attendees that make a recurring meeting large (M06)")
ap.add_argument("--hourly-cost", type=float, default=0.0, help="average loaded cost per person-hour, for cost estimates")
ap.add_argument("--lunch", default="11:30-14:00")
ap.add_argument("--top", type=int, default=8)
ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
ap.add_argument("--fail-on", choices=["none", "info", "low", "medium", "high"], 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.calendar:
ap.error("CALENDAR.ics is required")
try:
text = open(a.calendar, encoding="utf-8-sig").read()
res = analyze(text, a.me, a.tz, a.since, a.until, a.workday, a.workdays, a.focus_min, a.max_load,
a.min_focus_blocks, a.large, a.hourly_cost, a.lunch)
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr); return 2
print(render(res, a.format, a.top))
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())
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())