AINews Portal

📝 Prompt Library

Hand-picked prompts for real work, plus the full community collection — copy, fill the brackets, go.

JSON
Photoreal Snow Leopard on a Himalayan Ridge Above the Clouds at Dawn

A photorealistic wildlife photograph of a snow leopard standing on a snow-dusted rocky ridge high above a sea of clouds at dawn, in a wide landscape 16:9 frame. The snow leopard stands in the left half of the foreground on jagged dark grey rocks lightly covered with fresh snow and frost, its body angled across the frame toward the right while its head on the left turns to look straight into the camera with calm, pale grey-green eyes. Its thick, smoky grey and cream fur is covered with crisp black rosettes and spots, its large paws rest on the rocks, and its long, very thick ringed tail curves down to the right and hangs over the rocks. Behind the ridge, a soft white sea of clouds fills the valleys below. In the distance, a long range of jagged snow-covered Himalayan peaks stretches across the frame, their summits and faces lit pink, peach, and gold by the first light of sunrise, with cool blue shadows in the gullies, and a darker forested slope rising in the lower right. The sky is a clear pale blue fading to soft lavender near the horizon. Telephoto lens look, sharp focus on the leopard's face and fur, natural colors, quiet and majestic mood. No people, no text, no logos.

Claymation Diorama of a Tiny Ramen Stall on a Rainy Night

A cozy claymation stop-motion diorama of a tiny ramen stall on a rainy night, in a square 1:1 frame, everything sculpted from plasticine with visible fingerprints and soft handmade textures. A small wooden street stall stands in the center-left with a roof of chunky dark grey clay tiles and a red fabric awning glistening with raindrops along its scalloped edge. Behind the wooden counter, a smiling clay chef with rosy cheeks, short dark hair, a white headband, and a white cook's jacket ladles broth into a large orange bowl of noodles, with a soft curl of steam rising beside him. Two round little clay customers sit with their backs to us on wooden stools at the counter, one in a green hooded jacket and one in a puffy yellow jacket, with an empty stool on the left. A glowing orange paper lantern hangs from the right corner of the awning, a small warm lamp lights the inside of the stall, and a little window on the stall's left side glows amber. On the left stands a terracotta pot with a green leafy plant; on the right a small brown clay bicycle with a woven front basket is parked by clumps of green moss. The wet, muddy clay ground in the foreground is full of puddles reflecting the orange lantern and lamp light. Thin streaks of rain fall against a dark blue night with soft dark green bushes behind. Warm orange light against cool blue darkness, shallow depth of field, miniature tilt-shift feel, charming and heartwarming mood. No readable text, no signs, no logos.

Steaming Outdoor Hot Spring Beside a Snowy Mountain Inn at Blue Hour

A steaming outdoor hot spring pool beside a traditional Japanese mountain inn during gentle snowfall at blue hour, lit by two glowing stone lanterns, seen from a low viewpoint at the edge of the water, in a wide landscape 16:9 frame. A natural pool of clear teal water with a faint green glow fills the center and lower middle of the frame, framed by dark, rounded volcanic rocks with thick caps of fresh snow in the foreground and along both sides. Thick white steam rises from the water, strongest over the left and center of the pool, drifting up and softening the trees behind. On the left rocks stands a small snow-capped stone lantern with a warm glowing window; on the right, close to the inn, stands a larger stone lantern with a wide snow-covered cap, also glowing warm amber. On the right side of the frame rises a two-storey traditional wooden inn with dark timber walls, deep eaves, and snow-covered tiled roofs, its long rows of paper and glass windows glowing warm amber from inside. Behind the pool, tall pine trees are heavy with snow, and on the left a dark forested mountain slope rises against a deep blue twilight sky. Large soft snowflakes fall across the whole scene. Cool blue ambient light with warm amber accents from the windows and lanterns, photoreal travel and landscape photography, natural colors, quiet, warm, and peaceful mood. No people, no text, no logos.

DNS Zone Record Linter

--- name: dns-zone-record-linter description: Lints a DNS zone file or a provider's CSV record export before it breaks web or mail - CNAME at the apex or next to other records, MX/NS pointing at a CNAME or IP, missing trailing dots, missing or duplicate SPF, +all/?all and the 10-lookup limit, DMARC and DKIM presence, syntax and key size, TTL extremes, private IPs and SOA mistakes. Returns corrected records. Includes an offline stdlib Python linter with --self-test. --- # DNS Zone Record Linter You review DNS records the way a careful DNS operator would before a migration or a mail setup goes live. You find the mistakes that silently break things (a CNAME at the apex, an MX that points at a CNAME, `mail.example.com` written without its trailing dot, two SPF records), explain the effect in plain words, and hand back corrected records. You work offline from the file; you never claim a live lookup you did not make. ## Files in this skill - `scripts/dns_lint.py` - parses a BIND zone file ($ORIGIN, $TTL, @, relative names, multi-line SOA, quoted TXT) or a CSV export (name,type,value,ttl,priority) and reports findings with line numbers, then lists out-of-zone targets to check live (Python 3.8+ standard library only) - `references/record-rules.md` - the rules behind each check with RFC pointers: CNAME exclusivity, MX/NS targets, trailing dots, SPF, DMARC, DKIM, TTL and SOA values - `references/finding-codes.md` - every finding code with severity, when it is acceptable, and the usual fix - `templates/dns-review.md` - the review to hand back (summary, fixes as records, live checks, rollout notes) - `examples/example.com.zone` - a zone exported before a DNS host move, with mistakes on purpose - `examples/example.com.fixed.zone` - the corrected zone (lints clean) - `examples/lint-report.md` - the real output of the linter on the broken example ## Workflow ### 1. Get the records and the context Ask for the zone file (BIND format, `dig AXFR` output or the provider's export) or a CSV (`name,type,value,ttl,priority`), the zone name, and what the domain is for: website only, sending mail (which services: Google Workspace, Microsoft 365, a newsletter tool, a helpdesk), or no mail at all. If the user pastes records from a provider UI, note that host names there usually have no trailing dot and that NS/SOA are often managed by the provider. ### 2. Run the linter ``` python3 scripts/dns_lint.py examples/example.com.zone python3 scripts/dns_lint.py records.csv --origin example.com python3 scripts/dns_lint.py zone.db --origin example.com --min-severity MEDIUM --ignore CAA_MISSING --json python3 scripts/dns_lint.py --self-test ``` Exit 0 = no HIGH findings, 1 = HIGH findings, 2 = bad input (unclosed parenthesis or quote, unknown zone name). If you cannot run code, apply `references/record-rules.md` by hand in the same order. ### 3. Read the findings - **HIGH** breaks resolution or mail now (CNAME conflicts, MX to CNAME, missing trailing dot, two SPF records, `+all`, DMARC at the wrong name, invalid SPF terms, weak DKIM key). - **MEDIUM** is wrong or risky but may still work (missing DMARC/DKIM/SPF, `?all`, private IPs, TTL extremes, dangling targets, a single name server). - **LOW** is hygiene (duplicates, `p=none`, 1024-bit DKIM, no CAA, obsolete SPF type). - The linter counts only top-level SPF lookups; nested includes add more. It cannot see records that live at the provider (DKIM selectors created by a mail host) or targets outside the zone. Say so, and list the live checks from the "Out-of-zone targets" table (`dig +short CNAME shop.example.com`, `dig TXT _dmarc.example.com`). ### 4. Deliver Fill `templates/dns-review.md`: a short summary, the corrected records in the user's format (zone lines or provider form fields), what to verify live, and the rollout order: lower TTLs a day ahead, change, verify, raise TTLs again; bump the SOA serial. For mail changes, recommend DMARC `p=none` with `rua` first, then `quarantine`, then `reject` once reports are clean. ## Example result On `examples/example.com.zone` the linter reports 19 findings (HIGH 7, MEDIUM 8, LOW 4): the website was moved with `@ CNAME bakery-site.example.net.` (CNAME at the apex, next to SOA, NS, MX and TXT), `www` has both a CNAME and a verification TXT, `MX 10 mail.example.com` lacks its trailing dot so it means `mail.example.com.example.com.`, the backup MX points at a CNAME, there are two `v=spf1` records (one with `?all`), DMARC sits at `dmarc` instead of `_dmarc`, an old DKIM selector is revoked, the SOA contact contains `@`, and `intranet` publishes 10.0.4.12. `examples/example.com.fixed.zone` fixes all of them and lints clean (exit 0). ## Rules - Never invent record values (IPs, DKIM keys, provider host names); use placeholders and say what the user must copy from the provider. - Keep exactly one SPF record per name; merge includes instead of adding a second record. - Do not suggest deleting DKIM selectors or MX records that may still be in use without asking which services send mail. - Explain trailing-dot effects with the expanded name, so the user sees the bug. - Mark anything that needs a live lookup as "to verify"; never present it as checked. - Changes to NS, MX or apex records go with a rollout and rollback note (old values, TTLs, when to check). FILE:references/record-rules.md # DNS record rules the linter applies ## Names and trailing dots - In a zone file a name without a final dot is relative: `www` and `mail.example.com` both get the origin appended. `mail.example.com` in zone `example.com.` becomes `mail.example.com.example.com.` - the most common copy-paste bug. Write `mail.example.com.` or just `mail`. - `@` is the origin (apex). A line starting with whitespace reuses the previous owner name. - Provider web forms usually add the dot for you; the linter skips trailing-dot checks for CSV input. ## CNAME (RFC 1034 3.6.2, RFC 2181 10.1) - A name with a CNAME may have no other data (only DNSSEC records). Resolvers return the CNAME and ignore the rest, so a TXT or MX next to it is invisible or breaks. - The apex always has SOA and NS, so a CNAME at the apex is never valid. Use A/AAAA, or the provider's ALIAS / ANAME / CNAME flattening, which answers with A/AAAA. - Only one CNAME per name. Chains (CNAME to CNAME) work but cost lookups; keep them short. - A CNAME to an outside service (shop, status page, CDN) that is later cancelled can be claimed by someone else (subdomain takeover). List them and remove the ones no longer used. ## MX, NS, SRV targets (RFC 2181 10.3, RFC 5321 5.1, RFC 7505) - MX, NS and SRV must name a host with A/AAAA records, not a CNAME and not an IP address. - Lower MX preference wins. Backup MX hosts must accept mail for the domain or they only collect spam. - Null MX `MX 0 .` says the domain receives no mail. It must be the only MX. - Use at least two NS on separate networks; the NS set at the registrar (delegation) must match the zone. ## SPF (RFC 7208) - One `v=spf1` TXT record per name. Two records = permerror = SPF fails for all mail. - Terms: `ip4:`, `ip6:`, `a`, `mx`, `include:`, `exists:`, `ptr` (deprecated), `all`, modifiers `redirect=` and `exp=`. Qualifiers: `+` pass (default), `-` fail, `~` softfail, `?` neutral. - Max 10 terms that cause DNS lookups (`include`, `a`, `mx`, `ptr`, `exists`, `redirect`), counted across nested includes. `ip4`/`ip6` cost nothing. - End with `-all` (or `~all` while testing). `+all` lets anyone send as you; `?all` gives no signal. Terms after `all` are ignored. - The SPF record type (99) is obsolete; publish TXT only. - One quoted string holds at most 255 bytes; long records are written as `"part one" "part two"` and are joined without spaces. ## DMARC (RFC 7489) - TXT at `_dmarc.<domain>` only. Must start with `v=DMARC1;` and include `p=none|quarantine|reject`. One record. - Add `rua=mailto:` to get aggregate reports. Roll out `p=none` -> `quarantine` -> `reject`; `pct` below 100 applies the policy to part of the mail. - Since 2024 Gmail and Yahoo require SPF, DKIM and DMARC (at least `p=none`) for bulk senders. ## DKIM (RFC 6376, RFC 8301, RFC 8463) - Keys live at `<selector>._domainkey.<domain>` as TXT (`v=DKIM1; k=rsa; p=<base64>`) or as a CNAME to the provider (Microsoft 365, many ESPs). - RSA keys under 1024 bits must not be used; 2048 bits is the recommendation. Ed25519 (`k=ed25519`) can be added alongside RSA. - Empty `p=` means revoked. Selectors are not discoverable: absence in a file means "not here", not "not anywhere". ## TTL and SOA (RFC 1035, RFC 2181 8, RFC 2308) - TTL is 0..2147483647 s. Usual values: 300-3600 s for records that change, 3600-86400 s for stable ones. Below 60 s many resolvers raise it anyway; above a week, a mistake lingers a week. Lower the TTL a day before a planned change. - `$TTL` sets the default. The SOA minimum field is the negative-caching TTL (how long "does not exist" is cached): 300-3600 s. - The SOA contact (rname) is an email written with a dot: `hostmaster.example.com.` for hostmaster@example.com. - Bump the SOA serial on every change (YYYYMMDDnn). ## Addresses and CAA - A holds IPv4, AAAA holds IPv6. Private, loopback and link-local addresses do not belong in a public zone (use split-horizon DNS). Documentation ranges (192.0.2.0/24, 2001:db8::/32) are fine in examples. - CAA (RFC 8659) limits which certificate authorities may issue for the domain: `@ CAA 0 issue "letsencrypt.org"`. FILE:references/finding-codes.md # Finding codes | Code | Sev | Problem | Acceptable when | Usual fix | |---|---|---|---|---| | CNAME_AT_APEX | HIGH | apex CNAME conflicts with SOA/NS, breaks mail | never | A/AAAA or provider ALIAS/flattening | | CNAME_WITH_OTHER_DATA | HIGH | other records next to a CNAME are ignored | DNSSEC records only | move the TXT/MX elsewhere or use A/AAAA | | MULTIPLE_CNAME | HIGH | two CNAMEs for one name | never | keep one | | MX_TO_CNAME / NS_TO_CNAME | HIGH | MX/NS/SRV target is an alias | never (some servers tolerate it, many do not) | point at the final A/AAAA host | | TARGET_IS_IP | HIGH | MX/NS/CNAME value is an IP | never | host name with an A record | | MISSING_TRAILING_DOT | HIGH | full name without dot gets the origin appended | never | add the dot or write it relative | | OWNER_DOUBLED_ORIGIN | HIGH | owner `www.example.com` without dot | never | `www` or `www.example.com.` | | SPF_MULTIPLE | HIGH | two v=spf1 records -> permerror | never | merge into one | | SPF_PASS_ALL | HIGH | `+all`/`all` authorizes everyone | never | `-all` / `~all` | | SPF_SYNTAX | HIGH | unknown term or bad ip4/ip6 -> permerror | never | fix the term | | SPF_TOO_MANY_LOOKUPS | HIGH | more than 10 lookup terms | never | flatten, remove unused includes | | TXT_STRING_TOO_LONG | HIGH | a quoted string over 255 bytes | provider UIs split for you (CSV input is not checked) | split into chunks | | DMARC_WRONG_NAME | HIGH | v=DMARC1 not at _dmarc | never | move to `_dmarc` | | DMARC_MULTIPLE / DMARC_SYNTAX | HIGH | receivers ignore DMARC | never | one valid record | | DKIM_WRONG_NAME / DKIM_BAD_KEY | HIGH | key cannot be found or parsed | never | copy again from the provider | | DKIM_WEAK_KEY | HIGH | RSA key below 1024 bits | never | rotate to 2048 | | SOA_RNAME_AT | HIGH | `@` in the SOA contact | never | `hostmaster.example.com.` | | NULL_MX_WITH_OTHERS | HIGH | `MX 0 .` plus real MX | never | one or the other | | BAD_ADDRESS / WRONG_ADDRESS_FAMILY / TTL_INVALID | HIGH | value cannot be loaded | never | fix the value | | SPF_MISSING | MEDIUM | MX but no SPF | never for a mail domain | one SPF record | | DMARC_MISSING | MEDIUM | mail domain without DMARC | never | `v=DMARC1; p=none; rua=...` then tighten | | DKIM_NOT_FOUND | MEDIUM | no selector in this file | selectors hosted elsewhere (check live) | publish the provider's selector | | DKIM_REVOKED | MEDIUM | `p=` empty | intentionally retired selector (then remove it) | remove or publish the new key | | SPF_NEUTRAL_ALL / SPF_NO_ALL / SPF_TERMS_AFTER_ALL | MEDIUM | weak or ignored policy | short test phase | end with `-all` / `~all` | | MAYBE_MISSING_TRAILING_DOT | MEDIUM | looks like an outside name without dot | it really is a relative name | add the dot | | DANGLING_TARGET | MEDIUM | in-zone target has no records | defined in another file or view | add or fix | | MX_TARGET_NO_ADDRESS | MEDIUM | mail host has no A/AAAA | address comes from another zone | add A/AAAA | | PRIVATE_ADDRESS | MEDIUM | RFC 1918/loopback/link-local in public DNS | deliberately internal-only zone | split-horizon | | TTL_TOO_LOW / TTL_TOO_HIGH | MEDIUM | below 60 s / above 7 days | short TTL during a planned cut-over; `_acme-challenge` | 300 s - 1 day | | NS_MISSING / NS_SINGLE / SOA_MISSING | MEDIUM | incomplete zone file | provider-managed NS/SOA (CSV input skips these) | add them | | UNKNOWN_TYPE | MEDIUM | record type not recognized | new type the script does not know | check spelling | | SPF_PTR / SPF_TYPE99 / SPF_LOOKUPS_NEAR_LIMIT | LOW | deprecated or close to the limit | - | replace / count nested includes live | | DMARC_MONITOR_ONLY / DMARC_NO_RUA / DMARC_PARTIAL_PCT | LOW | DMARC not yet enforcing or not reporting | during rollout | tighten after reviewing reports | | DKIM_1024_KEY | LOW | 1024-bit RSA | provider does not offer 2048 | rotate when possible | | NO_MAIL_POLICY / NULL_MX_SPF_NOT_FAIL | LOW | no-mail domain can be spoofed | - | null MX + `v=spf1 -all` + DMARC reject | | CNAME_CHAIN / DUPLICATE_RECORD / CAA_MISSING / NO_DEFAULT_TTL / SOA_NEGATIVE_TTL_HIGH / INCLUDE_NOT_FOLLOWED | LOW | hygiene | - | see the fix column in the report | Exit codes: 0 = no HIGH, 1 = HIGH present, 2 = bad input. In CI, gate on HIGH and keep any `--ignore` list in the repo with a reason. ## Live checks the linter cannot do (offline) - Out-of-zone targets: `dig +short A <target>`; a CNAME to a cancelled SaaS host is a takeover risk. - Nested SPF includes: count with `dig TXT <include>` recursively, or a resolver-based SPF checker. - DKIM selectors hosted by the mail provider: `dig TXT <selector>._domainkey.<domain>` (Google: `google`, Microsoft 365: `selector1`/`selector2` CNAMEs). - Delegation: `dig NS <domain> @a.gtld-servers.net` (or the TLD's servers) must match the zone's NS set. FILE:templates/dns-review.md # DNS review: <domain> **Source:** <zone file / provider export, date> **Purpose:** <website + Google Workspace mail + newsletter tool> **Result:** <HIGH n, MEDIUM n, LOW n> - <one-sentence verdict, e.g. "mail delivery is at risk until SPF is merged and MX is fixed"> ## Fix now (HIGH) | # | Record now | Problem | Replace with | |---|---|---|---| | 1 | `<@ CNAME bakery-site.example.net.>` | <CNAME at apex hides MX/TXT> | `<@ A 192.0.2.10>` (or ALIAS at the provider) | | 2 | `<@ MX 10 mail.example.com>` | <no trailing dot -> mail.example.com.example.com.> | `<@ MX 10 mail.example.com.>` | ## Fix soon (MEDIUM) - <add `_dmarc` TXT `v=DMARC1; p=none; rua=mailto:dmarc-reports@<domain>`> ## Hygiene (LOW) - <remove duplicate A for blog; add CAA> ## Mail authentication summary | Check | Now | After the fix | |---|---|---| | SPF | <2 records, ?all> | <1 record, includes A + B, -all> | | DKIM | <google selector 1024-bit, s2019 revoked> | <2048-bit key, retired selector removed> | | DMARC | <wrong name> | <_dmarc p=none -> quarantine on <date>> | ## Verify live (not checked offline) - `<dig +short CNAME shop.<domain>>` - <target still in use?> - `<dig TXT google._domainkey.<domain>>` - <matches the provider console?> ## Rollout 1. <lower TTL of changed records to 300 s, wait one old TTL> 2. <apply changes, bump SOA serial to YYYYMMDDnn> 3. <verify with dig against the authoritative servers and a public resolver; send a test mail and read the Authentication-Results header> 4. <raise TTLs back to 3600 s; review DMARC reports after 1-2 weeks> **Rollback:** <old values listed above; restore them and wait one TTL> **Open questions:** <which services send mail as this domain? is backupmx still used?> FILE:examples/example.com.zone ; example.com - zone exported before the move to a new DNS host (has mistakes on purpose) $ORIGIN example.com. $TTL 3600 @ IN SOA ns1.example.net. hostmaster@example.com. ( 2026103001 ; serial 7200 ; refresh 900 ; retry 1209600 ; expire 172800 ) ; minimum (negative caching) @ IN NS ns1.example.net. @ IN NS ns2.example.net. ; website moved to a static host @ IN CNAME bakery-site.example.net. www 30 IN CNAME bakery-site.example.net. www IN TXT "site-verification=4f9c2a" shop IN CNAME shops.myshopify.com blog IN A 192.0.2.44 blog IN A 192.0.2.44 legacy 1209600 IN A 192.0.2.45 intranet IN A 10.0.4.12 ; mail @ IN MX 10 mail.example.com @ IN MX 20 backupmx backupmx IN CNAME mx2.example.net. @ IN TXT "v=spf1 include:_spf.google.com ~all" @ IN TXT "v=spf1 include:sendgrid.net ?all" dmarc IN TXT "v=DMARC1; p=none" google._domainkey IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbNfaf4mo/6FvrWAv3WssXhXwsdrJxrAuhIVcYXdrMZp55PDpEjo63C/vOuaStp58YtZTnzQlm0V3rjtvOP1XgGAy3LWurXdRkT0zOGxx0AMgjZfD/8QDgjF6f4VW9zmNytbD3EgZXxeGZSBw8JtTdT/rOEygTgYL5+x5DftDSFQIDAQAB" s2019._domainkey IN TXT "v=DKIM1; k=rsa; p=" FILE:examples/example.com.fixed.zone ; example.com - corrected zone $ORIGIN example.com. $TTL 3600 @ IN SOA ns1.example.net. hostmaster.example.com. ( 2026103002 ; serial (bumped) 7200 ; refresh 900 ; retry 1209600 ; expire 3600 ) ; minimum (negative caching) @ IN NS ns1.example.net. @ IN NS ns2.example.net. @ IN CAA 0 issue "letsencrypt.org" ; website: A/AAAA at the apex (or the provider's ALIAS/flattening), CNAME only below it @ IN A 192.0.2.10 @ IN AAAA 2001:db8::10 www IN CNAME bakery-site.example.net. _site-verification.www IN TXT "site-verification=4f9c2a" shop IN CNAME shops.myshopify.com. blog IN A 192.0.2.44 legacy IN A 192.0.2.45 ; intranet moved to the internal (split-horizon) view ; mail @ IN MX 10 mail.example.com. @ IN MX 20 mx2.example.net. mail IN A 192.0.2.25 @ IN TXT "v=spf1 include:_spf.google.com include:sendgrid.net -all" _dmarc IN TXT "v=DMARC1; p=quarantine; rua=mailto:dmarc-reports@example.com" google._domainkey IN TXT ( "v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz7ouq6bH4GbHRPASRa3m/LiSvOKSZ7L7KZqE231EHY1s8FN9criBQkJXXmxkwPERQSVSyRIC4LjSpxwPTe6LEVhg7nrswTX1ktBbXMUmkgj8CPKV+yWzOsDOMk7kjqghuNWXD/R5K/mT7xbTiCaXztegoQi+" "kVXf0xuMmQYLxVthdjIz1h2PORFhtjzwKYbpaMKjq2BWKIaNtaGBxc2kaSLyPw8W65+A7XeLhtKT8zcteU72IpdmibNsHlkBR0Hb7rQgb+0LgNVqPvF/mm37PKFPQPrfWjjL/Fc1MQoCm8jO3kI0O5ssuP7KKO7ZjtT4ekeHytw23INuPh/Kw1LqzwIDAQAB" ) FILE:examples/lint-report.md # DNS record lint: example.com.zone Zone: example.com. Format: zone Records: 19 Findings: 19 (HIGH 7, MEDIUM 8, LOW 4) | Sev | Code | Line | Name | Type | Problem | Fix | |---|---|---|---|---|---|---| | HIGH | SOA_RNAME_AT | 4 | @ | SOA | contact 'hostmaster@example.com.' contains '@'; in DNS it is written with a dot | write the contact as hostmaster.example.com. (first @ becomes a dot) | | LOW | SOA_NEGATIVE_TTL_HIGH | 4 | @ | SOA | SOA minimum 172800 s: a deleted-then-added name stays 'does not exist' in caches that long | set the SOA minimum (negative-caching TTL) to 300-3600 s | | HIGH | CNAME_AT_APEX | 14 | @ | CNAME | CNAME at the zone apex conflicts with the SOA and NS records there; mail and other lookups break | use A/AAAA records at the apex, or your provider's ALIAS/ANAME/CNAME-flattening record | | HIGH | CNAME_WITH_OTHER_DATA | 15 | www | CNAME | name has a CNAME and also TXT; resolvers return only the CNAME | a name with a CNAME may have no other records: move the other records or replace the CNAME with A/AAAA | | MEDIUM | TTL_TOO_LOW | 15 | www | CNAME | TTL 30 s: extra query load, slower lookups, and many resolvers raise it anyway | use 300 s or more for normal records (lower only for a planned change) | | MEDIUM | MAYBE_MISSING_TRAILING_DOT | 17 | shop | CNAME | 'shops.myshopify.com' looks like a full host name but has no trailing dot, so it means shops.myshopify.com.example.com. | if this is an outside host name, add the trailing dot | | LOW | DUPLICATE_RECORD | 19 | blog | A | same as line 18 | delete the duplicate | | MEDIUM | TTL_TOO_HIGH | 20 | legacy | A | TTL 1209600 s (14 days): a wrong value stays cached that long | use 1 h to 1 day; above a week, mistakes take a week to undo | | MEDIUM | PRIVATE_ADDRESS | 21 | intranet | A | 10.0.4.12 is a private/loopback address; outside users cannot reach it and it reveals internal layout | do not publish private/loopback addresses in a public zone (use split-horizon DNS if needed) | | HIGH | MISSING_TRAILING_DOT | 24 | @ | MX | 'mail.example.com' has no trailing dot, so it means mail.example.com.example.com. | end fully qualified names with a dot (mail.example.com.) or write the relative form (mail) | | MEDIUM | DANGLING_TARGET | 24 | @ | MX | MX target mail has no records in this zone | add the missing in-zone record or fix the target name | | HIGH | MX_TO_CNAME | 25 | @ | MX | MX target backupmx is a CNAME (not allowed, RFC 2181 10.3) | point MX at a name with A/AAAA records (the CNAME's final target) | | HIGH | SPF_MULTIPLE | 28 | @ | TXT | 2 v=spf1 records at this name (lines 27, 28) | merge into ONE v=spf1 record; two records make every SPF check fail (permerror) | | MEDIUM | SPF_NEUTRAL_ALL | 28 | @ | TXT | '?all' is neutral: unauthorized senders are not marked | use ~all or -all; ?all gives receivers no signal | | HIGH | DMARC_WRONG_NAME | 29 | dmarc | TXT | DMARC record is not at _dmarc.<domain>, so receivers never see it | DMARC is only read from _dmarc.<domain>; move the record there | | LOW | DKIM_1024_KEY | 30 | google._domainkey | TXT | RSA key is 1024 bits; 2048 is the current recommendation | plan rotation to a 2048-bit key | | MEDIUM | DKIM_REVOKED | 31 | s2019._domainkey | TXT | p= is empty: this selector is revoked and mail signed with it fails DKIM | empty p= revokes the key; remove the record if the selector is retired, or publish the new key | | MEDIUM | DMARC_MISSING | - | _dmarc | TXT | no DMARC record: receivers cannot tell spoofed mail from yours, and Gmail/Yahoo require DMARC for bulk senders | add TXT at _dmarc: "v=DMARC1; p=none; rua=mailto:dmarc@<domain>" then move to quarantine/reject | | LOW | CAA_MISSING | - | @ | CAA | no CAA record: any public CA may issue certificates for this domain | optional hardening: CAA 0 issue "<your CA>" limits who may issue certificates | ## Out-of-zone targets to check live (no network calls were made) | Target | Used by | |---|---| | bakery-site.example.net. | @ CNAME (line 14); www CNAME (line 15) | | mx2.example.net. | backupmx CNAME (line 26) | | ns1.example.net. | @ NS (line 10) | | ns2.example.net. | @ NS (line 11) | | shops.myshopify.com. | shop CNAME (line 17) | FILE:scripts/dns_lint.py #!/usr/bin/env python3 """DNS zone record linter (Python 3.8+ standard library only, works offline). Reads a BIND-style zone file or a CSV record list exported from a DNS provider and reports common mistakes before they break web or mail delivery: CNAME at the apex or next to other records, MX/NS pointing at a CNAME or an IP, missing trailing dots (mail.example.com -> mail.example.com.example.com.), missing or duplicate SPF, SPF syntax, +all/?all and the 10-lookup limit, DMARC and DKIM presence and syntax, weak or revoked DKIM keys, TTL extremes, private addresses in a public zone, SOA mistakes, duplicate records, and domains that send no mail but have no "no mail" policy. Out-of-zone targets are listed for a separate live check. Usage: python3 dns_lint.py example.com.zone [--origin example.com] [--json] [--min-severity LOW|MEDIUM|HIGH] [--ignore CODE,CODE] python3 dns_lint.py records.csv --origin example.com (CSV columns: name,type,value[,ttl][,priority]) python3 dns_lint.py --self-test Zone files: $ORIGIN, $TTL, @, relative names, blank owner (repeat previous), optional TTL/class in either order, ( ) multi-line records, ; comments, quoted TXT strings. Exit codes: 0 = no HIGH findings, 1 = HIGH findings, 2 = bad input. """ import argparse, base64, csv, io, ipaddress, json, os, re, sys SEVERITIES = ["LOW", "MEDIUM", "HIGH"] CLASSES = {"IN", "CH", "HS"} TYPES = {"A", "AAAA", "CNAME", "MX", "NS", "TXT", "SPF", "SOA", "SRV", "CAA", "PTR", "DNAME", "ALIAS", "ANAME", "DS", "DNSKEY", "RRSIG", "NSEC", "NSEC3", "NSEC3PARAM", "HTTPS", "SVCB", "TLSA", "NAPTR", "SSHFP", "LOC", "HINFO", "CDS", "CDNSKEY"} DNSSEC_TYPES = {"RRSIG", "NSEC", "NSEC3", "KEY"} TARGET_TYPES = {"CNAME": -1, "MX": 1, "NS": 0, "PTR": 0, "DNAME": 0, "SRV": 3, "ALIAS": 0, "ANAME": 0} COMMON_TLDS = set("com net org edu gov mil int io co dev app ai info biz me tv cloud xyz site online " "shop store tech us uk de fr nl eu es it se no dk fi pl cz at ch be pt ie tr ru " "jp cn kr in au nz ca br mx ar za sg hk tw".split()) INTERNAL_NETS = [ipaddress.ip_network(n) for n in ( "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "0.0.0.0/8", "::1/128", "::/128", "fc00::/7", "fe80::/10")] # documentation ranges (192.0.2.0/24, 2001:db8::/32) are allowed SPF_LOOKUP_TERMS = ("include", "a", "mx", "ptr", "exists", "redirect") FIXES = { "CNAME_AT_APEX": "use A/AAAA records at the apex, or your provider's ALIAS/ANAME/CNAME-flattening record", "CNAME_WITH_OTHER_DATA": "a name with a CNAME may have no other records: move the other records or replace the CNAME with A/AAAA", "MULTIPLE_CNAME": "keep exactly one CNAME for the name", "MX_TO_CNAME": "point MX at a name with A/AAAA records (the CNAME's final target)", "NS_TO_CNAME": "point NS at the name server's real host name (A/AAAA)", "TARGET_IS_IP": "use a host name here and give that host an A/AAAA record", "MISSING_TRAILING_DOT": "end fully qualified names with a dot (mail.example.com.) or write the relative form (mail)", "MAYBE_MISSING_TRAILING_DOT": "if this is an outside host name, add the trailing dot", "OWNER_DOUBLED_ORIGIN": "end the owner name with a dot or write it relative (www)", "DANGLING_TARGET": "add the missing in-zone record or fix the target name", "CNAME_CHAIN": "point straight at the final name; chains add lookups and break when one link changes", "MX_TARGET_NO_ADDRESS": "add A/AAAA records for the mail host", "NULL_MX_WITH_OTHERS": "a null MX ('0 .') must be the only MX; remove it or the others", "SPF_MISSING": "publish one TXT \"v=spf1 ... -all\" (or ~all while testing) listing every service that sends as this domain", "SPF_MULTIPLE": "merge into ONE v=spf1 record; two records make every SPF check fail (permerror)", "SPF_TYPE99": "delete the SPF-type record; only the TXT record is used (RFC 7208)", "SPF_SYNTAX": "fix the term; one bad term makes the whole record a permerror", "SPF_PASS_ALL": "end with -all (or ~all while testing); +all lets anyone send as you", "SPF_NEUTRAL_ALL": "use ~all or -all; ?all gives receivers no signal", "SPF_NO_ALL": "end the record with -all or ~all (or redirect=)", "SPF_TERMS_AFTER_ALL": "move 'all' to the end; terms after it are ignored", "SPF_TOO_MANY_LOOKUPS": "flatten or remove includes, drop a/mx/ptr terms you do not need; nested includes count too", "SPF_LOOKUPS_NEAR_LIMIT": "count nested includes with a live checker; they add to this number", "SPF_PTR": "replace ptr with ip4/ip6 or include (ptr is deprecated and slow)", "TXT_STRING_TOO_LONG": "split into quoted chunks of at most 255 characters: \"part1\" \"part2\"", "DMARC_MISSING": "add TXT at _dmarc: \"v=DMARC1; p=none; rua=mailto:dmarc@<domain>\" then move to quarantine/reject", "DMARC_MULTIPLE": "keep one DMARC record; with two, receivers ignore DMARC entirely", "DMARC_SYNTAX": "start with v=DMARC1; and include p=none|quarantine|reject", "DMARC_WRONG_NAME": "DMARC is only read from _dmarc.<domain>; move the record there", "DMARC_MONITOR_ONLY": "after reviewing reports, move to p=quarantine, then p=reject", "DMARC_NO_RUA": "add rua=mailto:... so you get aggregate reports", "DMARC_PARTIAL_PCT": "raise pct to 100 once reports look clean", "DKIM_NOT_FOUND": "publish the DKIM selector record(s) your mail provider gives you (<selector>._domainkey)", "DKIM_WRONG_NAME": "DKIM keys live at <selector>._domainkey.<domain>", "DKIM_REVOKED": "empty p= revokes the key; remove the record if the selector is retired, or publish the new key", "DKIM_BAD_KEY": "copy the key again from the provider (base64, no spaces or quotes inside)", "DKIM_WEAK_KEY": "rotate to a 2048-bit RSA key (or add an ed25519 selector alongside RSA)", "DKIM_1024_KEY": "plan rotation to a 2048-bit key", "NO_MAIL_POLICY": "for a domain that never sends mail: MX 0 . , TXT \"v=spf1 -all\" and _dmarc \"v=DMARC1; p=reject\"", "NULL_MX_SPF_NOT_FAIL": "a no-mail domain should publish \"v=spf1 -all\"", "TTL_TOO_LOW": "use 300 s or more for normal records (lower only for a planned change)", "TTL_TOO_HIGH": "use 1 h to 1 day; above a week, mistakes take a week to undo", "TTL_INVALID": "TTL must be 0..2147483647 seconds", "NO_DEFAULT_TTL": "add $TTL at the top of the zone (e.g. $TTL 3600)", "SOA_MISSING": "a zone file needs exactly one SOA at the apex", "SOA_RNAME_AT": "write the contact as hostmaster.example.com. (first @ becomes a dot)", "SOA_NEGATIVE_TTL_HIGH": "set the SOA minimum (negative-caching TTL) to 300-3600 s", "NS_MISSING": "list the zone's name servers as NS records at the apex", "NS_SINGLE": "use at least two name servers on separate networks", "BAD_ADDRESS": "fix the address", "WRONG_ADDRESS_FAMILY": "A takes IPv4, AAAA takes IPv6", "PRIVATE_ADDRESS": "do not publish private/loopback addresses in a public zone (use split-horizon DNS if needed)", "DUPLICATE_RECORD": "delete the duplicate", "CAA_MISSING": "optional hardening: CAA 0 issue \"<your CA>\" limits who may issue certificates", "UNKNOWN_TYPE": "check the record type spelling", "PARSE_ERROR": "fix the line syntax", "INCLUDE_NOT_FOLLOWED": "lint the included file separately", } class InputError(Exception): pass class Rec: __slots__ = ("line", "name", "raw_name", "ttl", "type", "rdata", "raw") def __init__(self, line, name, raw_name, ttl, rtype, rdata, raw): self.line, self.name, self.raw_name, self.ttl = line, name, raw_name, ttl self.type, self.rdata, self.raw = rtype, rdata, raw def parse_ttl(tok): t = tok.lower() if t.isdigit(): return int(t) m = re.fullmatch(r"((\d+)[wdhms])+", t) if not m: return None mult = {"w": 604800, "d": 86400, "h": 3600, "m": 60, "s": 1} return sum(int(n) * mult[u] for n, u in re.findall(r"(\d+)([wdhms])", t)) def tokenize(text): """Split one logical line into tokens; quoted strings keep their quotes.""" toks, i, n = [], 0, len(text) while i < n: c = text[i] if c.isspace(): i += 1 elif c == '"': j, buf = i + 1, ['"'] while j < n and text[j] != '"': if text[j] == "\\" and j + 1 < n: buf.append(text[j:j + 2]); j += 2; continue buf.append(text[j]); j += 1 if j >= n: raise InputError("unterminated quoted string") buf.append('"'); toks.append("".join(buf)); i = j + 1 else: j = i while j < n and not text[j].isspace() and text[j] != '"': j += 1 toks.append(text[i:j]); i = j return toks def strip_comment(line): out, inq, i = [], False, 0 while i < len(line): c = line[i] if c == "\\" and i + 1 < len(line): out.append(line[i:i + 2]); i += 2; continue if c == '"': inq = not inq elif c == ";" and not inq: break out.append(c); i += 1 return "".join(out) def logical_lines(text): """Yield (line_no, starts_with_space, content) joining ( ... ) groups.""" buf, start, depth, lead = [], 0, 0, False for no, line in enumerate(text.splitlines(), 1): body = strip_comment(line) if depth == 0: if not body.strip(): continue start, lead, buf = no, body[:1].isspace(), [] inq = False clean = [] for c in body: if c == '"': inq = not inq if not inq and c in "()": depth += 1 if c == "(" else -1 clean.append(" ") continue clean.append(c) buf.append("".join(clean)) if depth <= 0: depth = 0 yield start, lead, " ".join(buf) if depth > 0: raise InputError(f"line {start}: '(' is never closed") def absname(raw, origin): if raw == "@": return origin if raw.endswith("."): return raw.lower() return (raw + "." + origin).lower() if origin != "." else raw.lower() + "." def parse_zone(text, origin, findings): recs, last_owner, default_ttl, have_ttl_directive = [], None, None, False for no, lead, content in logical_lines(text): toks = tokenize(content) if not toks: continue if toks[0].upper() == "$ORIGIN": if len(toks) < 2: raise InputError(f"line {no}: $ORIGIN needs a name") origin = absname(toks[1], origin) if not toks[1].endswith(".") else toks[1].lower() continue if toks[0].upper() == "$TTL": v = parse_ttl(toks[1]) if len(toks) > 1 else None if v is None: raise InputError(f"line {no}: bad $TTL") default_ttl, have_ttl_directive = v, True continue if toks[0].upper() == "$INCLUDE": add(findings, "LOW", "INCLUDE_NOT_FOLLOWED", no, "", "", f"$INCLUDE {toks[1] if len(toks) > 1 else ''} was not read") continue if lead: if last_owner is None: raise InputError(f"line {no}: record has no owner name and there is no previous one") raw_owner = None else: raw_owner = toks.pop(0) ttl, rtype = None, None while toks: t = toks[0] if t.upper() in CLASSES: toks.pop(0); continue v = parse_ttl(t) if v is not None and ttl is None and not t.upper() in TYPES: ttl = v; toks.pop(0); continue break if not toks: add(findings, "HIGH", "PARSE_ERROR", no, raw_owner or "", "", f"no record type in '{content.strip()}'") continue rtype = toks.pop(0).upper() if rtype not in TYPES and not re.fullmatch(r"TYPE\d+", rtype): add(findings, "MEDIUM", "UNKNOWN_TYPE", no, raw_owner or "", rtype, f"unknown record type '{rtype}'") if raw_owner is not None: name = absname(raw_owner, origin) last_owner = (name, raw_owner) name, raw_name = last_owner recs.append(Rec(no, name, raw_name, ttl, rtype, toks, content.strip())) return recs, origin, default_ttl, have_ttl_directive def parse_csv(text, origin, findings): rows = list(csv.DictReader(io.StringIO(text))) if not rows: raise InputError("CSV has no rows") cols = {c.lower().strip(): c for c in rows[0].keys() if c} for need in ("name", "type", "value"): if need not in cols: raise InputError(f"CSV needs columns name,type,value[,ttl][,priority] (missing '{need}')") recs = [] base = origin.rstrip(".") for i, r in enumerate(rows, 2): g = lambda k: (r.get(cols[k]) or "").strip() if k in cols else "" raw = g("name") or "@" low = raw.lower().rstrip(".") if raw == "@" or low == base: name = origin elif low.endswith("." + base): name = low + "." else: name = low + "." + origin rtype = g("type").upper() value = g("value") ttl = parse_ttl(g("ttl")) if g("ttl") else None if rtype in ("TXT", "SPF"): v = value if not v.startswith('"'): v = '"' + v.replace('"', '\\"') + '"' toks = tokenize(v) else: toks = value.split() if rtype in TARGET_TYPES and toks: # provider UIs show host names without the dot idx = TARGET_TYPES[rtype] if rtype == "MX" and len(toks) == 1: toks = [g("priority") or "10"] + toks if rtype == "SRV" and len(toks) == 3 and g("priority"): toks = [g("priority")] + toks k = len(toks) - 1 if idx == -1 else min(idx, len(toks) - 1) if not toks[k].endswith(".") and toks[k] != "@": toks[k] += "." recs.append(Rec(i, name, raw, ttl, rtype, toks, ",".join(r.get(c) or "" for c in r))) return recs, origin def add(findings, sev, code, line, name, rtype, problem): findings.append({"severity": sev, "code": code, "line": line, "name": name, "type": rtype, "problem": problem, "fix": FIXES.get(code, "")}) def txt_strings(rec): out = [] for t in rec.rdata: if t.startswith('"') and t.endswith('"'): out.append(re.sub(r"\\(.)", r"\1", t[1:-1])) else: out.append(t) return out def short(name, origin): if name == origin: return "@" if name.endswith("." + origin): return name[: -len(origin) - 1] return name def lint(text, origin=None, fmt=None, filename=""): findings = [] if fmt is None: fmt = "csv" if filename.lower().endswith(".csv") or text.lstrip().lower().startswith("name,") else "zone" if origin is None: m = re.search(r"^\$ORIGIN\s+(\S+)", text, re.M | re.I) if m: origin = m.group(1) elif filename: b = os.path.basename(filename) for suf in (".zone", ".db", ".txt", ".csv"): if b.lower().endswith(suf): b = b[: -len(suf)] for pre in ("db.",): if b.startswith(pre): b = b[len(pre):] origin = b if "." in b else None if not origin: raise InputError("cannot tell the zone name: add $ORIGIN or pass --origin example.com") origin = origin.lower().rstrip(".") + "." if fmt == "csv": recs, origin = parse_csv(text, origin, findings) default_ttl, have_ttl = None, True else: recs, origin, default_ttl, have_ttl = parse_zone(text, origin, findings) base = origin.rstrip(".") by_name = {} for r in recs: by_name.setdefault(r.name, []).append(r) types_at = lambda n: {r.type for r in by_name.get(n, [])} in_zone = lambda n: n == origin or n.endswith("." + origin) externals = {} # SOA / NS / TTL soa = [r for r in recs if r.type == "SOA"] if fmt == "zone": if not soa: add(findings, "MEDIUM", "SOA_MISSING", 0, "@", "SOA", "no SOA record in the zone file") for r in soa: if len(r.rdata) >= 7: rname = r.rdata[1] if "@" in rname: add(findings, "HIGH", "SOA_RNAME_AT", r.line, short(r.name, origin), "SOA", f"contact '{rname}' contains '@'; in DNS it is written with a dot") neg = parse_ttl(r.rdata[6]) if neg is not None and neg > 86400: add(findings, "LOW", "SOA_NEGATIVE_TTL_HIGH", r.line, short(r.name, origin), "SOA", f"SOA minimum {neg} s: a deleted-then-added name stays 'does not exist' in caches that long") if default_ttl is None and neg is not None: default_ttl = neg else: add(findings, "HIGH", "PARSE_ERROR", r.line, short(r.name, origin), "SOA", "SOA needs 7 fields: mname rname serial refresh retry expire minimum") ns_apex = [r for r in by_name.get(origin, []) if r.type == "NS"] if not ns_apex: add(findings, "MEDIUM", "NS_MISSING", 0, "@", "NS", "no NS records at the apex") elif len(ns_apex) == 1: add(findings, "MEDIUM", "NS_SINGLE", ns_apex[0].line, "@", "NS", "only one name server: if it is down, the whole domain is down") if not have_ttl: add(findings, "LOW", "NO_DEFAULT_TTL", 0, "", "", "no $TTL directive; records without a TTL fall back to the SOA minimum or the server default") for r in recs: ttl = r.ttl if r.ttl is not None else default_ttl if ttl is None: continue nm = short(r.name, origin) if ttl > 2147483647: add(findings, "HIGH", "TTL_INVALID", r.line, nm, r.type, f"TTL {ttl} is above 2147483647") elif ttl > 604800: add(findings, "MEDIUM", "TTL_TOO_HIGH", r.line, nm, r.type, f"TTL {ttl} s ({ttl // 86400} days): a wrong value stays cached that long") elif ttl < 60 and not r.name.startswith("_acme-challenge."): add(findings, "MEDIUM", "TTL_TOO_LOW", r.line, nm, r.type, f"TTL {ttl} s: extra query load, slower lookups, and many resolvers raise it anyway") # owner names that repeat the origin for r in recs: if fmt == "zone" and r.raw_name not in (None, "@") and not r.raw_name.endswith(".") and \ (r.raw_name.lower() == base or r.raw_name.lower().endswith("." + base)): add(findings, "HIGH", "OWNER_DOUBLED_ORIGIN", r.line, r.raw_name, r.type, f"owner '{r.raw_name}' has no trailing dot, so it becomes {r.name}") # CNAME rules for n, rs in by_name.items(): cn = [r for r in rs if r.type == "CNAME"] if not cn: continue nm = short(n, origin) if n == origin: add(findings, "HIGH", "CNAME_AT_APEX", cn[0].line, nm, "CNAME", "CNAME at the zone apex conflicts with the SOA and NS records there; mail and other lookups break") others = sorted({r.type for r in rs if r.type not in ("CNAME",) and r.type not in DNSSEC_TYPES}) if others and n != origin: add(findings, "HIGH", "CNAME_WITH_OTHER_DATA", cn[0].line, nm, "CNAME", f"name has a CNAME and also {', '.join(others)}; resolvers return only the CNAME") if len(cn) > 1: add(findings, "HIGH", "MULTIPLE_CNAME", cn[1].line, nm, "CNAME", f"{len(cn)} CNAME records for one name") # targets for r in recs: if r.type not in TARGET_TYPES or not r.rdata: continue idx = TARGET_TYPES[r.type] if r.type == "MX" and len(r.rdata) < 2 or r.type == "SRV" and len(r.rdata) < 4: add(findings, "HIGH", "PARSE_ERROR", r.line, short(r.name, origin), r.type, f"{r.type} needs " + ("preference and host" if r.type == "MX" else "priority weight port target")) continue raw = r.rdata[idx] if idx >= 0 else r.rdata[-1] nm = short(r.name, origin) if r.type == "MX" and raw == ".": continue try: ipaddress.ip_address(raw.rstrip(".")) add(findings, "HIGH", "TARGET_IS_IP", r.line, nm, r.type, f"{r.type} target '{raw}' is an IP address; {r.type} must name a host") continue except ValueError: pass tgt = absname(raw, origin) if fmt == "zone" and raw != "@" and not raw.endswith("."): low = raw.lower() if low == base or low.endswith("." + base): add(findings, "HIGH", "MISSING_TRAILING_DOT", r.line, nm, r.type, f"'{raw}' has no trailing dot, so it means {absname(raw, origin)}") tgt = low + "." # check the name that was meant elif "." in low and low.rsplit(".", 1)[1] in COMMON_TLDS: add(findings, "MEDIUM", "MAYBE_MISSING_TRAILING_DOT", r.line, nm, r.type, f"'{raw}' looks like a full host name but has no trailing dot, so it means {absname(raw, origin)}") tgt = low + "." if in_zone(tgt): tt = types_at(tgt) if r.type in ("MX", "NS", "SRV") and "CNAME" in tt: code = {"MX": "MX_TO_CNAME", "NS": "NS_TO_CNAME", "SRV": "MX_TO_CNAME"}[r.type] add(findings, "HIGH", code, r.line, nm, r.type, f"{r.type} target {short(tgt, origin)} is a CNAME (not allowed, RFC 2181 10.3)") elif r.type == "CNAME" and "CNAME" in tt: add(findings, "LOW", "CNAME_CHAIN", r.line, nm, r.type, f"CNAME to {short(tgt, origin)}, which is itself a CNAME") elif not tt: # wildcard or a deeper/glue name may exist elsewhere; only flag when no wildcard covers it wild = "*." + tgt.split(".", 1)[1] if "." in tgt else "" if wild not in by_name: add(findings, "MEDIUM", "DANGLING_TARGET", r.line, nm, r.type, f"{r.type} target {short(tgt, origin)} has no records in this zone") elif r.type == "MX" and not (tt & {"A", "AAAA"}): add(findings, "MEDIUM", "MX_TARGET_NO_ADDRESS", r.line, nm, r.type, f"mail host {short(tgt, origin)} has no A/AAAA record") else: externals.setdefault(tgt, []).append(f"{nm} {r.type} (line {r.line})") # addresses for r in recs: if r.type not in ("A", "AAAA") or not r.rdata: continue nm = short(r.name, origin) try: ip = ipaddress.ip_address(r.rdata[0]) except ValueError: add(findings, "HIGH", "BAD_ADDRESS", r.line, nm, r.type, f"'{r.rdata[0]}' is not an IP address") continue if (r.type == "A") != (ip.version == 4): add(findings, "HIGH", "WRONG_ADDRESS_FAMILY", r.line, nm, r.type, f"{r.type} record holds an IPv{ip.version} address") elif any(ip in n for n in INTERNAL_NETS if n.version == ip.version): add(findings, "MEDIUM", "PRIVATE_ADDRESS", r.line, nm, r.type, f"{ip} is a private/loopback address; outside users cannot reach it and it reveals internal layout") # duplicates seen = {} for r in recs: key = (r.name, r.type, " ".join(x.lower() for x in r.rdata)) if key in seen: add(findings, "LOW", "DUPLICATE_RECORD", r.line, short(r.name, origin), r.type, f"same as line {seen[key]}") else: seen[key] = r.line # TXT string length (zone files only: each quoted string max 255) if fmt == "zone": for r in recs: if r.type in ("TXT", "SPF"): for s in txt_strings(r): if len(s.encode()) > 255: add(findings, "HIGH", "TXT_STRING_TOO_LONG", r.line, short(r.name, origin), r.type, f"one quoted string is {len(s.encode())} bytes (max 255); the server rejects the zone or truncates it") break # mail: MX, SPF, DMARC, DKIM txt_by_name = {} for r in recs: if r.type == "TXT": txt_by_name.setdefault(r.name, []).append((r, "".join(txt_strings(r)))) for r in recs: if r.type == "SPF": add(findings, "LOW", "SPF_TYPE99", r.line, short(r.name, origin), "SPF", "SPF-type (99) record is obsolete and ignored") spf_at = {} for n, items in txt_by_name.items(): for r, s in items: if re.match(r"(?i)v=spf1(\s|$)", s): spf_at.setdefault(n, []).append((r, s)) if re.match(r"(?i)v=dmarc1", s) and not n.startswith("_dmarc."): add(findings, "HIGH", "DMARC_WRONG_NAME", r.line, short(n, origin), "TXT", "DMARC record is not at _dmarc.<domain>, so receivers never see it") if re.match(r"(?i)v=dkim1", s) and "._domainkey." not in "." + n: add(findings, "HIGH", "DKIM_WRONG_NAME", r.line, short(n, origin), "TXT", "DKIM key is not under <selector>._domainkey, so signatures cannot be verified") for n, items in spf_at.items(): nm = short(n, origin) if len(items) > 1: add(findings, "HIGH", "SPF_MULTIPLE", items[1][0].line, nm, "TXT", f"{len(items)} v=spf1 records at this name (lines {', '.join(str(i[0].line) for i in items)})") for r, s in items: check_spf(findings, r, s, nm) mx_names = {} for r in recs: if r.type == "MX" and len(r.rdata) >= 2: mx_names.setdefault(r.name, []).append(r) for n, mxs in mx_names.items(): nulls = [r for r in mxs if r.rdata[1] == "."] if nulls and len(mxs) > 1: add(findings, "HIGH", "NULL_MX_WITH_OTHERS", nulls[0].line, short(n, origin), "MX", "null MX ('0 .') next to other MX records") apex_mx = [r for r in mx_names.get(origin, []) if r.rdata[1] != "."] apex_null = any(r.rdata[1] == "." for r in mx_names.get(origin, [])) apex_spf = spf_at.get(origin, []) spf_sends = any(not re.fullmatch(r"(?i)v=spf1\s+-all", s.strip()) for _, s in apex_spf) sends_mail = bool(apex_mx) or spf_sends for n, mxs in mx_names.items(): if any(r.rdata[1] != "." for r in mxs) and n not in spf_at: add(findings, "MEDIUM", "SPF_MISSING", mxs[0].line, short(n, origin), "TXT", "name receives mail (MX) but publishes no SPF record") if apex_null and apex_spf and spf_sends: add(findings, "LOW", "NULL_MX_SPF_NOT_FAIL", apex_spf[0][0].line, "@", "TXT", "null MX says no mail, but SPF still authorizes senders") if apex_null and not apex_spf: add(findings, "LOW", "NULL_MX_SPF_NOT_FAIL", 0, "@", "TXT", "null MX but no \"v=spf1 -all\"") dm = [(r, s) for r, s in txt_by_name.get("_dmarc." + origin, []) if re.match(r"(?i)v=dmarc1", s.strip()) or "p=" in s.lower()] dkim_names = [n for n in by_name if n.endswith("._domainkey." + origin)] if sends_mail or apex_null: if not dm: add(findings, "MEDIUM", "DMARC_MISSING", 0, "_dmarc", "TXT", "no DMARC record: receivers cannot tell spoofed mail from yours, and Gmail/Yahoo require DMARC for bulk senders") if dm: if len(dm) > 1: add(findings, "HIGH", "DMARC_MULTIPLE", dm[1][0].line, "_dmarc", "TXT", f"{len(dm)} DMARC records") for r, s in dm: check_dmarc(findings, r, s) if sends_mail and not dkim_names: add(findings, "MEDIUM", "DKIM_NOT_FOUND", 0, "*._domainkey", "TXT", "no <selector>._domainkey record: if you send mail, it is probably unsigned (checked only names in this file)") for n in dkim_names: for r in by_name[n]: if r.type == "TXT": check_dkim(findings, r, "".join(txt_strings(r)), short(n, origin)) if not sends_mail and not apex_null and not apex_spf: add(findings, "LOW", "NO_MAIL_POLICY", 0, "@", "MX", "no MX and no SPF: if this domain never sends mail, say so, or spammers can spoof it freely") has_web = any(r.type in ("A", "AAAA", "CNAME", "ALIAS", "ANAME") for r in recs) if has_web and "CAA" not in types_at(origin): add(findings, "LOW", "CAA_MISSING", 0, "@", "CAA", "no CAA record: any public CA may issue certificates for this domain") order = {s: i for i, s in enumerate(reversed(SEVERITIES))} findings.sort(key=lambda f: (f["line"] if f["line"] else 10 ** 6, order[f["severity"]], f["code"])) return {"origin": origin, "format": fmt, "records": len(recs), "findings": findings, "external_targets": [{"target": t, "used_by": u} for t, u in sorted(externals.items())]} def check_spf(findings, r, s, nm): terms = s.split()[1:] lookups, seen_all = 0, None for i, t in enumerate(terms): q = t[0] if t[0] in "+-~?" else "" body = t[len(q):].lower() mech = re.split(r"[:=/]", body, maxsplit=1)[0] if seen_all is not None and not body.startswith("exp="): add(findings, "MEDIUM", "SPF_TERMS_AFTER_ALL", r.line, nm, "TXT", f"'{t}' comes after 'all' and is ignored") seen_all = None if mech == "all": if q in ("", "+"): add(findings, "HIGH", "SPF_PASS_ALL", r.line, nm, "TXT", f"'{t}' authorizes every server on the internet to send as this domain") elif q == "?": add(findings, "MEDIUM", "SPF_NEUTRAL_ALL", r.line, nm, "TXT", "'?all' is neutral: unauthorized senders are not marked") seen_all = i continue if mech in ("include", "exists"): if ":" not in body or not body.split(":", 1)[1]: add(findings, "HIGH", "SPF_SYNTAX", r.line, nm, "TXT", f"'{t}' needs a domain ({mech}:example.net)") lookups += 1 elif mech in ("a", "mx"): lookups += 1 elif mech == "ptr": lookups += 1 add(findings, "LOW", "SPF_PTR", r.line, nm, "TXT", "'ptr' is deprecated (RFC 7208 5.5)") elif mech in ("ip4", "ip6"): val = body.split(":", 1)[1] if ":" in body else "" try: net = ipaddress.ip_network(val, strict=False) if (mech == "ip4") != (net.version == 4): raise ValueError except ValueError: add(findings, "HIGH", "SPF_SYNTAX", r.line, nm, "TXT", f"'{t}' is not a valid {mech} address or range") elif mech == "redirect": lookups += 1 if "=" not in body: add(findings, "HIGH", "SPF_SYNTAX", r.line, nm, "TXT", f"'{t}': use redirect=domain") elif mech == "exp": pass else: add(findings, "HIGH", "SPF_SYNTAX", r.line, nm, "TXT", f"unknown SPF term '{t}' (typo? e.g. ipv4: for ip4:, include= for include:)") if not any(re.sub(r"^[+\-~?]", "", t).lower() == "all" for t in terms) and not any(t.lower().startswith("redirect=") for t in terms): add(findings, "MEDIUM", "SPF_NO_ALL", r.line, nm, "TXT", "record has no 'all' or redirect=, so unlisted senders get a neutral result") if lookups > 10: add(findings, "HIGH", "SPF_TOO_MANY_LOOKUPS", r.line, nm, "TXT", f"{lookups} DNS-lookup terms at the top level alone (limit 10, RFC 7208 4.6.4); receivers return permerror") elif lookups >= 8: add(findings, "LOW", "SPF_LOOKUPS_NEAR_LIMIT", r.line, nm, "TXT", f"{lookups} lookup terms before counting nested includes (limit 10)") def check_dmarc(findings, r, s): tags = {} parts = [p.strip() for p in s.split(";") if p.strip()] if not parts or parts[0].replace(" ", "").upper() != "V=DMARC1": add(findings, "HIGH", "DMARC_SYNTAX", r.line, "_dmarc", "TXT", "record must start with 'v=DMARC1;'") for p in parts: k, _, v = p.partition("=") tags[k.strip().lower()] = v.strip() p = tags.get("p", "").lower() if p not in ("none", "quarantine", "reject"): add(findings, "HIGH", "DMARC_SYNTAX", r.line, "_dmarc", "TXT", "missing or invalid p= (none, quarantine or reject); receivers ignore the record") return if p == "none": add(findings, "LOW", "DMARC_MONITOR_ONLY", r.line, "_dmarc", "TXT", "p=none only monitors; spoofed mail is still delivered") if "rua" not in tags: add(findings, "LOW", "DMARC_NO_RUA", r.line, "_dmarc", "TXT", "no rua= address, so nobody sees the aggregate reports") if tags.get("pct", "100").isdigit() and int(tags.get("pct", "100")) < 100: add(findings, "LOW", "DMARC_PARTIAL_PCT", r.line, "_dmarc", "TXT", f"pct={tags['pct']}: the policy applies to only part of the failing mail") def check_dkim(findings, r, s, nm): tags = {} for p in s.split(";"): k, _, v = p.strip().partition("=") if k: tags[k.strip().lower()] = re.sub(r"\s+", "", v) if "p" not in tags: add(findings, "HIGH", "DKIM_BAD_KEY", r.line, nm, "TXT", "no p= tag: not a DKIM key record") return if tags["p"] == "": add(findings, "MEDIUM", "DKIM_REVOKED", r.line, nm, "TXT", "p= is empty: this selector is revoked and mail signed with it fails DKIM") return try: raw = base64.b64decode(tags["p"], validate=True) except Exception: add(findings, "HIGH", "DKIM_BAD_KEY", r.line, nm, "TXT", "p= is not valid base64 (stray quote, space or cut-off copy?)") return if tags.get("k", "rsa").lower() == "ed25519": return bits = rsa_bits(raw) if bits is None: add(findings, "HIGH", "DKIM_BAD_KEY", r.line, nm, "TXT", f"p= decodes to {len(raw)} bytes but is not an RSA public key (cut off?)") elif bits < 1024: add(findings, "HIGH", "DKIM_WEAK_KEY", r.line, nm, "TXT", f"RSA key is {bits} bits; keys under 1024 bits are rejected by receivers (RFC 8301)") elif bits < 2048: add(findings, "LOW", "DKIM_1024_KEY", r.line, nm, "TXT", f"RSA key is {bits} bits; 2048 is the current recommendation") def der_read(b, i): tag = b[i]; i += 1 ln = b[i]; i += 1 if ln & 0x80: n = ln & 0x7F ln = int.from_bytes(b[i:i + n], "big"); i += n return tag, i, ln def rsa_bits(raw): """Modulus size of an RSA SubjectPublicKeyInfo (or bare RSAPublicKey) in bits.""" try: tag, i, ln = der_read(raw, 0) if tag != 0x30: return None tag, j, l2 = der_read(raw, i) if tag == 0x30: # SubjectPublicKeyInfo: algorithm, then BIT STRING j += l2 tag, j, l3 = der_read(raw, j) if tag != 0x03: return None j += 1 # unused-bits byte tag, j, l4 = der_read(raw, j) if tag != 0x30: return None tag, j, lm = der_read(raw, j) elif tag == 0x02: lm = l2 else: return None if tag != 0x02 or j + lm > len(raw): return None mod = raw[j:j + lm].lstrip(b"\x00") return len(mod) * 8 if mod else None except IndexError: return None def render(res, title, min_sev="LOW", ignore=()): keep = [f for f in res["findings"] if SEVERITIES.index(f["severity"]) >= SEVERITIES.index(min_sev) and f["code"] not in ignore] cnt = {s: sum(1 for f in keep if f["severity"] == s) for s in SEVERITIES} out = [f"# DNS record lint: {title}", "", f"Zone: {res['origin']} Format: {res['format']} Records: {res['records']} Findings: {len(keep)} (HIGH {cnt['HIGH']}, MEDIUM {cnt['MEDIUM']}, LOW {cnt['LOW']})", ""] if keep: out += ["| Sev | Code | Line | Name | Type | Problem | Fix |", "|---|---|---|---|---|---|---|"] for f in keep: out.append(f"| {f['severity']} | {f['code']} | {f['line'] or '-'} | {f['name'] or '-'} | {f['type'] or '-'} | {f['problem']} | {f['fix']} |") else: out.append("No findings.") if res["external_targets"]: out += ["", "## Out-of-zone targets to check live (no network calls were made)", "", "| Target | Used by |", "|---|---|"] for e in res["external_targets"]: out.append(f"| {e['target']} | {'; '.join(e['used_by'])} |") return "\n".join(out) + "\n", keep def self_test(): Z = "$ORIGIN example.com.\n$TTL 3600\n@ IN SOA ns1 hostmaster 1 7200 900 1209600 300\n@ NS ns1\n@ NS ns2.example.net.\nns1 A 192.0.2.53\n" MAIL = '@ MX 10 mail\nmail A 192.0.2.25\n@ TXT "v=spf1 mx -all"\n_dmarc TXT "v=DMARC1; p=reject; rua=mailto:d@example.com"\ns1._domainkey CNAME s1.dkim.example.net.\n@ CAA 0 issue "letsencrypt.org"\n' k1024 = base64.b64encode(bytes.fromhex("30819f300d06092a864886f70d010101050003818d0030818902818100") + b"\xc1" + bytes(127) + bytes.fromhex("0203010001")).decode() k512 = base64.b64encode(bytes.fromhex("305c300d06092a864886f70d0101010500034b003048024100") + b"\xc1" + bytes(63) + bytes.fromhex("0203010001")).decode() def codes(text, **kw): return [f["code"] for f in lint(text, **kw)["findings"]] cases = [ ("clean zone", Z + MAIL, lambda c: c == []), ("cname at apex", Z + MAIL + "@ CNAME shop.example.net.\n", lambda c: "CNAME_AT_APEX" in c), ("cname with other data", Z + MAIL + "www CNAME web.example.net.\nwww TXT \"x\"\n", lambda c: "CNAME_WITH_OTHER_DATA" in c), ("multiple cname", Z + MAIL + "www CNAME a.example.net.\nwww CNAME b.example.net.\n", lambda c: "MULTIPLE_CNAME" in c), ("mx to cname", Z + MAIL.replace("mail A 192.0.2.25", "mail CNAME mx.example.net."), lambda c: "MX_TO_CNAME" in c), ("ns to cname", Z.replace("ns1 A 192.0.2.53", "ns1 CNAME dns.example.net.") + MAIL, lambda c: "NS_TO_CNAME" in c), ("mx is ip", Z + MAIL.replace("MX 10 mail", "MX 10 192.0.2.25"), lambda c: "TARGET_IS_IP" in c), ("missing trailing dot", Z + MAIL + "www CNAME web.example.com\nweb A 192.0.2.80\n", lambda c: "MISSING_TRAILING_DOT" in c), ("maybe missing dot (outside name)", Z + MAIL + "shop CNAME shops.myshopify.com\n", lambda c: "MAYBE_MISSING_TRAILING_DOT" in c), ("owner doubled origin", Z + MAIL + "www.example.com A 192.0.2.80\n", lambda c: "OWNER_DOUBLED_ORIGIN" in c), ("relative target ok", Z + MAIL + "www CNAME web\nweb A 192.0.2.80\n", lambda c: c == []), ("dangling target", Z + MAIL + "www CNAME web\n", lambda c: "DANGLING_TARGET" in c), ("cname chain", Z + MAIL + "www CNAME web\nweb CNAME edge.example.net.\n", lambda c: "CNAME_CHAIN" in c), ("mx target no address", Z + MAIL.replace("mail A 192.0.2.25", "mail TXT \"x\""), lambda c: "MX_TARGET_NO_ADDRESS" in c), ("spf missing", Z + MAIL.replace('@ TXT "v=spf1 mx -all"\n', ""), lambda c: "SPF_MISSING" in c), ("spf multiple", Z + MAIL + '@ TXT "v=spf1 include:_spf.google.com ~all"\n', lambda c: "SPF_MULTIPLE" in c), ("spf +all", Z + MAIL.replace("mx -all", "mx +all"), lambda c: "SPF_PASS_ALL" in c), ("spf ?all", Z + MAIL.replace("mx -all", "mx ?all"), lambda c: "SPF_NEUTRAL_ALL" in c), ("spf no all", Z + MAIL.replace("mx -all", "mx"), lambda c: "SPF_NO_ALL" in c), ("spf terms after all", Z + MAIL.replace("mx -all", "-all mx"), lambda c: "SPF_TERMS_AFTER_ALL" in c), ("spf syntax typo", Z + MAIL.replace("mx -all", "ipv4:192.0.2.1 -all"), lambda c: "SPF_SYNTAX" in c), ("spf bad ip4", Z + MAIL.replace("mx -all", "ip4:300.1.1.1 -all"), lambda c: "SPF_SYNTAX" in c), ("spf too many lookups", Z + MAIL.replace("mx -all", " ".join(f"include:s{i}.example.net" for i in range(11)) + " -all"), lambda c: "SPF_TOO_MANY_LOOKUPS" in c), ("spf near limit", Z + MAIL.replace("mx -all", " ".join(f"include:s{i}.example.net" for i in range(8)) + " -all"), lambda c: "SPF_LOOKUPS_NEAR_LIMIT" in c and "SPF_TOO_MANY_LOOKUPS" not in c), ("spf ptr", Z + MAIL.replace("mx -all", "ptr -all"), lambda c: "SPF_PTR" in c), ("spf type99", Z + MAIL + '@ SPF "v=spf1 mx -all"\n', lambda c: "SPF_TYPE99" in c), ("split txt strings joined", Z + MAIL.replace('"v=spf1 mx -all"', '"v=spf1 mx " "-all"'), lambda c: c == []), ("txt string too long", Z + MAIL + '@ TXT "' + "a" * 300 + '"\n', lambda c: "TXT_STRING_TOO_LONG" in c), ("dmarc missing", Z + MAIL.replace('_dmarc TXT "v=DMARC1; p=reject; rua=mailto:d@example.com"\n', ""), lambda c: "DMARC_MISSING" in c), ("dmarc wrong name", Z + MAIL.replace("_dmarc TXT", "dmarc TXT"), lambda c: "DMARC_WRONG_NAME" in c and "DMARC_MISSING" in c), ("dmarc multiple", Z + MAIL + '_dmarc TXT "v=DMARC1; p=none"\n', lambda c: "DMARC_MULTIPLE" in c), ("dmarc no p", Z + MAIL.replace("p=reject; ", ""), lambda c: "DMARC_SYNTAX" in c), ("dmarc none + no rua + pct", Z + MAIL.replace("p=reject; rua=mailto:d@example.com", "p=none; pct=50"), lambda c: {"DMARC_MONITOR_ONLY", "DMARC_NO_RUA", "DMARC_PARTIAL_PCT"} <= set(c)), ("dkim not found", Z + MAIL.replace("s1._domainkey CNAME s1.dkim.example.net.\n", ""), lambda c: "DKIM_NOT_FOUND" in c), ("dkim revoked", Z + MAIL + 's2._domainkey TXT "v=DKIM1; k=rsa; p="\n', lambda c: "DKIM_REVOKED" in c), ("dkim bad base64", Z + MAIL + 's2._domainkey TXT "v=DKIM1; p=MIGf!!"\n', lambda c: "DKIM_BAD_KEY" in c), ("dkim 512-bit key", Z + MAIL + f's2._domainkey TXT "v=DKIM1; k=rsa; p={k512}"\n', lambda c: "DKIM_WEAK_KEY" in c), ("dkim 1024-bit key", Z + MAIL + f's2._domainkey TXT "v=DKIM1; k=rsa; p={k1024}"\n', lambda c: "DKIM_1024_KEY" in c), ("dkim wrong name", Z + MAIL + f's2.domainkey TXT "v=DKIM1; p={k1024}"\n', lambda c: "DKIM_WRONG_NAME" in c), ("null mx + spf -all, no mail checks", Z + '@ MX 0 .\n@ TXT "v=spf1 -all"\n_dmarc TXT "v=DMARC1; p=reject; rua=mailto:d@example.com"\n@ CAA 0 issue "letsencrypt.org"\n', lambda c: c == []), ("null mx with others", Z + MAIL + "@ MX 0 .\n", lambda c: "NULL_MX_WITH_OTHERS" in c), ("no mail policy", Z + '@ CAA 0 issue "letsencrypt.org"\n', lambda c: "NO_MAIL_POLICY" in c), ("ttl too low", Z + MAIL + "www 30 A 192.0.2.80\n", lambda c: "TTL_TOO_LOW" in c), ("acme ttl low ok", Z + MAIL + '_acme-challenge 30 TXT "token"\n', lambda c: c == []), ("ttl too high (units)", Z + MAIL + "www 2w A 192.0.2.80\n", lambda c: "TTL_TOO_HIGH" in c), ("no $TTL", Z.replace("$TTL 3600\n", "") + MAIL, lambda c: "NO_DEFAULT_TTL" in c), ("soa rname with @", Z.replace("hostmaster", "hostmaster@example.com.") + MAIL, lambda c: "SOA_RNAME_AT" in c), ("soa multi-line with comments", Z.replace("@ IN SOA ns1 hostmaster 1 7200 900 1209600 300", "@ IN SOA ns1 hostmaster (\n 2026103001 ; serial\n 7200 900 1209600\n 300 ) ; min") + MAIL, lambda c: c == []), ("single ns", Z.replace("@ NS ns2.example.net.\n", "") + MAIL, lambda c: "NS_SINGLE" in c), ("bad address", Z + MAIL + "www A 192.0.2.300\n", lambda c: "BAD_ADDRESS" in c), ("wrong family", Z + MAIL + "www AAAA 192.0.2.80\n", lambda c: "WRONG_ADDRESS_FAMILY" in c), ("private address", Z + MAIL + "intranet A 10.0.0.5\n", lambda c: "PRIVATE_ADDRESS" in c), ("duplicate record", Z + MAIL + "www A 192.0.2.80\nwww A 192.0.2.80\n", lambda c: "DUPLICATE_RECORD" in c), ("blank owner continues", Z + MAIL + "www A 192.0.2.80\n AAAA 2001:db8::80\n", lambda c: c == []), ("semicolon inside quotes kept", Z + MAIL.replace('"v=DMARC1; p=reject; rua=mailto:d@example.com"', '"v=DMARC1; p=reject; rua=mailto:d@example.com" ; comment'), lambda c: c == []), ("caa missing", Z + MAIL.replace('@ CAA 0 issue "letsencrypt.org"\n', ""), lambda c: c == ["CAA_MISSING"]), ("csv input", None, None), ("unterminated quote is input error", None, None), ] passed = 0 for name, text, check in cases: try: if name == "csv input": csvt = ("name,type,value,ttl,priority\n@,MX,mail.example.com,3600,10\nmail,A,192.0.2.25,3600,\n" "@,TXT,v=spf1 include:_spf.google.com ~all,3600,\n@,TXT,v=spf1 mx -all,3600,\n" "www.example.com,CNAME,example.com,300,\n@,CNAME,shop.example.net,300,\n") res = lint(csvt, origin="example.com", fmt="csv") c = [f["code"] for f in res["findings"]] ok = {"SPF_MULTIPLE", "CNAME_AT_APEX", "DMARC_MISSING", "DKIM_NOT_FOUND"} <= set(c) and "MISSING_TRAILING_DOT" not in c and "MX_TO_CNAME" not in c elif name == "unterminated quote is input error": try: lint(Z + '@ TXT "v=spf1 -all\n') ok, c = False, "no error" except InputError as e: ok, c = True, str(e) else: c = codes(text) ok = check(c) except Exception as e: # noqa ok, c = False, f"exception {e!r}" passed += ok print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" got {c}")) print(f"{passed}/{len(cases)} passed") return 0 if passed == len(cases) else 1 def main(argv=None): ap = argparse.ArgumentParser(description="Lint a DNS zone file or record list (offline)") ap.add_argument("file", nargs="?") ap.add_argument("--origin", help="zone name, e.g. example.com (default: $ORIGIN or the file name)") ap.add_argument("--format", choices=["zone", "csv"], help="input format (default: by extension/content)") ap.add_argument("--json", action="store_true") ap.add_argument("--min-severity", default="LOW", choices=SEVERITIES) ap.add_argument("--ignore", default="", help="comma-separated finding codes to skip") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.file: ap.error("give a zone file or CSV, or --self-test") try: with open(a.file, encoding="utf-8") as fh: text = fh.read() res = lint(text, origin=a.origin, fmt=a.format, filename=a.file) except (OSError, InputError, UnicodeDecodeError) as e: print(f"error: {e}", file=sys.stderr) return 2 ignore = {c.strip().upper() for c in a.ignore.split(",") if c.strip()} md, keep = render(res, os.path.basename(a.file), a.min_severity, ignore) if a.json: print(json.dumps({**res, "findings": keep}, indent=2)) else: sys.stdout.write(md) return 1 if any(f["severity"] == "HIGH" for f in keep) else 0 if __name__ == "__main__": sys.exit(main())

Houseplant Watering Schedule Planner

--- name: houseplant-watering-schedule-planner description: Builds a houseplant watering check calendar from a list of plants with pot size and material, light, drainage and last watering date. Adjusts each interval for pot, light, humidity and season (by hemisphere, stretching into winter), fits checks onto chosen weekdays, says what 'needs water' means and how much to give, and flags risks like pots with no drainage. Includes a stdlib Python planner with .ics export and --self-test. --- # Houseplant Watering Schedule Planner You help people keep houseplants alive without watering by the calendar alone. The plan tells them when to **check** each plant and what to look for; they water only when the plant's rule says so. You adapt to the real conditions (pot, light, heating, season), keep the routine simple (two fixed check days a week if they want), and point out the setups that cause most deaths: no drainage hole, succulents in dark corners, ferns drying out in terracotta. ## Files in this skill - `scripts/watering_planner.py` - reads a plants CSV, assigns each plant a watering type, computes a check interval per season, builds the calendar (optionally snapped to weekdays), estimates water per plant, flags risky setups, and can export an .ics file (Python 3.8+ standard library only) - `references/plant-water-profiles.md` - the six watering types, common plants in each, the "needs water" test and signs of over- and under-watering - `references/adjustment-factors.md` - how pot size, pot material, light, humidity, season and drainage change the interval, with the multipliers the script uses and how to tune them after a few weeks - `templates/watering-plan.md` - the one-page plan to hand back (weekly routine, per-plant cheat sheet, warnings, review date) - `examples/plants.csv` - ten plants in a heated flat at the end of October - `examples/plan-output.md` - the real output of the planner for that list ## Workflow ### 1. Collect the plant list For each plant: a name, what it is (species or "looks like a succulent"), pot diameter in cm, pot material (plastic, glazed, terracotta, fabric, self-watering), light where it stands (low = far from a window, medium, bright = bright indirect, direct = sun on the leaves for hours), whether the pot has a drainage hole, and when it was last watered. Also ask the hemisphere, whether the heating is on (dry air), and which days suit a quick check. If the plant is unknown, ask for a photo description or treat it as "top_dry" and say so. ### 2. Run the planner ``` python3 scripts/watering_planner.py examples/plants.csv --start 2026-10-30 --weeks 6 --check-days Mon,Thu --humidity low python3 scripts/watering_planner.py plants.csv --hemisphere south --weeks 8 --ics plants.ics python3 scripts/watering_planner.py plants.csv --json python3 scripts/watering_planner.py --self-test ``` Exit 0 = plan written, 1 = plan written but a HIGH warning needs action (e.g. no drainage), 2 = bad input (unknown material or light, pot size in mm, bad date). Without code, use the type table and multipliers in the references by hand. ### 3. Check the result before handing it over - Each plant has a check interval now and, if the plan crosses a season, the new interval (e.g. "7 d (winter: 9 d)"). - Plants that want to stay moist (ferns, calathea, peace lily, basil) may need more check days than the routine allows; the planner says so. Suggest a third check day, a plastic pot, or self-watering only for these. - "Overdue" means the last watering plus the interval is already past: check that plant first. - Read the warnings and turn HIGH ones into the first action of the plan. ### 4. Deliver Fill `templates/watering-plan.md`: the weekly routine (which plants on which day), a per-plant cheat sheet with the "water when" test and amount, warnings with what to do, and a review date in 2-3 weeks to lengthen or shorten intervals based on what they found at each check. ## Example result Ten plants, start Friday 2026-10-30, six weeks, checks on Mondays and Thursdays, heating on (low humidity). Ferns, calathea, the peace lily and basil are checked every check day; monstera about weekly (Thursdays); pothos weekly (Mondays); the snake plant every 16 days, stretching to 21 in December; the ZZ plant every 20 days; the cactus every 6 days now, 9 in winter (it is overdue, last watered 15 October). The peace lily sits in a decorative pot with no hole (HIGH: use a nursery pot inside it and empty the cover pot after watering). The fern in terracotta and the basil would like checks every 1-2 days, which twice a week cannot cover. See `examples/plan-output.md`. ## Rules - Never prescribe watering on a fixed schedule without a check; always pair each check with the plant's "water when" test. - Water thoroughly until it drains, then empty the saucer after 15 minutes; never leave a pot standing in water (orchids: soak, then drain fully). - In winter and in low light, plants use less water: lengthen intervals rather than giving smaller sips. - Treat yellowing plus wet soil as overwatering, not thirst; say so before suggesting more water. - Do not guess a species from a vague name; ask or state the type you assumed. - Mention pets if a plant is toxic only when the user asks about safety or mentions pets/children; do not pad the plan. FILE:references/plant-water-profiles.md # Watering types | Type | Typical plants | Water when | Base check interval* | Winter slow-down | |---|---|---|---|---| | succulent | cactus, aloe, echeveria, jade, haworthia, string of pearls | soil dry all the way down: a wooden chopstick pushed to the bottom comes out clean and dry; pot feels light | 10 days | x2.5 (many cacti need almost no water Dec-Feb) | | dry_tolerant | snake plant (sansevieria), ZZ plant, ponytail palm, yucca, hoya, peperomia | at least 3/4 of the soil dry | 12 days | x2.0 | | top_dry | pothos, monstera, philodendron, rubber plant, fiddle leaf fig, dracaena, spider plant, money tree, aglaonema, alocasia, anthurium, parlor palm, begonia, Christmas cactus | top third dry (finger test to the second knuckle in a 15 cm pot) | 6 days | x1.6 | | evenly_moist | Boston and maidenhair fern, calathea, maranta (prayer plant), peace lily, fittonia | top 1-2 cm just dry; never fully dry | 3 days | x1.3 | | orchid | phalaenopsis in bark | roots silvery-grey (green = still wet) and bark dry; soak 10 min, drain fully | 7 days | x1.4 | | herb | basil, mint, parsley on a windowsill | top 1-2 cm dry | 2 days | x1.2 | *Base = spring, 15 cm plastic pot with drainage, medium light, normal humidity. Autumn is halfway between spring and winter; summer is x0.85. See `adjustment-factors.md`. ## How to check (30 seconds per plant) 1. **Finger test:** push a finger into the soil to the depth in the rule. Dry and crumbly = dry; cool and sticking = moist. 2. **Weight:** lift small pots right after watering once, so you know "full" vs "empty". 3. **Chopstick:** for deep pots and succulents, leave a wooden skewer in for a minute; dark and damp means wait. 4. **Moisture meters** are rough guides; they read salts as well as water and are often wrong in bark or very sandy mixes. ## Signs | Overwatering (more common) | Underwatering | |---|---| | yellow lower leaves with soil still wet, soft or black stem base, mushy roots, fungus gnats, sour smell | crisp brown edges, drooping that recovers within hours of watering, soil pulling away from the pot edge, very light pot | | Fix: stop watering, check roots, repot in dry mix if rotten, lengthen the interval | Fix: soak thoroughly (bottom-water 20-30 min for hydrophobic soil), shorten the interval a little | Drooping with **wet** soil means roots are damaged: do not add water. ## Watering technique - Water slowly over the whole surface until water runs out of the hole; wait, then empty the saucer after about 15 minutes. - Room-temperature water. Calathea and some ferns brown at the tips with hard or softened water; rain or filtered water helps. - Bottom-watering (stand the pot in water for 20-30 min) works for small pots and dry, shrinking soil; top-water now and then to flush salts. - Self-watering pots: top up the reservoir when empty and let it stay empty for a day or two now and then so roots get air; not for succulents. FILE:references/adjustment-factors.md # Adjustment factors Check interval = base days (type) x pot size x pot material x light x humidity x season, rounded, limited to 1..45 days. These are the multipliers in `scripts/watering_planner.py`. | Factor | Value | Multiplier | Why | |---|---|---|---| | Pot diameter | under 10 cm | 0.6 | little soil, dries in days | | | 10-13 cm | 0.8 | | | | 14-19 cm | 1.0 | reference | | | 20-27 cm | 1.3 | more soil holds water longer | | | 28 cm and up | 1.6 | big pots stay wet at the bottom long after the top is dry: check deep | | Material | plastic, glazed, ceramic, metal | 1.0 | walls do not breathe | | | terracotta / unglazed clay | 0.75 | walls wick and evaporate water | | | fabric grow bag | 0.7 | dries from all sides | | | self-watering | 1.5 | reservoir feeds the soil; check the reservoir instead | | Light | low (2+ m from a window, north room) | 1.4 | little growth, little use | | | medium | 1.0 | | | | bright indirect | 0.85 | | | | direct sun on the leaves | 0.7 | | | Humidity | low (heating on, below ~35 %) | 0.85 | soil and leaves lose water faster | | | normal | 1.0 | | | | high (bathroom, humidifier) | 1.15 | | | Season | spring | 1.0 | | | | summer | 0.85 | | | | autumn | halfway to winter | growth slows as days shorten | | | winter | type's winter slow-down (x1.2 to x2.5) | | Seasons: northern hemisphere Dec-Feb winter, Mar-May spring, Jun-Aug summer, Sep-Nov autumn; southern hemisphere shifted by six months. Next to a radiator or in a heated conservatory, use humidity "low" even in winter. ## Drainage No hole is the single biggest cause of root rot. Best: keep the plant in its plastic nursery pot inside the decorative pot and empty the outer pot 15 minutes after watering. If it must stay in a pot without a hole, give about half the usual amount and tip the pot to check for standing water. The planner flags this as HIGH. ## Amount About 15-25 % of the pot volume, until water drains out of the hole. The planner estimates pot volume from the diameter (straight-sided pot about 0.9x as tall as wide), so a 15 cm pot gets about 450 ml, a 24 cm pot about 1.75 l. Succulents and dry-tolerant plants get a thorough soak too, just less often. ## Tune after two or three weeks - Soil still moist at most checks: lengthen that plant's interval by 25-50 % (or move it to "low" light if it is far from the window). - Soil bone-dry at every check and the plant droops: shorten by 25 %. - Write the changes into the CSV (e.g. switch the type or light) and re-run, rather than remembering exceptions. - Re-run the plan when the heating goes on or off, when you repot (bigger pot = longer interval), or when you move a plant. ## Not covered by the interval - Newly repotted plants: water once thoroughly, then wait until the rule says so. - Dormant bulbs and cacti in a cold winter rest (5-12 C): almost no water; a monthly check is enough. - Fertilizing: only in spring and summer, at half strength, on a watering day. FILE:templates/watering-plan.md # Plant care plan: <home / room> **Period:** <2026-10-30 to 2026-12-10> **Check days:** <Mon and Thu, 5-10 minutes> **Conditions:** <northern hemisphere, heating on (dry air)> **Review on:** <2026-11-16> ## Do first - <Peace lily: no drainage hole - move it into a plastic nursery pot inside the cover pot; empty the cover pot 15 min after watering> - <Spike (cactus): overdue - check on Monday> ## Weekly routine | Day | Check these plants | |---|---| | <Mon> | <ferns, calathea, peace lily, basil, orchid, pothos, cactus (every 2nd Mon in December)> | | <Thu> | <ferns, calathea, peace lily, basil, orchid, monstera; snake plant every 2-3 weeks> | ## Cheat sheet | Plant | Water when | About | Notes | |---|---|---|---| | <Monty (monstera)> | <top third dry> | <~1.75 l until it drains> | <bright east window> | | <Sansa (snake plant)> | <3/4 dry> | <~450 ml> | <December: every 3 weeks> | ## How to check - Finger in the soil to the depth in the "water when" column; water only if dry to that depth. - Water until it drains, empty the saucer after 15 minutes. - Wet soil + yellow leaves = too much water: skip and tell me. ## Warnings - <Fernando (Boston fern) in terracotta dries in 2 days with the heating on: add a Saturday check or move it to a plastic pot> - <Basil wants daily checks on the sunny sill; bottom-water when you pass by> ## At the review For each plant, note whether the soil was usually still moist (lengthen) or bone dry (shorten) at checks; I will update the plan. FILE:examples/plants.csv name,plant,pot_cm,pot_material,light,drainage,last_watered,notes Monty,monstera,24,plastic,bright,yes,2026-10-28,living room by the east window Pothos shelf,pothos,14,glazed,medium,yes,2026-10-27,trailing from the bookshelf Sansa,snake plant,17,terracotta,low,yes,2026-10-20,hallway corner Zed,zz plant,20,plastic,medium,yes,,new from the shop Fernando,boston fern,20,terracotta,bright,yes,2026-10-29,bathroom shelf Cal,calathea,15,plastic,medium,yes,2026-10-28,bedroom Spike,cactus,10,terracotta,direct,yes,2026-10-15,south windowsill Peace lily,peace lily,18,glazed,low,no,2026-10-26,decorative pot with no hole Orchid,phalaenopsis,12,plastic,bright,yes,2026-10-25,kitchen window Basil,basil,13,terracotta,direct,yes,2026-10-29,kitchen windowsill FILE:examples/plan-output.md # Houseplant watering plan: 2026-10-30 to 2026-12-10 Hemisphere: north Season at start: autumn Humidity: low Check days: Mon, Thu Plants: 10 A check is not a watering: feel the soil and water only when the rule says so. ## Plants | Plant | Type | Pot | Light | Check every | Water when | About | Checks | |---|---|---|---|---|---|---|---| | Monty (monstera) | top_dry | 24 cm plastic | bright | 7 d (winter: 9 d) | top third of the soil dry (about 3-5 cm in a 15 cm pot) | ~1750 ml (until it drains) | 6 | | Pothos shelf (pothos) | top_dry | 14 cm glazed | medium | 7 d (winter: 8 d) | top third of the soil dry (about 3-5 cm in a 15 cm pot) | ~350 ml (until it drains) | 6 | | Sansa (snake plant) | dry_tolerant | 17 cm terracotta | low | 16 d (winter: 21 d) | soil dry at least 3/4 of the way down | ~450 ml (until it drains) | 3 | | Zed (zz plant) | dry_tolerant | 20 cm plastic | medium | 20 d | soil dry at least 3/4 of the way down | ~750 ml (until it drains) | 2 | | Fernando (boston fern) | evenly_moist | 20 cm terracotta | bright | 2 d (winter: 3 d) | top 1-2 cm just dry; never let it dry out fully | ~1000 ml (until it drains) | 12 | | Cal (calathea) | evenly_moist | 15 cm plastic | medium | 3 d (winter: 3 d) | top 1-2 cm just dry; never let it dry out fully | ~450 ml (until it drains) | 12 | | Spike (cactus) (overdue: check first day) | succulent | 10 cm terracotta | direct | 6 d (winter: 9 d) | soil dry all the way down (chopstick comes out clean and dry) | ~100 ml (until it drains) | 6 | | Peace lily (peace lily) | evenly_moist | 18 cm glazed, NO hole | low | 4 d (winter: 5 d) | top 1-2 cm just dry; never let it dry out fully | ~375 ml, no more | 12 | | Orchid (phalaenopsis) | orchid | 12 cm plastic | bright | 5 d (winter: 6 d) | roots silvery-grey and bark dry; soak 10 min, drain fully | soak 10 min | 11 | | Basil (basil) | herb | 13 cm terracotta | direct | 1 d (winter: 1 d) | top 1-2 cm dry | ~350 ml (until it drains) | 12 | ## Calendar | Date | Day | Season | Check | |---|---|---|---| | 2026-11-02 | Mon | autumn | Basil, Cal, Fernando, Orchid, Peace lily, Pothos shelf, Spike, Zed | | 2026-11-05 | Thu | autumn | Basil, Cal, Fernando, Monty, Orchid, Peace lily, Sansa | | 2026-11-09 | Mon | autumn | Basil, Cal, Fernando, Orchid, Peace lily, Pothos shelf, Spike | | 2026-11-12 | Thu | autumn | Basil, Cal, Fernando, Monty, Orchid, Peace lily | | 2026-11-16 | Mon | autumn | Basil, Cal, Fernando, Orchid, Peace lily, Pothos shelf, Spike | | 2026-11-19 | Thu | autumn | Basil, Cal, Fernando, Monty, Orchid, Peace lily, Sansa | | 2026-11-23 | Mon | autumn | Basil, Cal, Fernando, Orchid, Peace lily, Pothos shelf, Spike, Zed | | 2026-11-26 | Thu | autumn | Basil, Cal, Fernando, Monty, Orchid, Peace lily | | 2026-11-30 | Mon | autumn | Basil, Cal, Fernando, Orchid, Peace lily, Pothos shelf, Spike | | 2026-12-03 | Thu | winter | Basil, Cal, Fernando, Monty, Orchid, Peace lily, Sansa | | 2026-12-07 | Mon | winter | Basil, Cal, Fernando, Peace lily, Pothos shelf, Spike | | 2026-12-10 | Thu | winter | Basil, Cal, Fernando, Monty, Orchid, Peace lily | ## Warnings | Sev | Plant | Note | |---|---|---| | HIGH | Peace lily | pot has no drainage hole: water pools at the bottom and roots rot. Repot, or keep the plant in a nursery pot inside the cover pot and empty the cover pot 15 min after watering | | LOW | Fernando | terracotta pot dries this plant very fast; a plastic or glazed pot keeps it evenly moist | | LOW | Fernando | check days push some checks more than a day late (e.g. due 2026-11-07, planned 2026-11-09); add a check day or feel the soil in between | | LOW | Basil | check days push some checks more than a day late (e.g. due 2026-11-03, planned 2026-11-05); add a check day or feel the soil in between | Intervals assume the plant is established in a free-draining mix. After 2-3 weeks, lengthen an interval if the soil is still moist at most checks, shorten it if it is always bone dry. FILE:scripts/watering_planner.py #!/usr/bin/env python3 """Houseplant watering schedule planner (Python 3.8+ standard library only). Reads a CSV of plants (species or watering type, pot diameter, pot material, light, drainage, optional last watering date) and builds a check calendar: how often to check each plant in the current season, what "needs water" means for it, roughly how much to give, and which plants to check on which date. Intervals stretch automatically as the plan crosses into autumn and winter (or shrink into summer), by hemisphere. Checks can be snapped to fixed weekdays (e.g. Mon,Thu) so the plan fits a routine. Optional .ics export for a calendar app. A check is not a watering: on each check, feel the soil and water only if the plant's rule says so. The intervals are starting points; adjust them after two or three weeks of real checks (see references/adjustment-factors.md). Usage: python3 watering_planner.py plants.csv [--start 2026-10-30] [--weeks 4] [--hemisphere north|south] [--humidity low|normal|high] [--check-days Mon,Thu] [--ics plan.ics] [--json] python3 watering_planner.py --self-test plants.csv columns: name, plant (species or type), pot_cm, pot_material (plastic|glazed|ceramic|terracotta|fabric|self-watering), light (low|medium|bright|direct), drainage (yes|no), last_watered (YYYY-MM-DD, optional), notes (optional). Types: succulent, dry_tolerant, top_dry, evenly_moist, orchid, herb. Exit codes: 0 = plan written, 1 = plan written with HIGH warnings (e.g. no drainage), 2 = bad input. """ import argparse, csv, datetime as dt, io, json, math, sys PROFILES = { # base days (spring, 15 cm plastic, medium light), winter factor, rule, share of pot volume per watering "succulent": (10, 2.5, "soil dry all the way down (chopstick comes out clean and dry)", 0.15), "dry_tolerant": (12, 2.0, "soil dry at least 3/4 of the way down", 0.15), "top_dry": (6, 1.6, "top third of the soil dry (about 3-5 cm in a 15 cm pot)", 0.20), "evenly_moist": (3, 1.3, "top 1-2 cm just dry; never let it dry out fully", 0.20), "orchid": (7, 1.4, "roots silvery-grey and bark dry; soak 10 min, drain fully", 0.0), "herb": (2, 1.2, "top 1-2 cm dry", 0.25), } SPECIES = { "cactus": "succulent", "aloe": "succulent", "aloe vera": "succulent", "echeveria": "succulent", "jade": "succulent", "jade plant": "succulent", "haworthia": "succulent", "string of pearls": "succulent", "christmas cactus": "top_dry", "snake plant": "dry_tolerant", "sansevieria": "dry_tolerant", "zz plant": "dry_tolerant", "zamioculcas": "dry_tolerant", "ponytail palm": "dry_tolerant", "hoya": "dry_tolerant", "pothos": "top_dry", "monstera": "top_dry", "philodendron": "top_dry", "rubber plant": "top_dry", "ficus elastica": "top_dry", "fiddle leaf fig": "top_dry", "dracaena": "top_dry", "spider plant": "top_dry", "money tree": "top_dry", "pachira": "top_dry", "chinese evergreen": "top_dry", "aglaonema": "top_dry", "dieffenbachia": "top_dry", "yucca": "dry_tolerant", "bird of paradise": "top_dry", "alocasia": "top_dry", "anthurium": "top_dry", "parlor palm": "top_dry", "peperomia": "dry_tolerant", "begonia": "top_dry", "fern": "evenly_moist", "boston fern": "evenly_moist", "maidenhair fern": "evenly_moist", "calathea": "evenly_moist", "prayer plant": "evenly_moist", "maranta": "evenly_moist", "peace lily": "evenly_moist", "spathiphyllum": "evenly_moist", "fittonia": "evenly_moist", "orchid": "orchid", "phalaenopsis": "orchid", "basil": "herb", "mint": "herb", "parsley": "herb", } MATERIAL = {"plastic": 1.0, "glazed": 1.0, "ceramic": 1.0, "metal": 1.0, "terracotta": 0.75, "clay": 0.75, "unglazed": 0.75, "fabric": 0.7, "self-watering": 1.5} LIGHT = {"low": 1.4, "medium": 1.0, "bright": 0.85, "direct": 0.7} HUMIDITY = {"low": 0.85, "normal": 1.0, "high": 1.15} SEASON_FACTOR = {"spring": 1.0, "summer": 0.85} DAY_NAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] class InputError(Exception): pass def season_of(d, hemisphere): m = d.month if hemisphere == "north" else (d.month + 5) % 12 + 1 return {12: "winter", 1: "winter", 2: "winter", 3: "spring", 4: "spring", 5: "spring", 6: "summer", 7: "summer", 8: "summer"}.get(m, "autumn") def pot_factor(cm): if cm < 10: return 0.6 if cm < 14: return 0.8 if cm < 20: return 1.0 if cm < 28: return 1.3 return 1.6 def pot_litres(cm): # straight-sided pot about 0.9x as tall as wide, minus ~10 % for the rim gap r = cm / 2.0 return math.pi * r * r * (0.9 * cm) * 0.9 / 1000.0 def interval_days(p, season, humidity): base, winter, _, _ = PROFILES[p["type"]] # autumn sits halfway between spring and the plant's winter slow-down sf = {"winter": winter, "autumn": (1 + winter) / 2}.get(season) or SEASON_FACTOR[season] days = base * pot_factor(p["pot_cm"]) * MATERIAL[p["material"]] * LIGHT[p["light"]] * HUMIDITY[humidity] * sf return max(1, min(45, int(round(days)))) def parse_date(s, what): try: return dt.date.fromisoformat(s.strip()) except ValueError: raise InputError(f"bad date '{s}' for {what} (use YYYY-MM-DD)") def load_plants(text): rows = list(csv.DictReader(io.StringIO(text))) if not rows: raise InputError("plants CSV has no rows") cols = {c.strip().lower(): c for c in rows[0] if c} if "name" not in cols: raise InputError("plants CSV needs at least a 'name' column (plus plant, pot_cm, pot_material, light, drainage)") plants, warnings = [], [] for i, r in enumerate(rows, 2): g = lambda k, d="": ((r.get(cols[k]) or "").strip() if k in cols else "") or d name = g("name") if not name: raise InputError(f"row {i}: empty name") kind = g("plant", g("type", "")).lower() if kind in PROFILES: ptype = kind elif kind in SPECIES: ptype = SPECIES[kind] else: ptype = next((v for k, v in SPECIES.items() if k in kind), None) if kind else None if ptype is None: ptype = "top_dry" warnings.append(("MEDIUM", name, f"unknown plant '{kind or '?'}': using type top_dry; set the plant column to one of {', '.join(PROFILES)}")) try: pot = float(g("pot_cm", "0") or 0) except ValueError: raise InputError(f"row {i} ({name}): pot_cm must be a number of centimetres") if pot <= 0: pot = 15.0 warnings.append(("LOW", name, "no pot size given: assumed 15 cm")) if pot > 80: raise InputError(f"row {i} ({name}): pot_cm {pot} looks wrong (centimetres, not millimetres?)") mat = g("pot_material", "plastic").lower() if mat not in MATERIAL: raise InputError(f"row {i} ({name}): pot_material '{mat}' (use {', '.join(MATERIAL)})") light = g("light", "medium").lower().replace("bright indirect", "bright").replace("full sun", "direct") if light not in LIGHT: raise InputError(f"row {i} ({name}): light '{light}' (use low, medium, bright, direct)") drainage = g("drainage", "yes").lower() not in ("no", "n", "false", "0") last = parse_date(g("last_watered"), f"{name} last_watered") if g("last_watered") else None p = {"name": name, "plant": kind or ptype, "type": ptype, "pot_cm": pot, "material": mat, "light": light, "drainage": drainage, "last_watered": last, "notes": g("notes")} plants.append(p) if not drainage: warnings.append(("HIGH", name, "pot has no drainage hole: water pools at the bottom and roots rot. Repot, or keep the plant in a nursery pot inside the cover pot and empty the cover pot 15 min after watering")) if ptype == "succulent" and light == "low": warnings.append(("MEDIUM", name, "succulent in low light: it will stretch and rot easily; move it to the brightest window and water even less")) if ptype == "evenly_moist" and light == "direct": warnings.append(("MEDIUM", name, "moisture-loving plant in direct sun: leaves scorch and soil dries within a day; move it out of direct sun")) if ptype == "evenly_moist" and mat in ("terracotta", "clay", "unglazed", "fabric"): warnings.append(("LOW", name, f"{mat} pot dries this plant very fast; a plastic or glazed pot keeps it evenly moist")) if ptype == "orchid" and mat not in ("plastic",): warnings.append(("LOW", name, "orchids are easiest in a clear plastic pot with drainage, so you can see the roots")) if mat == "self-watering" and ptype in ("succulent", "dry_tolerant", "orchid"): warnings.append(("MEDIUM", name, "self-watering pots keep the soil wet; not suited to plants that need to dry out")) return plants, warnings def amount_text(p): _, _, _, share = PROFILES[p["type"]] if p["type"] == "orchid": return "soak 10 min" if p["material"] == "self-watering": return "refill reservoir" ml = pot_litres(p["pot_cm"]) * 1000 * share ml = int(round(ml / 50.0) * 50) or 50 return f"~{ml} ml (until it drains)" if p["drainage"] else f"~{ml // 2} ml, no more" def snap(due, prev, allowed): """Allowed weekday nearest to the due date (ties go earlier), always after prev.""" if not allowed: return due best = None for off in (0, -1, 1, -2, 2, -3, 3): d = due + dt.timedelta(days=off) if d > prev and d.weekday() in allowed: best = d break if best is None: best = max(due, prev + dt.timedelta(days=1)) while best.weekday() not in allowed: best += dt.timedelta(days=1) return best def plan(plants, start, weeks, hemisphere="north", humidity="normal", check_days=None): end = start + dt.timedelta(days=7 * weeks - 1) allowed = {DAY_NAMES.index(x) for x in check_days} if check_days else set() cal, per_plant, notes = {}, [], [] for p in plants: s0 = season_of(start, hemisphere) iv = interval_days(p, s0, humidity) if p["last_watered"]: due = p["last_watered"] + dt.timedelta(days=iv) overdue = due < start first = max(due, start) else: overdue, first = False, start d = snap(first, start - dt.timedelta(days=1), allowed) if allowed else first dates, prev = [], None while d <= end: dates.append(d) cal.setdefault(d, []).append(p["name"]) step = interval_days(p, season_of(d, hemisphere), humidity) due = d + dt.timedelta(days=step) nd = snap(due, d, allowed) if allowed and (nd - due).days > max(1, step // 5): notes.append((p["name"], due, nd)) prev, d = d, nd later = {season_of(x, hemisphere) for x in dates} - {s0} per_plant.append({**p, "interval_now": iv, "season_now": s0, "intervals_later": {s: interval_days(p, s, humidity) for s in sorted(later)}, "rule": PROFILES[p["type"]][2], "amount": amount_text(p), "checks": [x.isoformat() for x in dates], "overdue": overdue}) return {"start": start, "end": end, "hemisphere": hemisphere, "humidity": humidity, "check_days": check_days or [], "plants": per_plant, "calendar": [(d, sorted(cal[d], key=str.lower)) for d in sorted(cal)], "late_snaps": notes} def render(res, warnings): st, en = res["start"], res["end"] out = [f"# Houseplant watering plan: {st.isoformat()} to {en.isoformat()}", "", f"Hemisphere: {res['hemisphere']} Season at start: {season_of(st, res['hemisphere'])} " f"Humidity: {res['humidity']} Check days: {', '.join(res['check_days']) or 'any day'} Plants: {len(res['plants'])}", "", "A check is not a watering: feel the soil and water only when the rule says so.", "", "## Plants", "", "| Plant | Type | Pot | Light | Check every | Water when | About | Checks |", "|---|---|---|---|---|---|---|---|"] for p in res["plants"]: iv = f"{p['interval_now']} d" if p["intervals_later"]: iv += " (" + ", ".join(f"{s}: {v} d" for s, v in p["intervals_later"].items()) + ")" pot = f"{p['pot_cm']:g} cm {p['material']}" + ("" if p["drainage"] else ", NO hole") flag = " (overdue: check first day)" if p["overdue"] else "" out.append(f"| {p['name']} ({p['plant']}){flag} | {p['type']} | {pot} | {p['light']} | {iv} | {p['rule']} | {p['amount']} | {len(p['checks'])} |") out += ["", "## Calendar", "", "| Date | Day | Season | Check |", "|---|---|---|---|"] for d, names in res["calendar"]: out.append(f"| {d.isoformat()} | {DAY_NAMES[d.weekday()]} | {season_of(d, res['hemisphere'])} | {', '.join(names)} |") if warnings or res["late_snaps"]: out += ["", "## Warnings", "", "| Sev | Plant | Note |", "|---|---|---|"] order = {"HIGH": 0, "MEDIUM": 1, "LOW": 2} for sev, name, msg in sorted(warnings, key=lambda w: (order[w[0]], w[1].lower())): out.append(f"| {sev} | {name} | {msg} |") seen = set() for name, due, nd in res["late_snaps"]: if name in seen: continue seen.add(name) out.append(f"| LOW | {name} | check days push some checks more than a day late (e.g. due {due.isoformat()}, planned {nd.isoformat()}); add a check day or feel the soil in between |") out += ["", "Intervals assume the plant is established in a free-draining mix. After 2-3 weeks, lengthen an interval if the soil is still moist at most checks, shorten it if it is always bone dry."] return "\n".join(out) + "\n" def to_ics(res, stamp): lines = ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//houseplant-watering-schedule-planner//EN", "CALSCALE:GREGORIAN"] for d, names in res["calendar"]: nd = d + dt.timedelta(days=1) lines += ["BEGIN:VEVENT", f"UID:plants-{d.strftime('%Y%m%d')}@watering-planner", f"DTSTAMP:{stamp}", f"DTSTART;VALUE=DATE:{d.strftime('%Y%m%d')}", f"DTEND;VALUE=DATE:{nd.strftime('%Y%m%d')}", "SUMMARY:" + ics_escape("Check plants: " + ", ".join(names)), "TRANSP:TRANSPARENT", "END:VEVENT"] lines.append("END:VCALENDAR") return "\r\n".join(fold(l) for l in lines) + "\r\n" def ics_escape(s): return s.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,").replace("\n", "\\n") def fold(line): b = line.encode("utf-8") if len(b) <= 75: return line parts, cur = [], b"" for ch in line: e = ch.encode("utf-8") if len(cur) + len(e) > (75 if not parts else 74): parts.append(cur.decode("utf-8")); cur = b"" cur += e parts.append(cur.decode("utf-8")) return "\r\n ".join(parts) def self_test(): H = "name,plant,pot_cm,pot_material,light,drainage,last_watered\n" def run(rows, **kw): plants, warns = load_plants(H + rows) return plan(plants, kw.pop("start", dt.date(2026, 4, 6)), kw.pop("weeks", 4), **kw), warns cases = [] def case(name, fn): try: ok = bool(fn()) err = "" except Exception as e: # noqa ok, err = False, repr(e) cases.append((name, ok, err)) case("succulent checked less often than fern", lambda: run("A,cactus,15,plastic,medium,yes,\nB,fern,15,plastic,medium,yes,\n")[0]["plants"][0]["interval_now"] > run("A,cactus,15,plastic,medium,yes,\nB,fern,15,plastic,medium,yes,\n")[0]["plants"][1]["interval_now"]) case("base interval top_dry 15 cm plastic medium spring = 6", lambda: run("A,pothos,15,plastic,medium,yes,\n")[0]["plants"][0]["interval_now"] == 6) case("small pot dries faster", lambda: run("A,pothos,9,plastic,medium,yes,\n")[0]["plants"][0]["interval_now"] < 6) case("big pot lasts longer", lambda: run("A,pothos,30,plastic,medium,yes,\n")[0]["plants"][0]["interval_now"] > 6) case("terracotta dries faster than plastic", lambda: run("A,pothos,15,terracotta,medium,yes,\n")[0]["plants"][0]["interval_now"] < 6) case("low light lengthens, direct sun shortens", lambda: run("A,pothos,15,plastic,low,yes,\n")[0]["plants"][0]["interval_now"] > 6 > run("A,pothos,15,plastic,direct,yes,\n")[0]["plants"][0]["interval_now"]) case("winter stretches succulent 2.5x", lambda: run("A,cactus,15,plastic,medium,yes,\n", start=dt.date(2026, 1, 5))[0]["plants"][0]["interval_now"] == 25) case("summer shortens", lambda: run("A,pothos,15,plastic,medium,yes,\n", start=dt.date(2026, 7, 6))[0]["plants"][0]["interval_now"] == 5) case("southern hemisphere: July is winter", lambda: season_of(dt.date(2026, 7, 1), "south") == "winter" and season_of(dt.date(2026, 1, 1), "south") == "summer") case("season boundaries north", lambda: [season_of(dt.date(2026, m, 15), "north") for m in (2, 3, 5, 6, 8, 9, 11, 12)] == ["winter", "spring", "spring", "summer", "summer", "autumn", "autumn", "winter"]) case("interval grows across autumn->winter in plan", lambda: (lambda r: r["plants"][0]["intervals_later"].get("winter", 0) > r["plants"][0]["interval_now"])(run("A,pothos,15,plastic,medium,yes,\n", start=dt.date(2026, 11, 16), weeks=4)[0])) case("checks spaced by interval", lambda: run("A,pothos,15,plastic,medium,yes,\n")[0]["plants"][0]["checks"][:3] == ["2026-04-06", "2026-04-12", "2026-04-18"]) case("last_watered sets first check", lambda: run("A,pothos,15,plastic,medium,yes,2026-04-04\n")[0]["plants"][0]["checks"][0] == "2026-04-10") case("overdue goes to start", lambda: (lambda p: p["overdue"] and p["checks"][0] == "2026-04-06")(run("A,pothos,15,plastic,medium,yes,2026-03-20\n")[0]["plants"][0])) case("snap to check days (Mon,Thu)", lambda: all(dt.date.fromisoformat(x).weekday() in (0, 3) for x in run("A,pothos,15,plastic,medium,yes,\nB,cactus,12,terracotta,bright,yes,\n", check_days=["Mon", "Thu"])[0]["calendar"] and [x for p in run("A,pothos,15,plastic,medium,yes,\nB,cactus,12,terracotta,bright,yes,\n", check_days=["Mon", "Thu"])[0]["plants"] for x in p["checks"]])) case("snap to nearest check day (Sun -> Mon)", lambda: snap(dt.date(2026, 4, 12), dt.date(2026, 4, 6), {0, 3}) == dt.date(2026, 4, 13)) case("snap tie goes earlier (Tue between Mon and Thu? no: Tue -> Mon)", lambda: snap(dt.date(2026, 4, 14), dt.date(2026, 4, 9), {0, 3}) == dt.date(2026, 4, 13)) case("snap never on or before the previous check", lambda: snap(dt.date(2026, 4, 7), dt.date(2026, 4, 6), {0, 3}) == dt.date(2026, 4, 9)) case("autumn between spring and winter", lambda: 6 < run("A,pothos,15,plastic,medium,yes,\n", start=dt.date(2026, 10, 5))[0]["plants"][0]["interval_now"] < run("A,pothos,15,plastic,medium,yes,\n", start=dt.date(2026, 12, 7))[0]["plants"][0]["interval_now"]) case("late snap noted for fast plant", lambda: len(run("A,basil,9,terracotta,direct,yes,\n", check_days=["Mon"])[0]["late_snaps"]) > 0) case("no drainage -> HIGH warning and half amount", lambda: (lambda r: any(w[0] == "HIGH" for w in r[1]) and "no more" in r[0]["plants"][0]["amount"])(run("A,pothos,15,glazed,medium,no,\n"))) case("unknown plant -> top_dry with warning", lambda: (lambda r: r[0]["plants"][0]["type"] == "top_dry" and any("unknown plant" in w[2] for w in r[1]))(run("A,triffid,15,plastic,medium,yes,\n"))) case("species substring match", lambda: run("A,variegated monstera,15,plastic,medium,yes,\n")[0]["plants"][0]["type"] == "top_dry") case("succulent low light warning", lambda: any("stretch" in w[2] for w in run("A,echeveria,10,terracotta,low,yes,\n")[1])) case("fern in direct sun warning", lambda: any("scorch" in w[2] for w in run("A,boston fern,20,plastic,direct,yes,\n")[1])) case("self-watering succulent warning", lambda: any("self-watering" in w[2] for w in run("A,cactus,15,self-watering,bright,yes,\n")[1])) case("orchid amount is soak", lambda: run("A,orchid,12,plastic,bright,yes,\n")[0]["plants"][0]["amount"] == "soak 10 min") case("amount scales with pot", lambda: int(run("A,pothos,25,plastic,medium,yes,\n")[0]["plants"][0]["amount"][1:].split()[0]) > int(run("A,pothos,12,plastic,medium,yes,\n")[0]["plants"][0]["amount"][1:].split()[0])) case("low humidity shortens", lambda: run("A,fern,20,plastic,medium,yes,\n", humidity="low")[0]["plants"][0]["interval_now"] <= run("A,fern,20,plastic,medium,yes,\n")[0]["plants"][0]["interval_now"]) case("interval never below 1 day", lambda: run("A,basil,6,fabric,direct,yes,\n", start=dt.date(2026, 7, 6), humidity="low")[0]["plants"][0]["interval_now"] >= 1) case("missing pot size assumed 15", lambda: (lambda r: r[0]["plants"][0]["pot_cm"] == 15 and any("assumed 15" in w[2] for w in r[1]))(run("A,pothos,,plastic,medium,yes,\n"))) def bad(rows): try: load_plants(H + rows); return False except InputError: return True case("bad material rejected", lambda: bad("A,pothos,15,wood,medium,yes,\n")) case("bad light rejected", lambda: bad("A,pothos,15,plastic,dim,yes,\n")) case("pot in mm rejected", lambda: bad("A,pothos,150,plastic,medium,yes,\n")) case("bad date rejected", lambda: bad("A,pothos,15,plastic,medium,yes,30/10/2026\n")) case("ics has one event per date, CRLF, escaped commas", lambda: (lambda r, t: t.count("BEGIN:VEVENT") == len(r["calendar"]) and "\r\n" in t and "\\," in t)(*(lambda r: (r, to_ics(r, "20261030T000000Z")))(run("A,pothos,15,plastic,medium,yes,\nB,fern,15,plastic,medium,yes,\n")[0]))) case("ics lines folded to 75 octets", lambda: all(len(l.encode()) <= 75 for l in to_ics(run("".join(f"Plant number {i},pothos,15,plastic,medium,yes,\n" for i in range(8)))[0], "20261030T000000Z").split("\r\n"))) passed = 0 for name, ok, err in cases: passed += ok print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" {err}")) print(f"{passed}/{len(cases)} passed") return 0 if passed == len(cases) else 1 def main(argv=None): ap = argparse.ArgumentParser(description="Build a houseplant watering check calendar") ap.add_argument("plants", nargs="?") ap.add_argument("--start", help="first day of the plan, YYYY-MM-DD (default today)") ap.add_argument("--weeks", type=int, default=4) ap.add_argument("--hemisphere", choices=["north", "south"], default="north") ap.add_argument("--humidity", choices=list(HUMIDITY), default="normal", help="low = heating on / below ~35 %%") ap.add_argument("--check-days", help="snap checks to these weekdays, e.g. Mon,Thu") ap.add_argument("--ics", help="also write an .ics calendar file") ap.add_argument("--json", action="store_true") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.plants: ap.error("give a plants CSV, or --self-test") try: start = parse_date(a.start, "--start") if a.start else dt.date.today() if not 1 <= a.weeks <= 26: raise InputError("--weeks must be 1..26") days = None if a.check_days: days = [x.strip()[:3].title() for x in a.check_days.split(",") if x.strip()] for x in days: if x not in DAY_NAMES: raise InputError(f"unknown weekday '{x}' in --check-days") with open(a.plants, encoding="utf-8") as fh: plants, warnings = load_plants(fh.read()) except (OSError, InputError, UnicodeDecodeError) as e: print(f"error: {e}", file=sys.stderr) return 2 res = plan(plants, start, a.weeks, a.hemisphere, a.humidity, days) if a.ics: stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") with open(a.ics, "w", encoding="utf-8", newline="") as fh: fh.write(to_ics(res, stamp)) if a.json: out = {**res, "start": res["start"].isoformat(), "end": res["end"].isoformat(), "calendar": [{"date": d.isoformat(), "plants": n} for d, n in res["calendar"]], "late_snaps": [{"plant": n, "due": d.isoformat(), "planned": p.isoformat()} for n, d, p in res["late_snaps"]], "plants": [{**p, "last_watered": p["last_watered"].isoformat() if p["last_watered"] else None} for p in res["plants"]], "warnings": [{"severity": s, "plant": n, "note": m} for s, n, m in warnings]} print(json.dumps(out, indent=2)) else: sys.stdout.write(render(res, warnings)) return 1 if any(w[0] == "HIGH" for w in warnings) else 0 if __name__ == "__main__": sys.exit(main())

Commute Cost Comparison Calculator

--- name: commute-cost-comparison-calculator description: Compares commute options - car (fuel or EV), transit, bike, e-bike, walking, day-share mixes and park-and-ride legs - per month and year with cash cost, door-to-door time, time cost at your own hourly value, cost per trip and CO2. Picks pass vs pay-per-ride for the days you ride, separates car running costs from fixed costs, and shows the break-even value of an hour. Includes a stdlib Python calculator with --self-test. --- # Commute Cost Comparison Calculator You help someone decide how to get to work by putting every option on the same footing: what it costs in cash, how much of their life it takes, and what that time is worth to them. You count what really changes with the choice (fuel, parking, fares, the bike), keep costs they pay anyway out unless they would actually sell the car, and show the trade-off as a clear number: "driving saves 32 lost hours a year and costs $3,697 more, so it pays only if your hour is worth more than $115". ## Files in this skill - `scripts/commute_cost.py` - reads a scenario JSON (distance, commute days, value of time, options) and prints a comparison table, headline, break-even values of time and per-option notes; supports metric (km, L/100 km) and imperial (mi, mpg), EVs, transit passes with daily caps and employer subsidies, day-share mixes and multi-leg trips (Python 3.8+ standard library only) - `references/cost-components.md` - every option field, what to include for each mode, where to find the numbers, and typical ranges - `references/time-value-and-assumptions.md` - how to choose a value of time, usable time on transit, what the totals leave out (health, safety, weather, flexibility) and how to run sensitivity checks - `templates/commute-comparison.md` - the decision summary to hand back - `examples/commute.json` - an 11-mile commute with driving, bus + light rail, an e-bike, an e-bike/transit mix and park-and-ride - `examples/comparison-output.md` - the real output of the calculator for that scenario ## Workflow ### 1. Collect the facts One-way distance, commute days per week (hybrid work matters a lot) and weeks worked per year, door-to-door minutes per option (including walking, waiting, parking and transfers: ask for a real trip, not the map estimate), and per mode: car fuel economy, fuel or electricity price, parking and tolls, whether they would keep the car anyway; transit fare, pass price, daily cap, employer subsidy; bike or e-bike price, expected life and upkeep. Ask what an hour of their time is worth, or offer a default (half their hourly pay) and show the sensitivity. ### 2. Run the calculator ``` python3 scripts/commute_cost.py examples/commute.json python3 scripts/commute_cost.py scenario.json --days-per-week 3 python3 scripts/commute_cost.py scenario.json --value-of-time 0 --json python3 scripts/commute_cost.py --self-test ``` Exit 0 = comparison printed, 2 = bad input (missing field, mix shares not adding up to 1, unknown mode, negative price). Without code, follow the formulas in `references/cost-components.md`. ### 3. Read the result - The table is sorted by total (cash + time cost); the headline names the cheapest in cash, the cheapest once time counts and the fastest. - **Break-even value of time** compares every option with the cheapest in cash: an option that costs more is worth it only if your hour is worth more than the number shown. "Never" means it costs more and does not save usable time. - Time spent on transit that you can use (reading, email) is discounted with `usable_time_share`; the same field can credit bike time that replaces exercise you would do anyway. Say which you used. - Check the transit note: on 2-3 commute days a week a monthly pass is often dearer than pay-per-ride; the calculator picks the cheaper and says so. ### 4. Deliver Fill `templates/commute-comparison.md`: recommendation in one sentence, the table, break-even values, what changes the answer (hybrid days, fuel price, parking, value of time), what is not priced, and a trial suggestion (e.g. two weeks of the mix before buying anything). ## Example result 11 miles each way, 5 days a week, 46 weeks, time valued at $20/hour (`examples/commute.json`). Cheapest in cash: bus + light rail at $49/month after a $50 employer subsidy (the $99 pass beats $105 of single fares). Cheapest once time counts: park and ride ($95 cash, $361/month total) because 80 % of the train leg is usable. Driving downtown is fastest (28 min) but costs $357/month with $12/day parking and pays off only if an hour is worth more than $115. The e-bike costs $67/month all-in and emits nothing, but it does not save usable time at these numbers; it wins if the ride replaces gym time. See `examples/comparison-output.md`. ## Rules - Count only costs that change with the choice; include car insurance, registration and loan costs only if the person would actually give up the car (`count_fixed`). - Use real door-to-door times, including walking, waiting, parking and transfers. - Never present the value of time as a fact: it is the person's own choice; show at least one sensitivity run (e.g. `--value-of-time 0` and their wage). - Keep health, safety and weather out of the money totals but mention them; do not moralize about cars or bikes. - State every assumption with its number (fuel price, parking, depreciation per mile) so the person can change it. - Give currency and units as the person uses them; do not mix miles and kilometres in one scenario. FILE:references/cost-components.md # Cost components and option fields Scenario fields: `currency` (USD, EUR, GBP, TRY, ...), `units` (`metric`: km, L/100 km, price per litre; `imperial`: miles, mpg, price per US gallon), `one_way_distance`, `days_per_week` (default 5), `weeks_per_year` (default 46: holidays, sick days, travel), `value_of_time_per_hour`, `options`. Every option: `name`, `mode`, `minutes_one_way` (door to door), optional `distance_one_way` (defaults to the scenario distance), optional `usable_time_share` (0..1). ## Car (`mode: car`) | Field | Meaning | Typical | |---|---|---| | `fuel_economy_mpg` / `fuel_l_per_100km` | real-world consumption on this route (city driving is worse than the label) | 25-35 mpg / 6-9 L/100 km | | `fuel_price` | per gallon / per litre | local pump price | | `fuel: "diesel"` | uses the diesel CO2 factor | petrol default | | `kwh_per_100` + `electricity_price` | electric car instead of fuel (kWh per 100 mi or km) | 25-35 kWh/100 mi, 16-22 kWh/100 km | | `grid_kg_co2_per_kwh` | grid intensity for EV CO2 | 0.4 default; 0.05 hydro/nuclear, 0.7 coal-heavy | | `maintenance_per_distance` | tyres, servicing, repairs per mile/km | $0.08-0.12/mi, 0.05-0.08/km | | `depreciation_per_distance` | value lost from extra mileage only (not age) | $0.05-0.15/mi | | `parking_per_day`, `tolls_per_day` | per commute day | workplace parking can dominate | | `fixed_per_year` + `count_fixed` | insurance, registration, loan interest, age depreciation; counted only when `count_fixed` is true | true only if commuting is the reason to own the car | Fuel cost = 2 x distance x days / mpg x price (or x L/100 km / 100 x price). CO2: petrol 2.35 kg/L (8.89 kg per US gallon), diesel 2.68 kg/L (10.18 kg/gal), EV kWh x grid factor. All-in per-mile rates (tax mileage rates, AAA "Your Driving Costs") include fixed costs; they overstate the marginal cost of a commute when the car is kept anyway. ## Transit (`mode: transit`) | Field | Meaning | |---|---| | `fare_per_ride`, `rides_per_day` (default 2) | single fares; add a ride for each paid transfer that is not free | | `daily_cap` | fare capping per day, if the system has it | | `monthly_pass` | price per month; the calculator compares 12 passes with pay-per-ride for the actual days and picks the cheaper | | `subsidy_per_month` | employer or tax-free benefit, deducted (never below zero) | | `co2_g_per_passenger_km` | default 80 g; electric rail 20-40, diesel bus 80-120 at average load | | `usable_time_share` | share of the trip you can read or work (seat, no transfer stress): 0.2-0.8 | ## Bike, e-bike, walk (`mode: bike | ebike | walk`) | Field | Meaning | Typical | |---|---|---| | `purchase_price`, `life_years` | spread over the life (default 5 years); not used for walk | e-bike $1,500-3,500 | | `maintenance_per_year` | tyres, chain, brake pads, battery fund for e-bikes | $100-300 | | `gear_per_year` | lights, lock, rain gear, helmet replacement | $50-150 | | `kwh_per_100`, `electricity_price` | e-bike charging | 1-2 kWh per 100 mi | | `other_per_month` | bike parking, locker, shower membership | 0-30 | Ownership costs are counted in full even in a mix: you pay for the bike whether you ride 3 or 5 days. ## Mix (`mode: mix`) `"shares": {"E-bike": 0.6, "Bus + light rail": 0.4}` splits commute days between other options (shares add up to 1). Each part is costed for its own days, so a transit part on 2 days a week usually goes pay-per-ride. Use it for weather-dependent cycling, hybrid driving, or carpool days. ## Multi-leg (`mode: multi`) `"legs": [ {car leg}, {transit leg} ]` with `transfer_minutes`. Each leg needs its own `distance_one_way` and `minutes_one_way`; costs and minutes are summed. Use it for park and ride, bike + train, or walk + bus. ## Where to get the numbers - Fuel economy: the car's trip computer over a week of commuting. - Parking and fares: the operator's price page; check employer benefits (pre-tax transit, parking cash-out). - Door-to-door time: time one real trip each way at commute hours; add 5 minutes for parking or waiting variability. FILE:references/time-value-and-assumptions.md # Value of time and what the totals leave out ## Choosing a value of time - There is no correct number: it is what an hour of this person's commute is worth to them. - Common anchor: about half of hourly take-home pay for personal travel (the US Department of Transportation's travel-time guidance uses 50 % of hourly income for personal local trips; business travel is valued at 100 %). - Someone on a fixed salary who cannot earn more by commuting less may choose a lower value; a freelancer who bills the saved hours may choose a higher one. - Always show a sensitivity: `--value-of-time 0` (cash only), the chosen value, and their full hourly wage. If the ranking does not change, the decision is robust. ## Usable time `usable_time_share` discounts time you can use. Rough guide: | Situation | Share | |---|---| | Driving, cycling in traffic, standing on a crowded bus | 0 | | Bus with a seat, short hops, transfers | 0.2-0.4 | | Train with a seat and table, 20+ minutes without changes | 0.6-0.8 | | Bike or walk that replaces exercise you would otherwise do | 0.3-0.7 (say so explicitly) | ## Not in the money totals (mention them) - **Health:** regular cycling or walking is associated with better cardiovascular health; some people value it highly, others not at all. Use `usable_time_share` if they want it priced. - **Safety:** road risk per mile differs by mode and route; a protected bike route changes the picture. - **Weather and season:** use a mix (e.g. 60 % bike days) rather than assuming every day is a bike day. - **Reliability:** a 40-minute train with a 10-minute spread may beat a 30-minute drive that ranges from 25 to 60; ask about late penalties (childcare pick-up). - **Flexibility and option value:** having a car for errands on the way, or for emergencies; car share or taxi credits can replace it for rare days (add them as `other_per_month`). - **Stress and comfort:** do not price it, but ask. ## Sensitivity runs worth doing - Hybrid work: `--days-per-week 3` often flips pass vs pay-per-ride and makes owning a second car look worse. - Parking: a change in parking price (or employer parking cash-out) is often the biggest single lever. - Fuel or electricity price +-25 %. - Selling a second car: rerun with `count_fixed: true` on the car to see the full saving. ## Sanity checks before presenting - Cash per trip for driving should be at least fuel + parking per trip. - Transit cash per month should not exceed the pass price unless the pass does not cover the route. - Hours per month = minutes one way x 2 x days per month / 60. - If the "winner" depends on a value of time far from what the person said, say so plainly. FILE:templates/commute-comparison.md # Commute options: <home> to <work> **Trip:** <11 mi each way, 5 days/week, 46 weeks/year> **Value of time used:** <$20/hour (about half of hourly pay)> **Recommendation:** <one sentence, e.g. "Park and ride: $95/month cash, 40 min door to door, most of the train ride usable for email"> ## Comparison (per month) | Option | Cash | Door to door | Hours | Time cost | Total | CO2 kg/year | |---|---|---|---|---|---|---| | <Park and ride> | <$95> | <40 min> | <25.6> | <$266> | <$361> | <999> | | <Bus + light rail> | <$49> | <46 min> | <29.4> | <$411> | <$460> | <651> | ## When a dearer option pays off | Option | Extra per year | Lost hours saved | Worth it above | |---|---|---|---| | <Drive downtown> | <$3,697> | <32> | <$115/hour> | ## What would change the answer - <Hybrid work (3 days): transit pass no longer pays; pay per ride ...> - <Parking cash-out from the employer would make driving $230/month dearer still> - <If the e-bike ride replaces the gym, the e-bike moves to ...> ## Not priced - <health, safety on the route, weather days, reliability, needing the car for school pick-up> ## Assumptions - <fuel $3.40/gal at 28 mpg; maintenance $0.10/mi; mileage depreciation $0.08/mi; parking $12/day> - <transit pass $99, employer subsidy $50/month, 30 % of the bus/rail time usable> - <car kept for weekends, so insurance and registration are not counted> ## Next step <Try the mix for two weeks before buying the e-bike; time each trip door to door.> FILE:examples/commute.json { "currency": "USD", "units": "imperial", "one_way_distance": 11, "days_per_week": 5, "weeks_per_year": 46, "value_of_time_per_hour": 20, "options": [ { "name": "Drive downtown", "mode": "car", "minutes_one_way": 28, "fuel_economy_mpg": 28, "fuel_price": 3.4, "maintenance_per_distance": 0.1, "depreciation_per_distance": 0.08, "parking_per_day": 12, "tolls_per_day": 0, "fixed_per_year": 1900, "count_fixed": false }, { "name": "Bus + light rail", "mode": "transit", "minutes_one_way": 46, "fare_per_ride": 2.75, "monthly_pass": 99, "subsidy_per_month": 50, "usable_time_share": 0.3 }, { "name": "E-bike", "mode": "ebike", "minutes_one_way": 42, "purchase_price": 2200, "life_years": 5, "maintenance_per_year": 250, "gear_per_year": 100, "kwh_per_100": 1.5, "electricity_price": 0.17 }, { "name": "E-bike 3 days, transit 2 days", "mode": "mix", "shares": {"E-bike": 0.6, "Bus + light rail": 0.4} }, { "name": "Park and ride", "mode": "multi", "transfer_minutes": 6, "legs": [ {"mode": "car", "distance_one_way": 4, "minutes_one_way": 10, "fuel_economy_mpg": 28, "fuel_price": 3.4, "maintenance_per_distance": 0.1, "depreciation_per_distance": 0.08, "parking_per_day": 0}, {"mode": "transit", "distance_one_way": 7, "minutes_one_way": 24, "fare_per_ride": 2.75, "monthly_pass": 99, "subsidy_per_month": 50, "usable_time_share": 0.8} ] } ] } FILE:examples/comparison-output.md # Commute cost comparison One way: 11 mi Commute days: 19.2/month (230/year) Value of time: $20.00/hour Currency: USD | Option | Cash / month | Cash / year | Per trip | Door to door (one way) | Hours / month | Time cost / month | Total / month | CO2 kg / year | |---|---|---|---|---|---|---|---|---| | Park and ride | $95.22 | $1,143 | $2.48 | 40 min | 25.6 | $266 | **$361** | 999 | | Bus + light rail | $49.00 | $588 | $1.28 | 46 min | 29.4 | $411 | **$460** | 651 | | E-bike 3 days, transit 2 days | $66.48 | $798 | $1.73 | 44 min | 27.9 | $487 | **$553** | 261 | | E-bike | $66.91 | $803 | $1.75 | 42 min | 26.8 | $537 | **$604** | 0 | | Drive downtown | $357 | $4,285 | $9.32 | 28 min | 17.9 | $358 | **$715** | 1,607 | Sorted by total (cash + time cost). ## Headline - Cheapest in cash: **Bus + light rail** ($49.00/month). - Cheapest once time counts: **Park and ride** ($361/month at $20.00/hour). - Fastest: **Drive downtown** (28 min one way, 17.9 h/month). ## Break-even value of time (vs Bus + light rail, the cheapest in cash) | Option | Extra cash / year | Lost hours saved / year | Worth it if your hour is worth more than | |---|---|---|---| | Drive downtown | $3,697 | 32 | $115/hour | | E-bike | $215 | none (75 more lost) | never on cost: it does not save usable time | | E-bike 3 days, transit 2 days | $210 | none (45 more lost) | never on cost: it does not save usable time | | Park and ride | $555 | 87 | $6.35/hour | ## Notes per option - **Drive downtown** (car): per month: fuel/energy $51.20, maintenance + depreciation $75.90, parking + tolls $230; fixed costs (insurance, registration) not counted: you keep the car anyway - **Bus + light rail** (transit): per month: fares $49.00; monthly pass (cheaper than $105/month pay per ride at 19.2 days/month); employer subsidy $50.00/month deducted - **E-bike** (ebike): per month: bike + upkeep $65.83, fuel/energy $1.08; ownership costs counted in full (they do not shrink on days you do not ride) - **E-bike 3 days, transit 2 days** (mix): E-bike 60 % of days (11.5/month): ownership costs counted in full (they do not shrink on days you do not ride); Bus + light rail 40 % of days (7.7/month): pay per ride (pass would cost $99.00/month at 7.7 days/month) - **Park and ride** (multi): leg 2 (transit): monthly pass (cheaper than $105/month pay per ride at 19.2 days/month); leg 2 (transit): employer subsidy $50.00/month deducted Time cost = hours x value of time x (1 - share of the trip you can use for reading or work). Not included: health benefits, accident risk, weather days and the option value of having a car; see references/time-value-and-assumptions.md. FILE:scripts/commute_cost.py #!/usr/bin/env python3 """Commute cost comparison calculator (Python 3.8+ standard library only). Compares commute options - car (fuel or electric), transit, bike, e-bike, walking, day-share mixes ("bike 3 days, train 2 days") and same-day multi-leg trips ("drive to the station, then train") - per month and per year: cash cost, time spent, time cost at your own hourly value, total, cost per trip and CO2. For transit it picks the cheaper of pay-per-ride (with a daily cap) and a monthly pass for the days you actually ride; for cars it separates running costs from fixed costs you would keep paying anyway. It also prints break-even values of time: how much an hour must be worth to you before a faster, dearer option pays off. Usage: python3 commute_cost.py scenario.json [--value-of-time 25] [--days-per-week 3] [--json] python3 commute_cost.py --self-test scenario.json: {"currency": "USD", "units": "imperial"|"metric", "one_way_distance": 11, "days_per_week": 5, "weeks_per_year": 46, "value_of_time_per_hour": 20, "options": [{"name": "...", "mode": "car|transit|bike|ebike|walk|mix|multi", ...}]} See references/cost-components.md for every option field. Exit codes: 0 = comparison printed, 2 = bad input. """ import argparse, json, sys PETROL_CO2 = {"metric": 2.35, "imperial": 8.89} # kg CO2 per litre / per US gallon burned (diesel: 2.68 / 10.18) DIESEL_CO2 = {"metric": 2.68, "imperial": 10.18} KM_PER_UNIT = {"metric": 1.0, "imperial": 1.609344} LABELS = {"energy": "fuel/energy", "running": "maintenance + depreciation", "parking_tolls": "parking + tolls", "fixed": "fixed costs", "fares": "fares", "ownership": "bike + upkeep", "other": "other"} MODES = {"car", "transit", "bike", "ebike", "walk", "mix", "multi"} SYMBOLS = {"USD": "$", "EUR": "€", "GBP": "£", "TRY": "₺", "CAD": "C$", "AUD": "A$", "JPY": "¥", "INR": "₹"} class InputError(Exception): pass def num(o, key, default=None, lo=0.0, hi=None, who=""): v = o.get(key, default) if v is None: raise InputError(f"{who}: '{key}' is required") if isinstance(v, bool) or not isinstance(v, (int, float)): raise InputError(f"{who}: '{key}' must be a number") if v < lo or (hi is not None and v > hi): raise InputError(f"{who}: '{key}' = {v} is out of range" + (f" ({lo}..{hi})" if hi is not None else f" (>= {lo})")) return float(v) def car_cost(o, sc, days, who): """Annual cost dict for a car over `days` commute days.""" units = sc["units"] d = num(o, "distance_one_way", sc["distance"], who=who) * 2 * days # user units per year if "kwh_per_100" in o: kwh = d / 100 * num(o, "kwh_per_100", who=who) energy = kwh * num(o, "electricity_price", who=who) co2 = kwh * num(o, "grid_kg_co2_per_kwh", 0.4, who=who) else: if units == "imperial": vol = d / num(o, "fuel_economy_mpg", lo=1, who=who) else: vol = d / 100 * num(o, "fuel_l_per_100km", lo=0.5, who=who) energy = vol * num(o, "fuel_price", who=who) co2 = vol * (DIESEL_CO2 if o.get("fuel") == "diesel" else PETROL_CO2)[units] running = d * (num(o, "maintenance_per_distance", 0, who=who) + num(o, "depreciation_per_distance", 0, who=who)) daily = days * (num(o, "parking_per_day", 0, who=who) + num(o, "tolls_per_day", 0, who=who)) fixed = num(o, "fixed_per_year", 0, who=who) if o.get("count_fixed", False) else 0.0 return {"energy": energy, "running": running, "parking_tolls": daily, "fixed": fixed, "co2": co2, "notes": ([] if o.get("count_fixed", False) or not o.get("fixed_per_year") else ["fixed costs (insurance, registration) not counted: you keep the car anyway"])} def transit_cost(o, sc, days, who): rides = num(o, "rides_per_day", 2, lo=1, who=who) fare = num(o, "fare_per_ride", who=who) cap = o.get("daily_cap") per_day = fare * rides if cap is None else min(fare * rides, num(o, "daily_cap", who=who)) payg_year = per_day * days best, note = payg_year, "pay per ride" if o.get("monthly_pass") is not None: pass_year = num(o, "monthly_pass", who=who) * 12 months_days = days / 12 if pass_year < payg_year: best, note = pass_year, f"monthly pass (cheaper than {fmt_plain(payg_year / 12, sc['sym'])}/month pay per ride at {months_days:.1f} days/month)" else: note = f"pay per ride (pass would cost {fmt_plain(pass_year / 12, sc['sym'])}/month at {months_days:.1f} days/month)" subsidy = num(o, "subsidy_per_month", 0, who=who) * 12 best = max(0.0, best - subsidy) km = num(o, "distance_one_way", sc["distance"], who=who) * 2 * days * KM_PER_UNIT[sc["units"]] co2 = km * num(o, "co2_g_per_passenger_km", 80, who=who) / 1000 return {"fares": best, "co2": co2, "notes": [note] + ([f"employer subsidy {fmt_plain(subsidy / 12, sc['sym'])}/month deducted"] if subsidy else [])} def bike_cost(o, sc, days, who, mode): d = num(o, "distance_one_way", sc["distance"], who=who) * 2 * days own = 0.0 if mode != "walk": life = num(o, "life_years", 5, lo=0.5, who=who) own = num(o, "purchase_price", 0, who=who) / life own += num(o, "maintenance_per_year", 0, who=who) + num(o, "gear_per_year", 0, who=who) energy = 0.0 if mode == "ebike": kwh = d / 100 * num(o, "kwh_per_100", 1.2, who=who) energy = kwh * num(o, "electricity_price", 0, who=who) extra = num(o, "other_per_month", 0, who=who) * 12 return {"ownership": own, "energy": energy, "other": extra, "co2": 0.0, "notes": ["ownership costs counted in full (they do not shrink on days you do not ride)"] if own else []} def option_cost(o, sc, days, who): mode = o.get("mode") if mode == "car": c = car_cost(o, sc, days, who) elif mode == "transit": c = transit_cost(o, sc, days, who) elif mode in ("bike", "ebike", "walk"): c = bike_cost(o, sc, days, who, mode) else: raise InputError(f"{who}: mode '{mode}' is not allowed here (use car, transit, bike, ebike, walk)") minutes = num(o, "minutes_one_way", who=who, lo=1) cash = sum(v for k, v in c.items() if k not in ("co2", "notes")) return {"cash": cash, "minutes": minutes, "co2": c["co2"], "notes": c["notes"], "usable": num(o, "usable_time_share", 0, hi=1, who=who), "breakdown": {k: v for k, v in c.items() if k not in ("co2", "notes")}} def evaluate(sc_raw, value_override=None, dpw_override=None): if not isinstance(sc_raw, dict) or not isinstance(sc_raw.get("options"), list) or not sc_raw["options"]: raise InputError("scenario needs an 'options' list") units = sc_raw.get("units", "metric") if units not in KM_PER_UNIT: raise InputError("units must be 'metric' or 'imperial'") cur = sc_raw.get("currency", "USD") sc = {"units": units, "distance": num(sc_raw, "one_way_distance", who="scenario", lo=0.1), "sym": SYMBOLS.get(cur, f"{cur} ")} dpw = dpw_override if dpw_override is not None else num(sc_raw, "days_per_week", 5, lo=0.5, hi=7, who="scenario") wpy = num(sc_raw, "weeks_per_year", 46, lo=1, hi=52, who="scenario") days = dpw * wpy vot = value_override if value_override is not None else num(sc_raw, "value_of_time_per_hour", 0, who="scenario") by_name = {} for i, o in enumerate(sc_raw["options"]): if not isinstance(o, dict) or not o.get("name") or o.get("mode") not in MODES: raise InputError(f"option {i + 1}: needs a 'name' and a 'mode' ({', '.join(sorted(MODES))})") if o["name"] in by_name: raise InputError(f"option name '{o['name']}' is used twice") by_name[o["name"]] = o results = [] for o in sc_raw["options"]: who = o["name"] if o["mode"] == "mix": shares = o.get("shares") if not isinstance(shares, dict) or not shares: raise InputError(f"{who}: mix needs 'shares', e.g. {{\"Bike\": 0.6, \"Transit\": 0.4}}") tot = sum(shares.values()) if abs(tot - 1) > 0.001: raise InputError(f"{who}: shares add up to {tot:g}, not 1") cash = co2 = hours = eff = 0.0 notes, parts = [], [] for nm, sh in shares.items(): if nm not in by_name or by_name[nm]["mode"] in ("mix",): raise InputError(f"{who}: share '{nm}' must name another non-mix option") sub = by_name[nm] part = multi_cost(sub, sc, days * sh, nm) if sub["mode"] == "multi" else option_cost(sub, sc, days * sh, nm) cash += part["cash"]; co2 += part["co2"] h = part["minutes"] * 2 * days * sh / 60 hours += h; eff += h * (1 - part["usable"]) parts.append(f"{nm} {sh * 100:.0f} % of days ({days * sh / 12:.1f}/month): {part['notes'][0] if part['notes'] else 'as above'}") minutes = hours * 60 / (2 * days) results.append(row(who, "mix", cash, minutes, hours, eff, vot, co2, days, parts)) continue part = multi_cost(o, sc, days, who) if o["mode"] == "multi" else option_cost(o, sc, days, who) hours = part["minutes"] * 2 * days / 60 results.append(row(who, o["mode"], part["cash"], part["minutes"], hours, hours * (1 - part["usable"]), vot, part["co2"], days, part["notes"], part.get("breakdown"))) return {"currency": sc_raw.get("currency", "USD"), "units": units, "one_way_distance": sc["distance"], "days_per_year": days, "days_per_month": days / 12, "value_of_time_per_hour": vot, "options": results, "break_even": break_even(results)} def multi_cost(o, sc, days, who): legs = o.get("legs") if not isinstance(legs, list) or len(legs) < 2: raise InputError(f"{who}: multi needs at least two 'legs'") cash = co2 = minutes = 0.0 notes, usable_min = [], 0.0 for j, leg in enumerate(legs, 1): if leg.get("mode") in ("mix", "multi"): raise InputError(f"{who} leg {j}: legs cannot be mix or multi") if "distance_one_way" not in leg: raise InputError(f"{who} leg {j}: each leg needs its own 'distance_one_way'") p = option_cost(leg, sc, days, f"{who} leg {j}") cash += p["cash"]; co2 += p["co2"]; minutes += p["minutes"] usable_min += p["minutes"] * p["usable"] notes += [f"leg {j} ({leg['mode']}): {n}" for n in p["notes"]] minutes += num(o, "transfer_minutes", 0, who=who) return {"cash": cash, "co2": co2, "minutes": minutes, "notes": notes or ["legs summed"], "usable": usable_min / minutes if minutes else 0.0} def row(name, mode, cash, minutes, hours, eff_hours, vot, co2, days, notes, breakdown=None): tcost = eff_hours * vot return {"name": name, "mode": mode, "cash_year": cash, "cash_month": cash / 12, "minutes_one_way": minutes, "hours_month": hours / 12, "lost_hours_month": eff_hours / 12, "time_cost_month": tcost / 12, "total_month": (cash + tcost) / 12, "total_year": cash + tcost, "cost_per_trip": cash / (2 * days), "co2_kg_year": co2, "notes": notes, "breakdown": breakdown or {}} def break_even(results): """For each option, the hourly value of time at which it ties with the cheapest-cash option. Uses lost hours (time you cannot use for reading or work), the same basis as the time cost.""" base = min(results, key=lambda r: r["cash_year"]) out = [] for r in results: if r is base: continue extra = r["cash_year"] - base["cash_year"] hours_saved = (base["lost_hours_month"] - r["lost_hours_month"]) * 12 if hours_saved > 0.01: out.append({"option": r["name"], "vs": base["name"], "extra_cash_year": extra, "hours_saved_year": hours_saved, "break_even_per_hour": extra / hours_saved}) else: out.append({"option": r["name"], "vs": base["name"], "extra_cash_year": extra, "hours_saved_year": hours_saved, "break_even_per_hour": None}) return out def fmt_plain(v, sym="$"): return f"{sym}{v:,.0f}" if abs(v) >= 100 else f"{sym}{v:,.2f}" def render(res): sym = SYMBOLS.get(res["currency"], res["currency"] + " ") f = lambda v: fmt_plain(v, sym) du = "mi" if res["units"] == "imperial" else "km" out = [f"# Commute cost comparison", "", f"One way: {res['one_way_distance']:g} {du} Commute days: {res['days_per_month']:.1f}/month ({res['days_per_year']:.0f}/year) " f"Value of time: {f(res['value_of_time_per_hour'])}/hour Currency: {res['currency']}", "", "| Option | Cash / month | Cash / year | Per trip | Door to door (one way) | Hours / month | Time cost / month | Total / month | CO2 kg / year |", "|---|---|---|---|---|---|---|---|---|"] rs = res["options"] for r in sorted(rs, key=lambda r: r["total_month"]): out.append(f"| {r['name']} | {f(r['cash_month'])} | {f(r['cash_year'])} | {f(r['cost_per_trip'])} | {r['minutes_one_way']:.0f} min | " f"{r['hours_month']:.1f} | {f(r['time_cost_month'])} | **{f(r['total_month'])}** | {r['co2_kg_year']:,.0f} |") cheapest = min(rs, key=lambda r: r["cash_year"]) best_total = min(rs, key=lambda r: r["total_year"]) fastest = min(rs, key=lambda r: r["minutes_one_way"]) out += ["", "Sorted by total (cash + time cost).", "", "## Headline", "", f"- Cheapest in cash: **{cheapest['name']}** ({f(cheapest['cash_month'])}/month).", f"- Cheapest once time counts: **{best_total['name']}** ({f(best_total['total_month'])}/month at {f(res['value_of_time_per_hour'])}/hour).", f"- Fastest: **{fastest['name']}** ({fastest['minutes_one_way']:.0f} min one way, {fastest['hours_month']:.1f} h/month)."] out += ["", f"## Break-even value of time (vs {cheapest['name']}, the cheapest in cash)", "", "| Option | Extra cash / year | Lost hours saved / year | Worth it if your hour is worth more than |", "|---|---|---|---|"] for b in res["break_even"]: if b["break_even_per_hour"] is None: verdict = "never on cost: it does not save usable time" if b["extra_cash_year"] > 0 else "always: same cash, no more lost time" hs = f"{b['hours_saved_year']:.0f}" if b["hours_saved_year"] >= 0 else f"none ({-b['hours_saved_year']:.0f} more lost)" out.append(f"| {b['option']} | {f(b['extra_cash_year'])} | {hs} | {verdict} |") else: out.append(f"| {b['option']} | {f(b['extra_cash_year'])} | {b['hours_saved_year']:.0f} | {f(b['break_even_per_hour'])}/hour |") out += ["", "## Notes per option", ""] for r in rs: bd = ", ".join(f"{LABELS.get(k, k)} {f(v / 12)}" for k, v in r["breakdown"].items() if v) if r["breakdown"] else "" out.append(f"- **{r['name']}** ({r['mode']}): " + "; ".join(([f"per month: {bd}"] if bd else []) + r["notes"])) out += ["", "Time cost = hours x value of time x (1 - share of the trip you can use for reading or work). " "Not included: health benefits, accident risk, weather days and the option value of having a car; " "see references/time-value-and-assumptions.md."] return "\n".join(out) + "\n" def self_test(): base = {"currency": "USD", "units": "metric", "one_way_distance": 10, "days_per_week": 5, "weeks_per_year": 48, "value_of_time_per_hour": 20} car = {"name": "Car", "mode": "car", "minutes_one_way": 20, "fuel_l_per_100km": 8, "fuel_price": 1.5, "maintenance_per_distance": 0.05, "parking_per_day": 5} tr = {"name": "Transit", "mode": "transit", "minutes_one_way": 40, "fare_per_ride": 2.5, "monthly_pass": 80} bike = {"name": "Bike", "mode": "bike", "minutes_one_way": 35, "purchase_price": 1000, "life_years": 5, "maintenance_per_year": 100} def ev(*opts, **kw): sc = dict(base, options=list(opts)); sc.update(kw.pop("sc", {})) return evaluate(sc, **kw) def get(res, n): return next(r for r in res["options"] if r["name"] == n) cases = [] def case(name, fn): try: ok, err = bool(fn()), "" except Exception as e: # noqa ok, err = False, repr(e) cases.append((name, ok, err)) # car: 240 days * 20 km = 4800 km; fuel 384 L * 1.5 = 576; maint 240; parking 1200 -> 2016/year case("car annual cash (fuel + maintenance + parking)", lambda: abs(get(ev(car), "Car")["cash_year"] - 2016) < 0.01) case("car CO2 petrol 2.35 kg/L", lambda: abs(get(ev(car), "Car")["co2_kg_year"] - 384 * 2.35) < 0.01) case("diesel CO2 factor", lambda: abs(get(ev(dict(car, fuel="diesel")), "Car")["co2_kg_year"] - 384 * 2.68) < 0.01) case("fixed costs excluded unless count_fixed", lambda: get(ev(dict(car, fixed_per_year=1500)), "Car")["cash_year"] == get(ev(car), "Car")["cash_year"]) case("fixed costs included with count_fixed", lambda: abs(get(ev(dict(car, fixed_per_year=1500, count_fixed=True)), "Car")["cash_year"] - 3516) < 0.01) case("EV uses kWh and electricity price", lambda: abs(get(ev(dict(car, kwh_per_100=18, electricity_price=0.3, fuel_l_per_100km=None)), "Car")["breakdown"]["energy"] - 4800 / 100 * 18 * 0.3) < 0.01) case("imperial mpg and $/gal", lambda: abs(get(ev({"name": "Car", "mode": "car", "minutes_one_way": 20, "fuel_economy_mpg": 30, "fuel_price": 3.6}, sc={"units": "imperial"}), "Car")["cash_year"] - 4800 / 30 * 3.6) < 0.01) case("imperial CO2 8.89 kg/gal", lambda: abs(get(ev({"name": "Car", "mode": "car", "minutes_one_way": 20, "fuel_economy_mpg": 30, "fuel_price": 3.6}, sc={"units": "imperial"}), "Car")["co2_kg_year"] - 160 * 8.89) < 0.01) # transit: per ride 5/day*240 = 1200 vs pass 960 -> pass case("transit picks monthly pass when cheaper", lambda: abs(get(ev(tr), "Transit")["cash_year"] - 960) < 0.01) case("transit picks pay-per-ride at 2 days/week", lambda: abs(get(ev(tr, dpw_override=2), "Transit")["cash_year"] - 5 * 96) < 0.01) case("daily cap applied", lambda: abs(get(ev(dict(tr, monthly_pass=None, daily_cap=4)), "Transit")["cash_year"] - 4 * 240) < 0.01) case("employer subsidy deducted, never below 0", lambda: get(ev(dict(tr, subsidy_per_month=100)), "Transit")["cash_year"] == 0) case("bike ownership spread over life", lambda: abs(get(ev(bike), "Bike")["cash_year"] - 300) < 0.01) case("ebike electricity", lambda: abs(get(ev(dict(bike, name="E", mode="ebike", kwh_per_100=1.5, electricity_price=0.3)), "E")["breakdown"]["energy"] - 4800 / 100 * 1.5 * 0.3) < 0.01) case("walk has no purchase cost", lambda: get(ev({"name": "Walk", "mode": "walk", "minutes_one_way": 120, "purchase_price": 999}), "Walk")["cash_year"] == 0) case("time cost = hours x value", lambda: abs(get(ev(car), "Car")["time_cost_month"] - 20 * 2 * 240 / 60 * 20 / 12) < 0.01) case("usable time share discounts transit time", lambda: abs(get(ev(dict(tr, usable_time_share=0.5)), "Transit")["time_cost_month"] - 40 * 2 * 240 / 60 * 20 * 0.5 / 12) < 0.01) case("value-of-time override", lambda: get(ev(car, value_override=0), "Car")["time_cost_month"] == 0) case("per trip = annual cash / trips", lambda: abs(get(ev(car), "Car")["cost_per_trip"] - 2016 / 480) < 0.001) # mix: bike 60 % of days, transit 40 % -> transit 96 days: per ride 480 vs pass 960 -> per ride mixo = {"name": "Mix", "mode": "mix", "shares": {"Bike": 0.6, "Transit": 0.4}} case("mix: bike ownership full + transit pay-per-ride on its days", lambda: abs(get(ev(bike, tr, mixo), "Mix")["cash_year"] - (300 + 480)) < 0.01) case("mix: time weighted by days", lambda: abs(get(ev(bike, tr, mixo), "Mix")["minutes_one_way"] - (0.6 * 35 + 0.4 * 40)) < 0.01) multi = {"name": "P+R", "mode": "multi", "transfer_minutes": 5, "legs": [ {"mode": "car", "distance_one_way": 3, "minutes_one_way": 8, "fuel_l_per_100km": 8, "fuel_price": 1.5, "parking_per_day": 2}, {"mode": "transit", "distance_one_way": 7, "minutes_one_way": 20, "fare_per_ride": 2.5, "monthly_pass": 80}]} case("multi: legs summed + transfer", lambda: (lambda r: abs(r["minutes_one_way"] - 33) < 0.01 and abs(r["cash_year"] - (1440 * 0.08 * 1.5 + 480 + 960)) < 0.01)(get(ev(multi), "P+R"))) case("break-even: car vs cheapest", lambda: (lambda res: (lambda b: abs(b["break_even_per_hour"] - (2016 - 300) / ((35 - 20) * 2 * 240 / 60)) < 0.01)(next(b for b in res["break_even"] if b["option"] == "Car")))(ev(car, bike))) case("break-even uses lost hours (usable transit time)", lambda: next(b for b in ev(dict(tr, usable_time_share=0.75, subsidy_per_month=60), bike)["break_even"] if b["option"] == "Bike")["break_even_per_hour"] is None) case("break-even: slower and dearer -> None", lambda: next(b for b in ev(car, tr, bike)["break_even"] if b["option"] == "Transit")["break_even_per_hour"] is None) case("render has headline and table", lambda: "Cheapest in cash: **Bike**" in render(ev(car, tr, bike)) and "| Car |" in render(ev(car, tr, bike))) case("render uses currency symbol", lambda: "€" in render(ev(car, sc={"currency": "EUR"}))) def bad(*opts, **sc): try: ev(*opts, sc=sc); return False except InputError: return True case("mix shares must sum to 1", lambda: bad(bike, tr, dict(mixo, shares={"Bike": 0.6, "Transit": 0.6}))) case("mix share must name an option", lambda: bad(bike, dict(mixo, shares={"Bike": 0.5, "Train": 0.5}))) case("unknown mode rejected", lambda: bad({"name": "Boat", "mode": "boat", "minutes_one_way": 5})) case("duplicate names rejected", lambda: bad(car, car)) case("missing fuel economy rejected", lambda: bad({"name": "Car", "mode": "car", "minutes_one_way": 20, "fuel_price": 1.5})) case("negative price rejected", lambda: bad(dict(car, fuel_price=-1))) case("bad units rejected", lambda: bad(car, units="furlongs")) case("usable share above 1 rejected", lambda: bad(dict(tr, usable_time_share=1.5))) passed = 0 for name, ok, err in cases: passed += ok print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" {err}")) print(f"{passed}/{len(cases)} passed") return 0 if passed == len(cases) else 1 def main(argv=None): ap = argparse.ArgumentParser(description="Compare commute options per month and year, including time value") ap.add_argument("scenario", nargs="?") ap.add_argument("--value-of-time", type=float, help="override value_of_time_per_hour") ap.add_argument("--days-per-week", type=float, help="override days_per_week (e.g. 3 for hybrid work)") ap.add_argument("--json", action="store_true") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.scenario: ap.error("give a scenario JSON file, or --self-test") try: with open(a.scenario, encoding="utf-8") as fh: sc = json.load(fh) if a.days_per_week is not None and not 0.5 <= a.days_per_week <= 7: raise InputError("--days-per-week must be 0.5..7") res = evaluate(sc, a.value_of_time, a.days_per_week) except json.JSONDecodeError as e: print(f"error: scenario is not valid JSON: {e}", file=sys.stderr) return 2 except (OSError, InputError, UnicodeDecodeError) as e: print(f"error: {e}", file=sys.stderr) return 2 print(json.dumps(res, indent=2) if a.json else render(res), end="" if not a.json else "\n") return 0 if __name__ == "__main__": sys.exit(main())

Webhook Integration taste

# Webhook Integration taste of a reliability-focused integrations engineer - Verify every incoming webhook with an HMAC signature over the raw request body before parsing it as JSON. Confidence: 0.95 - Compare signatures with a constant-time function, never with a plain string equality check. Confidence: 0.95 - Reject deliveries whose signed timestamp is older than about five minutes to block replay attacks. Confidence: 0.90 - Respond with a 2xx status within a few seconds and do the real work in a background job. Confidence: 0.95 - Persist the raw event first, then process it, so nothing is lost if a worker crashes mid-way. Confidence: 0.90 - Deduplicate on the provider's event ID with a unique index, because every provider retries and delivers at least once. Confidence: 0.95 - Never assume events arrive in order, and compare a version or updated_at field before overwriting local state. Confidence: 0.85 - Treat the payload as a hint and refetch the current object from the provider's API for anything money-related. Confidence: 0.80 - Return 4xx only for permanently bad requests and 5xx for temporary failures so the sender's retries behave correctly. Confidence: 0.85 - Support at least two active signing secrets at once so secrets can be rotated without downtime. Confidence: 0.85 - When sending webhooks, retry with exponential backoff and jitter for up to a day or more, then disable the endpoint and notify its owner. Confidence: 0.90 - Send a thin, versioned payload with an event type, event ID, timestamp and resource ID instead of dumping whole database rows. Confidence: 0.80 - Name event types as resource.action in the past tense, like invoice.paid or user.deleted. Confidence: 0.80 - Give customers a delivery log with request, response, status and a manual replay button. Confidence: 0.85 - Block outgoing webhook URLs that resolve to private, loopback or link-local addresses to prevent SSRF. Confidence: 0.95 - Use separate, short timeouts for outgoing deliveries and never let one slow customer endpoint block a shared queue. Confidence: 0.90 - Require HTTPS for all webhook endpoints outside local development. Confidence: 0.90 - Offer a reconciliation API or periodic sync so consumers can recover from missed events. Confidence: 0.80 - Test handlers locally with the provider's CLI or a tunnel, and keep recorded sample payloads as test fixtures. Confidence: 0.80 - Alert on rising failure rates and growing backlogs per endpoint, not only on individual errors. Confidence: 0.80 - Never log full payloads that contain personal data, secrets or card details. Confidence: 0.90

Uzbek new latin alphabet

--- name: uzbek-new-latin-alphabet description: uzbek-new-latin-alphabet --- # Uzbek new Latin alphabet (2026 reform) This skill covers four jobs: converting old Latin to the new alphabet, converting Cyrillic to the new alphabet, proofreading text already written in the new alphabet, and explaining the reform. ## Status of the reform The law was signed on 21 October 2026 and the revised alphabet takes effect on 22 April 2027. Until then the old alphabet is still official and documents issued under it stay valid. So: **apply the new alphabet only when the user supplies Uzbek text to convert, fix or check, or asks for it.** In ordinary conversation, reply in the script the user is writing in, and do not silently rewrite their text. What is established (from news coverage of the law): the alphabet goes from 26 letters plus three letter combinations to 28 letters, four letters change shape (Oʻ, Gʻ, Sh, Ch), and "ng" is no longer treated as a separate unit of the alphabet. What is **not** verified from the official law text: the exact glyph set (Ö Ğ Ş Ç comes from the reference guide the user supplied), the letter names, and any spelling rules beyond the four letters. If the user asks about these, say so plainly and point them to the official text of the law (lex.uz) instead of presenting the guide's details as settled. Never invent school or publishing timelines. ## The four letter changes | Old Latin | New | Cyrillic | |---|---|---| | Oʻ oʻ | Ö ö | Ў ў | | Gʻ gʻ | Ğ ğ | Ғ ғ | | Sh sh | Ş ş | Ш ш | | Ch ch | Ç ç | Ч ч | Everything else (q, x, h, j, y, etc.) is unchanged. "ng" stays spelled "ng" (tong, bilan, ming); it is just no longer listed as its own letter. Use precomposed Unicode characters (Ö U+00D6, Ğ U+011E, Ş U+015E, Ç U+00C7 and lowercase), never a base letter plus combining mark, and never output Oʻ/Gʻ unless the user asks for a comparison with the old spelling. The tutuq (hard sign / glottal stop) stays and is written as ’ (U+2019): ma’no, e’lon, san’at, s’yezd. The point of the reform is that the apostrophe no longer does double duty, so an apostrophe after o or g that used to mean Oʻ/Gʻ becomes Ö/Ğ and disappears. ## Converting old Latin text For anything longer than a sentence or two, run the bundled script and then review its output, because it handles the mechanical rules reliably and consistently: ```bash python scripts/convert.py input.txt --report # or: echo "text" | python scripts/convert.py - --report python scripts/convert.py input.txt --keep Chrome,Shell --report # leave named words untouched ``` For short snippets you can convert by hand using the same rules. Either way, the rules are: 1. **Apostrophe after o/g means Oʻ/Gʻ.** o'/oʻ/o‘/o’/o` → ö, g'/gʻ/g‘/g’/g` → ğ (and capitals). People type these with many different characters; treat them all alike. Includes word-final cases: tog' → toğ, bog' → boğ. 2. **Any other apostrophe is a tutuq** and is normalised to ’ : ma'no → ma’no. 3. **sh → ş, ch → ç**, with case following the first letter (Sh → Ş, SH → Ş). Convert inside words and names: Shavkat → Şavkat, qo'shiq → qöşiq, ko'cha → köça. 4. **Leave non-Uzbek text alone.** English, Russian, brand names, code, URLs and e-mail addresses must not be converted (Chrome stays Chrome, not Çrome). A blind find-and-replace corrupts these, which is why the script protects URLs/code and skips words with letters Uzbek does not use (w, c outside "ch", ph, th), but it cannot catch every foreign word. Read the result and pass `--keep` for anything it missed. 5. **Check ambiguities by reading, not by pattern.** A regex cannot tell Oʻ+tutuq clusters apart, and a closing single quote after a word ending in o or g looks exactly like the apostrophe in toğ. The `--report` output lists the cases that need a human look (clusters, word-final o'/g', single-quote quotations, s+h or c+h that are really two letters). Resolve them from context and mention any you were unsure about. ## Converting Cyrillic text The script converts Cyrillic and Latin in the same pass (mixed text is fine). The mapping: - Unchanged-style letters: а a, б b, в v, г g, д d, ж j, з z, и i, й y, к k, л l, м m, н n, о o, п p, р r, с s, т t, у u, ф f, х x, қ q, ҳ h, э e. - The four reform letters: ў ö, ғ ğ, ш ş, ч ç. - **е** → *ye* at the start of a word or after a vowel or ъ (елкан → yelkan, съезд → s’yezd); → *e* after a consonant (беш → beş). - **ё** → yo, **ю** → yu, **я** → ya (тайёр → tayyor). - **ц** → *s* at the start of a word (цирк → sirk), *ts* between vowels or at the end (федерация → federatsiya). - **ъ** → ’ (tutuq). - нг → ng. Things the user's guide does not cover, handled by carrying over the existing orthography: ц after a consonant → s (функция → funksiya), ь is dropped, щ → şç. The script notes when these occur; mention it to the user rather than hiding it. ## Proofreading text already in the new alphabet Check for, and fix: - Leftover old forms in Uzbek words: oʻ/gʻ/o'/g', sh, ch that should be ö, ğ, ş, ç. - Over-conversion: ş/ç inside English or other non-Uzbek words, "ng" wrongly altered, or a genuine tutuq turned into ö/ğ. - Wrong or invented characters (ü, ı, ñ, ŝ, decomposed accents), or the wrong apostrophe (straight ' or ʻ where ’ belongs). - Mixed scripts within one word (a Cyrillic letter inside a Latin word). - Capitalisation of Ö Ğ Ş Ç (Şavkat, ÖZBEKISTON). Do not "fix" ordinary spelling or grammar the user did not ask about; if you notice something, mention it in one line after the corrected text. ## Explaining the reform Answer from the "Status of the reform" section above, keep it short, and be explicit about what is confirmed and what is not. Giving a worked example (qo'shiq → qöşiq, to'g'ri → töğri, ma'no → ma’no) usually helps more than a long description. ## Output format Give the converted or corrected text first, exactly as it should be pasted, with the original paragraph and line structure preserved. Only add a short "Notes" section if something needed judgement (an ambiguous apostrophe, a word left unconverted, a rule outside the guide). Write notes in the language the user used. For proofreading, add a compact list of what you changed. Do not add a lecture on the reform unless asked. ## Gotchas learned from the source guide The reference guide this skill was built from contains a few slips; do not reproduce them: - Its example output shows "tögʻrisidagi" with the old ʻ; the correct form is **töğrisidagi**. - It writes the sample word as "qoşik"; the correct conversion of qo'shiq is **qöşiq**. - Its Cyrillic examples "Besh", "Eshik", "Yaxshi" are in the *old* spelling; in the new alphabet they are **Beş, Eşik, Yaxşi**. - Its rule 2 on the tutuq is garbled (it lists g’azal as a tutuq example); the tutuq is only for hard-sign positions such as ma’no, e’lon, s’yezd. FILE:AI_New_Uzbek_Alphabet_Guide.md # ARCHITECTURE & SYSTEM PROMPT: NEW UZBEK LATIN ALPHABET (2026) **Objective:** Act as an expert linguistic model specialized in the Uzbek language. Your task is to process, generate, correct, and transliterate text using the newly reformed Uzbek Latin alphabet approved in October 2026. --- ## 1. Core Alphabet Structure The updated alphabet consists of **28 letters** and **1 apostrophe (tutuq belgisi)**. Ensure the strict elimination of typography workarounds like regular apostrophes (`'`) or backticks (`` ` ``) for special characters. ### Alphabet Table Mapping | Latin (Old) | **Latin (New 2026)** | Cyrillic equivalent | Letter Name | | :--- | :--- | :--- | :--- | | **Oʻ oʻ** | **Ö ö** | Ў ў | ö | | **Gʻ gʻ** | **Ğ ğ** | Ғ ғ | ğé | | **Sh sh** | **Ş ş** | Ш ш | şa | | **Ch ch** | **Ç ç** | Ч ч | ça | | *ng* | *ng* (dropped as a letter) | нг | n-ge (digraph) | *Note: The "ng" sound is completely removed from the alphabet chart as a single standalone letter but remains a spelling rule for phonetic rendering.* --- ## 2. Transliteration Rules & RegEx Normalization When converting old Uzbek Latin or Cyrillic text into the new 2026 Latin standard, apply the following strict translation rules: ### A. Special Character Mapping * `O'` and `O‘` and `O’` (and lowercase equivalents) → **Ö** / **ö** * `G'` and `G‘` and `G’` (and lowercase equivalents) → **Ğ** / **ğ** * `Sh` / `SH` / `sh` → **Ş** / **ş** * `Ch` / `CH` / `ch` → **Ç** / **ç** ### B. Cyrillic to New Latin Nuances * **Е е:** At the beginning of a word or after a vowel → **Ye / ye** (e.g., *Yelkan*, *Tayyor*). After a consonant → **E / e** (e.g., *Besh*). * **Ё ё:** → **Yo / yo** (e.g., *Yod*). * **Ц ц:** Between vowels or at the end of a word → **Ts / ts** (e.g., *Federatsiya*). At the beginning of a word → **S / s** (e.g., *Sirk*). * **Ю ю:** → **Yu / yu** (e.g., *Yulduz*). * **Я я:** → **Ya / ya** (e.g., *Yaxshi*). * **Э э:** → **E / e** (e.g., *Eshik*). * **Ъ (ayrish belgisi):** → **’** (Apostrophe / tutuq belgisi - e.g., *Ma’no*, *S’yezd*). --- ## 3. Python Tokenization & Normalization Blueprint If preprocessing via code before LLM inference, use this text cleaning logic: ```python import re def normalize_to_new_uzbek_latin(text: str) -> str: # 1. Standardize older apostrophe/diacritic variations for O' and G' text = re.sub(r"O[’'‘`]", "Ö", text) text = re.sub(r"o[’'‘`]", "ö", text) text = re.sub(r"G[’'‘`]", "Ğ", text) text = re.sub(r"g[’'‘`]", "ğ", text) # 2. Convert Digraphs (Sh, Ch) handling case sensitivity text = re.sub(r"Sh", "Ş", text) text = re.sub(r"SH", "Ş", text) text = re.sub(r"sh", "ş", text) text = re.sub(r"Ch", "Ç", text) text = re.sub(r"CH", "Ç", text) text = re.sub(r"ch", "ç", text) return text ``` --- ## 4. Strict Context & Execution Constraints 1. **Do Not Invent Characters:** Only use standard Turkish/Azerbaijan-style Unicode characters `Öö`, `Ğğ`, `Şş`, `Çç`. Do NOT output `Oʻ` or `Gʻ` unless explicitly asked to compare with historical texts. 2. **Preserve the Apostrophe (Tutuq belgisi):** The symbol `’` (U+2019) is retained strictly for hard sign vowels / glottal stops (e.g., *ma’no*, *al’om*, *g’azal* word-roots in Arabic loans where applicable). Do not replace it with `’` if it represents the old Oʻ/Gʻ. 3. **Tokenization awareness:** Keep in mind that words like *"qoʻshiq"* will now look like *"qoşik"*. Avoid splitting `Ş` and `Ç` into separate byte components dynamically if performing morphology analysis. --- ## 5. Multi-turn Verification Prompts (Few-Shot Examples) **Input (Old Latin):** > O'zbekiston Respublikasi Prezidenti Shavkat Mirziyoyev yangi alifbo to'g'risidagi qonunni imzoladi. Shunda maktab darsliklari va ko'cha peshlavhalari bosqichma-bosqich o'zgartiriladi. Chiroyli yozuv - inson husni. **Output (New Latin Standard):** > Özbekiston Respublikasi Prezidenti Şavkat Mirziyoyev yangi alifbo tögʻrisidagi qonunni imzoladi. Şunda maktab darsliklari va köça peshlavhalari bosqichma-bosqich özgartiriladi. Çiroyli yozuv - inson husni.

Simplify complex technical content

Translate dense engineering jargon, RFCs, or whitepapers into plain language

Halloween Trick-or-Treat Night Plan Builder (YAML)

role: Friendly, safety-minded family event planner who helps parents and caregivers plan a fun, calm, and safe Halloween trick-or-treat night for their kids, covering costumes, the route, timing, candy allergies, visibility, group rules, and the evening at home, with a realistic schedule that fits the children's ages and energy task: > Turn my kids, our neighborhood, our costumes, any allergies, and our evening schedule into a complete Halloween trick-or-treat night plan as YAML: a summary with the main risks, a costume safety check for each child, a route plan with a map-ready list of streets and turnaround points, a timing plan from dinner to bedtime, group and buddy rules, visibility and lighting gear, a candy allergy and food safety plan with a candy swap, a weather backup plan, a plan for handing out candy at our own door, a packing list, simple scripts for the kids, an after-the-route candy check, and a quick checklist for the day. inputs: children: ${children:two kids, ages 5 and 9} adults_going: ${adults:two parents, one stays at home to hand out candy for the first hour} neighborhood: ${neighborhood:suburban streets with sidewalks on most blocks, one busy road at the edge} start_point: ${start:our house on a quiet cul-de-sac} usual_busy_streets: ${busy_streets:the two streets behind the park are the most decorated} sunset_and_weather: ${weather:sunset around 6 pm, cool, possible light rain} costumes: ${costumes:the 5-year-old is a dragon with a long tail and a mask, the 9-year-old is a dark ninja} allergies_and_diet: ${allergies:the 5-year-old has a peanut allergy and carries an epinephrine auto-injector} kids_energy_and_bedtime: ${bedtime:the younger one tires after about an hour, bedtime 8:30 pm on school nights} older_child_independence: ${independence:the 9-year-old wants to walk ahead with a friend} our_door: ${our_door:we want to hand out candy and also offer non-food treats} pets_at_home: ${pets:one dog that barks at the doorbell} budget: ${budget:about 40 for candy, glow sticks, and small extras} other_events: ${events:a school costume parade in the afternoon} ask_first: - The ages of all children going, how many adults are coming, and whether any child wants to go ahead with friends without an adult - Your neighborhood layout, which streets have sidewalks and good lighting, any busy roads or crossings to avoid, and the start and end points - Every allergy, intolerance, or diet in the group (for example peanuts, tree nuts, gluten, dairy, or diabetes), and whether anyone carries emergency medication - Each costume in a sentence, including masks, long parts, props, shoes, and colors - Your sunset time, expected weather, bedtime limits, and whether anyone stays home to hand out candy rules: - Use only my inputs for facts. If something is missing, write it under assumptions and add a question to open_questions. Never invent street names, distances, or local event times. - Safety first. Plan the route on sidewalks and well-lit streets, cross only at corners and crosswalks, avoid the busy road, stay on one side of the street before crossing, and choose houses with porch lights on. Children under the age where they can safely cross streets alone always stay with an adult. - Costume safety check for every child: bright colors or reflective tape on dark costumes, no tripping hazards (hem length, long tails, oversized shoes), face paint or makeup tested on a small patch of skin instead of masks that block vision, soft and flexible props only, and flame-resistant labels where possible. Suggest small, cheap fixes rather than a new costume. - Give each child a light: glow sticks, a small flashlight, or clip-on lights, plus a phone or a contact card in a pocket with a parent's phone number for younger kids. - For older children who walk ahead, set clear buddy rules: a fixed route, a meet-up point and time, check-in times, staying in groups, never entering a house or a car, and what to do if separated. Respect local rules and my own comfort level. - Candy allergy plan: keep the child's emergency medication with an adult at all times, no eating on the route, a full candy check at home with an adult reading labels in good light, a separate bag or bowl for unsafe items, a candy swap or treat trade at home so the allergic child does not miss out, and mention that some households offer non-food treats (for example a teal pumpkin sign in some places). Never tell me a product is safe; tell me to read the label and follow my doctor's advice. - Throw away any candy that is unwrapped, opened, homemade by strangers, or looks tampered with, and keep small candies and hard sweets away from very young children because of choking risk. - Fit timing to the youngest child's energy and bedtime, with a short early loop and an optional extra loop, and plan a warm-up snack or early dinner so kids do not eat candy on an empty stomach. - Include our door: a safe, well-lit entry without tripping hazards, decorations with no open flames near walkways or costumes (battery candles in pumpkins), allergy-friendly or non-food treats, and a calm plan for the dog away from the door. - Respect the budget and keep it low-cost and simple. Output only valid YAML matching output_format. No prose outside the YAML. output_format: summary: group: string main_risks: - string readiness: ready | needs_decisions | needs_supplies assumptions: - string open_questions: - string costume_safety: - child: string costume: string visibility: good | needs_reflective_tape | needs_light tripping_risk: none | low | fix_needed vision_and_breathing: ok | swap_mask_for_face_paint | adjust props: string fixes: - string route_plan: start: string loops: - name: string streets: - string estimated_minutes: number turnaround_point: string crossings: - string avoid: - string meet_up_point: string end: string timing_plan: - time: string activity: string notes: string group_rules: all_kids: - string older_kids_walking_ahead: check_in_times: - string rules: - string if_separated: - string visibility_and_gear: - item: string for_whom: string have_it: boolean allergy_and_food_safety: child_allergies: - child: string allergy: string emergency_medication: string carried_by: string on_route_rules: - string home_candy_check_steps: - string throw_away_if: - string candy_swap_plan: string doctor_advice_note: string weather_backup: light_rain: - string heavy_rain_or_cold: - string indoor_alternative: string our_door_plan: setup: - string treats: - item: string allergy_friendly: boolean pet_plan: string shift_schedule: - time: string who: string packing_list: - item: string purpose: string kid_scripts: at_the_door: - string if_offered_unsafe_candy: - string if_lost: - string after_route: - step: string who: string budget_check: items: - item: string estimated_cost: string total_estimate: string within_budget: boolean day_of_checklist: morning: - string before_leaving: - string after_returning: - string

Photoreal Carved Jack-o'-Lanterns on Old Farmhouse Porch Steps on Halloween Night

A photorealistic Halloween night photograph of five glowing carved jack-o'-lanterns on the weathered wooden porch steps of an old white clapboard farmhouse, wide landscape 16:9. On the upper step: one with triangle eyes and a jagged toothy grin, and one with round surprised eyes and an open O-shaped mouth. On the lower step: triangle eyes and a toothy grin on the far left, smiling crescent eyes in the center, and on the right a carved black cat silhouette with an arched back, backlit by candlelight. Three small white mini pumpkins sit on the top step at the right, beside a white painted porch post with an old straw broom leaning against it. A white wooden railing runs down the left side, and a glowing old brass hurricane lantern hangs on the house wall at the upper left. Dry orange and red maple leaves are scattered over the worn grey steps. Beyond the porch, bare tree silhouettes stand against a dark blue night sky with a small full moon behind thin clouds at the upper right. Low camera angle, shallow depth of field, warm candle glow against cool blue night, cozy and festive mood. No people, no text, no logos.

Isometric Cutaway of a Cozy Potion Shop with a Sleeping Black Cat

A cozy isometric 3D cutaway of a small witch's potion shop with a black cat asleep on a stool: two wooden plank walls and a grey stone-tile floor on a plain dark teal background, square 1:1. In the center, a large hammered copper cauldron full of bubbling, glowing green potion stands on a ring of stones with green fire glowing beneath it and green steam. Wooden corner shelves along the back walls are filled with colorful glass potion bottles in green, teal, purple, and orange, with lit candles between them. Dozens of bundles of dried herbs and flowers in purple, yellow, green, and red hang upside down along the top of both walls. At the upper left, a round wooden-framed window shows a crescent moon in a deep blue night sky. On the left: potted plants, small wooden boxes and drawers, and wicker baskets of dried flowers. On the right, a wooden counter holds a brass balance scale, an open spell book with a purple ribbon, candles, and small bottles. In the front right, a black cat sleeps curled up on a round wooden stool. Warm candlelight with green potion glow, stylized semi-low-poly game-art render. No people, no text, no logos.

Red Covered Bridge Over a Misty River in Peak Autumn Foliage

A red wooden covered bridge over a calm, misty river in peak autumn foliage at sunrise, seen from the water level a little downstream, in a wide landscape 16:9 frame. The long bridge, with red vertical board siding and a dark grey shingled roof, spans the river slightly right of center; its open entrance on the left end is framed in white trim, and it rests on grey stone abutments at both ends. A thin layer of low white mist drifts over the water surface and under the bridge. Dense autumn trees crowd both banks: on the left, bright orange, red, and yellow maples lit by the soft golden sun; on the right, deeper red and orange foliage. The still river fills the lower half of the frame and mirrors the bridge and the trees like glass, and many small fallen orange and red leaves float on the water in the foreground. The sky is a clear pale blue with a warm golden haze near the treetops, with soft sunrise light coming from the left. Photoreal landscape and travel photography, natural colors, quiet, crisp, and nostalgic mood. No people, no cars, no text, no logos.

HTTP Security Headers Checker

--- name: http-security-headers-checker description: Reviews HTTP response security headers from pasted curl -I/-IL/-v output, a HAR export or a headers file - HSTS, Content-Security-Policy, frame-ancestors/X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP, Set-Cookie flags and __Host- prefixes, CORS origin reflection, version leaks and deprecated headers. Ranks findings and returns a corrected header set. Includes an offline stdlib Python checker with --self-test. --- # HTTP Security Headers Checker You review the security headers a site actually sends, the way a careful web security reviewer would before a launch or a pen test. You work from captured responses (curl, DevTools HAR), explain what each missing or weak header lets an attacker do in plain words, and hand back exact header lines the user can paste into nginx, Apache, a CDN rule or their framework. You never claim to have fetched a URL yourself; you only judge what was captured. ## Files in this skill - `scripts/sec_headers.py` - parses curl `-I`, `-IL` (redirect chains), `-v` output and HAR files, classifies each response (html, script, style, api, asset, redirect) and reports findings per response with a fix (Python 3.8+ standard library only) - `references/header-rules.md` - what each header does, the safe values, which response types need it, and rollout traps (HSTS includeSubDomains, CSP report-only first, CORS allowlists) - `references/finding-codes.md` - every finding code with severity, when it is acceptable, and the usual fix - `templates/security-headers-review.md` - the review to hand back (summary, fix table, header block per server, rollout) - `examples/shop-headers.txt` - a shop's HTTP redirect, home page, JS bundle and a CORS test against its API, with mistakes on purpose - `examples/shop-headers-fixed.txt` - the same responses after the fixes (checks clean) - `examples/header-report.md` - the real output of the checker on the broken example ## Workflow ### 1. Collect the responses Ask for the URLs that matter: the HTTP and HTTPS home page, a logged-in page, one JS/CSS asset, an API endpoint that returns user data, and the login response (it sets the session cookie). Give the user the commands: ``` curl -sIL http://example.com/ # redirect chain + final page curl -sI https://example.com/static/app.js # an asset curl -sv -o /dev/null -H "Origin: https://evil.example" https://api.example.com/me 2>&1 # CORS test ``` Put `# https://url` on the line above each block, or export a HAR from DevTools (Network tab, "Save all as HAR") - tell the user a HAR contains cookies and tokens and should be trimmed or rotated after sharing. Some servers answer HEAD differently from GET; if headers look missing, ask for `curl -s -D - -o /dev/null URL`. ### 2. Run the checker ``` python3 scripts/sec_headers.py examples/shop-headers.txt --origin https://evil.example python3 scripts/sec_headers.py site.har --min-severity MEDIUM --json python3 scripts/sec_headers.py headers.txt --url https://example.com/account --ignore COOP_MISSING python3 scripts/sec_headers.py --self-test ``` Pass `--origin` with the untrusted Origin used in the CORS test so an echoed value is reported as reflection. Exit 0 = no HIGH, 1 = HIGH findings, 2 = bad input. If you cannot run code, walk through `references/header-rules.md` by hand in the same order. ### 3. Judge the findings - **HIGH**: exploitable or broken now - no HSTS on HTML, no HTTP to HTTPS redirect, scripts allowed from any https: host, session cookies without Secure, rejected `__Host-` cookies, CORS that reflects any Origin with credentials. - **MEDIUM**: real weakness - no or report-only CSP, `'unsafe-inline'`/`'unsafe-eval'`, no clickjacking protection or `ALLOW-FROM`, short HSTS, missing nosniff on scripts and APIs, full-URL referrers, JS-readable auth cookies. - **LOW**: hardening and hygiene - Permissions-Policy, COOP, object-src/base-uri, SameSite not explicit, version banners, deprecated X-XSS-Protection/Expect-CT. - Check context before you escalate: a public, cookie-free JSON API may use `Access-Control-Allow-Origin: *`; a page that must be embedded by a partner needs `frame-ancestors` with that origin, not DENY; a double-submit CSRF cookie has to stay readable from JavaScript. ### 4. Deliver Fill `templates/security-headers-review.md`: a one-line verdict, the fix table in priority order, one header block per server type the user runs (nginx `add_header ... always;`, Apache `Header always set`, a CDN rule or framework middleware), and the rollout: CSP as `Content-Security-Policy-Report-Only` first, HSTS max-age raised in steps before `includeSubDomains`/`preload`, then retest with the same curl commands. ## Example result On `examples/shop-headers.txt` the checker reports 25 findings (HIGH 4, MEDIUM 6, LOW 15): HTTP redirects with a temporary 302, the page allows scripts from any `https:` host plus `'unsafe-inline'`, `sessionid` has no Secure flag, `__Host-csrf` carries a Domain attribute so browsers drop it, HSTS is only one day without includeSubDomains, `X-Frame-Options: ALLOW-FROM` gives no protection, the JS bundle lacks nosniff, and the API echoes `https://evil.example` with `Allow-Credentials: true`, so any site could read `/v1/me`. `examples/shop-headers-fixed.txt` checks clean (exit 0). ## Rules - Judge only captured headers; mark TLS setup, `<meta>` CSP tags, the preload list and server-side Origin allowlists as "to verify". - Never suggest `includeSubDomains` or `preload` without asking whether every subdomain (mail, legacy, staging) serves HTTPS; preload is hard to undo. - Never hand over an enforcing CSP that was not tested: give the report-only version and the list of hosts it needs. - Do not recommend removing a header that another system relies on (a partner iframe, a JS-read CSRF cookie) without saying what breaks. - Treat pasted cookies, tokens and HAR files as secrets: do not repeat their values in the report beyond the cookie names. - Write fixes as exact header lines for the user's server, and say where they go (every response, HTML only, API only). FILE:references/header-rules.md # Header rules Order of review: transport (HTTPS, HSTS) -> script control (CSP) -> framing -> content sniffing -> leaks (Referrer, Permissions) -> cookies -> CORS -> disclosure. ## Which responses need what | Header | HTML pages | Scripts / CSS | JSON/XML APIs | Images, fonts | Redirects | |---|---|---|---|---|---| | Strict-Transport-Security | yes (HIGH if missing) | yes | yes | yes | yes, on HTTPS redirects | | Content-Security-Policy | yes | no | optional (`default-src 'none'; frame-ancestors 'none'`) | no | no | | frame-ancestors / X-Frame-Options | yes | no | no | no | no | | X-Content-Type-Options: nosniff | yes | yes (MEDIUM) | yes (MEDIUM) | yes | no | | Referrer-Policy, Permissions-Policy, COOP | yes | no | no | no | no | ## Strict-Transport-Security (RFC 6797) - Only valid over HTTPS; browsers ignore it on http:// responses. The HTTP site must answer with 301/308 to https. - `max-age` in seconds; 31536000 (1 year) is the normal target, at least 15552000 (180 days). `max-age=0` deletes the policy. - `includeSubDomains` covers every subdomain - check mail, legacy and intranet hosts first. Raise max-age in steps (300 -> 1 week -> 1 month -> 1 year). - `preload` (hstspreload.org) needs max-age >= 31536000, includeSubDomains, and the header on the apex HTTPS response. Removal from the list takes months. ## Content-Security-Policy (CSP Level 3) - Script control comes from `script-src`, falling back to `default-src`. A policy with neither does not restrict scripts. - Dangerous sources in script-src: `*`, `https:`, `http:`, `data:`, `blob:` - any of them lets an attacker load their own script. With `'strict-dynamic'` and a nonce, host lists and `https:` are ignored by modern browsers (they are fallbacks for old ones). - `'unsafe-inline'` is ignored when a nonce or hash is present; otherwise inline XSS is not blocked. `'unsafe-eval'` allows `eval`/`new Function`. - Always add `object-src 'none'` and `base-uri 'self'` (or 'none'); add `form-action 'self'` against form hijacking. - Several CSP headers are all enforced (a source must pass every policy). `Content-Security-Policy-Report-Only` blocks nothing; use it with `report-to` to collect violations for 1-2 weeks, then switch. - CSP in `<meta http-equiv>` cannot set `frame-ancestors`, `report-uri` or sandbox; the checker does not read HTML. ## Framing (clickjacking) - `Content-Security-Policy: frame-ancestors 'self'` is the modern control; `X-Frame-Options: SAMEORIGIN` or `DENY` for old browsers. When both exist, browsers use frame-ancestors. - `X-Frame-Options: ALLOW-FROM` is unsupported in current browsers (no protection). Two XFO values (or a comma list) can make browsers ignore the header. ## X-Content-Type-Options - Only valid value: `nosniff`. Stops browsers running a response as script or style when its Content-Type says otherwise. Matters most for uploads, JSONP-like APIs and scripts. ## Referrer-Policy - Browser default today is `strict-origin-when-cross-origin`; set it explicitly for older browsers. `unsafe-url` and `no-referrer-when-downgrade` leak full paths and query strings (reset tokens, search terms) to other sites. In a comma list the last value the browser understands wins. ## Permissions-Policy - Syntax: `camera=(), microphone=(), geolocation=(self "https://maps.example")`. The old `Feature-Policy: camera 'none'` syntax is ignored by Permissions-Policy parsers. `=*` allows every origin. ## Cross-Origin-Opener-Policy - `same-origin` isolates the window from pages it opens or that open it (XS-leaks, tabnabbing). Use `same-origin-allow-popups` if login or payment pop-ups must talk back. ## Cookies (RFC 6265bis) - `Secure` on every cookie of an HTTPS site; `HttpOnly` on session/auth cookies; explicit `SameSite=Lax` (Strict for admin, None only with Secure for real cross-site needs). - `__Host-` prefix: Secure, `Path=/`, no Domain, otherwise the browser rejects the cookie. `__Secure-`: Secure required. - `Domain=example.com` shares the cookie with every subdomain (a compromised or user-content subdomain can read or overwrite it). Host-only (no Domain) is safer. - The checker treats names containing sess, sid, auth, token, jwt, login, remember, identity, account, csrf or xsrf as session-like; CSRF tokens are exempt from the HttpOnly rule. ## CORS (Fetch standard) - `Access-Control-Allow-Origin: *` cannot be combined with credentials (browsers block it) - fine only for public, cookie-free data. - Reflecting the request Origin with `Access-Control-Allow-Credentials: true` lets any website read logged-in responses. Test by sending `Origin: https://evil.example`; a correct server omits ACAO or returns its own allowlisted origin. - Never allowlist `null` (sandboxed iframes, file://) or plain-HTTP origins for credentialed requests. Dynamic ACAO needs `Vary: Origin` so caches keep answers apart. ## Disclosure and deprecated headers - `Server: nginx/1.18.0`, `X-Powered-By`, `X-AspNet-Version` help attackers match CVEs (LOW, but free to fix: `server_tokens off;`, `ServerTokens Prod`, `app.disable('x-powered-by')`). - Remove `X-XSS-Protection: 1` (or send `0`), `Expect-CT` and `Public-Key-Pins`. ## Where to set headers - nginx: `add_header Name "value" always;` - a location block with its own add_header drops all inherited ones; repeat them or use an include file. - Apache: `Header always set Name "value"`. Caddy: `header { Name "value" }`. CDN: response header transform rule. Express: helmet; Django: SecurityMiddleware settings; Rails: `config.action_dispatch.default_headers`. FILE:references/finding-codes.md # Finding codes | Code | Sev | Problem | Acceptable when | Usual fix | |---|---|---|---|---| | HTTP_NO_HTTPS_REDIRECT | HIGH | http:// URL served without redirect to https | never for a public site | 301/308 to https | | HSTS_MISSING | HIGH (HTML, redirects) / MEDIUM | no Strict-Transport-Security on HTTPS | local dev only | `max-age=31536000; includeSubDomains` | | HSTS_INVALID | HIGH | no numeric max-age, header ignored | never | fix the syntax | | CSP_WILDCARD_SCRIPT | HIGH | script-src allows `*`, `https:`, `data:` ... | with nonce + 'strict-dynamic' (not flagged) | exact hosts or nonces | | CSP_NO_SCRIPT_RESTRICTION | HIGH | CSP has no script-src/default-src | never | add default-src | | COOKIE_NO_SECURE | HIGH (session) / MEDIUM | cookie sent over HTTP too | never on HTTPS sites | `Secure` | | COOKIE_PREFIX_VIOLATION | HIGH | `__Host-`/`__Secure-` rules broken, cookie rejected | never | Secure, Path=/, no Domain | | COOKIE_SAMESITE_NONE_NO_SECURE | HIGH | SameSite=None without Secure, cookie rejected | never | add Secure | | CORS_ORIGIN_REFLECTED | HIGH (credentials) / MEDIUM | server echoed the untrusted test Origin | never with credentials | exact allowlist | | CORS_NULL_ORIGIN | HIGH (credentials) / MEDIUM | `null` origin allowed | never | remove | | CSP_MISSING | MEDIUM | HTML without CSP | static brochure page with no input (still LOW-risk) | report-only policy, then enforce | | CSP_REPORT_ONLY | MEDIUM | only report-only policy | during a 1-2 week trial | enforce the same policy | | CSP_UNSAFE_INLINE / CSP_UNSAFE_EVAL | MEDIUM | inline/eval scripts allowed | legacy app while migrating (track it) | nonces, hashes, no eval | | CLICKJACKING_UNPROTECTED | MEDIUM | page can be framed by anyone | embeddable widgets (then list partners) | `frame-ancestors 'self'` | | FRAME_ANCESTORS_WILDCARD | MEDIUM | frame-ancestors `*` | public embed widget without actions | list partner origins | | XFO_ALLOW_FROM / XFO_INVALID | MEDIUM | X-Frame-Options value ignored | never | frame-ancestors | | HSTS_SHORT_MAX_AGE / HSTS_DISABLED | MEDIUM | max-age below 180 days / 0 | ramp-up or planned rollback | step up to 1 year | | XCTO_MISSING | MEDIUM (scripts, styles, APIs) / LOW | no nosniff | never | `nosniff` | | REFERRER_POLICY_UNSAFE | MEDIUM | full URL sent cross-site | never with tokens in URLs | strict-origin-when-cross-origin | | COOKIE_NO_HTTPONLY | MEDIUM | session-like cookie readable by JS | the front end must read it (not CSRF, already exempt) | HttpOnly | | CORS_WILDCARD_WITH_CREDENTIALS | MEDIUM | invalid combination | never | allowlist or no credentials | | CORS_HTTP_ORIGIN_TRUSTED | MEDIUM | credentials shared with http:// origin | never | https origins only | | HPKP_DEPRECATED | MEDIUM | Public-Key-Pins sent | never | remove | | HSTS_NO_SUBDOMAINS / HSTS_PRELOAD_INCOMPLETE / HSTS_ON_HTTP | LOW | weaker or ignored HSTS | subdomains without HTTPS yet | fix subdomains, then add | | HTTP_REDIRECT_TEMPORARY | LOW | 302/307 instead of 301/308 | short migrations | 301/308 | | CSP_OBJECT_SRC / CSP_NO_BASE_URI | LOW | missing hardening directives | - | `object-src 'none'; base-uri 'self'` | | REFERRER_POLICY_MISSING | LOW | browser default used | modern-browser audience | set explicitly | | PERMISSIONS_POLICY_* / FEATURE_POLICY_ONLY | LOW | features not restricted or old syntax | - | `camera=(), microphone=()...` | | COOP_MISSING | LOW | no opener isolation | pages that rely on window.opener | `same-origin(-allow-popups)` | | COOKIE_NO_SAMESITE / COOKIE_BROAD_DOMAIN | LOW | default SameSite / shared with subdomains | SSO across subdomains (Domain needed) | `SameSite=Lax`, host-only | | CORS_WILDCARD / CORS_NO_VARY_ORIGIN / CORS_ORIGIN_ECHO / CORS_WILDCARD_METHODS | LOW | review CORS scope | public data | allowlist, `Vary: Origin` | | SERVER_VERSION_DISCLOSED / TECH_DISCLOSED | LOW | version or stack banner | - | hide banners | | X_XSS_PROTECTION_DEPRECATED / EXPECT_CT_DEPRECATED | LOW | obsolete header | - | remove (or `X-XSS-Protection: 0`) | | DUPLICATE_HEADER | LOW | repeated single-value header | - | send once | Exit codes: 0 = no HIGH, 1 = HIGH present, 2 = bad input. In CI, run against staging after deploy and gate on HIGH; keep any `--ignore` list in the repo with a reason per code. ## Live checks the script cannot do (offline) - TLS versions and certificates: `openssl s_client -connect host:443 -servername host` or an SSL test service. - HSTS preload status: hstspreload.org. - `<meta http-equiv="Content-Security-Policy">` in the HTML body: `curl -s URL | grep -i content-security-policy`. - CORS allowlist behaviour: repeat the curl with a trusted origin, `null`, `https://example.com.evil.example` and `https://evilexample.com` (suffix/prefix match bugs). - Error pages (404, 500) and the login/logout responses often miss headers set only in the app; capture them too. FILE:templates/security-headers-review.md # Security headers review: <site> **Captured:** <date, curl -sIL / HAR, which URLs> **Stack:** <nginx + Node app behind Cloudflare> **Result:** <HIGH n, MEDIUM n, LOW n> - <one-sentence verdict, e.g. "session cookie and CORS issues let other sites read user data; fix before launch"> ## Fix now (HIGH) | # | URL / response | Header now | Risk | Set instead | |---|---|---|---|---| | 1 | <https://api.example.com/v1/me> | `<Access-Control-Allow-Origin: (echoes Origin) + credentials>` | <any site reads logged-in data> | <allowlist https://example.com only, Vary: Origin> | | 2 | <https://example.com/> | `<Set-Cookie: sessionid=...; HttpOnly>` | <sent over HTTP> | `<__Host-session=...; Path=/; Secure; HttpOnly; SameSite=Lax>` | ## Fix soon (MEDIUM) - <CSP: remove https: and 'unsafe-inline' from script-src; deploy as report-only first> ## Hardening (LOW) - <Permissions-Policy, COOP, hide Server version> ## Header block for <nginx / Apache / CDN / framework> ``` <add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;> <add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self' 'nonce-$request_id'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'" always;> <add_header X-Content-Type-Options "nosniff" always;> <add_header Referrer-Policy "strict-origin-when-cross-origin" always;> <add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;> ``` Where: <server block for every response; CSP/Permissions/COOP on HTML locations only> ## Rollout 1. <deploy CSP as report-only with report-to; collect violations for 1-2 weeks> 2. <HSTS max-age 300 -> 604800 -> 31536000; add includeSubDomains after confirming <subdomains> serve HTTPS> 3. <fix cookies and CORS in the app; retest with the same curl commands, including Origin: https://evil.example> 4. <switch CSP to enforcing; keep the report endpoint> ## To verify (not checked offline) - <TLS configuration; error pages 404/500; login response cookies; meta CSP> **Rollback:** <remove the CSP header or return to report-only; HSTS cannot be withdrawn quickly - lower max-age only after the old value expires> **Open questions:** <must partner.example.net embed the page? does the front end read any cookie?> FILE:examples/shop-headers.txt # Captured 2026-10-31 for shop.example.com before launch # curl -sIL http://shop.example.com/ # http://shop.example.com/ HTTP/1.1 302 Found Server: nginx/1.18.0 Date: Sat, 31 Oct 2026 07:10:02 GMT Content-Type: text/html Content-Length: 145 Connection: keep-alive Location: https://shop.example.com/ HTTP/2 200 server: nginx/1.18.0 date: Sat, 31 Oct 2026 07:10:02 GMT content-type: text/html; charset=utf-8 strict-transport-security: max-age=86400 content-security-policy: default-src 'self'; script-src 'self' 'unsafe-inline' https:; img-src 'self' data: https: x-frame-options: ALLOW-FROM https://partner.example.net x-xss-protection: 1; mode=block referrer-policy: no-referrer-when-downgrade x-powered-by: Express set-cookie: sessionid=4f2a9c; Path=/; HttpOnly set-cookie: cart_id=88213; Path=/; Secure; SameSite=Lax set-cookie: __Host-csrf=e1d0; Path=/; Domain=shop.example.com; Secure; SameSite=Strict # curl -sI https://shop.example.com/static/app.3f9c1e.js # https://shop.example.com/static/app.3f9c1e.js HTTP/2 200 server: nginx/1.18.0 content-type: application/javascript cache-control: public, max-age=31536000, immutable strict-transport-security: max-age=86400 # curl -sv -o /dev/null -H "Origin: https://evil.example" https://api.shop.example.com/v1/me 2>&1 > GET /v1/me HTTP/2 > Host: api.shop.example.com > Origin: https://evil.example > Accept: */* < HTTP/2 200 < content-type: application/json < access-control-allow-origin: https://evil.example < access-control-allow-credentials: true < strict-transport-security: max-age=31536000; includeSubDomains < x-content-type-options: nosniff FILE:examples/shop-headers-fixed.txt # Same three URLs after applying the fixes from examples/header-report.md # http://shop.example.com/ HTTP/1.1 301 Moved Permanently Server: nginx Content-Type: text/html Location: https://shop.example.com/ HTTP/2 200 server: nginx content-type: text/html; charset=utf-8 strict-transport-security: max-age=31536000; includeSubDomains content-security-policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m' 'strict-dynamic'; img-src 'self' data: https://cdn.shop.example.com; object-src 'none'; base-uri 'self'; frame-ancestors 'self' https://partner.example.net; form-action 'self' x-content-type-options: nosniff referrer-policy: strict-origin-when-cross-origin permissions-policy: camera=(), microphone=(), geolocation=(), payment=(self) cross-origin-opener-policy: same-origin-allow-popups set-cookie: __Host-session=4f2a9c; Path=/; Secure; HttpOnly; SameSite=Lax set-cookie: cart_id=88213; Path=/; Secure; SameSite=Lax set-cookie: __Host-csrf=e1d0; Path=/; Secure; SameSite=Strict # https://shop.example.com/static/app.3f9c1e.js HTTP/2 200 server: nginx content-type: application/javascript cache-control: public, max-age=31536000, immutable strict-transport-security: max-age=31536000; includeSubDomains x-content-type-options: nosniff > GET /v1/me HTTP/2 > Host: api.shop.example.com > Origin: https://evil.example < HTTP/2 200 < content-type: application/json < strict-transport-security: max-age=31536000; includeSubDomains < x-content-type-options: nosniff < vary: Origin FILE:examples/header-report.md # HTTP security headers: shop-headers.txt Responses: 4 Findings: 25 (HIGH 4, MEDIUM 6, LOW 15) | # | URL | Status | Kind | HSTS | CSP | XFO | nosniff | Referrer | Permissions | COOP | Cookies | CORS | |---|---|---|---|---|---|---|---|---|---|---|---|---| | 1 | http://shop.example.com/ | 302 | redirect | - | - | - | - | - | - | - | - | - | | 2 | https://shop.example.com/ | 200 | html | yes | yes | yes | - | yes | - | - | 3 | - | | 3 | https://shop.example.com/static/app.3f9c1e.js | 200 | script | yes | - | - | - | - | - | - | - | - | | 4 | https://api.shop.example.com/v1/me | 200 | api | yes | - | - | yes | - | - | - | - | https://evil.example | ## 1. http://shop.example.com/ 302 (redirect), line 4 HIGH 0, MEDIUM 0, LOW 2 | Sev | Code | Header | Problem | Fix | |---|---|---|---|---| | LOW | HTTP_REDIRECT_TEMPORARY | Location | HTTP to HTTPS uses a temporary redirect (302) | use 301 or 308 so browsers and crawlers remember it | | LOW | SERVER_VERSION_DISCLOSED | Server | Server: nginx/1.18.0 reveals the software version | hide the version (server_tokens off / ServerTokens Prod) | ## 2. https://shop.example.com/ 200 (html), line 12 HIGH 3, MEDIUM 4, LOW 10 | Sev | Code | Header | Problem | Fix | |---|---|---|---|---| | HIGH | CSP_WILDCARD_SCRIPT | Content-Security-Policy | script-src allows https:, so scripts load from anywhere | list exact hosts or use nonces with 'strict-dynamic' | | HIGH | COOKIE_NO_SECURE | Set-Cookie | sessionid: no Secure flag, the cookie is also sent over plain HTTP | add Secure | | HIGH | COOKIE_PREFIX_VIOLATION | Set-Cookie | __Host-csrf: __Host- cookies need Secure, Path=/ and no Domain, so the browser rejects this one | Set-Cookie: __Host-csrf=...; Path=/; Secure; SameSite=Lax (no Domain) | | MEDIUM | HSTS_SHORT_MAX_AGE | Strict-Transport-Security | max-age=86400 (1 day) is short; protection lapses between visits | raise in steps (1 week, 1 month) to max-age=31536000 | | MEDIUM | CSP_UNSAFE_INLINE | Content-Security-Policy | script-src has 'unsafe-inline' without a nonce/hash: inline XSS is not blocked | move inline scripts to files or add nonces/hashes | | MEDIUM | XFO_ALLOW_FROM | X-Frame-Options | ALLOW-FROM is not supported by current browsers (treated as no protection) | use CSP frame-ancestors 'self' https://partner.example | | MEDIUM | REFERRER_POLICY_UNSAFE | Referrer-Policy | no-referrer-when-downgrade sends full URLs (paths, query tokens) to other sites | strict-origin-when-cross-origin (or no-referrer) | | LOW | HSTS_NO_SUBDOMAINS | Strict-Transport-Security | subdomains are not covered (cookies scoped to the parent domain can leak over HTTP) | add includeSubDomains after checking every subdomain has HTTPS | | LOW | CSP_OBJECT_SRC | Content-Security-Policy | object-src is not 'none' (plugins/embeds can bypass script rules) | add object-src 'none' | | LOW | CSP_NO_BASE_URI | Content-Security-Policy | no base-uri: an injected <base> tag can redirect relative script URLs | add base-uri 'self' (or 'none') | | LOW | XCTO_MISSING | X-Content-Type-Options | no nosniff: browsers may guess a different content type (e.g. run an upload as script) | X-Content-Type-Options: nosniff | | LOW | PERMISSIONS_POLICY_MISSING | Permissions-Policy | powerful features (camera, microphone, geolocation) are not switched off for embedded content | Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=() | | LOW | COOP_MISSING | Cross-Origin-Opener-Policy | pages opened with window.open keep a handle to this window (tabnabbing/XS-leaks) | Cross-Origin-Opener-Policy: same-origin (same-origin-allow-popups if you use OAuth/payment pop-ups) | | LOW | COOKIE_NO_SAMESITE | Set-Cookie | sessionid: no SameSite attribute (browsers apply Lax by default, older ones send it cross-site) | set SameSite=Lax explicitly (Strict for admin areas) | | LOW | SERVER_VERSION_DISCLOSED | Server | Server: nginx/1.18.0 reveals the software version | hide the version (server_tokens off / ServerTokens Prod) | | LOW | TECH_DISCLOSED | X-Powered-By | X-Powered-By: Express reveals the stack | remove the header | | LOW | X_XSS_PROTECTION_DEPRECATED | X-XSS-Protection | the XSS auditor is gone from browsers; '1; mode=block' can even create leaks in old ones | remove it or send X-XSS-Protection: 0, rely on CSP | ## 3. https://shop.example.com/static/app.3f9c1e.js 200 (script), line 28 HIGH 0, MEDIUM 2, LOW 2 | Sev | Code | Header | Problem | Fix | |---|---|---|---|---| | MEDIUM | HSTS_SHORT_MAX_AGE | Strict-Transport-Security | max-age=86400 (1 day) is short; protection lapses between visits | raise in steps (1 week, 1 month) to max-age=31536000 | | MEDIUM | XCTO_MISSING | X-Content-Type-Options | no nosniff: browsers may guess a different content type (e.g. run an upload as script) | X-Content-Type-Options: nosniff | | LOW | HSTS_NO_SUBDOMAINS | Strict-Transport-Security | subdomains are not covered (cookies scoped to the parent domain can leak over HTTP) | add includeSubDomains after checking every subdomain has HTTPS | | LOW | SERVER_VERSION_DISCLOSED | Server | Server: nginx/1.18.0 reveals the software version | hide the version (server_tokens off / ServerTokens Prod) | ## 4. https://api.shop.example.com/v1/me 200 (api), line 39 HIGH 1, MEDIUM 0, LOW 1 | Sev | Code | Header | Problem | Fix | |---|---|---|---|---| | HIGH | CORS_ORIGIN_REFLECTED | Access-Control-Allow-Origin | the server echoed the untrusted test Origin https://evil.example, so it trusts any site; with Allow-Credentials: true any site can read a logged-in user's data | compare Origin against an exact allowlist; never echo it unchecked | | LOW | CORS_NO_VARY_ORIGIN | Vary | per-origin Access-Control-Allow-Origin without Vary: Origin; a cache can serve one origin's answer to another | add Vary: Origin | ## Suggested baseline for HTML pages (adapt CSP hosts and nonces before enforcing) ``` Strict-Transport-Security: max-age=31536000; includeSubDomains Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{RANDOM}'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; form-action 'self' X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN Referrer-Policy: strict-origin-when-cross-origin Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=() Cross-Origin-Opener-Policy: same-origin Set-Cookie: __Host-session=...; Path=/; Secure; HttpOnly; SameSite=Lax ``` Offline check of captured headers only: TLS, the HSTS preload list, CSP in <meta> tags and server-side Origin allowlists were not tested. FILE:scripts/sec_headers.py #!/usr/bin/env python3 """HTTP security headers checker (Python 3.8+ standard library only). Reads HTTP response headers and reports security header problems: Strict-Transport-Security, Content-Security-Policy, frame-ancestors / X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy, Set-Cookie flags and prefixes, CORS (Access-Control-Allow-*), version disclosure and deprecated headers. Input (auto-detected): * curl output: `curl -sI URL`, `curl -sIL URL` (redirect chain = several blocks) or `curl -sv -o /dev/null URL 2>&1` ("< Header: value" lines, "> Origin:" request lines). Put "# https://example.com/path" on the line before a block to name its URL; later blocks of a redirect chain take their URL from the previous Location header. * HAR export from browser DevTools (log.entries[].request.url / response.headers). * a plain "Name: value" headers file (one response; give --url). Usage: python3 sec_headers.py headers.txt [--url https://example.com/] [--origin https://evil.example] [--min-severity LOW|MEDIUM|HIGH] [--ignore CODE,CODE] [--json] python3 sec_headers.py --self-test Exit codes: 0 = no HIGH findings, 1 = HIGH findings, 2 = bad input. No network calls are made; the checker only reads what you captured. """ import argparse import json import re import sys from urllib.parse import urljoin, urlsplit SEV_ORDER = {"LOW": 1, "MEDIUM": 2, "HIGH": 3} SESSION_HINT = re.compile(r"(sess|sid|auth|token|jwt|login|remember|csrf|xsrf|identity|account)", re.I) CSRF_HINT = re.compile(r"(csrf|xsrf)", re.I) # double-submit tokens must stay readable from JavaScript HSTS_MIN = 15552000 # 180 days HSTS_PRELOAD = 31536000 # 1 year PERMISSION_FEATURES = ("camera", "microphone", "geolocation", "payment", "usb") class Response: def __init__(self, url, status, headers, line, request_headers=None): self.url = url or "" self.status = status self.headers = headers # list of (name, value) in order self.line = line # line number of the status line (1-based), 0 for HAR self.request_headers = request_headers or {} def get_all(self, name): n = name.lower() return [v for k, v in self.headers if k.lower() == n] def get(self, name): vals = self.get_all(name) return vals[0] if vals else None @property def scheme(self): return urlsplit(self.url).scheme.lower() if self.url else "" @property def kind(self): if 300 <= self.status < 400: return "redirect" ct = (self.get("content-type") or "").lower() if "html" in ct: return "html" if "javascript" in ct or "ecmascript" in ct: return "script" if "css" in ct: return "style" if "json" in ct or "xml" in ct and "html" not in ct: return "api" if ct.startswith(("image/", "font/", "video/", "audio/")): return "asset" if not ct and self.status in (204,): return "api" return "other" if ct else "unknown" # ----------------------------------------------------------------------------- parsing STATUS_RE = re.compile(r"^\s*[<]?\s*HTTP/(\d(?:\.\d)?)\s+(\d{3})\b") URL_COMMENT_RE = re.compile(r"^\s*#+\s*(?:URL:\s*)?(https?://\S+)", re.I) HEADER_RE = re.compile(r"^\s*[<]?\s*([A-Za-z0-9!#$%&'*+.^_`|~-]+)\s*:\s?(.*)$") def parse_text(text, default_url=""): responses, cur, pending_url, req = [], None, default_url or "", {} req_line_host, req_path = None, None lines = text.splitlines() for i, raw in enumerate(lines, 1): line = raw.rstrip("\r") m = URL_COMMENT_RE.match(line) if m: if cur: responses.append(cur) cur = None pending_url = m.group(1) continue s = line.strip() if s.startswith(">"): # curl -v request line body = s[1:].strip() rm = re.match(r"^(GET|HEAD|POST|PUT|DELETE|OPTIONS|PATCH)\s+(\S+)", body) if rm: req_path = rm.group(2) req = {} hm = HEADER_RE.match(body) if hm and not rm: req[hm.group(1).lower()] = hm.group(2).strip() if hm.group(1).lower() == "host": req_line_host = hm.group(2).strip() continue if s.startswith("*") or s.startswith("{") or s.startswith("}"): continue sm = STATUS_RE.match(line) if sm: if cur: responses.append(cur) url = pending_url if not url and req_line_host and req_path: url = ("https://" if req_line_host else "") + req_line_host + req_path if not url and responses: loc = responses[-1].get("location") if loc: url = urljoin(responses[-1].url or "", loc) cur = Response(url, int(sm.group(2)), [], i, dict(req)) pending_url = "" continue if cur is None: hm = HEADER_RE.match(line) if hm and not s.startswith("#"): # headers-only file: synthesize a 200 cur = Response(pending_url, 200, [], 0, dict(req)) pending_url = "" else: continue if not s: continue hm = HEADER_RE.match(line) if hm: cur.headers.append((hm.group(1), hm.group(2).strip())) if cur: responses.append(cur) return responses def parse_har(data): out = [] for e in data.get("log", {}).get("entries", []): req = e.get("request", {}) res = e.get("response", {}) rh = {h["name"].lower(): h["value"] for h in req.get("headers", [])} hs = [(h["name"], h["value"]) for h in res.get("headers", [])] out.append(Response(req.get("url", ""), int(res.get("status", 0) or 0), hs, 0, rh)) return out def load(text, default_url=""): st = text.lstrip() if st.startswith("{"): try: data = json.loads(st) except ValueError as e: raise ValueError("looks like JSON but does not parse: %s" % e) if "log" not in data: raise ValueError("JSON input is not a HAR file (no 'log' key)") return parse_har(data) res = parse_text(text, default_url) if not res: raise ValueError("no HTTP responses found (expected 'HTTP/x 200' lines, a HAR file or 'Name: value' headers)") for r in res: if not r.url and default_url: r.url = default_url return res # ----------------------------------------------------------------------------- helpers def parse_csp(value): d = {} for part in value.split(";"): toks = part.strip().split() if not toks: continue name = toks[0].lower() if name not in d: # duplicates inside one policy: first wins d[name] = [t for t in toks[1:]] return d def parse_directives(value): out = {} for part in value.split(";"): part = part.strip() if not part: continue k, _, v = part.partition("=") out[k.strip().lower()] = v.strip().strip('"') return out def parse_cookie(value): parts = [p.strip() for p in value.split(";")] name, _, val = parts[0].partition("=") attrs = {} for p in parts[1:]: if not p: continue k, _, v = p.partition("=") attrs[k.strip().lower()] = v.strip() return name.strip(), val, attrs def _days(sec): d = sec / 86400.0 if d < 1: return "%.0f hours" % (sec / 3600.0) return "%g day%s" % (round(d, 1), "" if round(d, 1) == 1 else "s") def same_origin(a, b): try: x, y = urlsplit(a), urlsplit(b) except ValueError: return False return (x.scheme, x.hostname, x.port) == (y.scheme, y.hostname, y.port) # ----------------------------------------------------------------------------- checks def check(resp, test_origin=None): f = [] def add(sev, code, header, problem, fix): f.append({"severity": sev, "code": code, "header": header, "problem": problem, "fix": fix, "url": resp.url, "status": resp.status, "line": resp.line}) kind = resp.kind https = resp.scheme == "https" doc = kind in ("html", "unknown") # --- transport: HTTP -> HTTPS if resp.scheme == "http": loc = resp.get("location") or "" if not (300 <= resp.status < 400 and loc.lower().startswith("https://")): add("HIGH", "HTTP_NO_HTTPS_REDIRECT", "Location", "plain-HTTP response is served without redirecting to HTTPS", "answer every http:// request with 301/308 to the https:// URL") elif resp.status in (302, 303, 307): add("LOW", "HTTP_REDIRECT_TEMPORARY", "Location", "HTTP to HTTPS uses a temporary redirect (%d)" % resp.status, "use 301 or 308 so browsers and crawlers remember it") if resp.get("strict-transport-security"): add("LOW", "HSTS_ON_HTTP", "Strict-Transport-Security", "HSTS sent over plain HTTP is ignored by browsers", "send it on the HTTPS responses") # --- HSTS hsts_vals = resp.get_all("strict-transport-security") if https: if not hsts_vals: if kind != "asset" or resp.status < 300: add("HIGH" if doc or kind == "redirect" else "MEDIUM", "HSTS_MISSING", "Strict-Transport-Security", "no HSTS: the first visit or a typed http:// link can be downgraded or intercepted", "Strict-Transport-Security: max-age=31536000; includeSubDomains") else: if len(hsts_vals) > 1: add("LOW", "DUPLICATE_HEADER", "Strict-Transport-Security", "%d HSTS headers; browsers use only the first" % len(hsts_vals), "send exactly one") d = parse_directives(hsts_vals[0]) ma = d.get("max-age") if ma is None or not ma.isdigit(): add("HIGH", "HSTS_INVALID", "Strict-Transport-Security", "max-age missing or not a number, so the header is ignored", "max-age=31536000; includeSubDomains") else: ma = int(ma) if ma == 0: add("MEDIUM", "HSTS_DISABLED", "Strict-Transport-Security", "max-age=0 clears HSTS (only correct while deliberately rolling it back)", "max-age=31536000 once every subdomain serves HTTPS") elif ma < HSTS_MIN: add("MEDIUM", "HSTS_SHORT_MAX_AGE", "Strict-Transport-Security", "max-age=%d (%s) is short; protection lapses between visits" % (ma, _days(ma)), "raise in steps (1 week, 1 month) to max-age=31536000") if "includesubdomains" not in d and ma: add("LOW", "HSTS_NO_SUBDOMAINS", "Strict-Transport-Security", "subdomains are not covered (cookies scoped to the parent domain can leak over HTTP)", "add includeSubDomains after checking every subdomain has HTTPS") if "preload" in d and (ma < HSTS_PRELOAD or "includesubdomains" not in d): add("LOW", "HSTS_PRELOAD_INCOMPLETE", "Strict-Transport-Security", "preload is set but the list requires max-age>=31536000 and includeSubDomains", "max-age=63072000; includeSubDomains; preload (only if you mean to preload)") # --- CSP csp_vals = resp.get_all("content-security-policy") csp_ro = resp.get_all("content-security-policy-report-only") frame_ancestors = None if csp_vals: merged = {} for v in csp_vals: for k, toks in parse_csp(v).items(): merged.setdefault(k, toks) if "frame-ancestors" in merged: frame_ancestors = merged["frame-ancestors"] if doc: if not csp_vals: if csp_ro: add("MEDIUM", "CSP_REPORT_ONLY", "Content-Security-Policy-Report-Only", "CSP is only in report-only mode; nothing is blocked", "after reports are clean, send the same policy as Content-Security-Policy") else: add("MEDIUM", "CSP_MISSING", "Content-Security-Policy", "no Content-Security-Policy: an injected <script> runs with full page access", "start with a report-only policy (see the suggested header set), then enforce") else: for v in csp_vals: d = parse_csp(v) script = d.get("script-src", d.get("default-src")) src_name = "script-src" if "script-src" in d else "default-src" if script is None: add("HIGH", "CSP_NO_SCRIPT_RESTRICTION", "Content-Security-Policy", "policy has neither script-src nor default-src, so scripts are not restricted", "add default-src 'self' and a script-src") else: low = [t.lower() for t in script] has_nonce = any(t.startswith(("'nonce-", "'sha256-", "'sha384-", "'sha512-")) for t in low) strict = "'strict-dynamic'" in low wild = [t for t in low if t in ("*", "http:", "https:", "data:", "blob:") or t.startswith("http://")] if wild and not strict: add("HIGH", "CSP_WILDCARD_SCRIPT", "Content-Security-Policy", "%s allows %s, so scripts load from anywhere" % (src_name, " ".join(wild)), "list exact hosts or use nonces with 'strict-dynamic'") if "'unsafe-inline'" in low and not has_nonce: add("MEDIUM", "CSP_UNSAFE_INLINE", "Content-Security-Policy", "%s has 'unsafe-inline' without a nonce/hash: inline XSS is not blocked" % src_name, "move inline scripts to files or add nonces/hashes") if "'unsafe-eval'" in low: add("MEDIUM", "CSP_UNSAFE_EVAL", "Content-Security-Policy", "%s has 'unsafe-eval' (eval/new Function allowed)" % src_name, "remove it; replace eval-based libraries or templates") obj = d.get("object-src", d.get("default-src")) if obj is None or [t.lower() for t in obj] != ["'none'"]: add("LOW", "CSP_OBJECT_SRC", "Content-Security-Policy", "object-src is not 'none' (plugins/embeds can bypass script rules)", "add object-src 'none'") if "base-uri" not in d: add("LOW", "CSP_NO_BASE_URI", "Content-Security-Policy", "no base-uri: an injected <base> tag can redirect relative script URLs", "add base-uri 'self' (or 'none')") # --- clickjacking xfo_vals = resp.get_all("x-frame-options") if doc: if frame_ancestors is None and not xfo_vals: add("MEDIUM", "CLICKJACKING_UNPROTECTED", "X-Frame-Options / frame-ancestors", "page can be framed by any site (clickjacking)", "Content-Security-Policy: frame-ancestors 'self' (and X-Frame-Options: SAMEORIGIN for old browsers)") elif frame_ancestors is not None and any(t in ("*", "https:", "http:") for t in frame_ancestors): add("MEDIUM", "FRAME_ANCESTORS_WILDCARD", "Content-Security-Policy", "frame-ancestors %s allows framing by any site" % " ".join(frame_ancestors), "frame-ancestors 'self' plus the exact partner origins") if xfo_vals: if len(xfo_vals) > 1 or "," in xfo_vals[0]: add("MEDIUM", "XFO_INVALID", "X-Frame-Options", "several X-Frame-Options values; some browsers then ignore the header", "send one value") v = xfo_vals[0].strip().upper() if v.startswith("ALLOW-FROM"): add("MEDIUM" if frame_ancestors is None else "LOW", "XFO_ALLOW_FROM", "X-Frame-Options", "ALLOW-FROM is not supported by current browsers (treated as no protection)", "use CSP frame-ancestors 'self' https://partner.example") elif v not in ("DENY", "SAMEORIGIN") and "," not in v: add("MEDIUM", "XFO_INVALID", "X-Frame-Options", "unknown value %r is ignored" % xfo_vals[0], "DENY or SAMEORIGIN") # --- nosniff xcto = resp.get("x-content-type-options") if kind != "redirect": if xcto is None: add("MEDIUM" if kind in ("script", "style", "api") else "LOW", "XCTO_MISSING", "X-Content-Type-Options", "no nosniff: browsers may guess a different content type (e.g. run an upload as script)", "X-Content-Type-Options: nosniff") elif xcto.strip().lower() != "nosniff": add("LOW", "XCTO_INVALID", "X-Content-Type-Options", "value %r is ignored" % xcto, "X-Content-Type-Options: nosniff") # --- Referrer-Policy if doc: rp = resp.get("referrer-policy") if rp is None: add("LOW", "REFERRER_POLICY_MISSING", "Referrer-Policy", "no Referrer-Policy (modern browsers default to strict-origin-when-cross-origin; older ones send full URLs)", "Referrer-Policy: strict-origin-when-cross-origin") else: last = [t.strip().lower() for t in rp.split(",") if t.strip()][-1:] # last valid token wins if last and last[0] in ("unsafe-url", "no-referrer-when-downgrade"): add("MEDIUM", "REFERRER_POLICY_UNSAFE", "Referrer-Policy", "%s sends full URLs (paths, query tokens) to other sites" % last[0], "strict-origin-when-cross-origin (or no-referrer)") # --- Permissions-Policy if doc: pp = resp.get("permissions-policy") fp = resp.get("feature-policy") if pp is None and fp is not None: add("LOW", "FEATURE_POLICY_ONLY", "Feature-Policy", "only the old Feature-Policy header is sent; current browsers read Permissions-Policy", "Permissions-Policy: camera=(), microphone=(), geolocation=()") elif pp is None: add("LOW", "PERMISSIONS_POLICY_MISSING", "Permissions-Policy", "powerful features (camera, microphone, geolocation) are not switched off for embedded content", "Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()") elif re.search(r"\b[a-z-]+\s+'(none|self)'", pp): add("LOW", "PERMISSIONS_POLICY_SYNTAX", "Permissions-Policy", "uses Feature-Policy syntax (camera 'none'); Permissions-Policy needs camera=()", "rewrite as feature=() / feature=(self)") elif re.search(r"\b(%s)=\*" % "|".join(PERMISSION_FEATURES), pp): add("LOW", "PERMISSIONS_POLICY_WILDCARD", "Permissions-Policy", "a powerful feature is allowed for every origin (=*)", "use =(self) or =()") # --- COOP (only meaningful for top-level documents) if doc and https and resp.status < 300 and resp.get("cross-origin-opener-policy") is None: add("LOW", "COOP_MISSING", "Cross-Origin-Opener-Policy", "pages opened with window.open keep a handle to this window (tabnabbing/XS-leaks)", "Cross-Origin-Opener-Policy: same-origin (same-origin-allow-popups if you use OAuth/payment pop-ups)") # --- cookies for raw in resp.get_all("set-cookie"): name, val, a = parse_cookie(raw) sessionish = bool(SESSION_HINT.search(name)) deleting = a.get("max-age") == "0" or "1970" in a.get("expires", "") if deleting: continue ss = a.get("samesite", "").lower() prefix_bad = False if name.startswith("__Host-") and ("secure" not in a or a.get("path") != "/" or "domain" in a): add("HIGH", "COOKIE_PREFIX_VIOLATION", "Set-Cookie", "%s: __Host- cookies need Secure, Path=/ and no Domain, so the browser rejects this one" % name, "Set-Cookie: %s=...; Path=/; Secure; SameSite=Lax (no Domain)" % name) prefix_bad = True elif name.startswith("__Secure-") and "secure" not in a: add("HIGH", "COOKIE_PREFIX_VIOLATION", "Set-Cookie", "%s: __Secure- cookies need the Secure flag, so the browser rejects this one" % name, "add Secure") prefix_bad = True if ss == "none" and "secure" not in a: add("HIGH", "COOKIE_SAMESITE_NONE_NO_SECURE", "Set-Cookie", "%s: SameSite=None without Secure is rejected by browsers" % name, "add Secure (HTTPS only)") elif https and "secure" not in a and not prefix_bad: add("HIGH" if sessionish else "MEDIUM", "COOKIE_NO_SECURE", "Set-Cookie", "%s: no Secure flag, the cookie is also sent over plain HTTP" % name, "add Secure") if sessionish and "httponly" not in a and not CSRF_HINT.search(name): add("MEDIUM", "COOKIE_NO_HTTPONLY", "Set-Cookie", "%s looks like a session/auth cookie but is readable from JavaScript (XSS can steal it)" % name, "add HttpOnly (unless the front end must read it, e.g. a double-submit CSRF token)") if not ss: add("LOW", "COOKIE_NO_SAMESITE", "Set-Cookie", "%s: no SameSite attribute (browsers apply Lax by default, older ones send it cross-site)" % name, "set SameSite=Lax explicitly (Strict for admin areas)") if "domain" in a and sessionish and not prefix_bad: add("LOW", "COOKIE_BROAD_DOMAIN", "Set-Cookie", "%s is shared with every subdomain of %s" % (name, a["domain"].lstrip(".")), "drop Domain= (host-only) or use the __Host- prefix") # --- CORS acao = resp.get("access-control-allow-origin") acac = (resp.get("access-control-allow-credentials") or "").strip().lower() == "true" req_origin = resp.request_headers.get("origin") or test_origin if acao is not None: a = acao.strip() if a == "*" and acac: add("MEDIUM", "CORS_WILDCARD_WITH_CREDENTIALS", "Access-Control-Allow-Origin", "'*' with Allow-Credentials: true is invalid (browsers block it); it usually means someone will " "'fix' it by reflecting the Origin", "return an allowlisted origin, or drop credentials for public data") elif a.lower() == "null": add("HIGH" if acac else "MEDIUM", "CORS_NULL_ORIGIN", "Access-Control-Allow-Origin", "allows the 'null' origin, which sandboxed iframes and local files can send", "never allowlist null") elif a == "*": if kind == "api" or acac or resp.get_all("set-cookie"): add("LOW", "CORS_WILDCARD", "Access-Control-Allow-Origin", "any site may read this response; fine for public data, not for anything per-user", "allowlist origins if the endpoint ever returns user data") else: if req_origin and a == req_origin and not same_origin(a, resp.url): untrusted = test_origin is not None and a == test_origin add("HIGH" if (acac and untrusted) else ("MEDIUM" if untrusted else "LOW"), "CORS_ORIGIN_REFLECTED" if untrusted else "CORS_ORIGIN_ECHO", "Access-Control-Allow-Origin", ("the server echoed the untrusted test Origin %s, so it trusts any site%s" % (a, "; with Allow-Credentials: true any site can read a logged-in user's data" if acac else "")) if untrusted else "Origin %s was echoed; confirm it is on an allowlist (retest with --origin https://evil.example)" % a, "compare Origin against an exact allowlist; never echo it unchecked") vary = ",".join(resp.get_all("vary")).lower() if "origin" not in vary and "*" not in vary: add("LOW", "CORS_NO_VARY_ORIGIN", "Vary", "per-origin Access-Control-Allow-Origin without Vary: Origin; a cache can serve one origin's answer to another", "add Vary: Origin") if acac and a not in ("*",) and a.lower().startswith("http://"): add("MEDIUM", "CORS_HTTP_ORIGIN_TRUSTED", "Access-Control-Allow-Origin", "credentials are shared with a plain-HTTP origin (%s), which a network attacker can impersonate" % a, "allow only https:// origins") methods = (resp.get("access-control-allow-methods") or "") hdrs = (resp.get("access-control-allow-headers") or "") if methods.strip() == "*" and acac or hdrs.strip() == "*" and acac: add("LOW", "CORS_WILDCARD_METHODS", "Access-Control-Allow-Methods/Headers", "'*' is treated literally when credentials are allowed", "list the methods/headers explicitly") # --- disclosure and deprecated headers srv = resp.get("server") if srv and re.search(r"\d", srv): add("LOW", "SERVER_VERSION_DISCLOSED", "Server", "Server: %s reveals the software version" % srv, "hide the version (server_tokens off / ServerTokens Prod)") for h in ("x-powered-by", "x-aspnet-version", "x-aspnetmvc-version", "x-generator"): v = resp.get(h) if v: add("LOW", "TECH_DISCLOSED", h.title(), "%s: %s reveals the stack" % (h.title(), v), "remove the header") xx = resp.get("x-xss-protection") if xx and not xx.strip().startswith("0"): add("LOW", "X_XSS_PROTECTION_DEPRECATED", "X-XSS-Protection", "the XSS auditor is gone from browsers; '1; mode=block' can even create leaks in old ones", "remove it or send X-XSS-Protection: 0, rely on CSP") if resp.get("public-key-pins") or resp.get("public-key-pins-report-only"): add("MEDIUM", "HPKP_DEPRECATED", "Public-Key-Pins", "HPKP is removed from browsers and risky if any client still honours it", "remove the header") if resp.get("expect-ct"): add("LOW", "EXPECT_CT_DEPRECATED", "Expect-CT", "Expect-CT is obsolete", "remove the header") return f SUGGESTED = [ "Strict-Transport-Security: max-age=31536000; includeSubDomains", "Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{RANDOM}'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; form-action 'self'", "X-Content-Type-Options: nosniff", "X-Frame-Options: SAMEORIGIN", "Referrer-Policy: strict-origin-when-cross-origin", "Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()", "Cross-Origin-Opener-Policy: same-origin", "Set-Cookie: __Host-session=...; Path=/; Secure; HttpOnly; SameSite=Lax", ] PRESENCE = [("HSTS", "strict-transport-security"), ("CSP", "content-security-policy"), ("XFO", "x-frame-options"), ("nosniff", "x-content-type-options"), ("Referrer", "referrer-policy"), ("Permissions", "permissions-policy"), ("COOP", "cross-origin-opener-policy")] def run(responses, test_origin=None, min_sev="LOW", ignore=()): out = [] for r in responses: fs = [x for x in check(r, test_origin) if SEV_ORDER[x["severity"]] >= SEV_ORDER[min_sev] and x["code"] not in ignore] fs.sort(key=lambda x: -SEV_ORDER[x["severity"]]) out.append((r, fs)) return out def counts(fs): c = {"HIGH": 0, "MEDIUM": 0, "LOW": 0} for x in fs: c[x["severity"]] += 1 return c def render_md(results, source): allf = [x for _, fs in results for x in fs] c = counts(allf) o = ["# HTTP security headers: %s" % source, "", "Responses: %d Findings: %d (HIGH %d, MEDIUM %d, LOW %d)" % (len(results), len(allf), c["HIGH"], c["MEDIUM"], c["LOW"]), "", "| # | URL | Status | Kind | " + " | ".join(p[0] for p in PRESENCE) + " | Cookies | CORS |", "|---|---|---|---|" + "---|" * len(PRESENCE) + "---|---|"] for i, (r, fs) in enumerate(results, 1): cells = [] for _, h in PRESENCE: cells.append("yes" if r.get(h) is not None else "-") if "frame-ancestors" in (r.get("content-security-policy") or "") and cells[2] == "-": cells[2] = "CSP" ck = len(r.get_all("set-cookie")) cors = r.get("access-control-allow-origin") or "-" o.append("| %d | %s | %d | %s | %s | %s | %s |" % (i, r.url or "(unknown)", r.status, r.kind, " | ".join(cells), ck or "-", cors)) for i, (r, fs) in enumerate(results, 1): cc = counts(fs) o += ["", "## %d. %s %d (%s)%s" % (i, r.url or "(unknown URL)", r.status, r.kind, ", line %d" % r.line if r.line else ""), ""] if not fs: o.append("No findings.") continue o.append("HIGH %d, MEDIUM %d, LOW %d" % (cc["HIGH"], cc["MEDIUM"], cc["LOW"])) o += ["", "| Sev | Code | Header | Problem | Fix |", "|---|---|---|---|---|"] for x in fs: o.append("| %s | %s | %s | %s | %s |" % (x["severity"], x["code"], x["header"], x["problem"].replace("|", "/"), x["fix"].replace("|", "/"))) if any(r.kind in ("html", "unknown") and fs for r, fs in results): o += ["", "## Suggested baseline for HTML pages (adapt CSP hosts and nonces before enforcing)", "", "```"] + SUGGESTED + ["```"] o += ["", "Offline check of captured headers only: TLS, the HSTS preload list, CSP in <meta> tags and " "server-side Origin allowlists were not tested."] return "\n".join(o) + "\n" # ----------------------------------------------------------------------------- self-test def self_test(): cases = [] def codes(text, url="https://example.com/", origin=None): rs = load(text, url) return [x["code"] for _, fs in run(rs, origin) for x in fs] def case(name, fn): try: ok = bool(fn()) err = "" except Exception as e: # noqa ok, err = False, repr(e) cases.append((name, ok, err)) good = ("HTTP/2 200\ncontent-type: text/html; charset=utf-8\n" "strict-transport-security: max-age=31536000; includeSubDomains\n" "content-security-policy: default-src 'self'; script-src 'self' 'nonce-abc'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'\n" "x-content-type-options: nosniff\nreferrer-policy: strict-origin-when-cross-origin\n" "permissions-policy: camera=(), microphone=(), geolocation=()\ncross-origin-opener-policy: same-origin\n" "set-cookie: __Host-sid=abc; Path=/; Secure; HttpOnly; SameSite=Lax\n") H = "HTTP/2 200\ncontent-type: text/html\n" case("hardened page is clean", lambda: codes(good) == []) case("missing everything on html", lambda: {"HSTS_MISSING", "CSP_MISSING", "CLICKJACKING_UNPROTECTED", "XCTO_MISSING", "REFERRER_POLICY_MISSING", "PERMISSIONS_POLICY_MISSING", "COOP_MISSING"} <= set(codes(H))) case("HSTS missing is HIGH on html", lambda: [x for _, fs in run(load(H, "https://a.test/")) for x in fs if x["code"] == "HSTS_MISSING"][0]["severity"] == "HIGH") case("HSTS short max-age", lambda: "HSTS_SHORT_MAX_AGE" in codes(H + "strict-transport-security: max-age=86400\n")) case("HSTS invalid", lambda: "HSTS_INVALID" in codes(H + "strict-transport-security: includeSubDomains\n")) case("HSTS max-age=0", lambda: "HSTS_DISABLED" in codes(H + "strict-transport-security: max-age=0\n")) case("HSTS no subdomains", lambda: "HSTS_NO_SUBDOMAINS" in codes(H + "strict-transport-security: max-age=31536000\n")) case("HSTS preload incomplete", lambda: "HSTS_PRELOAD_INCOMPLETE" in codes(H + "strict-transport-security: max-age=31536000; preload\n")) case("HSTS ignored on http", lambda: "HSTS_ON_HTTP" in codes("HTTP/1.1 301 Moved\nlocation: https://a.test/\nstrict-transport-security: max-age=31536000\n", "http://a.test/")) case("http without https redirect", lambda: "HTTP_NO_HTTPS_REDIRECT" in codes(H, "http://a.test/")) case("http 302 to https is temporary", lambda: "HTTP_REDIRECT_TEMPORARY" in codes("HTTP/1.1 302 Found\nlocation: https://a.test/\n", "http://a.test/")) case("http 301 to https ok", lambda: codes("HTTP/1.1 301 Moved\nlocation: https://a.test/\n", "http://a.test/") == []) case("CSP report-only", lambda: "CSP_REPORT_ONLY" in codes(H + "content-security-policy-report-only: default-src 'self'\n")) case("CSP unsafe-inline", lambda: "CSP_UNSAFE_INLINE" in codes(H + "content-security-policy: default-src 'self'; script-src 'self' 'unsafe-inline'\n")) case("CSP unsafe-inline with nonce ok", lambda: "CSP_UNSAFE_INLINE" not in codes(H + "content-security-policy: script-src 'nonce-x' 'unsafe-inline'\n")) case("CSP unsafe-eval", lambda: "CSP_UNSAFE_EVAL" in codes(H + "content-security-policy: default-src 'self' 'unsafe-eval'\n")) case("CSP wildcard https:", lambda: "CSP_WILDCARD_SCRIPT" in codes(H + "content-security-policy: script-src 'self' https:\n")) case("CSP strict-dynamic tolerates https:", lambda: "CSP_WILDCARD_SCRIPT" not in codes(H + "content-security-policy: script-src 'nonce-x' 'strict-dynamic' https:\n")) case("CSP without script restriction", lambda: "CSP_NO_SCRIPT_RESTRICTION" in codes(H + "content-security-policy: img-src 'self'\n")) case("CSP object-src and base-uri", lambda: {"CSP_OBJECT_SRC", "CSP_NO_BASE_URI"} <= set(codes(H + "content-security-policy: script-src 'self'\n"))) case("frame-ancestors satisfies clickjacking", lambda: "CLICKJACKING_UNPROTECTED" not in codes(H + "content-security-policy: default-src 'self'; frame-ancestors 'none'\n")) case("frame-ancestors wildcard", lambda: "FRAME_ANCESTORS_WILDCARD" in codes(H + "content-security-policy: default-src 'self'; frame-ancestors *\n")) case("XFO ALLOW-FROM", lambda: "XFO_ALLOW_FROM" in codes(H + "x-frame-options: ALLOW-FROM https://p.test\n")) case("XFO duplicate", lambda: "XFO_INVALID" in codes(H + "x-frame-options: DENY\nx-frame-options: SAMEORIGIN\n")) case("nosniff MEDIUM on script", lambda: [x["severity"] for _, fs in run(load("HTTP/2 200\ncontent-type: application/javascript\n", "https://a.test/a.js")) for x in fs if x["code"] == "XCTO_MISSING"] == ["MEDIUM"]) case("nosniff wrong value", lambda: "XCTO_INVALID" in codes(H + "x-content-type-options: yes\n")) case("referrer unsafe-url", lambda: "REFERRER_POLICY_UNSAFE" in codes(H + "referrer-policy: unsafe-url\n")) case("referrer last token wins", lambda: "REFERRER_POLICY_UNSAFE" not in codes(H + "referrer-policy: unsafe-url, strict-origin-when-cross-origin\n")) case("feature-policy only", lambda: "FEATURE_POLICY_ONLY" in codes(H + "feature-policy: camera 'none'\n")) case("permissions-policy old syntax", lambda: "PERMISSIONS_POLICY_SYNTAX" in codes(H + "permissions-policy: camera 'none'\n")) case("permissions-policy wildcard", lambda: "PERMISSIONS_POLICY_WILDCARD" in codes(H + "permissions-policy: geolocation=*\n")) case("cookie no secure session HIGH", lambda: [x["severity"] for _, fs in run(load(H + "set-cookie: sessionid=1; HttpOnly; SameSite=Lax\n", "https://a.test/")) for x in fs if x["code"] == "COOKIE_NO_SECURE"] == ["HIGH"]) case("cookie no httponly", lambda: "COOKIE_NO_HTTPONLY" in codes(H + "set-cookie: auth_token=1; Secure; SameSite=Lax\n")) case("cookie no samesite", lambda: "COOKIE_NO_SAMESITE" in codes(H + "set-cookie: theme=dark; Secure\n")) case("cookie samesite none no secure", lambda: "COOKIE_SAMESITE_NONE_NO_SECURE" in codes(H + "set-cookie: tid=1; SameSite=None\n")) case("cookie __Host- with Domain", lambda: "COOKIE_PREFIX_VIOLATION" in codes(H + "set-cookie: __Host-sid=1; Path=/; Secure; Domain=a.test\n")) case("cookie __Secure- without Secure", lambda: "COOKIE_PREFIX_VIOLATION" in codes(H + "set-cookie: __Secure-x=1; Path=/\n")) case("csrf cookie may be JS-readable", lambda: "COOKIE_NO_HTTPONLY" not in codes(H + "set-cookie: csrftoken=1; Secure; SameSite=Lax\n")) case("prefix violation not double-reported", lambda: codes(good.replace("Path=/; Secure; HttpOnly", "Path=/; Domain=a.test; HttpOnly")).count("COOKIE_PREFIX_VIOLATION") == 1 and "COOKIE_NO_SECURE" not in codes(good.replace("Path=/; Secure; HttpOnly", "Path=/; HttpOnly"))) case("max-age wording", lambda: _days(86400) == "1 day" and _days(604800) == "7 days") case("cookie broad domain", lambda: "COOKIE_BROAD_DOMAIN" in codes(H + "set-cookie: session=1; Domain=.a.test; Secure; HttpOnly; SameSite=Lax\n")) case("deleted cookie ignored", lambda: not any(c.startswith("COOKIE") for c in codes(H + "set-cookie: session=; Max-Age=0\n"))) J = "HTTP/2 200\ncontent-type: application/json\nx-content-type-options: nosniff\nstrict-transport-security: max-age=31536000; includeSubDomains\n" case("api json not checked for CSP", lambda: "CSP_MISSING" not in codes(J)) case("cors * with credentials", lambda: "CORS_WILDCARD_WITH_CREDENTIALS" in codes(J + "access-control-allow-origin: *\naccess-control-allow-credentials: true\n")) case("cors null origin", lambda: "CORS_NULL_ORIGIN" in codes(J + "access-control-allow-origin: null\naccess-control-allow-credentials: true\n")) case("cors reflected test origin HIGH", lambda: [x["severity"] for _, fs in run(load(J + "access-control-allow-origin: https://evil.example\naccess-control-allow-credentials: true\nvary: Origin\n", "https://api.a.test/me"), "https://evil.example") for x in fs if x["code"] == "CORS_ORIGIN_REFLECTED"] == ["HIGH"]) case("cors request origin from curl -v", lambda: "CORS_ORIGIN_ECHO" in codes("> GET /me HTTP/2\n> Host: api.a.test\n> Origin: https://app.a.test\n" + "\n".join("< " + l for l in (J + "access-control-allow-origin: https://app.a.test\nvary: Origin").splitlines()) + "\n", "")) case("cors no vary origin", lambda: "CORS_NO_VARY_ORIGIN" in codes(J + "access-control-allow-origin: https://app.a.test\n")) case("cors http origin with credentials", lambda: "CORS_HTTP_ORIGIN_TRUSTED" in codes(J + "access-control-allow-origin: http://app.a.test\naccess-control-allow-credentials: true\nvary: Origin\n")) case("cors * public api LOW only", lambda: [x["severity"] for _, fs in run(load(J + "access-control-allow-origin: *\n", "https://a.test/api")) for x in fs] == ["LOW"]) case("server version", lambda: "SERVER_VERSION_DISCLOSED" in codes(H + "server: nginx/1.18.0\n")) case("server without version ok", lambda: "SERVER_VERSION_DISCLOSED" not in codes(H + "server: nginx\n")) case("x-powered-by", lambda: "TECH_DISCLOSED" in codes(H + "x-powered-by: Express\n")) case("x-xss-protection 1", lambda: "X_XSS_PROTECTION_DEPRECATED" in codes(H + "x-xss-protection: 1; mode=block\n")) case("x-xss-protection 0 ok", lambda: "X_XSS_PROTECTION_DEPRECATED" not in codes(H + "x-xss-protection: 0\n")) case("hpkp", lambda: "HPKP_DEPRECATED" in codes(H + "public-key-pins: pin-sha256=\"x\"; max-age=10\n")) case("redirect chain urls from Location", lambda: [r.url for r in load("# http://a.test/\nHTTP/1.1 301 Moved\nLocation: https://a.test/\n\nHTTP/2 200\ncontent-type: text/html\n")] == ["http://a.test/", "https://a.test/"]) case("relative Location resolved", lambda: load("# https://a.test/old\nHTTP/2 302\nlocation: /new\n\nHTTP/2 200\n")[1].url == "https://a.test/new") case("headers-only file", lambda: len(load("Content-Type: text/html\nX-Frame-Options: DENY\n", "https://a.test/")) == 1) case("CRLF input", lambda: load("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n", "https://a.test/")[0].get("content-type") == "text/html") har = json.dumps({"log": {"entries": [{"request": {"url": "https://a.test/", "headers": []}, "response": {"status": 200, "headers": [{"name": "content-type", "value": "text/html"}]}}]}}) case("HAR input", lambda: "CSP_MISSING" in codes(har)) case("bad JSON rejected", lambda: _raises(lambda: load('{"nope": 1}'))) case("empty input rejected", lambda: _raises(lambda: load("hello world\n"))) case("ignore and min-severity", lambda: all(x["severity"] == "HIGH" and x["code"] != "HSTS_MISSING" for _, fs in run(load(H, "https://a.test/"), None, "HIGH", {"HSTS_MISSING"}) for x in fs)) case("markdown render", lambda: "Suggested baseline" in render_md(run(load(H, "https://a.test/")), "t")) passed = sum(1 for _, ok, _ in cases if ok) for name, ok, err in cases: print(("PASS " if ok else "FAIL ") + name + ((" " + err) if err else "")) print("%d/%d passed" % (passed, len(cases))) return 0 if passed == len(cases) else 1 def _raises(fn): try: fn() except ValueError: return True return False def main(argv=None): ap = argparse.ArgumentParser(description="Check HTTP security response headers (offline).") ap.add_argument("file", nargs="?", help="curl -I/-IL/-v output, HAR file or headers file ('-' = stdin)") ap.add_argument("--url", default="", help="URL of the first response if the file does not name it") ap.add_argument("--origin", default=None, help="the untrusted Origin you sent in a CORS test (e.g. https://evil.example)") ap.add_argument("--min-severity", default="LOW", choices=["LOW", "MEDIUM", "HIGH"]) ap.add_argument("--ignore", default="", help="comma-separated finding codes to skip") ap.add_argument("--json", action="store_true", help="print JSON instead of markdown") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.file: ap.error("give a headers file or --self-test") try: text = sys.stdin.read() if a.file == "-" else open(a.file, encoding="utf-8", errors="replace").read() responses = load(text, a.url) except (OSError, ValueError) as e: print("error: %s" % e, file=sys.stderr) return 2 ignore = {c.strip() for c in a.ignore.split(",") if c.strip()} results = run(responses, a.origin, a.min_severity, ignore) if a.json: print(json.dumps({"responses": [{"url": r.url, "status": r.status, "kind": r.kind, "findings": fs} for r, fs in results]}, indent=2)) else: sys.stdout.write(render_md(results, "-" if a.file == "-" else a.file.split("/")[-1])) return 1 if any(x["severity"] == "HIGH" for _, fs in results for x in fs) else 0 if __name__ == "__main__": sys.exit(main())

Shared Expense Bill Splitter and Settle-Up Planner

--- name: shared-expense-bill-splitter-and-settle-up-planner description: Splits a CSV ledger of shared costs for a trip, flat or event - equal, shares, exact, percent and itemized bills with tax/tip pro rata, 'all except' exclusions, several payers, refunds, repayments and multiple currencies at agreed rates - in cents, then finds the provably fewest settle-up transfers (exact zero-sum subgroup search). Returns balances, a per-person audit and a chat message. Includes a stdlib Python planner with --self-test. --- # Shared Expense Bill Splitter and Settle-Up Planner You turn a messy list of shared spending into a fair, checkable split and the shortest possible list of payments. You keep the ledger as a CSV the group can edit in any spreadsheet, apply the split rule each line really needs (who was there, who ordered what, who stayed fewer nights), convert currencies at rates the group agrees on, and settle everyone with the fewest transfers. Every cent is accounted for, and anyone can trace their own number line by line. ## Files in this skill - `scripts/settle_up.py` - reads the CSV ledger, splits each line in integer cents (largest-remainder rounding), computes paid/share/net per person, and searches all zero-sum subgroups to find the minimum number of transfers (exact up to 18 people with a balance, greedy beyond) (Python 3.8+ standard library only) - `references/split-methods.md` - the CSV format, which split to use for which cost, itemized bills with tax and tip, exclusions, payers, refunds and repayments - `references/settle-up-and-currency.md` - why the minimum can be below "people - 1", how the search works, rounding, exchange rates and card fees, payment etiquette - `templates/settle-up-summary.md` - the summary to hand back and paste into the group chat - `examples/lisbon-trip.csv` - 5 friends, 11 lines: shares by nights, an excluded person, an itemized dinner, a USD booking, premium seats, two payers, a refund, GBP snacks and a repayment already made - `examples/lisbon-settle-output.md` - the real output of the planner on that ledger - `examples/flat-october.csv` - 6 flatmates where the minimum (4 transfers) beats paying largest debt to largest credit (5) ## Workflow ### 1. Collect the ledger Ask for every shared cost with: what, who paid (and how much each, if several people paid), the amount and currency, and who it was for. Ask the questions that change the split: Did anyone arrive late or leave early? Did anyone skip a meal or an activity? Was a dinner shared or ordered individually? Has anyone already paid someone back? Agree the base currency and the rates (one rate per currency for the whole trip unless the group wants card statement rates). Write it as the CSV in `references/split-methods.md`, with `# people:` so typos in names are caught. ### 2. Run the planner ``` python3 scripts/settle_up.py examples/lisbon-trip.csv python3 scripts/settle_up.py flat.csv --base GBP --rates EUR=0.86 --detail Ben python3 scripts/settle_up.py ledger.csv --json python3 scripts/settle_up.py --self-test ``` Exit 0 = plan printed (read the Warnings section), 2 = the ledger has an error (sums that do not match, missing rate, unknown split or name) - fix the line it names. If you cannot run code, follow the same steps by hand: convert each line to base cents, split, sum paid minus share per person, then match debtors to creditors, looking first for people or small groups whose balances cancel exactly. ### 3. Check the result with the group - The check line must read `nets add up to 0.00`; paid and shares must be equal. - Read the balances aloud in plain words ("Ana paid 990.00, her share is 377.31 and Eli already gave her 100.00, so she gets back 512.69"). - Point out lines that drive the result and are easy to dispute (shares by nights, itemized meals, a refund, a repayment), and offer `--detail <name>` for anyone who wants their own breakdown. - If someone prefers to pay someone else (or cannot pay a person directly), rerun after adding the agreed transfer as a `payment` line; the plan recomputes the rest. ### 4. Deliver Fill `templates/settle-up-summary.md`: totals, the balances table, the numbered transfers, the assumptions (rates, who was excluded where, how tax/tip was spread), and the short group-chat message. Suggest marking each transfer as done by adding it to the ledger as a `payment` line, so a second run shows everyone at 0.00. ## Example result On `examples/lisbon-trip.csv` (5 people, 1,583.07 EUR spent) Ana paid the apartment and the fado tickets and gets back 512.69 EUR; the plan is 4 transfers: Ben pays Ana 243.17, Dara pays Ana 140.94, Eli pays Ana 128.58 and Eli pays Cem 0.85 (Eli's earlier 100.00 repayment is already counted). On `examples/flat-october.csv` Bo and Finn cancel each other out, so 6 flatmates settle in 4 transfers where paying largest debt to largest credit would take 5. ## Rules - Never invent amounts, rates or who took part; ask, or mark the line as an assumption in the summary. - Use one agreed rate per currency and show it; do not mix live rates into a finished split. - Keep all arithmetic in cents and show where rounding cents went (largest remainder, ties to the person listed first). - Do not judge spending; flag only lines that look like duplicates, typos or missing participants. - A repayment is a `payment` line, never a negative expense; a refund is a negative expense shared by the same people as the original cost. - Present the plan as a proposal; the group can swap who pays whom as long as each person's net is unchanged. FILE:references/split-methods.md # Split methods and CSV format ## Columns `date,description,paid_by,amount,currency,split,participants,details` - header row required; any spreadsheet can export it. Optional comment lines before the header: ``` # people: Ana, Ben, Cem, Dara, Eli (strict list: a misspelt name is an error) # base: EUR # rates: USD=0.92, GBP=1.16 (1 USD = 0.92 EUR) ``` Without `# people:` everyone named anywhere in the file is a member and `all` means all of them; names are matched case-insensitively. ## Choosing a split | Cost | Split | Example `participants` / `details` | |---|---|---| | Groceries, taxi, fuel, shared tickets | `equal` | `all`, `Ana;Ben`, `all-Eli` | | Accommodation when people stayed different nights, rooms of different size | `shares` | `Ana:3;Ben:3;Dara:2` (nights or room weights) | | Tickets with different prices, a known per-person amount | `exact` | `Ana:30;Ben:45` (others in participants split the rest equally) | | Agreed percentages (rent by income, wine for those who drank) | `percent` | `Ana:25;Ben:25;Dara:50` (must total 100) | | Restaurant bill where people ordered separately | `itemized` | `Ana:31;Ben:28.50;shared:42` | | Someone already paid someone back | `payment` | participants = the one recipient | ## Itemized bills - `details` lists each person's items before tax, service and tip; `shared` is the sum of starters, bottles or anything everyone shared (split equally among `participants`). - `amount` is the final bill. The difference (amount - items) is tax, service and tip, spread in proportion to what each person had, so a person who ordered more pays more tip. The output shows it as `+17.3% tax/tip`. - If the items add up to more than the bill (a discount or a typo), the planner stops; enter the discount by lowering the item prices it applied to. ## Exclusions and partial participation - `all-Eli` or `all except Eli` = everyone but Eli; chain several: `all-Bo-Finn`. - For people present part of the time, use `shares` with nights or days instead of excluding them. - A child or a guest paid for by one member: list them under the member's name (`shares` weight 1.5) or add them to `# people:` and settle with their parent. ## Payers - One payer: `Ana`. Several payers on one bill: `Ben:40;Cem:20` (amounts in the row currency, must add up to `amount`). - A card shared by a couple: treat the couple as one person or split the payer amount. ## Refunds, deposits, repayments - Refund received after a cancellation: negative `amount`, `paid_by` = who received the money, same participants as the original cost. - Deposit returned by a landlord: negative `amount` split the same way as the deposit. - Money handed over between members: `payment` (from `paid_by` to the one person in `participants`). Record settle-up transfers the same way; rerunning then shows who is still open. ## Common mistakes the planner catches - Exact amounts or percentages that do not add up, payer amounts that differ from the bill, items over the bill. - A currency without a rate, an unknown split word, a misspelt name when `# people:` is set. - Two identical lines (same date, description, amount and payer) - reported as a warning, not removed. - Zero amounts - skipped with a warning. FILE:references/settle-up-and-currency.md # Settle-up and currency ## Net balance For every person: `net = paid + payments sent - share - payments received`. Positive = gets money back, negative = owes. The nets always add up to exactly 0.00 because every line is split in integer cents that sum to the line total. ## Why "fewest transfers" can be less than people - 1 - Any group with k people who have a balance can settle in at most k - 1 transfers (each transfer clears at least one person). - If the group splits into subgroups whose balances each add up to zero, each subgroup settles on its own: with g such subgroups the minimum is k - g. Example: Bo +300 and Finn -300 cancel, so 6 flatmates need 4 transfers, not 5. - Paying the largest debt to the largest credit (the usual app approach) does not look for these subgroups and can take more transfers. - Finding the best split into zero-sum subgroups is a hard problem in general; the planner solves it exactly for up to 18 people with a non-zero balance (dynamic programming over subsets, under a second) and falls back to the greedy plan above that, saying so. - Within each subgroup the plan pays largest debt to largest credit, which uses exactly (subgroup size - 1) transfers. - Several plans can have the same minimum count; any of them is fair, because each person's total in or out is fixed by their net. ## Rounding - Each line is converted to base cents once (`amount x rate`, rounded half up), then split with the largest-remainder method: everyone gets the rounded-down amount, and the leftover cents go to the largest fractions, ties to the person listed first in `# people:`. - Over a whole trip this moves at most a few cents per person; say so if someone asks why 10.00 / 3 is 3.34 for one person. ## Exchange rates - Agree one rate per currency before splitting: the rate on the day most costs were paid, the average of the trip, or the rate on the payer's card statement (which includes the bank's markup). - If the payer's card charged a foreign transaction fee, either include it in the amount (the group shares it) or leave it out (the payer absorbs it) - decide once for the whole trip. - Enter amounts in the currency actually paid and let the planner convert; do not pre-convert some lines by hand. - Settle in the base currency. If someone pays in another currency, convert the transfer at the same agreed rate and record it as a `payment` line in that currency. ## Payment etiquette - Send the group-chat message with the transfers and a link to the ledger; give people a day or two to dispute a line before paying. - Small transfers (under ~2 EUR/USD) can be waived or rolled into the next shared cost if both people agree - record that as a `payment` line so the ledger stays exact. - When everyone has paid, add each transfer as a `payment` line and rerun: every net should be 0.00. FILE:templates/settle-up-summary.md # Settle-up: <trip / flat / event>, <dates> **Group:** <Ana, Ben, Cem, Dara, Eli> **Base currency:** <EUR> **Total spent:** <1,583.07 EUR> over <11> lines **Rates agreed:** <1 USD = 0.92 EUR, 1 GBP = 1.16 EUR (trip average)> ## Balances | Person | Paid | Fair share | Already sent / received | Net | |---|---|---|---|---| | <Ana> | <990.00> | <377.31> | <received 100.00> | <+512.69 gets back> | | <Ben> | <64.00> | <307.17> | <-> | <-243.17 owes> | ## Transfers (<n>, the minimum possible) 1. <Ben pays Ana 243.17 EUR> 2. <Dara pays Ana 140.94 EUR> 3. <...> ## How lines were split - <Apartment: by nights, Dara and Eli 2 of 3 nights> - <Airport taxi: everyone except Eli (came by train)> - <Dinner: itemized, 17.3% tax and tip spread by what each person ordered; starters 42.00 shared> - <Palace tickets refund: back to Ben and Cem, who paid for them> - <Eli's 100.00 to Ana is already counted> ## Assumptions and open points - <rates above; card fees not included> - <check line 5 (surf lesson): was Ben in?> ## Group chat message ``` Settle-up (<EUR>, <11> lines, rates: <USD 0.92, GBP 1.16>): - <Ben -> Ana: 243.17 EUR> - <Dara -> Ana: 140.94 EUR> Full table: <link to the sheet>. Shout within 2 days if a line is wrong. ``` **When paid:** add each transfer as a `payment` line and rerun - every net should read 0.00. FILE:examples/lisbon-trip.csv # people: Ana, Ben, Cem, Dara, Eli # base: EUR # rates: USD=0.92, GBP=1.16 date,description,paid_by,amount,currency,split,participants,details 2026-10-02,Apartment 3 nights (Dara and Eli 2 nights),Ana,840.00,EUR,shares,all,Ana:3;Ben:3;Cem:3;Dara:2;Eli:2 2026-10-02,Airport taxi (Eli came by train),Ben,48.00,EUR,equal,all-Eli, 2026-10-02,Groceries for the flat,Eli,63.75,EUR,equal,all, 2026-10-03,Dinner at Taberna do Mar,Cem,212.40,EUR,itemized,all,Ana:31;Ben:28.50;Cem:24;Dara:36;Eli:19.50;shared:42 2026-10-03,Surf lesson (booked on a US site),Dara,180.00,USD,equal,Ana;Dara;Eli, 2026-10-03,Fado tickets (premium seats for Dara and Eli),Ana,150.00,EUR,exact,all-Cem,Ana:30;Ben:30;Dara:45;Eli:45 2026-10-04,Train to Sintra,Ben:40;Cem:20,60.00,EUR,equal,all, 2026-10-04,Wine for the flat,Dara,36.00,EUR,percent,,Ana:25;Ben:25;Dara:50 2026-10-04,Palace tickets refunded (rain),Ben,-24.00,EUR,equal,Ben;Cem, 2026-10-05,Snacks at the London layover,Cem,27.00,GBP,equal,all, 2026-10-05,Eli paid Ana back for the apartment,Eli,100.00,EUR,payment,Ana, FILE:examples/lisbon-settle-output.md # Settle-up plan Base currency: EUR People: 5 Lines: 11 Total spent: 1,583.07 EUR Rates used: 1 GBP = 1.16 EUR, 1 USD = 0.92 EUR ## Expenses | # | Date | What | Paid by | Amount | In EUR | Split | Among | |---|---|---|---|---|---|---|---| | 1 | 2026-10-02 | Apartment 3 nights (Dara and Eli 2 nights) | Ana | 840.00 EUR | 840.00 | shares | all | | 2 | 2026-10-02 | Airport taxi (Eli came by train) | Ben | 48.00 EUR | 48.00 | equal | Ana, Ben, Cem, Dara | | 3 | 2026-10-02 | Groceries for the flat | Eli | 63.75 EUR | 63.75 | equal | all | | 4 | 2026-10-03 | Dinner at Taberna do Mar | Cem | 212.40 EUR | 212.40 | itemized (+17.3% tax/tip) | all | | 5 | 2026-10-03 | Surf lesson (booked on a US site) | Dara | 180.00 USD | 165.60 | equal | Ana, Dara, Eli | | 6 | 2026-10-03 | Fado tickets (premium seats for Dara and Eli) | Ana | 150.00 EUR | 150.00 | exact | Ana, Ben, Dara, Eli | | 7 | 2026-10-04 | Train to Sintra | Ben 40.00, Cem 20.00 | 60.00 EUR | 60.00 | equal | all | | 8 | 2026-10-04 | Wine for the flat | Dara | 36.00 EUR | 36.00 | percent | Ana, Ben, Dara | | 9 | 2026-10-04 | Palace tickets refunded (rain) | Ben | -24.00 EUR | -24.00 | equal | Ben, Cem | | 10 | 2026-10-05 | Snacks at the London layover | Cem | 27.00 GBP | 31.32 | equal | all | | 11 | 2026-10-05 | Eli paid Ana back for the apartment | Eli | 100.00 EUR | 100.00 | payment | to Ana | ## Balances | Person | Paid | Share | Sent | Received | Net | |---|---|---|---|---|---| | Ana | 990.00 | 377.31 | 0.00 | 100.00 | 512.69 (gets back) | | Ben | 64.00 | 307.17 | 0.00 | 0.00 | -243.17 (owes) | | Cem | 263.72 | 262.87 | 0.00 | 0.00 | 0.85 (gets back) | | Dara | 201.60 | 342.54 | 0.00 | 0.00 | -140.94 (owes) | | Eli | 63.75 | 293.18 | 100.00 | 0.00 | -129.43 (owes) | Check: nets add up to 0.00 (paid 1,583.07 = shares 1,583.07). ## Transfers (4) 1. Ben pays Ana **243.17 EUR** 2. Dara pays Ana **140.94 EUR** 3. Eli pays Ana **128.58 EUR** 4. Eli pays Cem **0.85 EUR** Minimum possible: 4 transfers for 5 people with a balance (no smaller subgroup evens out on its own). ## Message for the group chat ``` Settle-up (EUR, 11 lines, rates: GBP 1.16, USD 0.92): - Ben -> Ana: 243.17 EUR - Dara -> Ana: 140.94 EUR - Eli -> Ana: 128.58 EUR - Eli -> Cem: 0.85 EUR Full table in the shared sheet. Shout within 2 days if a line is wrong. ``` FILE:examples/flat-october.csv # people: Asha, Bo, Chen, Dev, Ema, Finn # base: EUR date,description,paid_by,amount,currency,split,participants,details 2026-10-01,Festival tickets for Bo and Finn,Bo,600,EUR,exact,Bo;Finn,Bo:300;Finn:300 2026-10-31,October groceries (Bo and Finn on tour),Asha,800,EUR,equal,all-Bo-Finn, 2026-10-31,Electricity Sep-Oct (Bo and Finn on tour),Chen,600,EUR,equal,all-Bo-Finn, 2026-10-20,Second-hand sofa (Dev and Ema's part),Asha,250,EUR,exact,Dev;Ema,Dev:150;Ema:100 FILE:scripts/settle_up.py #!/usr/bin/env python3 """Shared expense bill splitter and settle-up planner (Python 3.8+ standard library only). Reads a CSV ledger of shared costs (a trip, a flat, an event), splits every line in integer cents, and finds the SMALLEST possible number of transfers that settles the group (exact search over zero-sum subgroups, not just "at most people - 1"). CSV columns (header row required, extra columns ignored): date,description,paid_by,amount,currency,split,participants,details paid_by Ana one payer Ana:40;Ben:20 several payers (amounts in the row currency, must add up) amount total in the row currency; negative = refund received by paid_by currency blank = base currency split equal | shares | exact | percent | itemized | payment participants all | Ana;Ben;Cem | all-Eli (everyone except Eli) | blank = names in details details shares: Ana:3;Ben:2 (people in participants but not listed get 1) exact: Ana:30;Ben:45 (rest, if any, split equally among the other participants) percent: Ana:50;Ben:30;Cem:20 (must total 100) itemized: Ana:18;Ben:22.50;shared:12 (item prices before tax/tip; "shared" items are split equally; amount - items = tax/service/tip, split in proportion to what each person ordered) payment: (none) paid_by gave `amount` to the one person in participants Comment lines at the top set the group and the rates (or use the CLI flags): # people: Ana, Ben, Cem # base: EUR # rates: USD=0.92, GBP=1.16 (1 unit of that currency = rate units of base) Usage: python3 settle_up.py ledger.csv [--base EUR] [--rates USD=0.92,GBP=1.16] [--people Ana,Ben] [--detail Ana] [--json] python3 settle_up.py --self-test Exit codes: 0 = settled plan printed, 2 = bad input (unknown split, sums that do not match, missing exchange rate, unknown person in a strict list). """ import argparse import csv import io import json import re import sys from decimal import Decimal, ROUND_HALF_UP, InvalidOperation MAX_EXACT = 18 # people with a non-zero balance for the exact minimum search (2^18 states) SPLITS = ("equal", "shares", "exact", "percent", "itemized", "payment") class LedgerError(ValueError): pass def dec(s, what): try: return Decimal(str(s).replace(",", "").strip()) except (InvalidOperation, AttributeError): raise LedgerError("%s: %r is not a number" % (what, s)) def to_cents(amount): return int((amount * 100).quantize(Decimal("1"), rounding=ROUND_HALF_UP)) def fmt(cents, cur=""): sign = "-" if cents < 0 else "" c = abs(cents) s = "%s%d.%02d" % (sign, c // 100, c % 100) s = re.sub(r"(\d)(?=(\d{3})+\.)", r"\1,", s) return (s + " " + cur).strip() def allocate(total, weights, order): """Split integer `total` cents in proportion to `weights` (dict name -> Decimal >= 0). Largest remainder method; ties go to the earlier name in `order`. Sum is exact.""" names = [n for n in order if n in weights] wsum = sum(weights[n] for n in names) if wsum <= 0: raise LedgerError("weights add up to zero") sign = -1 if total < 0 else 1 t = abs(total) raw = {n: Decimal(t) * weights[n] / wsum for n in names} base = {n: int(raw[n]) for n in names} left = t - sum(base.values()) rank = sorted(names, key=lambda n: (-(raw[n] - base[n]), order.index(n))) for n in rank[:left]: base[n] += 1 return {n: sign * v for n, v in base.items() if v} def parse_pairs(text, what): out = {} for part in [p for p in re.split(r"[;|]", text or "") if p.strip()]: if ":" not in part: raise LedgerError("%s: %r should look like Name:value" % (what, part.strip())) k, v = part.split(":", 1) k = k.strip() out[k] = out.get(k, Decimal(0)) + dec(v, what) return out class Ledger: def __init__(self, text, base=None, rates=None, people=None): self.warnings = [] self.base = base self.rates = {} self.people = [] self._canon = {} header_people = None body = [] for line in text.splitlines(): s = line.strip() if s.startswith("#"): m = re.match(r"#\s*(people|base|rates?)\s*:\s*(.*)$", s, re.I) if m: key, val = m.group(1).lower(), m.group(2) if key == "people": header_people = [p.strip() for p in re.split(r"[,;]", val) if p.strip()] elif key == "base" and not self.base: self.base = val.strip().upper() elif key.startswith("rate"): self._add_rates(val) continue body.append(line) self.base = (self.base or "EUR").upper() if rates: self._add_rates(rates) self.rates[self.base] = Decimal(1) for p in (people or header_people or []): self._person(p, declare=True) self.strict = bool(people or header_people) rows = list(csv.DictReader(io.StringIO("\n".join(body)))) if not rows: raise LedgerError("no expense rows found (need a header row and at least one line)") need = {"description", "paid_by", "amount", "split"} cols = {c.strip().lower() for c in rows[0].keys() if c} if not need <= cols: raise LedgerError("missing CSV columns: %s" % ", ".join(sorted(need - cols))) self.rows = [] for r in rows: r = {(k or "").strip().lower(): (v or "").strip() for k, v in r.items()} if not any(r.values()): continue self.rows.append(r) # first pass: learn every name when no people list was given if not self.strict: for r in self.rows: for p in self._names_in(r): self._person(p, declare=True) self.lines = [self._line(n, r) for n, r in enumerate(self.rows, 1)] self._check_duplicates() # -- people and rates def _add_rates(self, text): for part in re.split(r"[,;]", text): if not part.strip(): continue if "=" not in part: raise LedgerError("rate %r should look like USD=0.92" % part.strip()) k, v = part.split("=", 1) r = dec(v, "rate " + k.strip()) if r <= 0: raise LedgerError("rate for %s must be positive" % k.strip()) self.rates[k.strip().upper()] = r def _person(self, name, declare=False): key = name.strip().lower() if not key: raise LedgerError("empty person name") if key in self._canon: canon = self._canon[key] if canon != name.strip() and declare: self.warnings.append("'%s' and '%s' treated as the same person" % (canon, name.strip())) return canon if not declare: raise LedgerError("unknown person %r (not in the people list)" % name.strip()) self._canon[key] = name.strip() self.people.append(name.strip()) return name.strip() def _names_in(self, r): names = [] pb = r.get("paid_by", "") names += list(parse_pairs(pb, "paid_by").keys()) if ":" in pb else [pb] part = r.get("participants", "") if part and not part.lower().startswith("all"): names += [p for p in re.split(r"[;|]", part) if p.strip()] if r.get("split", "").lower() != "payment": names += [k for k in parse_pairs(r.get("details", ""), "details") if k.lower() != "shared"] return [n for n in names if n.strip()] def _participants(self, r, ln): part = r.get("participants", "").strip() if not part: return None if part.lower().startswith("all"): rest = part[3:].strip() excl = [] if rest: rest = re.sub(r"^(except|but|without)\s+", "", rest.lstrip("-").strip(), flags=re.I) excl = [self._person(x) for x in re.split(r"[-;|,]", rest) if x.strip()] return [p for p in self.people if p not in excl] return [self._person(p) for p in re.split(r"[;|]", part) if p.strip()] # -- one CSV line -> paid / share in base cents def _line(self, ln, r): desc = r.get("description") or "line %d" % ln where = "line %d (%s)" % (ln, desc) split = (r.get("split") or "equal").lower() if split not in SPLITS: raise LedgerError("%s: unknown split %r (use %s)" % (where, split, ", ".join(SPLITS))) cur = (r.get("currency") or self.base).upper() if cur not in self.rates: raise LedgerError("%s: no exchange rate for %s (add '# rates: %s=...' or --rates)" % (where, cur, cur)) amount = dec(r.get("amount"), where + " amount") if amount == 0: self.warnings.append("%s has amount 0 and was skipped" % where) total = to_cents(amount * self.rates[cur]) # payers pb = r.get("paid_by", "") if ":" in pb: pays = {self._person(k): v for k, v in parse_pairs(pb, where + " paid_by").items()} if sum(pays.values()) != amount: raise LedgerError("%s: payers add up to %s but amount is %s" % (where, sum(pays.values()), amount)) paid = allocate(total, {k: abs(v) for k, v in pays.items()}, self.people) if total else {} if total < 0: paid = {k: -abs(v) for k, v in paid.items()} else: paid = {self._person(pb): total} if total else {} people = self._participants(r, ln) details = parse_pairs(r.get("details", ""), where + " details") if split != "payment" else {} share = {} if split == "payment": if not people or len(people) != 1: raise LedgerError("%s: a payment needs exactly one recipient in participants" % where) share = {people[0]: total} elif split == "equal": people = people or self.people share = allocate(total, {p: Decimal(1) for p in people}, self.people) elif split == "shares": d = {self._person(k): v for k, v in details.items()} people = people or list(d) w = {p: d.get(p, Decimal(1)) for p in people} extra = [p for p in d if p not in people] if extra: raise LedgerError("%s: %s in details but not in participants" % (where, ", ".join(extra))) if any(v < 0 for v in w.values()): raise LedgerError("%s: shares cannot be negative" % where) share = allocate(total, w, self.people) elif split == "percent": d = {self._person(k): v for k, v in details.items()} if sum(d.values()) != 100: raise LedgerError("%s: percentages add up to %s, not 100" % (where, sum(d.values()))) people = list(d) share = allocate(total, d, self.people) elif split == "exact": d = {self._person(k): v for k, v in details.items()} people = people or list(d) fixed = sum(d.values()) rest_people = [p for p in people if p not in d] if fixed > abs(amount) or (fixed != abs(amount) and not rest_people): raise LedgerError("%s: exact amounts add up to %s but the bill is %s" % (where, fixed, amount)) w = dict(d) if rest_people: each = (abs(amount) - fixed) / len(rest_people) for p in rest_people: w[p] = each share = allocate(total, w, self.people) elif split == "itemized": people = people or self.people shared = details.pop("shared", details.pop("Shared", Decimal(0))) d = {self._person(k): v for k, v in details.items()} items = sum(d.values()) + shared if items > abs(amount): raise LedgerError("%s: items add up to %s, more than the bill %s" % (where, items, amount)) per = {p: d.get(p, Decimal(0)) + (shared / len(people) if shared else 0) for p in people} for p in d: if p not in per: per[p] = d[p] if sum(per.values()) <= 0: raise LedgerError("%s: no items to split" % where) # tax/tip proportional to each person's items == allocate the total by item weights share = allocate(total, per, self.people) rec = {"n": ln, "date": r.get("date", ""), "desc": desc, "split": split, "currency": cur, "amount": amount, "total": total, "paid": paid, "share": share, "among": sorted(share, key=self.people.index)} if split == "itemized": rec["extra_pct"] = (abs(amount) - items) / items * 100 if items else Decimal(0) if sum(paid.values()) != sum(share.values()): raise LedgerError("%s: internal rounding error" % where) # never expected return rec def _check_duplicates(self): seen = {} for l in self.lines: key = (l["date"], l["desc"].lower(), l["total"], tuple(sorted(l["paid"]))) if key in seen: self.warnings.append("line %d looks like a duplicate of line %d (%s, %s)" % (l["n"], seen[key], l["desc"], fmt(l["total"], self.base))) else: seen[key] = l["n"] def balances(self): b = {p: {"paid": 0, "share": 0, "sent": 0, "received": 0} for p in self.people} for l in self.lines: if l["split"] == "payment": for p, c in l["paid"].items(): b[p]["sent"] += c for p, c in l["share"].items(): b[p]["received"] += c else: for p, c in l["paid"].items(): b[p]["paid"] += c for p, c in l["share"].items(): b[p]["share"] += c for p in b: b[p]["net"] = b[p]["paid"] + b[p]["sent"] - b[p]["share"] - b[p]["received"] return b # ----------------------------------------------------------------------------- settle-up def greedy(net, order): """Largest debtor pays largest creditor until everyone is even (at most k-1 transfers).""" cred = {p: v for p, v in net.items() if v > 0} debt = {p: -v for p, v in net.items() if v < 0} out = [] while cred and debt: c = max(cred, key=lambda p: (cred[p], -order.index(p))) d = max(debt, key=lambda p: (debt[p], -order.index(p))) x = min(cred[c], debt[d]) out.append((d, c, x)) cred[c] -= x debt[d] -= x if not cred[c]: del cred[c] if not debt[d]: del debt[d] return out def minimal(net, order): """Fewest transfers: n - (max number of disjoint zero-sum groups). Returns (transfers, groups, exact).""" people = [p for p in order if net.get(p)] n = len(people) if n == 0: return [], [], True if n > MAX_EXACT: return greedy(net, order), [people], False vals = [net[p] for p in people] size = 1 << n sums = [0] * size for m in range(1, size): low = m & -m sums[m] = sums[m ^ low] + vals[low.bit_length() - 1] dp = [0] * size for m in range(1, size): best = 0 mm = m while mm: low = mm & -mm v = dp[m ^ low] if v > best: best = v mm ^= low dp[m] = best + (1 if sums[m] == 0 else 0) # walk down, cutting a group at each zero-sum checkpoint groups, m, last = [], size - 1, size - 1 while m: mm, pick = m, None target = dp[m] - (1 if sums[m] == 0 else 0) while mm: low = mm & -mm if dp[m ^ low] == target: pick = low break mm ^= low m ^= pick if sums[m] == 0: groups.append(last ^ m) last = m out, named = [], [] for g in reversed(groups): members = [people[i] for i in range(n) if g >> i & 1] named.append(members) out += greedy({p: net[p] for p in members}, order) return out, named, True # ----------------------------------------------------------------------------- output def render(led, detail=None): b = led.balances() net = {p: b[p]["net"] for p in led.people} tr, groups, exact = minimal(net, led.people) gr = greedy(net, led.people) B = led.base o = ["# Settle-up plan", "", "Base currency: %s People: %d Lines: %d Total spent: %s" % ( B, len(led.people), len(led.lines), fmt(sum(l["total"] for l in led.lines if l["split"] != "payment"), B))] others = sorted(c for c in led.rates if c != B) if others: o.append("Rates used: " + ", ".join("1 %s = %s %s" % (c, led.rates[c].normalize(), B) for c in others)) o += ["", "## Expenses", "", "| # | Date | What | Paid by | Amount | In %s | Split | Among |" % B, "|---|---|---|---|---|---|---|---|"] for l in led.lines: payer = ", ".join("%s %s" % (p, fmt(c)) if len(l["paid"]) > 1 else p for p, c in l["paid"].items()) among = "all" if len(l["among"]) == len(led.people) and l["split"] != "payment" else ", ".join(l["among"]) split = l["split"] + (" (+%.1f%% tax/tip)" % l["extra_pct"] if l["split"] == "itemized" else "") if l["split"] == "payment": among = "to " + among o.append("| %d | %s | %s | %s | %s %s | %s | %s | %s |" % (l["n"], l["date"], l["desc"].replace("|", "/"), payer, fmt(to_cents(l["amount"])), l["currency"], fmt(l["total"]), split, among)) o += ["", "## Balances", "", "| Person | Paid | Share | Sent | Received | Net |", "|---|---|---|---|---|---|"] for p in led.people: x = b[p] state = "gets back" if x["net"] > 0 else ("owes" if x["net"] < 0 else "even") o.append("| %s | %s | %s | %s | %s | %s (%s) |" % (p, fmt(x["paid"]), fmt(x["share"]), fmt(x["sent"]), fmt(x["received"]), fmt(x["net"]), state)) o.append("") o.append("Check: nets add up to %s (paid %s = shares %s)." % (fmt(sum(net.values())), fmt(sum(x["paid"] for x in b.values())), fmt(sum(x["share"] for x in b.values())))) nz = sum(1 for v in net.values() if v) o += ["", "## Transfers (%d)" % len(tr), ""] if not tr: o.append("Everyone is even. Nothing to pay.") else: for i, (d, c, x) in enumerate(tr, 1): o.append("%d. %s pays %s **%s**" % (i, d, c, fmt(x, B))) o.append("") if exact: if len(groups) > 1: o.append("Minimum possible: %d transfers. The group splits into %d sets that settle among themselves (%s), so %d people need only %d transfers; paying largest debt to largest credit would take %d." % ( len(tr), len(groups), "; ".join(" + ".join(g) for g in groups), nz, len(tr), len(gr))) else: o.append("Minimum possible: %d transfers for %d people with a balance (no smaller subgroup evens out on its own)." % (len(tr), nz)) else: o.append("%d people have a balance; exact minimum search skipped (limit %d), greedy plan uses at most %d transfers." % (nz, MAX_EXACT, nz - 1)) if detail: p = led._person(detail) o += ["", "## Detail: %s" % p, "", "| # | What | Paid | Share | Running net |", "|---|---|---|---|---|"] run = 0 for l in led.lines: pd, sh = l["paid"].get(p, 0), l["share"].get(p, 0) if not pd and not sh: continue run += pd - sh o.append("| %d | %s | %s | %s | %s |" % (l["n"], l["desc"], fmt(pd), fmt(sh), fmt(run))) if led.warnings: o += ["", "## Warnings", ""] + ["- " + w for w in led.warnings] o += ["", "## Message for the group chat", "", "```"] msg = ["Settle-up (%s, %d lines, rates: %s):" % (B, len(led.lines), ", ".join("%s %s" % (c, led.rates[c].normalize()) for c in others) or "none")] msg += ["- %s -> %s: %s" % (d, c, fmt(x, B)) for d, c, x in tr] or ["- everyone is even"] msg.append("Full table in the shared sheet. Shout within 2 days if a line is wrong.") o += msg + ["```"] return "\n".join(o) + "\n" def as_json(led): b = led.balances() net = {p: b[p]["net"] for p in led.people} tr, groups, exact = minimal(net, led.people) return {"base": led.base, "people": led.people, "balances_cents": b, "transfers": [{"from": d, "to": c, "cents": x} for d, c, x in tr], "groups": groups, "exact_minimum": exact, "warnings": led.warnings} # ----------------------------------------------------------------------------- self-test def self_test(): import random cases = [] def case(name, fn): try: ok, err = bool(fn()), "" except Exception as e: # noqa ok, err = False, repr(e) cases.append((name, ok, err)) H = "date,description,paid_by,amount,currency,split,participants,details\n" def L(rows, **kw): return Ledger(H + rows, **kw) def nets(led): b = led.balances() return {p: b[p]["net"] for p in led.people} def raises(fn): try: fn() except LedgerError: return True return False case("equal split to the cent", lambda: nets(L(",Taxi,Ana,10.00,,equal,Ana;Ben;Cem,\n")) == {"Ana": 666, "Ben": -333, "Cem": -333}) case("remainder cent goes to first in order", lambda: L(",X,Ana,0.10,,equal,Ana;Ben;Cem,\n").lines[0]["share"] == {"Ana": 4, "Ben": 3, "Cem": 3}) case("all minus exclusion", lambda: Ledger("# people: Ana, Ben, Cem\n" + H + ",X,Ana,30,,equal,all-Cem,\n").lines[0]["among"] == ["Ana", "Ben"]) case("all except words", lambda: Ledger("# people: Ana, Ben, Cem\n" + H + ",X,Ana,30,,equal,all except Ben,\n").lines[0]["among"] == ["Ana", "Cem"]) case("shares weights", lambda: L(",Room,Ana,100,,shares,,Ana:3;Ben:1\n").lines[0]["share"] == {"Ana": 7500, "Ben": 2500}) case("shares default 1 for unlisted participants", lambda: L(",Room,Ana,90,,shares,Ana;Ben;Cem,Ana:2;Ben:0\n").lines[0]["share"] == {"Ana": 6000, "Cem": 3000}) case("exact amounts", lambda: L(",Tickets,Ana,75,,exact,,Ana:30;Ben:45\n").lines[0]["share"] == {"Ana": 3000, "Ben": 4500}) case("exact with rest split equally", lambda: L(",T,Ana,100,,exact,Ana;Ben;Cem,Ana:40\n").lines[0]["share"] == {"Ana": 4000, "Ben": 3000, "Cem": 3000}) case("exact mismatch rejected", lambda: raises(lambda: L(",T,Ana,80,,exact,,Ana:30;Ben:45\n"))) case("percent", lambda: L(",Wine,Ana,36,,percent,,Ana:25;Ben:25;Cem:50\n").lines[0]["share"] == {"Ana": 900, "Ben": 900, "Cem": 1800}) case("percent not 100 rejected", lambda: raises(lambda: L(",W,Ana,36,,percent,,Ana:25;Ben:25\n"))) case("itemized with shared and tax/tip", lambda: L(",Dinner,Ana,66,,itemized,Ana;Ben,Ana:20;Ben:30;shared:10\n").lines[0]["share"] == {"Ana": 2750, "Ben": 3850}) case("itemized over bill rejected", lambda: raises(lambda: L(",D,Ana,40,,itemized,Ana;Ben,Ana:20;Ben:30\n"))) case("payment row", lambda: nets(L(",Food,Ana,20,,equal,Ana;Ben,\n,Paid back,Ben,10,,payment,Ana,\n")) == {"Ana": 0, "Ben": 0}) case("payment needs one recipient", lambda: raises(lambda: L(",P,Ben,10,,payment,Ana;Cem,\n"))) case("several payers", lambda: L(",Train,Ana:40;Ben:20,60,,equal,Ana;Ben;Cem,\n").lines[0]["paid"] == {"Ana": 4000, "Ben": 2000}) case("several payers must add up", lambda: raises(lambda: L(",Train,Ana:40;Ben:10,60,,equal,Ana;Ben,\n"))) case("refund (negative amount)", lambda: nets(L(",Museum refund,Ben,-24,,equal,Ben;Cem,\n")) == {"Ben": -1200, "Cem": 1200}) case("currency conversion", lambda: L(",Surf,Ana,100,USD,equal,Ana;Ben,\n", rates="USD=0.92").lines[0]["total"] == 9200) case("rates from comment line", lambda: Ledger("# base: EUR\n# rates: USD=0.92, GBP=1.16\n" + H + ",S,Ana,10,GBP,equal,Ana;Ben,\n").lines[0]["total"] == 1160) case("missing rate rejected", lambda: raises(lambda: L(",S,Ana,10,CHF,equal,Ana;Ben,\n"))) case("unknown split rejected", lambda: raises(lambda: L(",S,Ana,10,,halves,Ana;Ben,\n"))) case("strict people list rejects typo", lambda: raises(lambda: Ledger("# people: Ana, Ben\n" + H + ",S,Anna,10,,equal,all,\n"))) case("case-insensitive names merge", lambda: L(",A,Ana,10,,equal,ana;Ben,\n").people == ["Ana", "Ben"]) case("duplicate line warning", lambda: any("duplicate" in w for w in L("1,Taxi,Ana,10,,equal,Ana;Ben,\n1,Taxi,Ana,10,,equal,Ana;Ben,\n").warnings)) case("missing columns rejected", lambda: raises(lambda: Ledger("what,who\nx,y\n"))) case("bad number rejected", lambda: raises(lambda: L(",S,Ana,ten,,equal,Ana;Ben,\n"))) # minimum transfers case("zero-sum pairs found (4 people -> 2 transfers)", lambda: len(minimal({"A": 500, "B": -500, "C": 300, "D": -300}, list("ABCD"))[0]) == 2) case("no zero-sum subgroup -> people - 1 transfers", lambda: len(greedy({"A": 600, "B": 400, "C": -500, "D": -500}, list("ABCD"))) == 3 and len(minimal({"A": 600, "B": 400, "C": -500, "D": -500}, list("ABCD"))[0]) == 3) case("min beats greedy on 6 people", lambda: (lambda n: len(minimal(n, list("ABCDEF"))[0]) == 4 and len(greedy(n, list("ABCDEF"))) == 5)({"A": 700, "B": 300, "C": 250, "D": -500, "E": -450, "F": -300})) case("everyone even -> no transfers", lambda: minimal({"A": 0, "B": 0}, ["A", "B"])[0] == []) def brute_min(net): ps = [p for p in net if net[p]] best = len(ps) - 1 if ps else 0 for parts in _partitions(ps): if all(sum(net[p] for p in g) == 0 for g in parts): best = min(best, len(ps) - len(parts)) return best def check_random(): rnd = random.Random(7) for _ in range(60): k = rnd.randint(2, 7) vals = [rnd.choice([-1, 1]) * rnd.choice([100, 200, 300, 500, 250, 50]) for _ in range(k - 1)] vals.append(-sum(vals)) net = {chr(65 + i): v for i, v in enumerate(vals)} tr = minimal(net, list(net))[0] bal = dict(net) for d, c, x in tr: assert x > 0 bal[d] += x bal[c] -= x if any(bal.values()) or len(tr) != brute_min(net): return False return True case("minimal == brute force on 60 random groups and settles everyone", check_random) case("transfers settle the example-like ledger", lambda: _settles(L(",Flat,Ana,840,,shares,,Ana:3;Ben:3;Cem:2\n,Food,Cem,63.75,,equal,all,\n,Wine,Ben,36,,percent,,Ana:25;Ben:25;Cem:50\n"))) case("render has transfers and chat message", lambda: "Message for the group chat" in render(L(",Taxi,Ana,10,,equal,Ana;Ben,\n"))) case("detail view", lambda: "Detail: Ben" in render(L(",Taxi,Ana,10,,equal,Ana;Ben,\n"), "ben")) case("json output", lambda: as_json(L(",Taxi,Ana,10,,equal,Ana;Ben,\n"))["transfers"] == [{"from": "Ben", "to": "Ana", "cents": 500}]) case("format thousands", lambda: fmt(123456789, "EUR") == "1,234,567.89 EUR" and fmt(-5) == "-0.05") passed = sum(1 for _, ok, _ in cases if ok) for name, ok, err in cases: print(("PASS " if ok else "FAIL ") + name + ((" " + err) if err else "")) print("%d/%d passed" % (passed, len(cases))) return 0 if passed == len(cases) else 1 def _partitions(items): if not items: yield [] return first, rest = items[0], items[1:] for p in _partitions(rest): for i in range(len(p)): yield p[:i] + [[first] + p[i]] + p[i + 1:] yield [[first]] + p def _settles(led): b = led.balances() net = {p: b[p]["net"] for p in led.people} for d, c, x in minimal(net, led.people)[0]: net[d] += x net[c] -= x return not any(net.values()) def main(argv=None): ap = argparse.ArgumentParser(description="Split shared expenses and plan the fewest settle-up transfers.") ap.add_argument("file", nargs="?", help="CSV ledger ('-' = stdin)") ap.add_argument("--base", default=None, help="base currency (default: '# base:' line or EUR)") ap.add_argument("--rates", default=None, help="USD=0.92,GBP=1.16 (1 unit = rate units of base)") ap.add_argument("--people", default=None, help="comma-separated group members (strict: typos are errors)") ap.add_argument("--detail", default=None, help="show the line-by-line breakdown for one person") ap.add_argument("--json", action="store_true") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.file: ap.error("give a CSV ledger or --self-test") try: text = sys.stdin.read() if a.file == "-" else open(a.file, encoding="utf-8-sig").read() people = [p.strip() for p in a.people.split(",")] if a.people else None led = Ledger(text, a.base, a.rates, people) out = json.dumps(as_json(led), indent=2) + "\n" if a.json else render(led, a.detail) except (OSError, LedgerError) as e: print("error: %s" % e, file=sys.stderr) return 2 sys.stdout.write(out) return 0 if __name__ == "__main__": sys.exit(main())

Based on Everything You Know About Me, Carve This Pumpkin (Personalized Jack-o'-Lantern)

Based on everything you know about me, carve this pumpkin.

Holiday Houseguest Hosting Plan Builder (YAML)

role: Warm, organized holiday hosting planner who helps people welcome overnight houseguests for Thanksgiving or other year-end holidays, covering sleeping arrangements, arrivals and departures, shared meals, bathroom and kitchen flow, quiet time, diets and allergies, kids and pets, house rules, and the budget, with a realistic plan that keeps the host rested and the guests comfortable task: > Turn my home, my guests, their travel dates, our holiday plans, any diets or health needs, and my budget into a complete houseguest hosting plan as YAML: a summary with the main pressure points, a sleeping plan with a bed for every guest, an arrival and departure plan, a day-by-day schedule with free time, a meal plan that shares the cooking, a bathroom and morning routine plan, a guest room prep list, house notes for guests, a diet and allergy plan, a kids and pets plan, a shared chores list, a budget check, polite scripts for tricky moments, a shopping list, and a countdown checklist. inputs: holiday_and_dates: ${dates:Thanksgiving, guests arrive Wednesday evening and leave Sunday morning} guests: ${guests:my parents in their 70s, my sister, her husband, and their two kids aged 7 and 12} our_household: ${household:me, my partner, and our 3-year-old} home_layout: ${layout:three bedrooms, one and a half bathrooms, a living room with a sofa bed, a small home office} available_beds: ${beds:one queen bed in the spare room, a sofa bed, one air mattress, a toddler bed} guest_travel: ${travel:my parents drive 4 hours, my sister's family flies in and lands at 6 pm} big_meal: ${big_meal:Thanksgiving dinner Thursday at 4 pm for nine people} other_plans: ${plans:a local parade Thursday morning, a walk or a movie Friday, leftovers and games Saturday} diets_and_health: ${diets:my father is diabetic, my nephew has a tree nut allergy, my sister is vegetarian} mobility_and_sleep_needs: ${needs:my mother cannot do stairs easily, the 12-year-old is a light sleeper} pets: ${pets:our cat, and my sister's husband is allergic to cats} work_or_quiet_time: ${quiet:my partner works remotely Wednesday and Friday mornings} host_energy: ${energy:I want to enjoy the visit and not cook every meal} budget: ${budget:about 450 for food, extra bedding, and outings} ask_first: - The exact arrival and departure days and times for each guest, how they travel, and whether anyone needs a pickup - Every room, bed, sofa bed, and air mattress you have, which rooms have doors, and how many bathrooms there are - Each guest's age, any mobility, sleep, or health needs, and who may need a quiet or ground-floor space - Every allergy, intolerance, diet, or medical need in the group, and any pet allergies - Which meals and outings are already planned, who has offered to cook or bring food, and your total budget rules: - Use only my inputs for facts. If something is missing, write it under assumptions and add a question to open_questions. Never invent guest preferences, store hours, travel times, or local events. - Every guest gets a defined sleeping spot that fits their age and needs. Put older or less mobile guests closest to a bathroom and away from stairs where possible, give light sleepers the quietest spot, keep children with their parents or in a clearly agreed room, and check that air mattresses and sofa beds have enough bedding. - Protect the host. Share cooking and cleanup across guests, plan at least one simple or leftover-based meal, plan short daily rest or free time for everyone, and leave space in the schedule instead of filling every hour. - Plan bathroom flow for busy mornings with a simple shower order, towels labeled by person, spare toiletries, and a basket with essentials so guests do not need to ask. - Diet and allergy plan for every affected guest. Keep allergen-free dishes clearly separate, label dishes on the table, avoid cross-contact when cooking and serving, plan meals that work for diabetic and vegetarian guests without making them feel singled out, and keep any emergency medication accessible. Never tell me a product is safe; tell me to read the label and follow the guest's own doctor's advice. - For pet allergies, plan a pet-free guest room, cleaning and vacuuming before arrival, washing bedding, and a quiet space for the pet, and suggest asking allergic guests about their own medication. - Include house notes for guests (wifi, heating and thermostat, quiet hours, kitchen and laundry use, keys or door codes, trash and recycling, where to find extra blankets) written warmly and briefly. - Scripts must be kind and short, for example asking guests to help with dishes, handling an early bedtime, setting quiet hours, or declining one more outing. - Respect the budget and prefer borrowing or reusing over buying. Output only valid YAML matching output_format. No prose outside the YAML. output_format: summary: group: string nights: number pressure_points: - string readiness: ready | needs_decisions | needs_supplies assumptions: - string open_questions: - string sleeping_plan: - guest: string room: string bed: string bedding_needed: - string why_this_spot: string arrivals_and_departures: - guest: string arrives: string departs: string transport: string pickup_needed: boolean welcome_or_goodbye_plan: string daily_schedule: - day: string blocks: - time: string activity: string who: string notes: string free_time: string meal_plan: - day: string meal: breakfast | lunch | dinner | snack dish: string cook: string diet_notes: - string make_ahead: boolean bathroom_and_mornings: shower_order: - time: string who: string guest_basket: - string towel_plan: string guest_room_prep: - task: string room: string when: string done: boolean house_notes_for_guests: - topic: string note: string diet_and_allergy_plan: guests: - guest: string need: string medication_or_supplies: string kitchen_rules: - string table_labels: - string doctor_advice_note: string kids_and_pets: kids: - string pets: - string shared_chores: - chore: string who: string when: string budget_check: items: - item: string estimated_cost: string borrow_instead: boolean total_estimate: string within_budget: boolean scripts: asking_for_help: - string quiet_hours_and_bedtime: - string declining_politely: - string shopping_list: - item: string quantity: string for_what: string countdown_checklist: one_week_before: - string two_days_before: - string arrival_day: - string after_guests_leave: - string

Photoreal Bull Moose Wading in a Misty Mountain Lake at Autumn Sunrise

A photorealistic wildlife photograph of a large bull moose wading knee-deep in a glassy mountain lake at autumn sunrise, wide landscape 16:9. The dark-brown moose stands left of center in side profile, body facing right, head turned slightly toward the camera, crowned with wide palmate antlers with many tines; drops of water fall from its muzzle and small ripples ring its legs. A thin layer of low white mist hangs over the still water. The far shoreline is a band of dark spruce and fir trees mixed with bright golden-yellow aspens and birches, with more gold on the right side. Behind them rise jagged snow-capped mountain peaks lit soft pink and peach by the first sun, under a pale, clear sky. The calm lake mirrors everything below the shoreline: the moose, its antlers, the golden trees, and the glowing peaks, in an almost perfect reflection. Telephoto lens look with gentle compression and a sharp subject, warm soft sunrise light with cool shadows, rich natural autumn colors, quiet and majestic mood. No people, no text, no logos.

Floating Market Boats Laden with Tropical Fruit on a Misty Canal at Sunrise

Long wooden boats piled with tropical fruit gliding along a calm, misty canal at a floating market at sunrise, seen from eye level on the water looking straight down the canal, in a wide landscape 16:9 frame. On the left bank stands a weathered wooden stilt house with a rusty corrugated tin roof and a balcony with railings full of potted plants, above lush green bushes. Tall coconut palms and dense tropical greenery line both banks and fade into soft golden morning mist in the distance. Five long, narrow wooden boats are on the brown-green water, each paddled by one woman vendor in a conical straw hat and a long-sleeve patterned shirt: the front-left boat carries yellow bananas, green mangoes and limes, and pink dragon fruit; the front-center boat carries golden pineapples and big green pomelos and coconuts; the front-right boat is piled with green limes and yellow mangoes; two smaller boats further back in the center carry pineapples and mixed fruit; and one tiny boat sits far away in the mist. Soft golden backlight comes from the top right, with warm reflections and gentle wakes on the water. Photoreal travel and documentary photography, natural colors, peaceful, warm, and timeless mood. No text, no signs, no logos.

WEB APP UI

# Taste - Package manager is npm (not pnpm or yarn). Confidence: 0.95 - Use Next.js App Router with React Server Components by default; add `"use client"` only for interactive components. Confidence: 0.95

Education

--- name: education description: To be extremely clear and efficient , i need bulletproof thinking --- # Education Describe what this skill does and how the agent should use it. ## Instructions - Step 1: ... - Step 2: ...

AI Response Structure G

--- name: ai-response-structure-guide description: Formats AI responses for low cognitive load, high clarity, and concrete structure. --- # ROLE & INSTRUCTIONS FOR AI RESPONSES You are an accessibility-focused communication assistant helping a user who benefits from low-cognitive-load, highly concrete, and structured information. Whenever you answer questions, provide feedback, or format text, you MUST follow these structural rules: 1. **KEEP IT CONCRETE AND BRIEF**: Use short, active-voice sentences. Avoid abstract metaphors, corporate jargon, hyperbole, or multi-step conditional clauses. Aim for a maximum of 15 words per sentence where possible. 2. **USE BULLET POINTS**: Break down information into small, digestible chunks instead of long paragraphs. 3. **NO ASSUMED SUBTEXT**: State things directly. Do not rely on hidden meaning or subtle emotional hints. 4. **VALIDATE WITHOUT OVERWHELM**: Keep explanations grounded in practical reality and clear logic.

Black Friday Deal and Purchase Decision Check (JSON)

{ "role": "Calm, numbers-first shopping decision assistant who helps people decide which Black Friday, Cyber Monday, and holiday sale deals are worth buying by checking real need, the true total price, price history evidence, alternatives, return rules, and the budget, without pushing anyone to spend and without inventing prices, discounts, or store policies", "task": "Turn my shopping list, the deals I am looking at, my budget, and what I already own into a single strict JSON purchase decision report: a summary, a need check for every item, a true total price for each deal, a discount reality check against the evidence I provide, alternatives to compare, return and warranty checks, a budget fit, a buy, wait, or skip verdict per item with reasons, a scam and safety check, a final buying list in priority order, and a checklist for sale day. Never invent prices, price history, discounts, stock levels, or store policies.", "context": { "shopping_list": "${list:a new laptop for school, a robot vacuum, winter boots for my child, and gifts for two nieces}", "deals_found": "${deals:Laptop X at 649 (was 899) at Store A, Robot vacuum Y at 199 (was 399) at Store B, boots at 30% off at Store C, a 3-for-2 toy offer at Store D}", "price_evidence": "${evidence:I saw Laptop X at 699 in September, the vacuum's lowest tracked price is 219, no evidence for the others}", "total_budget": "${budget:900 for everything, paid from savings, no credit card debt}", "already_own": "${own:a 6-year-old laptop that is slow but works, a corded vacuum, last year's boots are too small}", "must_haves": "${must_haves:the laptop needs 16 GB RAM, at least 512 GB storage, and good battery life}", "timing": "${timing:the laptop is needed before school starts in January, gifts before December 20}", "payment_methods": "${payment:debit card and a store credit card with 0% for 6 months that I would rather not use}", "shipping_and_returns": "${returns:I need free returns, I live in an apartment and packages are sometimes stolen}", "impulse_risks": "${impulse:I tend to add extra cheap items to reach free shipping and buy things just because they are on sale}", "country_or_region": "${region:United States}" }, "ask_first": [ "Every item on your list with why you need it, what you already own that does the same job, and the latest date you need it by", "Each deal you are considering: the exact product name and model, the store, the sale price, the claimed regular price, shipping cost, and any bundle or coupon terms", "Any price history you have seen yourself (screenshots, price tracker results, or prices you remember with dates)", "Your total budget for this shopping round, how you will pay, and whether any purchase would go on credit", "Which return window, warranty, and delivery conditions you need, and any items you feel tempted to buy that are not on your list" ], "rules": [ "Use only my inputs for prices, discounts, price history, and policies. If something is missing, set it to null, add it to open_questions, and never guess prices, past prices, discounts, stock, or store rules.", "Run a need check for every item before looking at the deal: does it replace something broken or outgrown, solve a real problem, or only look like a bargain? Mark each item need, nice_to_have, or impulse, and say so kindly.", "Calculate the true total price for each deal as: sale price plus shipping, plus required accessories, plus taxes or fees I provided, minus coupons or cashback I can actually use. Show the formula. Mark tax unknown if I did not give a rate.", "Check the discount honestly: compare the sale price with the price evidence I gave, not only with the store's 'was' price. If there is no evidence, set discount_confidence to unverified and tell me how to check (a price tracker, the store's own price history if shown, or comparing two or three other stores the same day).", "For each deal, compare at least one alternative I mentioned or a general option such as waiting, buying refurbished or second-hand, repairing what I own, borrowing, or a cheaper model that still meets my must-haves. Never invent a specific product, price, or store.", "List return window, restocking fees, price adjustment policy, warranty, and delivery protection as items to confirm on the store's official pages before buying, and mark each confirm true. Do not state any store's policy as fact.", "Budget fit: add up the true totals of all buy verdicts and compare them with my budget. If the total is over budget, cut the lowest-priority items first and explain the order. Never suggest paying with credit I said I would rather not use or taking on debt.", "Verdict per item is buy_now, wait_and_watch, buy_later_full_price_ok, or skip, with reasons tied to need, evidence, timing, and budget. Never create urgency, and point out fake urgency signals such as countdown timers or 'only 2 left' messages.", "Scam and safety check: list warning signs to look for (unknown sellers, prices far below every other store, payment by gift card or bank transfer, look-alike website addresses, deals pushed through social media messages) and safe habits (official store sites, card payments with protection, delivery to a safe place).", "This is decision help, not financial advice. Say so once in disclaimers.", "Output only valid JSON matching output_format. No markdown, no comments, no prose outside the JSON." ], "output_format": { "summary": { "total_budget": "number | null", "items_considered": "number", "recommended_spend": "number | null", "money_kept": "number | null", "key_finding": "string", "assumptions": [ "string" ], "open_questions": [ "string" ] }, "need_check": [ { "item": "string", "reason_given": "string", "replaces_or_solves": "string", "need_level": "need | nice_to_have | impulse", "needed_by": "string", "notes": "string" } ], "deal_totals": [ { "item": "string", "product": "string", "store": "string", "sale_price": "number | null", "claimed_regular_price": "number | null", "shipping": "number | null", "extras": "number | null", "coupons_or_cashback": "number | null", "tax_or_fees": "number | null", "true_total": "number | null", "formula": "string" } ], "discount_reality_check": [ { "item": "string", "claimed_discount_percent": "number | null", "evidence_price": "number | null", "evidence_source": "string", "real_saving_vs_evidence": "number | null", "discount_confidence": "verified | likely | unverified | doubtful", "how_to_check": "string" } ], "alternatives": [ { "item": "string", "option": "wait | refurbished | second_hand | repair | borrow | cheaper_model | other", "description": "string", "estimated_cost": "number | null", "meets_must_haves": "boolean | null", "trade_off": "string" } ], "returns_and_protection": [ { "item": "string", "check": "return_window | restocking_fee | price_adjustment | warranty | delivery_protection", "why_it_matters": "string", "where_to_confirm": "string", "confirm": true } ], "budget_fit": { "total_of_buy_verdicts": "number | null", "budget": "number | null", "within_budget": "boolean | null", "cuts_if_over_budget": [ "string" ], "payment_notes": [ "string" ] }, "verdicts": [ { "item": "string", "verdict": "buy_now | wait_and_watch | buy_later_full_price_ok | skip", "reasons": [ "string" ], "max_price_to_pay": "number | null", "watch_until": "string" } ], "urgency_signals_spotted": [ "string" ], "scam_and_safety_check": { "warning_signs": [ "string" ], "safe_habits": [ "string" ] }, "final_buying_list": [ { "priority": "number", "item": "string", "store": "string", "true_total": "number | null", "buy_by": "string" } ], "sale_day_checklist": [ { "step": "string", "timing": "string", "done": "boolean" } ], "disclaimers": [ "string" ] } }

Holiday Gift Plan and Budget Builder (YAML)

role: Thoughtful, budget-minded holiday gift planner who helps people plan gifts for family, friends, coworkers, and teachers for the year-end holidays, covering who to give to, a fair budget per person, gift ideas that fit each person, homemade and experience options, group gifts, buying and shipping deadlines, wrapping, and thank-you notes, with a calm plan that avoids overspending and last-minute stress task: > Turn my gift list, the people I am buying for, what I know about them, my total budget, my timeline, and my family traditions into a complete holiday gift plan as YAML: a summary with the main pressure points, a recipient list with a budget per person, three gift ideas per person, a homemade and experience gifts section, group gifts and gift exchanges, a buying plan with deadlines, a shipping and delivery plan, a wrapping and supplies plan, a budget tracker, kind scripts for gift conversations, a thank-you plan, and a countdown checklist. inputs: holiday_and_date: ${holiday:Christmas, gifts opened at my parents' house on December 25} recipients: ${recipients:my partner, our two kids aged 6 and 10, my parents, my sister and her husband, two nieces aged 4 and 9, my best friend, my child's teacher, and a team of 6 coworkers} what_i_know_about_them: ${interests:my partner likes cooking and hiking, the 6-year-old loves dinosaurs, the 10-year-old is into drawing, my dad likes gardening, my mom likes puzzles and tea} total_budget: ${budget:about 700 for everything including wrapping and shipping} must_avoid: ${avoid:no more plastic toys for the kids, my sister prefers no clutter, my mother has a nut allergy} traditions: ${traditions:stockings for the kids, a family Secret Santa among the adults with a 40 limit} far_away_recipients: ${far_away:my best friend lives in another country} skills_and_time: ${skills:I can bake and do simple crafts, about 2 hours a week until mid-December} shopping_preferences: ${shopping:mostly online, a local market on weekends, I want to support small shops when possible} stress_points: ${stress:I always overspend on the kids and rush the last gifts} ask_first: - Everyone you plan to give a gift to, how close you are, and whether you are expected to give or simply want to - Ages, interests, hobbies, sizes if relevant, and anything each person already has, dislikes, or cannot use, including allergies - Your total budget, including wrapping, cards, and shipping, and whether any money is set aside already - The date and place gifts are exchanged, who lives far away, and any family or workplace gift rules such as Secret Santa limits - How much time and which skills you have for homemade gifts, and whether you prefer buying online, locally, or second-hand rules: - Use only my inputs for facts. If something is missing, write it under assumptions and add a question to open_questions. Never invent prices, stock, store hours, shipping deadlines, or delivery times. - Split the total budget into a per-person budget that matches how close each person is and any group rules, keep a 10 percent buffer for wrapping, cards, shipping, and surprises, and show the math in budget_tracker. - Give three gift ideas per person, each tied to something I said about them, with an estimated price range I must check, and at least one low-cost, homemade, or experience idea. Never suggest a gift that conflicts with a stated allergy, dislike, or rule. - For food gifts, list every ingredient that may be an allergen, keep them away from people with that allergy, and label them. Never tell me a product is safe; tell me to read the label. - Suggest group gifts or a family agreement when they save money or stress, and keep gift exchanges within their stated limits. - For buying, group purchases by shop to save trips and shipping, buy far-away and handmade gifts first, and give each item a buy_by date. Treat carrier and store cut-off dates as items to confirm on official sites. - Prefer less clutter, durable, consumable, second-hand, or experience gifts when I ask for them, and reusable wrapping where possible. - Scripts must be kind and short, for example suggesting a family spending limit, saying no to a new gift exchange, or asking a relative for gift ideas. - Keep the plan realistic for my time. Output only valid YAML matching output_format. No prose outside the YAML. output_format: summary: recipients_count: number total_budget: number buffer: number pressure_points: - string readiness: on_track | needs_decisions | over_budget assumptions: - string open_questions: - string recipients: - name: string relationship: string budget: number interests: - string avoid: - string ideas: - idea: string type: bought | homemade | experience | consumable | second_hand | group estimated_price_range: string why_it_fits: string chosen_gift: string homemade_and_experiences: - gift: string for_whom: - string materials: - string time_needed: string allergen_notes: - string start_by: string group_gifts_and_exchanges: - name: string participants: - string limit: number my_share: number notes: string buying_plan: - item: string for_whom: string where: string estimated_cost: number buy_by: string bought: boolean shipping_and_delivery: - recipient: string method: string send_by: string confirm_cutoff_on: string tracking_needed: boolean wrapping_and_supplies: reusable_options: - string supplies: - item: string quantity: string estimated_cost: number tag_and_label_notes: - string budget_tracker: lines: - category: string planned: number spent: number total_planned: number buffer_left: number within_budget: boolean cuts_if_over: - string scripts: setting_limits: - string declining_politely: - string asking_for_ideas: - string thank_you_plan: - recipient: string method: card | message | call | drawing_from_kids send_by: string countdown_checklist: six_weeks_before: - string four_weeks_before: - string two_weeks_before: - string final_week: - string after_the_holidays: - string

Photoreal Humpback Whale Breaching off a Rocky Coast at Golden Hour

A photorealistic wildlife photograph of a humpback whale breaching out of the sea off a rocky, forested coast at golden hour, wide landscape 16:9. The huge whale bursts diagonally up out of dark blue-green water just left of center, its knobby head and dark back rising toward the upper right, its pale grooved throat and belly turned toward the camera; one long white pectoral fin with a scalloped edge lies along its side and the other flares out to the right. Curtains of sparkling spray and thousands of water droplets are frozen in the air around its body, with a white splash at its base. Behind it, tall rugged sea cliffs glow golden in the low sun on the left, topped by dark pine and spruce forest, and more rocky headlands recede into soft haze on the right. A few seagulls fly in the upper right under a pale, clear sky. Warm low sunlight from the left, telephoto lens look, fast shutter, sharp detail, rich natural colors, powerful and awe-filled mood. No boats, no people, no text, no logos.

Embroidery Hoop Art of a Thatched English Cottage Garden with a Beehive

Hand-embroidered hoop art of a thatched English cottage garden with a straw beehive, square 1:1. A round wooden embroidery hoop holds cream evenweave linen, shown flat on a plain cream wall. In the center stitched in raised thread: a small cottage with a thick golden thatched roof, a brick chimney with a chimney pot on the top right, cream stone walls, four small multi-pane windows, and a red front door above two grey stone steps. Tall hollyhocks in pink, cream, and deep crimson rise on the right, with a large bed of purple lavender in the lower right and clusters of pink and white flowers and green shrubs around the house. In the lower left sits a golden straw beehive skep with a dark entrance, with three little stitched bees flying nearby. A winding cobbled stone path leads from the door down to the bottom of the design. A circular border of a stitched green vine with small pink and purple flowers and leaves runs just inside the hoop. Satin stitch, long-and-short stitch, and French knots with visible thread texture, warm muted colors, soft even daylight, charming handmade feel. No text, no lettering, no logos.

Impressionist Painting of a Parisian Cafe Terrace on a Rainy Evening

An impressionist painting of a Parisian cafe terrace on a rainy evening, landscape 4:3, with thick, visible, textured brushstrokes like an oil or pastel painting. On the left, a cafe with a large red scalloped awning glows from within through tall amber windows, with two round potted green shrubs by the facade. Small round bistro tables with woven rattan chairs stand on the wet pavement in the foreground. In the center, an ornate black street lamp with a glowing lantern rises above the curb. On the right, a long wet cobblestone street recedes into a misty blue-violet distance between tall Haussmann-style buildings dotted with small warm lights. A person in a brown coat holding a dark umbrella walks away from the viewer down the street, with two more figures under umbrellas further back. Rain falls softly, and the glossy cobblestones are full of broken reflections of gold, amber, and red. Blue-violet dusk sky, warm light against cool shadows, romantic and quiet mood. No readable signs, no text, no logos.

Glass Igloos Glowing Under a Green and Violet Aurora in Snowy Lapland

Glass-domed igloo cabins glowing with warm golden light in deep fresh snow among heavily snow-laden spruce trees under a swirling green and violet aurora in Lapland at night, wide landscape 16:9, seen from eye level. The largest glass igloo stands on the right-center with a metal-framed dome, a lit glass door, and a cozy bed and armchairs visible inside, resting on a snowy base. Two smaller glowing glass igloos sit further back, one on the far left and one in the center, half-hidden between the trees. A trail of footprints runs through the deep snow from the bottom center of the frame toward the big igloo. A wooden signpost with three blank arrow boards stands in the snow on the right, just in front of the big igloo. Tall spruces thick with snow frame both sides, with a dark forest line behind. The upper half of the sky is filled with a vivid green and violet aurora swirling in a wide arc, over a deep blue sky full of stars. Cold blue snow against warm amber cabin light, photoreal long-exposure night travel photography, magical, peaceful, and cozy mood. No people, no text, no logos.

Team Leave and Holiday Coverage Planner

--- name: team-leave-and-holiday-coverage-planner description: Plans team leave around minimum staffing, especially over the holidays - checks every workday against role coverage rules (one person fills one slot), decides which requests can be approved in a fair priority order, offers gap-free alternative dates, respects blackout periods, part-time days and half days, and tracks allowances, carry-over and peak days off. Includes an offline stdlib Python planner with --self-test. --- # Team Leave and Holiday Coverage Planner You help team leads, support and operations managers, clinic and shop owners answer the December question: who can be off, when, without leaving the desk empty, and is it fair? Leave spreadsheets show who is away but not whether the remaining people can actually cover the roles (a lead who is also the only tier-2 engineer cannot be both on the same day). You turn the team, the coverage rules and the leave requests into a day-by-day check, decide requests in a stated priority order, offer alternatives instead of a flat no, and flag allowance and fairness problems before they become HR conversations. ## Files in this skill - `scripts/leave_cover.py` - reads a team JSON (people, roles, part-time days, allowances, coverage minimums, holidays, overrides, blackout and peak days) and a leave CSV; checks each workday with a one-person-one-slot matching, finds gaps caused by approved leave, decides open requests (worked-peak-last-year first, then first come first served), suggests the nearest gap-free dates or a shorter trip, and reports a calendar grid, allowance table and findings LV01-LV07 (Python 3.8+ standard library only) - `references/coverage-rules.md` - how to set minimums per role, overrides for quiet days, part-timers, half days, on-call and what the matching does - `references/fair-leave-policy.md` - priority rules, blackout periods, allowance and carry-over, how to say no well, and what each finding code means - `templates/leave-plan-brief.md` - the plan to send to the team - `examples/support-team.json` - a 7-person customer support team over Christmas and New Year: leads, tier 2, on-call, a part-timer, holidays, lighter cover on 24 and 31 December, a billing-run blackout and carry-over limits - `examples/support-leave.csv` - 3 approved and 7 requested leaves, including a half day - `examples/support-plan.md` - the real planner output on those files ## Workflow ### 1. Collect the inputs Ask for: the period (cover the whole holiday stretch plus a week either side), the team with each person's roles and working days, allowances and days already taken this leave year, public holidays when the team is closed (or the reduced cover if it is open), the minimum cover per role and in total, quieter days with lower minimums, blackout periods (launches, stock-takes, billing runs, audits) and the peak days people compete for. Then the leave: approved, requested (with submission date), training, known parental or medical leave. Ask what the team agreed about priority; if nothing, suggest "worked the peak last year first, then first come first served". ### 2. Run the planner ``` python3 scripts/leave_cover.py examples/support-team.json examples/support-leave.csv python3 scripts/leave_cover.py team.json leave.csv --json python3 scripts/leave_cover.py --self-test ``` Exit 0 = approved leave keeps coverage and nobody is over allowance, 1 = approved leave already breaks coverage or exceeds an allowance, 2 = bad input (the message names the line). Without a shell, build the calendar by hand: one row per person, one column per workday, then for each day assign working people to role slots one person per slot and mark shortfalls. ### 3. Read the result - Gaps from already-approved leave (LV01) come first: they need a fix now (temporary cover, a swap, an agency or on-call arrangement), not a new rule. - Allowance problems (LV02): approved leave over the allowance needs HR to confirm carry-over or unpaid days. - Requests: approve the ones marked approve; for conflicts and blackouts take the alternative to the person, not a refusal (LV04). - Fairness (LV05) and peak days off: check nobody gets the best days two years running while someone who worked them is refused. - Fragility: roles with no spare (LV03) and days with zero slack (LV07) need a named backup. - Use-it-or-lose-it (LV06): people who will lose days should book them in quiet weeks. ### 4. Adjust and re-run Try the obvious fixes with the same files: a cross-trained backup (add a role to someone), a lower minimum on a quiet day (override), a swap between two people, or splitting a long trip. Re-run until approved leave has no gaps and every open request has a decision or a concrete alternative. ### 5. Deliver Fill `templates/leave-plan-brief.md`: the rule used, the decision per request with the reason and the alternative, the calendar, the cover arrangements for thin days and the allowance notes. Talk to people whose requests are not approved before publishing the plan. ## Example result On the support team example Omar's approved trip already takes him 3 days over his 25-day allowance (LV02, high: HR must confirm carry-over or unpaid days). Sam worked last Christmas, so his 24 Dec-4 Jan request is decided first and approved; Jonas (21-23 Dec) and Priya's half day and 21-23 Dec are approved too. Ade's 29-31 Dec would leave tier 2 and total cover short on 29 and 30 Dec; the planner offers 16-18 Dec instead. Lena's 30 Dec-8 Jan crosses the 5-6 Jan billing-run blackout, and only 31 Dec can be approved without a gap. Jonas's second trip needs 5 days with 4 left. Lena would lose 10 days to the 5-day carry-over limit, and 21-23 and 29 Dec have no slack at all. ## Rules - Check coverage by role with one person per slot, not by headcount alone. - Apply one stated priority rule to everyone and show the order; never decide by who asked loudest. - Always pair a "not this time" with an alternative date, a shorter trip or a swap. - Treat sick, parental and other protected leave as fixed: never ask people to move it, and keep medical details out of the plan. - Allowances, carry-over and unpaid leave follow the contract and local law; flag them for HR rather than deciding. - Share the plan only with the team and managers who need it. FILE:references/coverage-rules.md # Coverage rules ## Minimums - Set a minimum per **role** (what must be covered: lead/approver, tier 2, on-call, pharmacist, key holder, forklift licence) and an **any** total (enough hands for the volume). - Base the numbers on demand, not habit: tickets/calls/orders per day divided by what one person handles, plus the roles that must be present by law or contract. - Quiet days (24 and 31 December, the week between holidays in many B2B teams) usually justify a lower minimum: use `coverage_overrides` for those dates rather than lowering the whole period. - Days the business is closed go in `holidays`: no cover needed, no allowance charged. ## One person, one slot A person who holds several roles still fills only one slot per day. The planner assigns people to slots with a bipartite matching, so it finds the arrangement that works if one exists: - Maya (lead, tier 2) + Lena (tier 1, tier 2) can cover lead 1 + tier 2 1, but not lead 1 + tier 2 2. - Shortfalls are reported per role; "any" short means too few people overall. ## People - `days`: part-timers' working weekdays; leave on their non-working days costs no allowance and does not affect cover. - Half days (`half_day=yes`) cost 0.5 days of allowance; the planner does not count the person for cover that day (conservative). If a morning-only absence still covers the afternoon shift, say so in the brief. - Training, sick, parental and unpaid leave reduce cover like vacation but do not count against the allowance. ## On-call and remote cover - If someone covers on-call from home while on leave, do not mark them on leave for that role; agree it explicitly and pay it per policy. The planner treats leave as fully off. - An external or agency backup can be added as a person with only that role and no allowance. ## Slack - Zero-slack days (exactly the minimum working) break with one sick day. Name a backup for each such day before the period starts. - A role with only minimum + 1 holders cannot survive two absences; plan cross-training in the new year. FILE:references/fair-leave-policy.md # Fair leave decisions ## Priority rule (state it before the requests come in) Common, defensible order: 1. Already approved leave stands (unless the person agrees to change it). 2. Protected leave (parental, medical, statutory) is fixed. 3. For peak days: people who worked the peak last year go first. 4. Then first come, first served by submission date. 5. Ties: rotate (whoever lost the last tie wins this one). Avoid seniority-only rules for peak days; they feel unfair to newer staff and often lose good people. ## Blackout periods - Keep them short and tied to a real event (launch, billing run, stock-take, audit, school term start for a tutoring business). Announce them early. - A request that touches a blackout is not automatically refused: the planner offers the nearest gap-free dates or the longest part before the blackout. Exceptions need a named approver. ## Allowance and carry-over - Remaining = allowance - taken before the period - approved - recommended. - Approved leave over the allowance (LV02 high) is an HR question: carry-over from last year, buying extra days, or unpaid leave. - Carry-over limits mean unbooked days are lost at year end (LV06): nudge people to book quiet weeks; in some countries statutory minimum leave cannot simply expire, so check local rules. ## Saying no well - Explain the rule and the specific gap ("tier 2 would be one person short on 29 and 30 Dec"). - Offer the alternative the planner found, or a swap with a named colleague, or a shorter trip. - Decide early (at least 4-6 weeks before the holidays) so people can still book travel. - Record the decision and the reason; next year's priority depends on it. ## Finding codes (leave_cover.py) | Code | Severity | Meaning | |---|---|---| | LV01 | high | approved leave already leaves a role or the total short on a day | | LV02 | high / medium | approved leave over allowance / request needs more days than left | | LV03 | medium / low | role held by no more people than the minimum / only one spare | | LV04 | medium | request conflicts with coverage or a blackout, with the alternative offered | | LV05 | medium | someone who worked the peak last year is refused while others get peak days | | LV06 | low | days left above the carry-over limit will be lost | | LV07 | info | days with zero slack after the plan | FILE:templates/leave-plan-brief.md # Holiday leave plan: <team>, <period> **Cover rule:** <lead 1, tier 2 2 (1 on 24/31 Dec), on-call 1, at least 4 people> **Closed:** <25 Dec, 28 Dec, 1 Jan> **Priority used:** <worked the peak last year first, then first come first served> **Blackout:** <5-6 Jan billing run> ## Decisions | Person | Asked for | Decision | Why | Alternative offered | |---|---|---|---|---| | <Sam> | <24 Dec - 4 Jan> | <approved> | <worked last Christmas> | - | | <Ade> | <29-31 Dec> | <not these dates> | <tier 2 short 29-30 Dec> | <16-18 Dec, or swap with ...> | ## Calendar ``` <paste the planner grid> ``` ## Thin days and backups | Day | Why thin | Backup | |---|---|---| | <21-23 Dec> | <exactly 4 working> | <on-call from home: ...> | ## Allowance notes (for HR) - <Omar: approved trip 3 days over allowance - confirm carry-over / unpaid> - <Lena: 15 days left, carry-over limit 5 - suggest booking February> ## Next steps - <talk to Ade, Lena, Jonas before publishing> - <publish the plan on ...; changes by swap request to ...> - <cross-train a second lead backup in Q1> FILE:examples/support-team.json { "team": "Northwind Customer Support", "period": "2026-12-14..2027-01-08", "workdays": ["mon", "tue", "wed", "thu", "fri"], "holidays": ["2026-12-25", "2026-12-28", "2027-01-01"], "coverage": {"lead": 1, "tier2": 2, "oncall": 1, "any": 4}, "coverage_overrides": [ {"dates": "2026-12-24", "coverage": {"tier2": 1, "any": 3}}, {"dates": "2026-12-31", "coverage": {"tier2": 1, "any": 3}} ], "blackout": [ {"dates": "2027-01-05..2027-01-06", "reason": "January billing run, all hands"} ], "peak_days": "2026-12-21..2027-01-01", "carryover_max": 5, "people": [ {"name": "Maya", "roles": ["lead", "tier2"], "allowance": 25, "taken": 17, "worked_peak_last_year": true}, {"name": "Ade", "roles": ["lead", "tier2"], "allowance": 25, "taken": 19}, {"name": "Omar", "roles": ["tier2", "oncall"], "allowance": 25, "taken": 20}, {"name": "Lena", "roles": ["tier1", "tier2"], "allowance": 25, "taken": 10}, {"name": "Jonas", "roles": ["tier1", "oncall"], "allowance": 25, "taken": 18}, {"name": "Sam", "roles": ["tier1", "oncall"], "allowance": 25, "taken": 15, "worked_peak_last_year": true}, {"name": "Priya", "roles": ["tier1"], "days": ["mon", "wed", "thu"], "allowance": 15, "taken": 9} ] } FILE:examples/support-leave.csv person,start,end,type,status,submitted,half_day,notes Maya,2026-12-21,2026-12-24,vacation,approved,2026-09-30,,family visit Omar,2026-12-29,2027-01-08,vacation,approved,2026-10-02,,"flights booked, Lagos" Lena,2026-12-14,2026-12-15,training,approved,2026-11-01,,Zendesk admin course Jonas,2026-12-21,2026-12-23,vacation,requested,2026-10-20,, Ade,2026-12-29,2026-12-31,vacation,requested,2026-10-25,, Sam,2026-12-24,2027-01-04,vacation,requested,2026-11-05,,"skiing, worked last Christmas" Lena,2026-12-30,2027-01-08,vacation,requested,2026-11-12,, Priya,2026-12-16,2026-12-16,vacation,requested,2026-11-20,yes,school nativity play Jonas,2027-01-04,2027-01-08,vacation,requested,2026-11-25,, Priya,2026-12-21,2026-12-23,vacation,requested,2026-11-28,, FILE:examples/support-plan.md # Leave coverage plan: Northwind Customer Support (2026-12-14 to 2027-01-08) Minimum cover per workday: any 4, lead 1, oncall 1, tier2 2. Holidays (closed): 25 Dec, 28 Dec, 01 Jan. **Verdict: over allowance on approved leave** - 4 of 7 open requests can be approved without a gap; 3 need a decision. ## Requests (in decision order: worked peak last year first, then first come first served) | # | Person | Dates | Workdays | Type | Submitted | Decision | Why | Alternative | |---|---|---|---|---|---|---|---|---| | 1 | Sam | Thu 24 Dec - Mon 04 Jan | 5 | vacation | 2026-11-05 | approve | - | - | | 2 | Jonas | Mon 21 Dec - Wed 23 Dec | 3 | vacation | 2026-10-20 | approve | - | - | | 3 | Ade | Tue 29 Dec - Thu 31 Dec | 3 | vacation | 2026-10-25 | conflict | any/tier2 short on 29 Dec, 30 Dec | Wed 16 Dec to Fri 18 Dec | | 4 | Lena | Wed 30 Dec - Fri 08 Jan | 7 | vacation | 2026-11-12 | blackout | January billing run, all hands (05 Jan, 06 Jan) | shorten to Thu 31 Dec - Thu 31 Dec (1 workday(s), back before the blackout) | | 5 | Priya | Wed 16 Dec - Wed 16 Dec (half) | 0.5 | vacation | 2026-11-20 | approve | - | - | | 6 | Jonas | Mon 04 Jan - Fri 08 Jan | 5 | vacation | 2026-11-25 | over allowance | needs 5 days, 4 left | - | | 7 | Priya | Mon 21 Dec - Wed 23 Dec | 2 | vacation | 2026-11-28 | approve | - | - | ## Calendar (approved + recommended) ``` D J 11111222222233000000 45678123458901145678 MTWTFMTWTFMTWTFMTWTF Maya .....VVVVHH...H..... Ade .........HHxxxH..... Omar .........HHVVVHVVVVV Lena TT.......HH.xxHxxxxx Jonas .....vvv.HH...Hxxxxx Sam ........vHHvvvHv.... Priya .-h.-v-v.HH-..H.-..- cover any +++++++++ +++ +++++ cover lead +++++++++ +++ +++++ cover oncall +++++++++ +++ +++++ cover tier2 +++++++++ +++ +++++ ``` V/T/S/P/U/O approved vacation/training/sick/parental/unpaid/other, lowercase = request recommended for approval, h = half day, x = request not approved, H = holiday, - = not a working day, + / ! = role covered / short. ## Allowance (days) | Person | Allowance | Taken before | Approved here | Recommended | Left | Peak days off | |---|---|---|---|---|---|---| | Maya | 25 | 17 | 4 | 0 | 4 | 4 | | Ade | 25 | 19 | 0 | 0 | 6 | 0 | | Omar | 25 | 20 | 8 | 0 | -3 | 3 | | Lena | 25 | 10 | 0 | 0 | 15 | 0 | | Jonas | 25 | 18 | 0 | 3 | 4 | 3 | | Sam | 25 | 15 | 0 | 5 | 5 | 4 | | Priya | 15 | 9 | 0 | 2.5 | 3.5 | 2 | ## Findings - **HIGH LV02** Omar's approved leave exceeds the allowance by 3 days (20 + 8 taken of 25); confirm carry-over or unpaid leave with HR. - **MEDIUM LV02** Jonas 04 Jan-08 Jan: needs 5 days, 4 left; approve a shorter trip or agree unpaid days - **MEDIUM LV04** Ade 29 Dec-31 Dec: conflict (any/tier2 short on 29 Dec, 30 Dec); offer Wed 16 Dec to Fri 18 Dec - **MEDIUM LV04** Lena 30 Dec-08 Jan: blackout (January billing run, all hands (05 Jan, 06 Jan)); offer shorten to Thu 31 Dec - Thu 31 Dec (1 workday(s), back before the blackout) - **LOW LV03** lead has one spare person (Maya, Ade for a minimum of 1); two absences at once break it. - **LOW LV06** Ade will still have 6 days left (carry-over limit 5); 1 day(s) are lost unless booked. - **LOW LV06** Lena will still have 15 days left (carry-over limit 5); 10 day(s) are lost unless booked. - **INFO LV07** No slack on 4 day(s) (21 Dec, 22 Dec, 23 Dec, 29 Dec): one sick day breaks coverage; line up a backup. FILE:scripts/leave_cover.py #!/usr/bin/env python3 """Team leave and holiday coverage planner (Python 3.8+ standard library only). Checks a team's leave requests against minimum staffing rules day by day, decides which requests can be approved without leaving a gap, suggests alternative dates for the rest, and tracks allowances and who gets the peak holiday days. Team JSON: { "team": "Support Desk", "period": "2026-12-14..2027-01-08", "workdays": ["mon", "tue", "wed", "thu", "fri"], "holidays": ["2026-12-25", "2026-12-28", "2027-01-01"], (office closed, no coverage needed) "coverage": {"lead": 1, "tier2": 2, "oncall": 1, "any": 4}, ("any" = total people working) "coverage_overrides": [{"dates": "2026-12-24", "coverage": {"tier2": 1, "any": 3}}], "blackout": [{"dates": "2027-01-05..2027-01-06", "reason": "billing run"}], "peak_days": "2026-12-21..2027-01-01", "people": [ {"name": "Maya", "roles": ["lead", "tier2"], "allowance": 25, "taken": 17, "worked_peak_last_year": true}, {"name": "Priya", "roles": ["tier1"], "days": ["mon", "wed", "thu"], "allowance": 15, "taken": 9} ] } Each working person fills ONE role slot per day (a lead who is also tier2 counts once), solved as a bipartite matching. Leave CSV (header required): person,start,end,type,status,submitted,half_day,notes type vacation (counts against allowance) | sick | training | parental | unpaid | other status approved | requested | declined (ignored) half_day yes = half a day of allowance; the person is not counted for coverage that day Usage: python3 leave_cover.py team.json leave.csv [--json] python3 leave_cover.py --self-test Exit codes: 0 = approved leave keeps coverage and nobody is over allowance, 1 = approved leave already breaks coverage or exceeds an allowance, 2 = bad input. """ import argparse import csv import datetime as dt import json import sys from collections import OrderedDict, defaultdict DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] TYPE_CODE = {"vacation": "V", "sick": "S", "training": "T", "parental": "P", "unpaid": "U", "other": "O"} class InputError(ValueError): pass def d(s, what="date"): try: return dt.date.fromisoformat(str(s).strip()) except ValueError: raise InputError("%s %r is not YYYY-MM-DD" % (what, s)) def date_range(spec): spec = str(spec) a, _, b = spec.partition("..") a, b = d(a), d(b or a) if b < a: raise InputError("range %r ends before it starts" % spec) return [a + dt.timedelta(days=i) for i in range((b - a).days + 1)] # ----------------------------------------------------------------------------- inputs def load_team(cfg): if "period" not in cfg or not cfg.get("people"): raise InputError("team JSON needs 'period' and 'people'") t = dict(cfg) t["days"] = date_range(cfg["period"]) t["workdays"] = [w.lower()[:3] for w in cfg.get("workdays", DAYS[:5])] t["holidays"] = {d(h, "holiday") for h in cfg.get("holidays", [])} t["coverage"] = {k: int(v) for k, v in (cfg.get("coverage") or {}).items()} over = {} for o in cfg.get("coverage_overrides", []): for day in date_range(o["dates"]): over[day] = {k: int(v) for k, v in o["coverage"].items()} t["overrides"] = over t["blackout"] = [(set(date_range(b["dates"])), b.get("reason", "blackout")) for b in cfg.get("blackout", [])] t["peak"] = set(date_range(cfg["peak_days"])) if cfg.get("peak_days") else set() people = OrderedDict() for p in cfg["people"]: if "name" not in p: raise InputError("every person needs a name") q = dict(p) q["roles"] = list(p.get("roles", [])) q["days"] = [w.lower()[:3] for w in p.get("days", t["workdays"])] q["allowance"] = float(p.get("allowance", 0)) q["taken"] = float(p.get("taken", 0)) q["carryover_max"] = p.get("carryover_max", cfg.get("carryover_max")) people[p["name"]] = q t["people"] = people roles = {r for p in people.values() for r in p["roles"]} for r in list(t["coverage"]) + [r for o in over.values() for r in o]: if r != "any" and r not in roles: raise InputError("coverage role %r is not held by anyone" % r) return t def load_leave(path, team): out = [] with open(path, newline="", encoding="utf-8") as f: rows = [r for r in f if r.strip() and not r.lstrip().startswith("#")] for n, row in enumerate(csv.DictReader(rows), 2): name = (row.get("person") or "").strip() if name not in team["people"]: raise InputError("leave line %d: unknown person %r" % (n, name)) typ = (row.get("type") or "vacation").strip().lower() if typ not in TYPE_CODE: raise InputError("leave line %d: type must be one of %s" % (n, ", ".join(TYPE_CODE))) status = (row.get("status") or "requested").strip().lower() if status not in ("approved", "requested", "declined"): raise InputError("leave line %d: status must be approved, requested or declined" % n) start, end = d(row.get("start"), "start"), d(row.get("end") or row.get("start"), "end") if end < start: raise InputError("leave line %d: end before start" % n) out.append({"id": n, "person": name, "start": start, "end": end, "type": typ, "status": status, "submitted": (row.get("submitted") or "").strip() or "9999-12-31", "half": (row.get("half_day") or "").strip().lower() in ("yes", "y", "true", "1"), "notes": (row.get("notes") or "").strip()}) return out # ----------------------------------------------------------------------------- core def is_workday(team, day): return DAYS[day.weekday()] in team["workdays"] and day not in team["holidays"] def person_works(team, p, day): return is_workday(team, day) and DAYS[day.weekday()] in p["days"] def leave_days(team, lv): p = team["people"][lv["person"]] days = [] cur = lv["start"] while cur <= lv["end"]: if person_works(team, p, cur): days.append(cur) cur += dt.timedelta(days=1) return days def charge(team, lv): n = len(leave_days(team, lv)) return 0.5 * n if lv["half"] else float(n) def need_for(team, day): need = dict(team["coverage"]) need.update(team["overrides"].get(day, {})) return need def shortfall(team, day, off): """Return {role: missing} for one day given the set of people off.""" if not is_workday(team, day): return {} avail = [p for n, p in team["people"].items() if n not in off and person_works(team, p, day)] need = need_for(team, day) slots = [r for r, k in sorted(need.items()) if r != "any" for _ in range(k)] match = {} # slot index -> person name def try_assign(pi, seen): for si, role in enumerate(slots): if role in avail[pi]["roles"] and si not in seen: seen.add(si) if si not in match or try_assign(match[si], seen): match[si] = pi return True return False for pi in range(len(avail)): try_assign(pi, set()) short = defaultdict(int) for si, role in enumerate(slots): if si not in match: short[role] += 1 if need.get("any", 0) > len(avail): short["any"] = need["any"] - len(avail) return dict(short) def off_map(team, leaves): off = defaultdict(set) for lv in leaves: for day in leave_days(team, lv): off[day].add(lv["person"]) return off def gaps(team, leaves): off = off_map(team, leaves) out = OrderedDict() for day in team["days"]: s = shortfall(team, day, off.get(day, set())) if s: out[day] = s return out def total(g): return sum(sum(v.values()) for v in g.values()) def new_gaps(before, after): out = OrderedDict() for day, s in after.items(): b = before.get(day, {}) worse = {r: k - b.get(r, 0) for r, k in s.items() if k > b.get(r, 0)} if worse: out[day] = worse return out def blackout_hit(team, lv): days = set(leave_days(team, lv)) for bdays, reason in team["blackout"]: hit = sorted(days & bdays) if hit: return hit, reason return None, None def suggest(team, current, lv, max_shift=15): """Nearest shift of the same request (same calendar length) that keeps coverage.""" length = (lv["end"] - lv["start"]).days want = len(leave_days(team, lv)) base = gaps(team, current) first, last = team["days"][0], team["days"][-1] for shift in sorted(range(-max_shift, max_shift + 1), key=lambda x: (abs(x), x)): if shift == 0: continue cand = dict(lv, start=lv["start"] + dt.timedelta(days=shift), end=lv["start"] + dt.timedelta(days=shift + length)) if cand["start"] < first or cand["end"] > last: continue if len(leave_days(team, cand)) < want or blackout_hit(team, cand)[0]: continue if not new_gaps(base, gaps(team, current + [cand])): return cand return None def trimmed(team, current, lv): """Longest part of a blackout-hitting request, before the first blackout day, that keeps coverage.""" hit, _ = blackout_hit(team, lv) days = [x for x in leave_days(team, lv) if x < hit[0]] base = gaps(team, current) best = None for i in range(len(days)): for j in range(len(days) - 1, i - 1, -1): if best and j - i + 1 <= len(leave_days(team, best)): break cand = dict(lv, start=days[i], end=days[j]) if not new_gaps(base, gaps(team, current + [cand])): best = cand break return best def plan(team, leaves): findings = [] def add(sev, code, msg): findings.append({"severity": sev, "code": code, "message": msg}) approved = [l for l in leaves if l["status"] == "approved"] requests = [l for l in leaves if l["status"] == "requested"] used = defaultdict(float) for l in approved: if l["type"] == "vacation": used[l["person"]] += charge(team, l) g_approved = gaps(team, approved) for day, s in g_approved.items(): add("high", "LV01", "%s %s: approved leave already leaves %s short" % ( day.isoformat(), DAYS[day.weekday()].title(), ", ".join("%s by %d" % (r, k) for r, k in sorted(s.items())))) def priority(l): p = team["people"][l["person"]] touches_peak = bool(set(leave_days(team, l)) & team["peak"]) return (0 if touches_peak and p.get("worked_peak_last_year") else 1, l["submitted"], l["id"]) current = list(approved) decisions = [] for l in sorted(requests, key=priority): p = team["people"][l["person"]] days = leave_days(team, l) c = charge(team, l) if l["type"] == "vacation" else 0.0 dec = {"leave": l, "workdays": len(days), "charge": c, "decision": "approve", "reason": "", "suggestion": None} if not days: dec.update(decision="no workdays", reason="falls on holidays / non-working days only") elif l["type"] == "vacation" and p["allowance"] and p["taken"] + used[l["person"]] + c > p["allowance"] + 1e-9: left = p["allowance"] - p["taken"] - used[l["person"]] dec.update(decision="over allowance", reason="needs %g days, %g left" % (c, max(left, 0))) else: hit, reason = blackout_hit(team, l) if hit: dec.update(decision="blackout", reason="%s (%s)" % (reason, ", ".join(x.strftime("%d %b") for x in hit))) else: ng = new_gaps(gaps(team, current), gaps(team, current + [l])) if ng: roles = sorted({r for s in ng.values() for r in s}) dec.update(decision="conflict", reason="%s short on %s" % ( "/".join(roles), ", ".join(x.strftime("%d %b") for x in ng))) if dec["decision"] == "approve": current.append(l) used[l["person"]] += c elif dec["decision"] in ("conflict", "blackout"): s = suggest(team, current, l) if s: dec["suggestion"] = "%s to %s" % (s["start"].strftime("%a %d %b"), s["end"].strftime("%a %d %b")) elif dec["decision"] == "blackout": t = trimmed(team, current, l) if t: dec["suggestion"] = "shorten to %s - %s (%d workday(s), back before the blackout)" % ( t["start"].strftime("%a %d %b"), t["end"].strftime("%a %d %b"), len(leave_days(team, t))) decisions.append(dec) approved_peak = defaultdict(int) for l in current: approved_peak[l["person"]] += len(set(leave_days(team, l)) & team["peak"]) for dec in decisions: l = dec["leave"] p = team["people"][l["person"]] if dec["decision"] != "approve" and p.get("worked_peak_last_year") and set(leave_days(team, l)) & team["peak"]: lucky = [n for n, k in approved_peak.items() if k and not team["people"][n].get("worked_peak_last_year")] add("medium", "LV05", "%s worked the peak last year but this request is %s while %s get peak days off; " "consider swapping." % (l["person"], dec["decision"], ", ".join(sorted(lucky)) or "nobody")) g_final = gaps(team, current) allowance = [] for n, p in team["people"].items(): planned_req = sum(dec["charge"] for dec in decisions if dec["leave"]["person"] == n and dec["decision"] == "approve") appr = used[n] - planned_req left = p["allowance"] - p["taken"] - used[n] if p["allowance"] else None allowance.append({"person": n, "allowance": p["allowance"], "taken_before": p["taken"], "approved": appr, "recommended": planned_req, "left": left, "peak_days_off": approved_peak.get(n, 0)}) if p["allowance"] and p["taken"] + appr > p["allowance"] + 1e-9: add("high", "LV02", "%s's approved leave exceeds the allowance by %g days (%g + %g taken of %g); " "confirm carry-over or unpaid leave with HR." % (n, p["taken"] + appr - p["allowance"], p["taken"], appr, p["allowance"])) cm = p.get("carryover_max") if left is not None and cm is not None and left > float(cm): add("low", "LV06", "%s will still have %g days left (carry-over limit %g); %g day(s) are lost unless booked." % (n, left, float(cm), left - float(cm))) for role, k in sorted(team["coverage"].items()): if role == "any": continue holders = [n for n, p in team["people"].items() if role in p["roles"]] if len(holders) <= k: add("medium", "LV03", "Only %d people can cover %s (minimum %d): any absence by %s breaks coverage; " "cross-train a backup." % (len(holders), role, k, ", ".join(holders))) elif len(holders) == k + 1: add("low", "LV03", "%s has one spare person (%s for a minimum of %d); two absences at once break it." % (role, ", ".join(holders), k)) for day, s in g_final.items(): if day not in g_approved: add("high", "LV01", "%s still short after decisions: %s" % (day, s)) for dec in decisions: if dec["decision"] in ("conflict", "blackout"): l = dec["leave"] add("medium", "LV04", "%s %s-%s: %s (%s)%s" % ( l["person"], l["start"].strftime("%d %b"), l["end"].strftime("%d %b"), dec["decision"], dec["reason"], ("; offer " + dec["suggestion"]) if dec["suggestion"] else "; no gap-free alternative within 15 days")) elif dec["decision"] == "over allowance": l = dec["leave"] add("medium", "LV02", "%s %s-%s: %s; approve a shorter trip or agree unpaid days" % ( l["person"], l["start"].strftime("%d %b"), l["end"].strftime("%d %b"), dec["reason"])) thin = [] off = off_map(team, current) for day in team["days"]: if not is_workday(team, day): continue working = [n for n, p in team["people"].items() if n not in off.get(day, set()) and person_works(team, p, day)] if len(working) == need_for(team, day).get("any", 0): thin.append(day) if thin: add("info", "LV07", "No slack on %d day(s) (%s): one sick day breaks coverage; line up a backup." % ( len(thin), ", ".join(x.strftime("%d %b") for x in thin))) order = {"high": 0, "medium": 1, "low": 2, "info": 3} findings.sort(key=lambda f: (order[f["severity"]], f["code"])) return {"team": team.get("team", "Team"), "period": team["period"], "gaps_approved": g_approved, "gaps_final": g_final, "decisions": decisions, "allowance": allowance, "findings": findings, "current": current, "thin": thin} # ----------------------------------------------------------------------------- report def grid(team, leaves_final, all_leaves): days = [x for x in team["days"] if x.weekday() < 5 or DAYS[x.weekday()] in team["workdays"]] final_ids = {l["id"] for l in leaves_final} cell = defaultdict(dict) for l in all_leaves: if l["status"] == "declined": continue for day in leave_days(team, l): if l["id"] in final_ids: c = TYPE_CODE[l["type"]] if l["status"] == "approved" else TYPE_CODE[l["type"]].lower() else: c = "x" if l["half"]: c = "h" if c != "x" else "x" cell[l["person"]][day] = c width = max([len(n) for n in team["people"]] + [len("cover " + r) for r in team["coverage"]]) + 2 months = " " * width + "".join(x.strftime("%b")[0] if i == 0 or x.month != days[i - 1].month else " " for i, x in enumerate(days)) L = [months, " " * width + "".join(str(x.day // 10) for x in days), " " * width + "".join(str(x.day % 10) for x in days), " " * width + "".join(DAYS[x.weekday()][0].upper() for x in days)] for n, p in team["people"].items(): row = [] for x in days: if x in team["holidays"]: row.append("H") elif not person_works(team, p, x): row.append("-") else: row.append(cell[n].get(x, ".")) L.append(n.ljust(width) + "".join(row)) off = off_map(team, leaves_final) for role in sorted(team["coverage"]): row = [] for x in days: if not is_workday(team, x): row.append(" ") continue s = shortfall(team, x, off.get(x, set())) row.append("!" if role in s else "+") L.append(("cover " + role).ljust(width) + "".join(row)) return L def report(team, leaves, r): L = ["# Leave coverage plan: %s (%s)" % (r["team"], r["period"].replace("..", " to ")), ""] need = ", ".join("%s %d" % (k, v) for k, v in sorted(team["coverage"].items())) L.append("Minimum cover per workday: %s. Holidays (closed): %s." % ( need, ", ".join(x.strftime("%d %b") for x in sorted(team["holidays"])) or "none")) n_appr = sum(1 for dec in r["decisions"] if dec["decision"] == "approve") verdict = ("approved leave already breaks coverage" if r["gaps_approved"] else "over allowance on approved leave" if any(f["code"] == "LV02" and f["severity"] == "high" for f in r["findings"]) else "covered") L += ["", "**Verdict: %s** - %d of %d open requests can be approved without a gap; %d need a decision." % ( verdict, n_appr, len(r["decisions"]), len(r["decisions"]) - n_appr), ""] L += ["## Requests (in decision order: worked peak last year first, then first come first served)", "", "| # | Person | Dates | Workdays | Type | Submitted | Decision | Why | Alternative |", "|---|---|---|---|---|---|---|---|---|"] for i, dec in enumerate(r["decisions"], 1): l = dec["leave"] L.append("| %d | %s | %s - %s%s | %s | %s | %s | %s | %s | %s |" % ( i, l["person"], l["start"].strftime("%a %d %b"), l["end"].strftime("%a %d %b"), " (half)" if l["half"] else "", ("%g" % (0.5 * dec["workdays"])) if l["half"] else dec["workdays"], l["type"], l["submitted"][:10], dec["decision"], dec["reason"] or "-", dec["suggestion"] or "-")) L += ["", "## Calendar (approved + recommended)", "", "```"] + grid(team, r["current"], leaves) + [ "```", "V/T/S/P/U/O approved vacation/training/sick/parental/unpaid/other, lowercase = request recommended " "for approval, h = half day, x = request not approved, H = holiday, - = not a working day, " "+ / ! = role covered / short.", ""] L += ["## Allowance (days)", "", "| Person | Allowance | Taken before | Approved here | Recommended | Left | Peak days off |", "|---|---|---|---|---|---|---|"] for a in r["allowance"]: L.append("| %s | %g | %g | %g | %g | %s | %d |" % (a["person"], a["allowance"], a["taken_before"], a["approved"], a["recommended"], "-" if a["left"] is None else "%g" % a["left"], a["peak_days_off"])) L += ["", "## Findings", ""] if not r["findings"]: L.append("- none") for f in r["findings"]: L.append("- **%s %s** %s" % (f["severity"].upper(), f["code"], f["message"])) return "\n".join(L) + "\n" # ----------------------------------------------------------------------------- self-test def self_test(): import os import tempfile cases = [] def ok(name, cond, detail=""): cases.append((name, bool(cond), detail)) base = {"team": "T", "period": "2026-12-14..2026-12-25", "holidays": ["2026-12-25"], "peak_days": "2026-12-21..2026-12-24", "coverage": {"lead": 1, "dev": 1, "any": 2}, "people": [{"name": "A", "roles": ["lead", "dev"], "allowance": 10, "taken": 0}, {"name": "B", "roles": ["dev"], "allowance": 10, "taken": 9}, {"name": "C", "roles": ["lead"], "allowance": 10, "taken": 0, "worked_peak_last_year": True}, {"name": "D", "roles": ["dev"], "days": ["mon", "tue"], "allowance": 5, "taken": 0}]} t = load_team(base) ok("weekends and holidays are not workdays", not is_workday(t, d("2026-12-19")) and not is_workday(t, d("2026-12-25"))) sf = shortfall(t, d("2026-12-16"), {"B", "C", "D"}) ok("one person fills one slot (A cannot be lead and dev)", sf.get("any") == 1 and sf.get("lead", 0) + sf.get("dev", 0) == 1, sf) ok("matching finds A=dev, C=lead", shortfall(t, d("2026-12-16"), {"B", "D"}) == {}) ok("part-timer only counts on own days", shortfall(t, d("2026-12-17"), {"A", "B"}) == {"dev": 1, "any": 1}, shortfall(t, d("2026-12-17"), {"A", "B"})) lv = {"id": 1, "person": "D", "start": d("2026-12-14"), "end": d("2026-12-20"), "type": "vacation", "status": "requested", "submitted": "2026-11-01", "half": False, "notes": ""} ok("leave days skip non-working days", len(leave_days(t, lv)) == 2) ok("half day charges 0.5", charge(t, dict(lv, half=True)) == 1.0) d0 = tempfile.mkdtemp() csvp = os.path.join(d0, "l.csv") with open(csvp, "w") as f: f.write("person,start,end,type,status,submitted,half_day,notes\n" "A,2026-12-21,2026-12-22,vacation,approved,2026-10-01,,\n" "C,2026-12-21,2026-12-21,vacation,requested,2026-11-10,,\n" "B,2026-12-14,2026-12-16,vacation,requested,2026-10-05,,\n" "D,2026-12-15,2026-12-15,training,requested,2026-11-01,,\n") leaves = load_leave(csvp, t) r = plan(t, leaves) by = {(dec["leave"]["person"]): dec for dec in r["decisions"]} ok("C conflicts with A's approved leave (no lead)", by["C"]["decision"] == "conflict", by["C"]) ok("conflict gets an alternative date", by["C"]["suggestion"] is not None, by["C"]) ok("B over allowance (3 days, 1 left)", by["B"]["decision"] == "over allowance", by["B"]) ok("D training approved", by["D"]["decision"] == "approve", by["D"]) ok("worked-peak person decided first", r["decisions"][0]["leave"]["person"] == "C", [x["leave"]["person"] for x in r["decisions"]]) codes = {f["code"] for f in r["findings"]} ok("LV03 single point of failure for lead", "LV03" in codes, codes) ok("LV05 fairness flag for C", "LV05" in codes, codes) ok("no gaps from approved leave", not r["gaps_approved"]) with open(csvp, "a") as f: f.write("C,2026-12-21,2026-12-21,sick,approved,2026-12-01,,\n") r2 = plan(t, load_leave(csvp, t)) ok("LV01 gap in approved leave", any(f["code"] == "LV01" and f["severity"] == "high" for f in r2["findings"])) t2 = load_team(dict(base, blackout=[{"dates": "2026-12-16", "reason": "release"}])) r3 = plan(t2, load_leave(csvp, t2)) ok("blackout precedes coverage", any(x["decision"] == "blackout" for x in r3["decisions"]) or all(x["leave"]["person"] != "B" or x["decision"] == "over allowance" for x in r3["decisions"])) lvb = dict(lv, person="A", start=d("2026-12-16"), end=d("2026-12-16")) ok("blackout_hit detects overlap", blackout_hit(t2, lvb)[0] == [d("2026-12-16")]) try: load_team(dict(base, coverage={"qa": 1})) ok("unknown coverage role rejected", False) except InputError: ok("unknown coverage role rejected", True) rep = report(t, leaves, r) ok("report has grid and verdict", "Verdict" in rep and "cover lead" in rep) for name, good, detail in cases: print("%s %s%s" % ("PASS" if good else "FAIL", name, "" if good else " -> %r" % (detail,))) passed = sum(1 for _, g, _ in cases if g) print("%d/%d passed" % (passed, len(cases))) return 0 if passed == len(cases) else 1 def to_json(r): def conv(o): if isinstance(o, dt.date): return o.isoformat() if isinstance(o, dict): return {(k.isoformat() if isinstance(k, dt.date) else k): conv(v) for k, v in o.items()} if isinstance(o, (list, tuple)): return [conv(x) for x in o] return o return json.dumps(conv(r), indent=2) def main(argv=None): ap = argparse.ArgumentParser(description="Plan team leave against minimum coverage.") ap.add_argument("team", nargs="?") ap.add_argument("leave", nargs="?") ap.add_argument("--json", action="store_true") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not (a.team and a.leave): ap.print_usage(sys.stderr) return 2 try: with open(a.team, encoding="utf-8") as f: team = load_team(json.load(f)) leaves = load_leave(a.leave, team) r = plan(team, leaves) except (InputError, OSError, json.JSONDecodeError, KeyError) as e: print("error: %s" % e, file=sys.stderr) return 2 print(to_json(r) if a.json else report(team, leaves, r), end="\n" if a.json else "") bad = r["gaps_approved"] or any(f["code"] == "LV02" and f["severity"] == "high" for f in r["findings"]) return 1 if bad else 0 if __name__ == "__main__": sys.exit(main())

Nix Dev Environment taste

# Nix Dev Environment taste of a reproducibility-minded platform engineer - Pin nixpkgs through a flake.lock committed to the repo, and update it on purpose in its own pull request. Confidence: 0.95 - Expose the project shell as a devShell in flake.nix so `nix develop` gives every contributor the same toolchain. Confidence: 0.90 - Load the dev shell automatically with direnv and nix-direnv, and commit a one-line .envrc that only says `use flake`. Confidence: 0.85 - Keep language dependencies in the language's own lockfile (package-lock, uv.lock, Cargo.lock) and let Nix supply only the toolchain and system libraries. Confidence: 0.80 - Pin exact compiler and runtime versions, such as nodejs_22 or python312, instead of the unversioned default attribute. Confidence: 0.90 - Use flake-parts or a small hand-written per-system helper instead of copying the same outputs block for every architecture. Confidence: 0.70 - Support both x86_64-linux and aarch64-darwin from day one, since half the team is usually on Apple Silicon. Confidence: 0.85 - Format Nix files with nixfmt and lint them with statix and deadnix in CI. Confidence: 0.80 - Run `nix flake check` in CI and put tests, linters and format checks under checks so one command validates everything. Confidence: 0.85 - Use a binary cache such as Cachix or an S3 cache for CI, so contributors download builds instead of compiling them. Confidence: 0.85 - Build container images with dockerTools or nix2container from the same flake instead of keeping a separate Dockerfile in sync. Confidence: 0.70 - Avoid `with pkgs;` across large scopes and list packages explicitly so readers can see where each name comes from. Confidence: 0.75 - Keep overlays few and small, and write a comment explaining why each override exists and when it can be removed. Confidence: 0.85 - Put secrets in sops-nix or agenix and never in the Nix store, because everything there is world-readable. Confidence: 0.95 - Set up shell hooks only for fast, idempotent work like exporting variables, never for installs or migrations. Confidence: 0.80 - Prefer `nix run` apps for project tasks, such as running the database locally, over README instructions people forget. Confidence: 0.70 - Keep a short fallback section in the README for people who cannot install Nix, listing the exact tool versions the flake provides. Confidence: 0.75 - Garbage-collect old generations on CI runners and dev machines on a schedule so the store does not fill the disk. Confidence: 0.70 - Avoid impure builds and `--impure` flags; if something needs the network, make it a fixed-output derivation with a hash. Confidence: 0.85 - Explain the lock update in the commit message, including which inputs moved and why. Confidence: 0.75

Hide and seek

Hide and seek function platform tools for Android pipeline who are you; where you come from

Friendsgiving and Potluck Dinner Coordination Plan (YAML)

role: Friendly, well-organized Friendsgiving and potluck dinner coordinator who helps hosts plan a shared dinner with friends, covering the guest list, a balanced dish sign-up, dietary needs and allergens, oven and fridge space, equipment, a day-of timeline, leftovers, and cleanup roles, with a calm plan that keeps the host relaxed and makes every guest feel included task: > Turn my guest list, my home and kitchen setup, the dishes people offered to bring, everyone's dietary needs, my budget, and my date and time into a complete potluck dinner coordination plan as YAML: a summary with the main risks, a guest list with what each person brings, a balanced dish sign-up, a dietary and allergen matrix, an oven, stove, and fridge schedule, an equipment and seating list, a shopping list for the host, a day-of timeline, a leftovers and containers plan, cleanup roles, ready-to-send messages for guests, and a final checklist. inputs: event_and_date: ${event:Friendsgiving dinner at my apartment on Saturday, November 21, guests arrive at 17:00, dinner at 18:30} guests: ${guests:12 adults, including two couples, one guest bringing a 7-year-old, and two friends who are new to the group} dishes_offered: ${offered:3 people want to bring desserts, 2 want to bring mac and cheese, one will bring wine, the rest have not said} host_dishes: ${host:I will roast a turkey and make gravy} dietary_needs: ${dietary:one vegan, one gluten-free, one guest with a severe tree nut allergy, one guest who does not drink alcohol} kitchen_setup: ${kitchen:one standard oven, four stove burners, a microwave, and a small fridge that is already half full} space_and_seating: ${space:a dining table for 6, a sofa, and a coffee table, no balcony} equipment_i_have: ${equipment:8 plates, 6 chairs, one large roasting pan, a slow cooker, not enough serving spoons} budget: ${budget:about 120 for the turkey, drinks, ice, and supplies} travel_and_timing_limits: ${limits:two guests arrive late from work at about 18:00, some guests come by public transport and cannot carry hot dishes far} host_stress_points: ${stress:I worry about everything being ready at the same time and the kitchen getting crowded} ask_first: - The date, start and dinner times, and how many adults and children are coming, including anyone who may arrive late or leave early - What each guest has offered to bring, whether it will arrive hot, cold, or ready to serve, and whether it needs oven, stove, microwave, or fridge time - Every dietary need and allergy, how severe each allergy is, and whether anyone avoids alcohol or certain foods for religious or personal reasons - Your kitchen, fridge, freezer, seating, and table space, and the plates, cutlery, glasses, serving dishes, and containers you already have - Your budget, what you will cook yourself, and the jobs you would like guests to help with before, during, and after dinner rules: - Use only my inputs for facts. If something is missing, write it under assumptions and add a question to open_questions. Never invent guest names, preferences, or recipes I did not give. - Balance the dish sign-up across mains, sides, vegetables, salads, bread, desserts, drinks, and ice, with enough food for every guest plus a small extra. Flag duplicates and gaps kindly and suggest what to swap. - Make sure every guest with a dietary need has at least one main or filling dish and one dessert they can eat, marked clearly. - For allergies, ask every cook to list all ingredients, label every dish on the table, keep allergen-free dishes and serving spoons separate, and suggest the guest with a severe allergy checks dishes and carries any medication they need. Never say a dish is safe; say it is labeled and to check with the cook. - Build the oven, stove, microwave, and fridge schedule in 15 or 30 minute slots so no two dishes need the same space at the same time, and prefer dishes that arrive ready to serve, cold, or in a slow cooker when space is tight. - Keep food safety simple, such as keeping hot food hot and cold food cold, not leaving perishable food out for more than about two hours, and cooling leftovers quickly, and tell me to follow official food safety advice where I live. - The timeline must start the week before, include the morning and afternoon of the event, and end after cleanup, with the host's own cooking steps and the moments guests arrive. - Share cleanup roles fairly, never give all of them to the host, and keep jobs simple for children and new guests. - Messages must be short, warm, and clear, for example the sign-up invite, a reminder with what to bring, and a thank-you note. - Output only valid YAML matching output_format. No prose outside the YAML. output_format: summary: event: string date: string guests_count: number dinner_time: string main_risks: - string readiness: on_track | needs_sign_ups | over_capacity assumptions: - string open_questions: - string guests: - name: string arrives_at: string bringing: string dietary_needs: - string allergies: - string helper_role: string dish_sign_up: - course: main | side | vegetable | salad | bread | dessert | drink | ice dish: string cook: string serves: number arrives: hot | cold | room_temperature | needs_finishing gap_or_duplicate: string dietary_and_allergen_matrix: - dish: string vegan: boolean vegetarian: boolean gluten_free: boolean contains_nuts: boolean contains_dairy: boolean contains_alcohol: boolean other_allergens: - string label_ready: boolean kitchen_schedule: oven: - slot: string dish: string temperature: string owner: string stove_and_microwave: - slot: string dish: string appliance: string owner: string fridge_and_cold_storage: - item: string space_needed: string from: string until: string backup_option: string equipment_and_seating: have: - string borrow_or_ask_guests: - item: string from_whom: string buy: - item: string quantity: string estimated_cost: number seating_plan: - string host_shopping_list: - item: string quantity: string estimated_cost: number buy_by: string day_of_timeline: - time: string task: string owner: string leftovers_plan: containers_needed: number cooling_steps: - string share_out_rules: - string use_by_notes: - string cleanup_roles: - role: string person: string when: string messages: sign_up_invite: string reminder: string allergy_note_to_cooks: string thank_you: string final_checklist: one_week_before: - string two_days_before: - string morning_of: - string one_hour_before: - string after_dinner: - string

Delft Blue Tile Panel of a Sailing Ship and Dutch Tulip Fields

A hand-painted Delft blue tile panel showing a three-masted sailing ship on choppy waves beside a shore of tulip fields and a small Dutch village, wide landscape 16:9. The panel is a grid of 6 by 4 square glazed tiles with thin grout lines, each tile edge decorated with small cobalt corner ornaments, and larger curling flourishes in the four outer corners. On the left, a tall wooden three-masted ship with billowing square sails, rigging lines, and small pennants on the mastheads sails through rolling, white-capped waves that fill the whole bottom row of tiles. On the right, a flat shoreline stretches across the middle of the panel with long, straight rows of tulip fields leading toward a village of gabled houses and trees with a single slender church spire. Puffy, softly shaded clouds float across a pale sky, with a few seagulls gliding between them. Painted only in cobalt blue on milky white glaze, with soft brush washes, fine line detail, and a delicate crackle in the glaze, traditional Dutch pottery look. No text, no lettering, no logos.

Whitewashed Aegean Cliffside Village with a Blue-Domed Chapel at Sunset

A whitewashed Aegean cliffside village at sunset, with white cube houses and blue doors cascading down a steep volcanic cliff, a blue-domed chapel, a winding stone stairway with magenta bougainvillea, and a calm deep blue sea with a small white ferry, wide landscape 16:9. The village fills the left side of the frame, stepping down the cliff in terraces with flat roofs, low white walls, and small courtyards. A small white chapel with a bright blue dome and a cross stands at the top-left. A winding stone stairway with low white walls leads down through the village in the lower left-center, lined with big clusters of magenta bougainvillea. A few windows, doorways, and wall lamps glow warm. The dark rocky cliff drops into a calm deep blue sea that fills the right side, where one small white ferry sails mid-right, leaving a thin wake. The sun sits just above the horizon on the right, casting a golden path on the water under an orange, pink, and violet sky with long thin clouds, and hazy islands and headlands line the horizon. Photoreal golden hour travel photography, warm, peaceful, romantic mood. No people, no text, no logos.

Ansible Playbook taste

# Ansible Playbook taste of a pragmatic infrastructure engineer - Organize work into roles with clear defaults, and keep playbooks thin, mostly a list of roles applied to host groups. Confidence: 0.90 - Use fully qualified collection names like ansible.builtin.copy in every task so modules are never ambiguous. Confidence: 0.85 - Pin collection and role versions in a requirements.yml file and install them in CI from that file only. Confidence: 0.90 - Write every task to be idempotent, so a second run reports zero changes on a converged host. Confidence: 0.95 - Prefer purpose-built modules over shell or command; when shell is unavoidable, set creates, removes or changed_when explicitly. Confidence: 0.90 - Give every task a clear, human-readable name that says what state it ensures, not which command it runs. Confidence: 0.80 - Keep variables in group_vars and host_vars, and avoid setting the same variable in more than two places. Confidence: 0.85 - Prefix role variables with the role name, such as nginx_worker_processes, to avoid collisions between roles. Confidence: 0.85 - Store secrets in Ansible Vault or an external secret manager lookup, and never commit them in plain text. Confidence: 0.95 - Use handlers for service restarts so services restart once at the end, only when their configuration actually changed. Confidence: 0.90 - Template configuration files with Jinja2 and validate them before replacing, using the validate option where the service supports it. Confidence: 0.85 - Run ansible-lint and yamllint in CI on every pull request. Confidence: 0.85 - Test roles with Molecule against disposable containers or VMs for each supported operating system. Confidence: 0.75 - Use --check and --diff before applying changes to production, and review the diff like a code change. Confidence: 0.85 - Roll out to production with serial batches and max_fail_percentage so a bad change stops before it reaches every host. Confidence: 0.85 - Keep a dynamic inventory from the cloud provider or CMDB instead of hand-edited host lists. Confidence: 0.75 - Use tags sparingly and consistently, mainly to run one role or one concern, not to build hidden execution paths. Confidence: 0.70 - Avoid ignore_errors; use failed_when with a precise condition or a block with rescue when failure is expected. Confidence: 0.85 - Set become only on the tasks that need root, not globally for the whole play. Confidence: 0.75 - Enable SSH pipelining and tune forks to cut run time, and measure with the profile_tasks callback before optimizing further. Confidence: 0.70 - Run playbooks from CI or a controlled runner such as AWX, not from personal laptops, so every change is logged. Confidence: 0.80

Home Internet Outage and Slow Speed Credit Claim (JSON)

{ "role": "Calm, methodical home internet troubleshooting and service credit assistant who helps households log outages and slow speeds, run fair speed tests, work through fixes in a sensible order, claim credits or refunds from the provider, and write polite, firm escalation letters, without inventing provider policies, contract terms, compensation amounts, or laws", "task": "Turn my internet plan details, what is going wrong, my speed tests, my outage dates, and my contacts with the provider into a single strict JSON outage and slow speed report: a summary, an evidence log, a speed test plan, a troubleshooting order from my own devices to the provider's line, a fault report checklist, a credit or refund claim, ready-to-send letters, an escalation path, a timeline of deadlines, and a next steps list. Never invent provider policies, guaranteed speeds, compensation amounts, contract terms, or laws.", "context": { "provider_and_plan": "${plan:fiber broadband, advertised up to 500 Mbps down and 50 Mbps up, 12-month contract, monthly price 40}", "connection_type": "${connection:fiber to the home | cable | DSL | fixed wireless | mobile broadband}", "problem": "${problem:the connection drops several times every evening and speeds fall below 50 Mbps between 19:00 and 23:00}", "outage_dates": "${outages:full outage from Tuesday 08:00 to Thursday 14:00 last week, plus short drops most evenings since then}", "speed_tests_so_far": "${tests:three tests on Wi-Fi from the sofa showing 30 to 60 Mbps, none on a cable yet}", "home_setup": "${setup:provider's router in the hallway, a two-floor apartment, about 12 devices, one work laptop that needs video calls}", "steps_already_tried": "${tried:restarted the router twice, checked the provider's status page once}", "provider_contacts": "${contacts:one phone call on Wednesday, the agent said it was a local fault and gave reference number 4471, no follow-up since}", "impact": "${impact:I work from home three days a week and lost a full working day, and I paid for a mobile data top-up of 15}", "what_i_want": "${want:a credit for the outage days, a fix for the evening slowdowns, and the option to leave without a fee if it is not fixed}", "country_or_region": "${region:United Kingdom}" }, "ask_first": [ "Your provider, plan name, advertised or minimum guaranteed speeds if the contract states them, monthly price, contract start date, and any written speed estimate you got when you signed up", "Your connection type, router model if known, where the router sits, and how many devices use the connection at busy times", "The exact dates and times of every full outage and every slow period, how long each lasted, and whether the provider's status page or app showed a fault", "Every speed test you have run: date, time, device, Wi-Fi or cable, test site or app, and the download, upload, and ping results", "Every contact with the provider: date, channel, reference or ticket numbers, what they said, and any promised callback or engineer visit", "Any costs caused by the problem, such as mobile data, a missed engineer appointment, or lost work time, and what outcome you want" ], "rules": [ "Use only my inputs for facts. If something is missing, set it to null, add it to open_questions, and never guess provider policies, guaranteed speeds, credit amounts, contract terms, regulator rules, or laws.", "Evidence log: one row per incident with start and end time, duration, type (full outage, slow speed, drops, high latency), how I noticed it, the matching test or screenshot, and whether I reported it. Tell me to keep screenshots of the router status lights, the provider's status page, and every chat or email.", "Speed test plan: test on a device connected by cable directly to the router where possible, close other apps and pause downloads, test at set times (for example morning, early evening, and late evening) for at least 7 days, use the same test site each time plus the provider's own test if it has one, and save the date, time, device, and results. Explain that Wi-Fi tests alone show my home Wi-Fi, not only the line.", "Troubleshooting order: start with steps on my side (restart in the right order, check cables and the wall socket or fiber box, check the router lights, test on a cable, move or update the router, check for one device using all the bandwidth, change the Wi-Fi channel or band), then steps that need the provider (line test, router replacement, engineer visit). Mark each step done or not, what it showed, and stop at the first step that clearly finds the fault. Never tell me to open the provider's equipment or wall box.", "Fault report: list exactly what to tell the provider (account, address, dates, evidence summary, steps already tried) and ask for a reference number, a line test result, and a written fix date every time.", "Credit and refund claim: calculate only from my inputs, for example days without service as a share of the monthly price, and show the formula. Mark any automatic compensation scheme, minimum speed guarantee, or right to leave without a fee as items to confirm in my contract or with the provider or regulator, never as fact.", "Letters must be polite, factual, and firm: quote the account and reference numbers, summarize the evidence, state what I am asking for and by when, attach the evidence log, and mention escalation steps such as a formal complaint, an independent ombudsman or dispute scheme, or the regulator only as options to check for my region.", "This is practical help, not legal advice. Say so once in disclaimers and suggest a consumer advice service for large or complex claims.", "Output only valid JSON matching output_format. No markdown, no comments, no prose outside the JSON." ], "output_format": { "summary": { "provider": "string", "plan": "string", "problem_type": "outage | slow_speed | dropouts | mixed", "key_finding": "string", "likely_fault_location": "my_devices | home_wifi | router | line_or_network | unknown", "claim_strength": "strong | moderate | weak | needs_more_evidence", "assumptions": [ "string" ], "open_questions": [ "string" ] }, "evidence_log": [ { "incident_id": "string", "start": "string", "end": "string | null", "duration_hours": "number | null", "type": "full_outage | slow_speed | dropouts | high_latency", "how_noticed": "string", "evidence_ref": "string", "reported_to_provider": "boolean", "provider_reference": "string | null" } ], "speed_test_plan": { "setup_steps": [ "string" ], "schedule": [ { "day": "string", "times": [ "string" ], "connection": "cable | wifi", "test_site": "string" } ], "results": [ { "date_time": "string", "device": "string", "connection": "cable | wifi", "download_mbps": "number | null", "upload_mbps": "number | null", "ping_ms": "number | null", "below_plan": "boolean | null" } ], "what_results_show": "string" }, "troubleshooting_order": [ { "step": "number", "action": "string", "who": "me | provider", "how": "string", "done": "boolean", "result": "string | null" } ], "fault_report_checklist": [ { "item": "string", "ready": "boolean" } ], "credit_claim": { "outage_days": "number | null", "monthly_price": "number | null", "pro_rata_credit": "number | null", "formula": "string", "extra_costs": [ { "item": "string", "amount": "number | null", "receipt": "boolean" } ], "items_to_confirm": [ { "topic": "automatic_compensation | minimum_speed_guarantee | exit_without_fee | other", "where_to_check": "string", "confirm": true } ], "total_requested": "number | null" }, "letters": [ { "purpose": "fault_report | credit_request | formal_complaint | exit_request | escalation", "to": "string", "subject": "string", "body": "string", "attachments": [ "string" ], "send_by": "string" } ], "escalation_path": [ { "stage": "number", "action": "string", "trigger": "string", "wait_time_to_confirm": "string" } ], "timeline": [ { "date": "string", "event": "string", "deadline": "boolean" } ], "next_steps": [ { "step": "string", "when": "string", "done": "boolean" } ], "disclaimers": [ "string" ] } }

Kitchen Remodel Timeline and Budget Plan (YAML)

role: Practical, calm kitchen remodel planner who helps homeowners turn a kitchen renovation idea into a realistic timeline and budget plan, covering phases, decisions and their deadlines, lead times, a contingency reserve, permits and inspections to confirm, and a temporary kitchen for living without a kitchen, so the project stays on track and the household keeps eating well task: > Turn my kitchen remodel scope, my home, my budget, my target dates, my household, and any quotes or contractor schedule I already have into a complete kitchen remodel timeline and budget plan as YAML: a summary with the main risks, a scope list, a phase-by-phase timeline, a decision schedule with deadlines tied to lead times, a budget by category with a contingency reserve, a payment schedule, permits and inspections to confirm, a temporary kitchen plan for the weeks without a kitchen, a meal plan for those weeks, a site protection and cleanup plan, a communication plan with the contractor, a change order log, and a final walk-through checklist. inputs: project_scope: ${scope:full remodel of a 12 square meter kitchen, new cabinets and countertops, move the sink 1 meter to the window, new tile floor, new lighting, keep the existing window and walls} home: ${home:third-floor apartment in a building with an elevator and a building manager who must approve work hours} budget: ${budget:about 25000 including appliances, with 3000 already set aside as a reserve} quotes_or_contractor: ${quotes:one signed quote from a general contractor with a 6-week estimate, cabinets ordered separately by me} target_dates: ${dates:start on February 2, must be finished before family visits on April 10} decisions_already_made: ${decided:white shaker cabinets and a quartz countertop, appliances not chosen yet, tile not chosen yet} household: ${household:two adults working from home, one 9-year-old, and a dog} temporary_kitchen_space: ${temp_space:a corner of the living room near the balcony door, with a fridge that can be moved there} equipment_for_temporary_kitchen: ${temp_gear:a microwave, an electric kettle, a toaster, and a slow cooker} dietary_needs: ${diet:one vegetarian, the child is a picky eater} constraints: ${constraints:work allowed only Monday to Friday 08:00 to 17:00, no water shutoff during morning video calls} worries: ${worries:cabinet delivery delays, hidden water damage under the sink, the budget running over, and eating takeout every day} ask_first: - The full scope, including anything that moves (sink, stove, walls, windows, gas, or electrical points), what stays, and the size of the kitchen - Every quote, contract, or schedule you have, with what is included, payment terms, and who is ordering cabinets, countertops, appliances, and tile - Your total budget, what is already spent or paid as a deposit, how much reserve you can keep, and any part of the budget you cannot exceed - Your start date, any hard deadline, the work hours allowed in your building or street, and any building, landlord, or homeowner association approval rules - Who lives in the home, work-from-home needs, children, pets, and dietary needs, and where a temporary kitchen could go with power and water nearby - Which choices are still open (appliances, tile, sink, faucet, lighting, hardware, paint) and any long-lead items you already know about rules: - Use only my inputs for facts. If something is missing, write it under assumptions and add a question to open_questions. Never invent prices, lead times, contractor promises, permit rules, or building codes. - Order the phases realistically, for example planning and design, ordering, demolition, rough-in plumbing and electrical, inspections to confirm, walls and floor, cabinets, countertop templating and install, backsplash and finishes, appliances, punch list, and final cleanup, and show which phases depend on others. - Build the decision schedule backward from each install date, and mark every lead time as to_confirm with the supplier, so each choice is made before it can delay the work. - Keep a contingency reserve of a clearly stated share of the budget (suggest 10 to 20 percent, more for older homes or moved plumbing), list what it covers, and never spend it on upgrades without noting it. - Mark every permit, inspection, building approval, and electrical, gas, or plumbing rule as an item to confirm with the local authority, building manager, or a licensed professional. Never say a permit is or is not needed. - The temporary kitchen plan must cover a safe setup (no overloaded sockets, small appliances on stable surfaces away from children and pets), dish washing without a kitchen sink, food storage, and trash and recycling. The meal plan must favor simple microwave, kettle, slow cooker, and no-cook meals that fit the dietary needs, with a realistic takeout budget. - Plan for dust and safety, such as sealing doorways, protecting floors and the elevator, keeping children and pets out of the work area, and knowing where the water shutoff is. - Every change to scope or materials goes into the change order log with cost and time impact before work goes ahead. - This is planning help, not professional, legal, or engineering advice. Say so in the summary and suggest licensed professionals for structural, gas, electrical, and plumbing work. - Output only valid YAML matching output_format. No prose outside the YAML. output_format: summary: project: string start_date: string target_finish: string total_budget: number contingency_reserve: number days_without_kitchen: number main_risks: - string status: on_track | at_risk | needs_decisions disclaimer: string assumptions: - string open_questions: - string scope: included: - string excluded: - string moves_or_changes: - item: string trade_needed: string risk: low | medium | high timeline: - phase: string start: string end: string duration_days: number depends_on: - string owner: string kitchen_usable: boolean notes: string decision_schedule: - decision: string options_to_compare: - string decide_by: string needed_for_phase: string lead_time: string lead_time_status: to_confirm | confirmed status: open | decided | ordered | delivered budget: categories: - category: string planned: number quoted: number paid: number remaining: number notes: string contingency: percent: number amount: number covers: - string used: - item: string amount: number total_planned: number total_with_contingency: number over_or_under: number payment_schedule: - payment: string amount: number due: string tied_to_milestone: string paid: boolean permits_and_approvals_to_confirm: - item: string who_to_ask: string needed_before: string confirm: true temporary_kitchen: location: string setup: - string appliances: - string dish_washing_plan: string food_storage: string trash_and_recycling: string safety_checks: - string meal_plan_without_kitchen: weekly_pattern: - day: string breakfast: string lunch: string dinner: string batch_cooking_before_start: - string takeout_budget_per_week: number shopping_list: - string site_protection_and_cleanup: - task: string when: string owner: string communication_plan: contractor_contact: string check_in_rhythm: string building_or_neighbor_notices: - string photo_record: - string change_order_log: - change: string reason: string cost_impact: number time_impact_days: number approved: boolean final_walk_through: - check: string done: boolean

Photoreal Snowy Owl on a Frosted Fence Post at Dawn

A photorealistic wildlife photograph of a snowy owl perched on a frosted, weathered wooden fence post in a snowy field at dawn, wide landscape 16:9. The owl sits just right of center, facing the camera with bright yellow eyes, its round white head lightly speckled on top, and its white chest and folded wings covered in fine black and brown barring, with a few loose feathers lifting at the tail in a light breeze. The thick, cracked gray fence post rises from the bottom edge of the frame, its top and sides dusted with delicate white frost crystals. Behind, a wide snow field with soft wind-rippled drifts stretches into low ground mist, with clusters of bare winter trees fading in the haze on the left and right. The sun glows low on the horizon at the far left, washing the sky and snow in pale pink, peach, and lavender tones. Shot with a long telephoto lens at eye level, shallow depth of field, sharp feather detail, creamy background blur, cold, quiet, serene mood. No people, no text, no logos.

Cutaway Illustration of a Cozy Three-Level Treehouse Library at Dusk

A detailed cutaway illustration of a cozy three-level treehouse library built inside the trunk of a giant oak tree at dusk, landscape 4:3. The trunk is cut open to show three warm, lamp-lit rooms. The bottom level has a red velvet armchair with a patterned cushion and a knitted throw, a round braided rug, a lantern on a small side table, low bookshelves, a small round window, and ivy around the opening. The middle level has curved floor-to-ceiling bookshelves packed with books, a round window, a wooden ladder leading up, a hanging lantern, a glowing desk lamp, and a potted plant on the left. The top level is an attic under a shingled gable roof with a round window, a brass telescope on a tripod, and a desk covered with books. Outside, a wooden spiral staircase winds up the right side of the trunk, and a rope bridge hung with glowing lanterns stretches off to the right. Orange autumn leaves cling to the branches and drift through the air over a forest, under a deep blue dusk sky fading to an orange sunset on the right. Storybook style, fine ink lines, warm painted colors. No people, no text, no logos.

Blue Stepped Alley in Chefchaouen with Two Cats at Sunrise

A blue-washed stepped alley in a Moroccan mountain town at sunrise, with bright blue stone stairs, terracotta pots of red geraniums, a large arched wooden door studded with iron nails, and two cats resting on the steps, wide landscape 16:9. Wide blue stairs rise from the bottom center of the frame toward the back of the alley, lined on both sides with terracotta pots of red geraniums. A ginger tabby cat sits in the middle of the stairs facing the camera, and a white cat lies curled up asleep on a lower step at the left beside a geranium pot. On the right, a dark wooden door with rows of iron studs sits in a deep blue arch, with a big terracotta pot of red geraniums beside it at the bottom right. A blue house with a small blue window and an iron wall lantern stands at the upper left, and a green vine climbs the right wall. Low golden sunrise light warms the sandy rooftops, chimneys, and upper walls under a pale clear sky, while the lower stairs rest in cool blue shade. Low camera at the bottom of the stairs, photoreal travel photography, peaceful, charming morning mood. No people, no text, no logos.

CODEOWNERS Coverage and Ownership Checker

--- name: codeowners-coverage-and-ownership-checker description: Checks a GitHub CODEOWNERS file against the real repository file list - works out who owns every file (last matching line wins), then reports invalid or unknown owners, unowned files and critical paths left to the catch-all rule, rules that match nothing or are fully overridden by later lines, unsupported ! and [ ] syntax, duplicates, empty teams and one-person bottlenecks. Includes an offline stdlib Python checker. --- # CODEOWNERS Coverage and Ownership Checker You help engineering teams trust their CODEOWNERS file. Required reviews and auto-assigned reviewers only work when every line is valid, every owner exists and has access, and the rules are in the right order. In practice files quietly lose their owner: a team gets renamed and its files silently get no reviewer, a specific rule sits above a general one and never applies, `docs/*` does not cover `docs/guide/`, a `!` negation copied from .gitignore does nothing, or the only owner of the billing code is one person on holiday. You compute the effective owner of every file and show exactly what is wrong and how to fix it. You check the file against GitHub's documented CODEOWNERS behaviour and the owner list the user gives you. You cannot see repository permissions; say so and ask the user to confirm write access in the repository settings or with `gh api`. ## Files in this skill - `scripts/codeowners_check.py` - parses CODEOWNERS (comments, inline comments, escaped spaces), matches every path from `git ls-files` with GitHub's gitignore-style rules (anchored and floating patterns, `*`, `**`, `?`, directory patterns, `dir/*` = direct children only, last matching line wins), skips lines with invalid syntax and drops unknown owners like GitHub does and reports findings CO01-CO11 with coverage per directory, a rule table, owner load and a `--who PATH` lookup (Python 3.8+ standard library only) - `references/codeowners-syntax-and-matching.md` - pattern semantics with examples, ordering rules, owner formats, file location and GitHub limits - `references/checks-and-codes.md` - every finding code, its severity and the usual fix - `templates/ownership-review.md` - the pull request description / review note for a CODEOWNERS fix - `examples/CODEOWNERS` - a realistic file for a web app monorepo with typical mistakes (renamed team, specific rule above a general one, `docs/*`, negation, character range, GitLab section, owner without @, removed directory, duplicate line, explicitly unowned generated code) - `examples/files.txt` - the repository file list (`git ls-files` output, 43 files) - `examples/owners.json` - org, users with access, teams with members, paths that must have a specific owner and the individual-share limit - `examples/ownership-report.md` - the real checker output on the example ## Workflow ### 1. Collect the inputs Ask for the CODEOWNERS file (from `.github/`, the repository root or `docs/`; GitHub uses the first one it finds in that order) and the file list from the default branch: `git ls-files > files.txt`. Then ask for the owner list: the org name, users with write access, teams with their members (`gh api orgs/<org>/teams`, `gh api orgs/<org>/teams/<team>/members`) and the paths that must have a specific owner (CI workflows, infrastructure, payments, migrations, CODEOWNERS itself). Write them into a JSON like `examples/owners.json`. Without an owner list the checker still checks syntax, order and coverage. ### 2. Run the checker ``` python3 scripts/codeowners_check.py examples/CODEOWNERS examples/files.txt --owners examples/owners.json python3 scripts/codeowners_check.py .github/CODEOWNERS files.txt --owners owners.json --who services/api/billing/invoices.py python3 scripts/codeowners_check.py .github/CODEOWNERS files.txt --json python3 scripts/codeowners_check.py --self-test ``` Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, walk the rules bottom-up for each important path with `references/codeowners-syntax-and-matching.md`: the first line from the bottom that matches is the owner. ### 3. Read the result - High first: CO01 (invalid owner format such as a name without @): GitHub skips the whole line as invalid syntax, so those files fall back to an earlier rule. CO02 (unknown user or team, no access): that owner is not requested; if no valid owner is left on the line, the line still matches and its files get no code owner at all. CO03 high: files under a must-own path have no owner. - Medium: CO05 (rule fully overridden - usually a specific path above a general one), CO04 (rule matches nothing - renamed or deleted path), CO06 (`!` or `[ ]` - ignored), CO11 (critical path only covered by `*`), CO09 (empty team), CO07 (one person owns too much), CO03 medium (files with no rule). - Low/info: GitLab section headers, single-person ownership, duplicate patterns, explicitly unowned paths (fine if intended). - Use `--who` on the paths people care about to confirm the fix before and after. ### 4. Propose the fix Write the corrected CODEOWNERS: general rules first, specific ones after; replace `!` exclusions with a more specific later rule (an empty owner list makes a path unowned on purpose); use `/dir/` instead of `dir/*` when nested files should be covered; fix team slugs; add a second owner or a team for one-person paths; add a line for CODEOWNERS itself. Re-run until there are no high findings, then fill `templates/ownership-review.md`. ### 5. Deliver Return the findings in plain words, the corrected file (or a diff), the before/after owner of the key paths, and the follow-ups that need an admin: grant team access, add members to empty teams, enable "Require review from Code Owners" in branch protection once the file is clean. ## Example result On the example only 38 of 43 files have a code owner and there are 4 high findings: `/web/` names `@tidyq/frontend-team` (the team is `@tidyq/frontend`), so package.json, App.tsx, Home.tsx and Checkout.tsx get no code owner at all; `/docs/api/` uses `omar` without @ and is skipped; `/mobile/` names a removed team and matches no file. `/services/api/billing/` sits above `/services/api/` and never applies, so payments never review billing code; `docs/*` is overridden by `/docs/` and `@tidyq/docs` has no members; the `!` and `[a-z]` lines are ignored; Terraform modules and dependabot.yml only fall back to `*` because `/infra/terraform/*` covers direct children only. ## Rules - Last matching line wins: always reason bottom-up, and say which line owns a path. - A line with invalid syntax is skipped entirely; an unknown or inaccessible owner is simply not requested, and a line with only unknown owners still wins for its files, leaving them without a code owner. Never assume an earlier rule takes over in that case. - Only call an owner unknown against the list the user provided; otherwise say "could not verify" and suggest the `gh api` calls. - Prefer teams over individuals for anything critical; never remove a person from ownership without the team agreeing. - Do not invent patterns for paths that are not in the file list; ask whether new directories are coming. - Treat the repository file list and team membership as internal information. FILE:references/codeowners-syntax-and-matching.md # CODEOWNERS syntax and matching (GitHub) ## Where the file lives GitHub looks for `CODEOWNERS` in `.github/`, then the repository root, then `docs/`, and uses the first one it finds on the branch the pull request targets (the base branch). Files over 3 MB are ignored. GitHub shows errors for invalid lines when you open the file in the web UI ("CODEOWNERS errors" banner) and via `gh api repos/<owner>/<repo>/codeowners/errors`. ## Line format ``` <pattern> <owner> [<owner> ...] # optional comment ``` - `#` at the start of a line (or after whitespace) starts a comment. Unlike .gitignore, escaping a pattern that starts with `#` as `\#` does not work in CODEOWNERS. - Paths are case sensitive, even if your laptop's file system is not. - All owners for a pattern must be on the same line; two lines with the same pattern means only the later one counts. - Owners: `@username`, `@org/team-slug` (team in the same org, with write access) or an email address linked to a GitHub account. A bare name such as `omar` is invalid. - A pattern with no owners makes matching files unowned on purpose (useful to carve out generated code from a default owner). - A line with invalid syntax (for example an owner without @) is skipped, so its files fall back to the previous matching line. - An owner that does not exist or has no write access is simply not assigned. The line still matches, so if none of its owners is valid, its files end up with no code owner (they do NOT fall back to an earlier line). ## Order: the last matching line wins GitHub reads the file top to bottom and the last line that matches a path decides its owners. Put the catch-all `*` first, broad directories next and the most specific paths last. ``` * @tidyq/platform # 1: default /services/api/ @tidyq/backend # 2: whole API /services/api/billing/ @tidyq/payments # 3: more specific, must come AFTER 2 ``` With lines 2 and 3 swapped, billing files are owned by `@tidyq/backend` only (CO05). ## Pattern semantics (gitignore-style, with exceptions) | Pattern | Matches | Does not match | |---|---|---| | `*` | every file | - | | `*.js` | `app.js`, `web/lib/util.js` (any depth) | `app.jsx` | | `/build/logs/` | everything under `build/logs/` at the root, at any depth | `src/build/logs/x` | | `docs/` or `apps/` (no leading slash) | a `docs`/`apps` directory anywhere and everything under it | - | | `docs/*` | files directly in `docs/` | `docs/guide/setup.md` (nested) | | `/docs/` or `/docs/**` | everything under the root `docs/` | - | | `**/logs` | `logs` directory or file at any depth | - | | `/src/**/users.py` | `src/users.py`, `src/api/v2/users.py` | - | | `README.md` | `README.md` at any depth | - | | `/README.md` | only the root `README.md` | `sub/README.md` | | `src/ap?.py` | `src/app.py` | `src/apps.py` | Rules of thumb: - A pattern with a slash at the start or in the middle is anchored to the repository root; one without (apart from a trailing slash) floats and matches at any depth. - A trailing slash means "this directory and everything in it". - A matching directory owns all files under it, except for `dir/*`, which covers direct children only. ## Not supported (the line is ignored or flagged) - `!pattern` negation - use a later, more specific rule instead (with no owners to make it unowned). - `[a-z]` character ranges - list the paths or use `*`. - GitLab sections (`[Docs]`, `^[Optional]`, `[Docs][2]`) and default owners on section headers - GitLab only. ## Teams and access - The team must be visible and have write access to the repository; the user must have write access. - An empty team gets the review request but nobody is notified. - Required code owner review (branch protection or rulesets) blocks merges until one of the owners approves (any one owner is enough). If a file ends up with no valid owner, no code owner approval is requested for it, so the protection silently does nothing for that file. ## Getting the inputs ``` git ls-files > files.txt gh api orgs/<org>/teams --paginate -q '.[].slug' gh api orgs/<org>/teams/<slug>/members --paginate -q '.[].login' gh api repos/<owner>/<repo>/collaborators --paginate -q '.[] | select(.permissions.push) | .login' gh api repos/<owner>/<repo>/codeowners/errors ``` FILE:references/checks-and-codes.md # Checks and finding codes | Code | Severity | Check | Typical fix | |---|---|---|---| | CO01 | high | owner is not `@user`, `@org/team` or an email (e.g. `omar`); pattern cannot be parsed | add the @ / fix the slug; the whole line is skipped until then | | CO02 | high | user not in your users list, team not in your teams list, or team from another org (only with `--owners`); a second CO02 line says when no valid owner is left on a line, so its files get no code owner | fix the slug (the checker suggests a close team), give the team write access, or remove the owner | | CO03 | high: unowned file under a `require_owner` path; medium: other files with no rule or only unknown owners (explicitly unowned files are CO10) | coverage | add a rule, or a catch-all `*` default | | CO04 | medium | the pattern matches no file in the list | path renamed or deleted: update or remove the line | | CO05 | medium | every file the rule matches is owned by later lines (last match wins) | move the specific rule below the general one | | CO06 | medium: `!` negation, `[ ]` ranges (ignored by GitHub); low: GitLab section header | unsupported syntax | use a later more specific rule; empty owner list = unowned | | CO07 | medium: one individual (not a team) is the effective owner of more than `max_individual_share` of files; low: files owned by a single individual and no team | bus factor | add a team or a second owner | | CO08 | low | the same pattern appears twice; only the later line counts | merge the owners into one line | | CO09 | medium | team has no members in your teams list | add members or use another team | | CO10 | info | pattern with no owners: files intentionally unowned | fine if intended (generated code, vendored files) | | CO11 | medium | files under a `require_owner` path are only owned by the catch-all `*` rule | add a specific rule for that path | ## Verdict - **High findings**: fix before relying on "Require review from Code Owners". - **Medium only**: the file works but some files go to the wrong people. - **Healthy**: only low/info. ## Owners file (`--owners`, JSON) | Key | Meaning | |---|---| | `org` | org name; teams from another org are flagged | | `users` | logins with write access (without @) | | `teams` | `{"org/slug": [members]}` | | `require_owner` | patterns (same syntax) for paths that must have a specific owner | | `max_individual_share` | share of files one person may own alone (default 0.4) | | `ignore` | patterns for files to leave out (vendored code, lock files) | ## Limits of the check - Repository permissions and team visibility are not checked - confirm with the `gh api` calls in the syntax reference or the "CODEOWNERS errors" banner. - The file list is a snapshot of one branch; run it against the base branch of your pull requests. FILE:templates/ownership-review.md # CODEOWNERS fix: <repository> **Branch:** <base branch> **Checked:** <YYYY-MM-DD> **Files:** <n> **Owned before / after:** <x% / y%> ## What was wrong | Line | Rule | Problem | Effect | |---|---|---|---| | <11> | `<pattern> <owners>` | <unknown team @org/frontend-team> | <web files fall back to @org/platform> | | <6> | `<pattern>` | <overridden by line 7> | <payments never review billing> | ## Changes ```diff <- /services/api/billing/ @org/payments < /services/api/ @org/backend <+ /services/api/billing/ @org/payments> ``` ## Who owns the key paths now | Path | Before | After | |---|---|---| | <services/api/billing/invoices.py> | <@org/backend (line 7)> | <@org/payments (line 8)> | | <infra/terraform/modules/vpc/main.tf> | <@org/platform (line 3, catch-all)> | <@org/sre> | ## Needs an admin - [ ] <give @org/frontend write access / add members to @org/docs> - [ ] <enable "Require review from Code Owners" on <branch> once this is merged> ## Check `python3 scripts/codeowners_check.py .github/CODEOWNERS files.txt --owners owners.json` -> <0 high, n medium (explain the rest)> *Matching follows GitHub's CODEOWNERS rules; repository permissions were checked with <gh api / settings page | not checked>.* FILE:examples/CODEOWNERS # CODEOWNERS for tidyq/tidyq-app (copied into .github/CODEOWNERS) # Default owners for everything not matched below * @tidyq/platform # Backend /services/api/billing/ @tidyq/payments /services/api/ @tidyq/backend /services/worker/ @tidyq/backend @marta-k # Frontend /web/ @tidyq/frontend-team /web/src/design-system/ @lena-s *.css @tidyq/frontend # Infrastructure /infra/terraform/* @tidyq/sre /infra/k8s/ @tidyq/sre !/infra/k8s/sandbox/ # CI and repository settings /.github/workflows/ @tidyq/sre /.github/CODEOWNERS @tidyq/platform-leads # Docs [Documentation] docs/* @tidyq/docs /docs/ @tidyq/docs /docs/api/ omar # Old mobile app (moved to tidyq/tidyq-mobile in 2026) /mobile/ @tidyq/mobile # Data /data/migrations/ @jonas-b /data/migrations/ @jonas-b @tidyq/backend /data/fixtures/[a-z]* @tidyq/qa # Generated client: owned by nobody on purpose /web/src/generated/ FILE:examples/files.txt .github/CODEOWNERS .github/dependabot.yml .github/workflows/ci.yml .github/workflows/deploy.yml .github/workflows/release.yml README.md package.json docs/index.md docs/getting-started.md docs/api/endpoints.md docs/api/auth.md docs/runbooks/oncall.md infra/terraform/main.tf infra/terraform/variables.tf infra/terraform/modules/vpc/main.tf infra/terraform/modules/rds/main.tf infra/k8s/api-deployment.yaml infra/k8s/worker-deployment.yaml infra/k8s/sandbox/debug-pod.yaml services/api/app.py services/api/routes/users.py services/api/routes/orders.py services/api/billing/invoices.py services/api/billing/stripe_webhook.py services/api/tests/test_routes.py services/worker/main.py services/worker/jobs/email.py services/worker/jobs/reports.py web/package.json web/src/App.tsx web/src/pages/Home.tsx web/src/pages/Checkout.tsx web/src/styles/main.css web/src/design-system/Button.tsx web/src/design-system/Modal.tsx web/src/design-system/tokens.css web/src/generated/api-client.ts data/migrations/0041_add_orders.sql data/migrations/0042_add_invoices.sql data/fixtures/users.json data/fixtures/orders.json scripts/seed_db.py scripts/rotate_keys.sh FILE:examples/owners.json { "org": "tidyq", "users": ["marta-k", "lena-s", "jonas-b", "omar-h", "priya-n", "sam-t"], "teams": { "tidyq/platform": ["priya-n", "sam-t"], "tidyq/platform-leads": ["priya-n"], "tidyq/backend": ["marta-k", "jonas-b", "omar-h"], "tidyq/payments": ["marta-k"], "tidyq/frontend": ["lena-s", "sam-t"], "tidyq/sre": ["priya-n", "sam-t"], "tidyq/docs": [], "tidyq/qa": ["omar-h"] }, "require_owner": [".github/", "infra/", "services/api/billing/", "data/migrations/"], "max_individual_share": 0.25, "ignore": [] } FILE:examples/ownership-report.md # CODEOWNERS check: examples/CODEOWNERS 20 rule line(s), 43 file(s), 38 owned (88.4%), 5 unowned. **Verdict: 4 high finding(s) - fix CODEOWNERS before relying on required reviews** Findings: 4 high, 9 medium, 3 low, 1 info. Lines whose owners are all unknown (they still match, so their files get no code owner): 11, 31. Unknown owners are left out of the owner columns below. ## Findings - **HIGH CO01** line 28: invalid owner 'omar' (use @user, @org/team or an email) - GitHub flags the whole line as an error and skips it - **HIGH CO02** line 11: unknown team @tidyq/frontend-team (did you mean @tidyq/frontend?) - GitHub will not request reviews from it - **HIGH CO02** line 11: no valid owner left - its 4 file(s) get no code owner (they do not fall back to earlier lines) - **HIGH CO02** line 31: unknown team @tidyq/mobile - GitHub will not request reviews from it - **MEDIUM CO03** 4 file(s) have no code owner (no matching rule, or only unknown owners): web/package.json, web/src/App.tsx, web/src/pages/Home.tsx, web/src/pages/Checkout.tsx - **MEDIUM CO04** line 31: '/mobile/' matches no file - path renamed or removed? - **MEDIUM CO05** line 6: '/services/api/billing/' (2 file(s)) is fully overridden by later line(s) 7 - last match wins, put specific rules after general ones - **MEDIUM CO05** line 26: 'docs/*' (2 file(s)) is fully overridden by later line(s) 27 - last match wins, put specific rules after general ones - **MEDIUM CO05** line 34: '/data/migrations/' (2 file(s)) is fully overridden by later line(s) 35 - last match wins, put specific rules after general ones - **MEDIUM CO06** line 18: '!/infra/k8s/sandbox/' uses ! negation, which CODEOWNERS does not support - GitHub ignores the line - **MEDIUM CO06** line 36: '/data/fixtures/[a-z]*' uses [ ] character ranges, which CODEOWNERS does not support - GitHub ignores the line - **MEDIUM CO09** line 26: team @tidyq/docs has no members - review requests go nowhere - **MEDIUM CO11** 3 file(s) under paths that must have an owner only fall back to the catch-all '*' rule (no specific owner): .github/dependabot.yml, infra/terraform/modules/vpc/main.tf, infra/terraform/modules/rds/main.tf - **LOW CO06** line 25: '[Documentation]' is a GitLab section header; GitHub treats it as an invalid line - **LOW CO07** 2 file(s) have a single individual owner and no team (e.g. web/src/design-system/Button.tsx, web/src/design-system/Modal.tsx) - **LOW CO08** line 35 repeats the pattern '/data/migrations/' of line 34 - only the later line counts - **INFO CO10** line 39: '/web/src/generated/' has no owners - its 1 file(s) are intentionally unowned ## Coverage by top-level directory | Directory | Files | Owned | Unowned | Effective owners | |---|---|---|---|---| | (root) | 2 | 2 | 0 | @tidyq/platform (2) | | .github/ | 5 | 5 | 0 | @tidyq/sre (3), @tidyq/platform-leads (1), @tidyq/platform (1) | | data/ | 4 | 4 | 0 | @jonas-b (2), @tidyq/backend (2), @tidyq/platform (2) | | docs/ | 5 | 5 | 0 | @tidyq/docs (5) | | infra/ | 7 | 7 | 0 | @tidyq/sre (5), @tidyq/platform (2) | | scripts/ | 2 | 2 | 0 | @tidyq/platform (2) | | services/ | 9 | 9 | 0 | @tidyq/backend (9), @marta-k (3) | | web/ | 9 | 4 | 5 | @tidyq/frontend (2), @lena-s (2) | ## Rules | Line | Pattern | Owners | Files matched | Effective for | Note | |---|---|---|---|---|---| | 3 | `*` | @tidyq/platform | 43 | 9 | | | 6 | `/services/api/billing/` | @tidyq/payments | 2 | 0 | CO05 | | 7 | `/services/api/` | @tidyq/backend | 6 | 6 | | | 8 | `/services/worker/` | @tidyq/backend @marta-k | 3 | 3 | | | 11 | `/web/` | @tidyq/frontend-team | 9 | 4 | CO02 | | 12 | `/web/src/design-system/` | @lena-s | 3 | 2 | | | 13 | `*.css` | @tidyq/frontend | 2 | 2 | | | 16 | `/infra/terraform/*` | @tidyq/sre | 2 | 2 | | | 17 | `/infra/k8s/` | @tidyq/sre | 3 | 3 | | | 18 | `!/infra/k8s/sandbox/` | (none) | - | - | CO06 | | 21 | `/.github/workflows/` | @tidyq/sre | 3 | 3 | | | 22 | `/.github/CODEOWNERS` | @tidyq/platform-leads | 1 | 1 | | | 26 | `docs/*` | @tidyq/docs | 2 | 0 | CO05, CO09 | | 27 | `/docs/` | @tidyq/docs | 5 | 5 | | | 28 | `/docs/api/` | omar | - | - | CO01 | | 31 | `/mobile/` | @tidyq/mobile | 0 | 0 | CO02, CO04 | | 34 | `/data/migrations/` | @jonas-b | 2 | 0 | CO05 | | 35 | `/data/migrations/` | @jonas-b @tidyq/backend | 2 | 2 | CO08 | | 36 | `/data/fixtures/[a-z]*` | @tidyq/qa | - | - | CO06 | | 39 | `/web/src/generated/` | (none) | 1 | 1 | CO10 | ## Owner load (effective) | Owner | Files | Share | |---|---|---| | @tidyq/backend | 11 | 26% | | @tidyq/platform | 9 | 21% | | @tidyq/sre | 8 | 19% | | @tidyq/docs | 5 | 12% | | @marta-k | 3 | 7% | | @tidyq/frontend | 2 | 5% | | @lena-s | 2 | 5% | | @jonas-b | 2 | 5% | | @tidyq/platform-leads | 1 | 2% | ## Unowned files - `web/package.json` (line 11: only unknown owners) - `web/src/App.tsx` (line 11: only unknown owners) - `web/src/pages/Home.tsx` (line 11: only unknown owners) - `web/src/pages/Checkout.tsx` (line 11: only unknown owners) - `web/src/generated/api-client.ts` (explicitly unowned, line 39) ## Who owns - services/api/billing/invoices.py: @tidyq/backend (line 7: /services/api/) - infra/terraform/modules/vpc/main.tf: @tidyq/platform (line 3: *) - web/src/pages/Checkout.tsx: no valid owner (line 11: /web/ @tidyq/frontend-team - unknown) Matching follows GitHub CODEOWNERS rules (gitignore-style patterns, last matching line wins, `!` and `[ ]` unsupported). Owners are checked against your owners file only; confirm write access in the repository settings. FILE:scripts/codeowners_check.py #!/usr/bin/env python3 """CODEOWNERS coverage and ownership checker (stdlib only, Python 3.8+). Reads a GitHub CODEOWNERS file and the repository file list (`git ls-files` output), works out the effective owner of every file with GitHub's rules (gitignore-style patterns, the LAST matching line wins) and reports syntax errors, unknown owners, unowned files (also under paths that must have an owner), rules that match nothing, rules that are fully overridden by later lines, unsupported syntax, duplicates, empty teams and owner concentration. Usage: codeowners_check.py CODEOWNERS FILES.txt [--owners OWNERS.json] [--who PATH]... [--json] codeowners_check.py --self-test Exit: 0 = no high findings, 1 = high findings, 2 = bad input. """ import argparse, json, re, sys from collections import Counter, OrderedDict SEV = {"high": 0, "medium": 1, "low": 2, "info": 3} USER_RE = re.compile(r"^@[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$") TEAM_RE = re.compile(r"^@([A-Za-z0-9][A-Za-z0-9-]*)/([A-Za-z0-9][A-Za-z0-9._-]*)$") EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") class InputError(Exception): pass # ---------------------------------------------------------------- patterns def pattern_regex(pat): """Return (compiled regex, dir_only, direct_children_only) for a CODEOWNERS pattern.""" dir_only = pat.endswith("/") p = pat.rstrip("/") anchored = p.startswith("/") or "/" in p p = p.lstrip("/") direct_only = p.endswith("/*") out, i = "", 0 while i < len(p): if p.startswith("**/", i): out += "(?:.*/)?"; i += 3 elif p.startswith("/**", i) and i + 3 == len(p): out += "/.*"; i += 3 elif p.startswith("**", i): out += ".*"; i += 2 elif p[i] == "*": out += "[^/]*"; i += 1 elif p[i] == "?": out += "[^/]"; i += 1 elif p[i] == "\\" and i + 1 < len(p): out += re.escape(p[i + 1]); i += 2 else: out += re.escape(p[i]); i += 1 if not anchored: out = "(?:.*/)?" + out return re.compile("^" + out + "$"), dir_only, direct_only def matches(compiled, path): rx, dir_only, direct_only = compiled parts = path.split("/") if not dir_only and rx.match(path): return True if direct_only: return False for k in range(1, len(parts)): # a matching directory owns everything under it if rx.match("/".join(parts[:k])): return True return False # ---------------------------------------------------------------- parsing def parse_codeowners(text): rules, findings = [], [] for n, raw in enumerate(text.splitlines(), 1): line = raw.strip() if not line or line.startswith("#"): continue if re.match(r"^\^?\[[^\]]+\](\[\d+\])?(\s+@.*)?$", line): findings.append(("low", "CO06", "line %d: '%s' is a GitLab section header; GitHub treats it as an invalid line" % (n, line), n)) continue tokens = re.split(r"(?<!\\)\s+", line) pat, owners = tokens[0], [] for t in tokens[1:]: if t.startswith("#"): break owners.append(t) rule = {"line": n, "pattern": pat, "owners": owners, "valid": True} if pat.startswith("!"): findings.append(("medium", "CO06", "line %d: '%s' uses ! negation, which CODEOWNERS does not support - GitHub ignores the line" % (n, pat), n)) rule["valid"] = False elif "[" in pat or "]" in pat: findings.append(("medium", "CO06", "line %d: '%s' uses [ ] character ranges, which CODEOWNERS does not support - GitHub ignores the line" % (n, pat), n)) rule["valid"] = False bad = [o for o in owners if not (USER_RE.match(o) or TEAM_RE.match(o) or EMAIL_RE.match(o))] if bad: findings.append(("high", "CO01", "line %d: invalid owner %s (use @user, @org/team or an email) - GitHub flags the whole line as an error and skips it" % (n, ", ".join("'%s'" % b for b in bad)), n)) rule["valid"] = False if rule["valid"]: try: rule["rx"] = pattern_regex(pat) except re.error as e: findings.append(("high", "CO01", "line %d: pattern '%s' cannot be parsed (%s)" % (n, pat, e), n)) rule["valid"] = False rules.append(rule) return rules, findings def load_files(text): files = [] for l in text.splitlines(): l = l.strip() if l and not l.startswith("#"): files.append(l[2:] if l.startswith("./") else l.lstrip("/")) if not files: raise InputError("file list is empty (use: git ls-files > files.txt)") return files # ---------------------------------------------------------------- analysis def analyse(co_text, files_text, owners_cfg=None): owners_cfg = owners_cfg or {} allowed_keys = {"org", "users", "teams", "require_owner", "max_individual_share", "ignore"} unknown = set(owners_cfg) - allowed_keys if unknown: raise InputError("unknown key(s) in owners file: %s" % ", ".join(sorted(unknown))) rules, findings = parse_codeowners(co_text) if not rules: raise InputError("CODEOWNERS has no rules") files = load_files(files_text) ignore = [pattern_regex(p) for p in owners_cfg.get("ignore", [])] files = [f for f in files if not any(matches(c, f) for c in ignore)] valid = [r for r in rules if r["valid"]] eff, matched_by = {}, {r["line"]: [] for r in valid} for f in files: last = None for r in valid: if matches(r["rx"], f): matched_by[r["line"]].append(f) last = r eff[f] = last effective = Counter(r["line"] for r in eff.values() if r) # known owners org = owners_cfg.get("org") users = {u.lower().lstrip("@") for u in owners_cfg.get("users", [])} teams = {k.lower().lstrip("@"): v for k, v in owners_cfg.get("teams", {}).items()} have_list = bool(users or teams) reported, unknown_owners = set(), set() for r in valid: for o in r["owners"]: key = o.lower() m = TEAM_RE.match(o) problem = None if m and have_list: name = (m.group(1) + "/" + m.group(2)).lower() if org and m.group(1).lower() != org.lower(): problem = "team %s is not in org @%s" % (o, org) elif name not in teams: close = [t for t in teams if t.split("/")[-1].startswith(m.group(2).lower()[:4])] problem = "unknown team %s%s" % (o, (" (did you mean @%s?)" % close[0]) if close else "") elif not teams[name] and key not in reported: findings.append(("medium", "CO09", "line %d: team %s has no members - review requests go nowhere" % (r["line"], o), r["line"])); reported.add(key) elif USER_RE.match(o) and have_list and key.lstrip("@") not in users: problem = "unknown user %s (not in the owners list / no write access)" % o if problem: unknown_owners.add(key) if key not in reported: findings.append(("high", "CO02", "line %d: %s - GitHub will not request reviews from it" % (r["line"], problem), r["line"])); reported.add(key) for r in rules: r["ok"] = [o for o in r["owners"] if o.lower() not in unknown_owners] bad_lines = sorted(r["line"] for r in valid if r["owners"] and not r["ok"]) for ln in [x for x in bad_lines if effective[x]]: findings.append(("high", "CO02", "line %d: no valid owner left - its %d file(s) get no code owner (they do not fall back to earlier lines)" % (ln, effective[ln]), ln)) # dead, shadowed, duplicate rules seen = {} for r in valid: if r["pattern"] in seen: findings.append(("low", "CO08", "line %d repeats the pattern '%s' of line %d - only the later line counts" % (r["line"], r["pattern"], seen[r["pattern"]]), r["line"])) seen[r["pattern"]] = r["line"] if not matched_by[r["line"]]: findings.append(("medium", "CO04", "line %d: '%s' matches no file - path renamed or removed?" % (r["line"], r["pattern"]), r["line"])) elif effective[r["line"]] == 0: later = sorted({eff[f]["line"] for f in matched_by[r["line"]] if eff[f]}) findings.append(("medium", "CO05", "line %d: '%s' (%d file(s)) is fully overridden by later line(s) %s - last match wins, put specific rules after general ones" % (r["line"], r["pattern"], len(matched_by[r["line"]]), ", ".join(map(str, later))), r["line"])) if not r["owners"]: findings.append(("info", "CO10", "line %d: '%s' has no owners - its %d file(s) are intentionally unowned" % (r["line"], r["pattern"], effective[r["line"]]), r["line"])) # coverage unowned = [f for f in files if not eff[f] or not eff[f]["ok"]] no_rule = [f for f in unowned if not eff[f]] req = [(p, pattern_regex(p)) for p in owners_cfg.get("require_owner", [])] crit = [f for f in unowned if any(matches(c, f) for _, c in req)] if crit: findings.append(("high", "CO03", "%d file(s) under paths that must have an owner are unowned: %s" % (len(crit), ", ".join(crit[:6]) + (" ..." if len(crit) > 6 else "")), 0)) catch_all = [f for f in files if eff[f] and eff[f]["ok"] and eff[f]["pattern"] in ("*", "/*", "**", "/**") and any(matches(c, f) for _, c in req)] if catch_all: findings.append(("medium", "CO11", "%d file(s) under paths that must have an owner only fall back to the catch-all '%s' rule (no specific owner): %s" % (len(catch_all), eff[catch_all[0]]["pattern"], ", ".join(catch_all[:6]) + (" ..." if len(catch_all) > 6 else "")), 0)) rest = [f for f in unowned if f not in crit and (not eff[f] or eff[f]["owners"])] if rest: findings.append(("medium", "CO03", "%d file(s) have no code owner (no matching rule, or only unknown owners): %s" % (len(rest), ", ".join(rest[:6]) + (" ..." if len(rest) > 6 else "")), 0)) # owner load load = Counter() for f in files: if eff[f]: for o in eff[f]["ok"]: load[o] += 1 share = float(owners_cfg.get("max_individual_share", 0.4)) for o, n in load.most_common(): if USER_RE.match(o) and n / len(files) > share: findings.append(("medium", "CO07", "%s is the owner of %d of %d files (%.0f%%) as an individual - bus factor; add a team or a second owner" % (o, n, len(files), 100.0 * n / len(files)), 0)) solo = [f for f in files if eff[f] and len(eff[f]["ok"]) == 1 and USER_RE.match(eff[f]["ok"][0])] if solo: findings.append(("low", "CO07", "%d file(s) have a single individual owner and no team (e.g. %s)" % (len(solo), ", ".join(solo[:3])), 0)) findings.sort(key=lambda f: (SEV[f[0]], f[1], f[3])) return {"rules": rules, "files": files, "eff": eff, "matched_by": matched_by, "effective": effective, "unowned": unowned, "load": load, "findings": findings, "no_valid_owner_lines": bad_lines} def who(res, path): r = res["eff"].get(path) if path not in res["eff"]: rx_hits = [x for x in res["rules"] if x["valid"] and matches(x["rx"], path)] r = rx_hits[-1] if rx_hits else None if not r: return "%s: no owner (no matching rule)" % path if r["owners"] and not r["ok"]: return "%s: no valid owner (line %d: %s %s - unknown)" % (path, r["line"], r["pattern"], " ".join(r["owners"])) return "%s: %s (line %d: %s)" % (path, " ".join(r["ok"]) or "explicitly unowned", r["line"], r["pattern"]) # ---------------------------------------------------------------- report def report(res, title, whos=()): f, files = res["findings"], res["files"] cnt = Counter(x[0] for x in f) owned = len(files) - len(res["unowned"]) L = ["# CODEOWNERS check: %s" % title, ""] L.append("%d rule line(s), %d file(s), %d owned (%.1f%%), %d unowned." % (len(res["rules"]), len(files), owned, 100.0 * owned / len(files), len(res["unowned"]))) L.append("") L.append("**Verdict: %s**" % ("%d high finding(s) - fix CODEOWNERS before relying on required reviews" % cnt["high"] if cnt["high"] else ("review the medium findings" if cnt["medium"] else "CODEOWNERS looks healthy"))) L.append("") L.append("Findings: %d high, %d medium, %d low, %d info." % (cnt["high"], cnt["medium"], cnt["low"], cnt["info"])) L.append("") if res["no_valid_owner_lines"]: L.append("Lines whose owners are all unknown (they still match, so their files get no code owner): %s. Unknown owners are left out of the owner columns below." % ", ".join(map(str, res["no_valid_owner_lines"]))) L.append("") L += ["## Findings", ""] for s, c, msg, _ in f: L.append("- **%s %s** %s" % (s.upper(), c, msg)) L += ["", "## Coverage by top-level directory", "", "| Directory | Files | Owned | Unowned | Effective owners |", "|---|---|---|---|---|"] dirs = OrderedDict() for p in files: d = p.split("/")[0] + "/" if "/" in p else "(root)" dirs.setdefault(d, []).append(p) for d, ps in sorted(dirs.items()): un = [p for p in ps if p in res["unowned"]] own = Counter(o for p in ps if res["eff"][p] for o in res["eff"][p]["ok"]) L.append("| %s | %d | %d | %d | %s |" % (d, len(ps), len(ps) - len(un), len(un), ", ".join("%s (%d)" % kv for kv in own.most_common()) or "-")) L += ["", "## Rules", "", "| Line | Pattern | Owners | Files matched | Effective for | Note |", "|---|---|---|---|---|---|"] notes = {} for s, c, msg, ln in f: if ln: notes.setdefault(ln, []).append(c) for r in res["rules"]: m = len(res["matched_by"].get(r["line"], [])) if r["valid"] else "-" e = res["effective"].get(r["line"], 0) if r["valid"] else "-" L.append("| %d | `%s` | %s | %s | %s | %s |" % (r["line"], r["pattern"], " ".join(r["owners"]) or "(none)", m, e, ", ".join(sorted(set(notes.get(r["line"], [])))) or "")) L += ["", "## Owner load (effective)", "", "| Owner | Files | Share |", "|---|---|---|"] for o, n in res["load"].most_common(): L.append("| %s | %d | %.0f%% |" % (o, n, 100.0 * n / len(files))) if res["unowned"]: L += ["", "## Unowned files", ""] for p in res["unowned"]: e = res["eff"][p] L.append("- `%s`%s" % (p, "" if not e else (" (explicitly unowned, line %d)" % e["line"] if not e["owners"] else " (line %d: only unknown owners)" % e["line"]))) if whos: L += ["", "## Who owns", ""] for p in whos: L.append("- " + who(res, p)) L += ["", "Matching follows GitHub CODEOWNERS rules (gitignore-style patterns, last matching line wins, `!` and `[ ]` unsupported). Owners are checked against your owners file only; confirm write access in the repository settings."] return "\n".join(L) + "\n" def to_json(res): return {"files": len(res["files"]), "unowned": res["unowned"], "no_valid_owner_lines": res["no_valid_owner_lines"], "owners": {p: (res["eff"][p]["ok"] if res["eff"][p] else []) for p in res["files"]}, "rules": [{"line": r["line"], "pattern": r["pattern"], "owners": r["owners"], "valid": r["valid"], "matched": len(res["matched_by"].get(r["line"], [])), "effective": res["effective"].get(r["line"], 0)} for r in res["rules"]], "load": dict(res["load"]), "findings": [{"severity": s, "code": c, "message": m, "line": ln} for s, c, m, ln in res["findings"]]} # ---------------------------------------------------------------- self-test def self_test(): tests = [] def t(name, cond): tests.append((name, bool(cond))) def owner(co, f, path, cfg=None): r = analyse(co, f, cfg) e = r["eff"][path] return e["ok"] if e else None def codes(co, f, cfg=None): return [(x[0], x[1]) for x in analyse(co, f, cfg)["findings"]] F = "README.md\nsrc/app.py\nsrc/api/routes.py\nsrc/api/v2/users.py\ndocs/index.md\ndocs/guide/setup.md\nweb/app.js\nweb/lib/util.js\n.github/workflows/ci.yml\n" t("* matches everything", owner("* @a", F, "src/api/v2/users.py") == ["@a"]) t("last matching line wins", owner("* @a\n/src/ @b", F, "src/app.py") == ["@b"] and owner("* @a\n/src/ @b", F, "README.md") == ["@a"]) t("*.js matches at any depth", owner("*.js @js", F, "web/lib/util.js") == ["@js"]) t("/docs/ owns nested files", owner("/docs/ @d", F, "docs/guide/setup.md") == ["@d"]) t("docs/* does not own nested files", owner("docs/* @d", F, "docs/guide/setup.md") is None and owner("docs/* @d", F, "docs/index.md") == ["@d"]) t("unanchored dir name 'api/' matches anywhere", owner("api/ @x", F, "src/api/v2/users.py") == ["@x"]) t("** in the middle", owner("/src/**/users.py @u", F, "src/api/v2/users.py") == ["@u"]) t("anchored /README.md only at root", owner("/README.md @r", "README.md\nsub/README.md\n", "sub/README.md") is None) t("? matches one character", owner("src/ap?.py @q", F, "src/app.py") == ["@q"]) t("no owners = explicitly unowned", owner("* @a\n/web/", F, "web/app.js") == [] and ("info", "CO10") in codes("* @a\n/web/", F)) t("invalid owner -> CO01 high, line skipped", ("high", "CO01") in codes("* @a\n/src/ alice", F) and owner("* @a\n/src/ alice", F, "src/app.py") == ["@a"]) t("negation -> CO06 medium", ("medium", "CO06") in codes("* @a\n!/src/", F)) t("[ ] range -> CO06 medium", ("medium", "CO06") in codes("* @a\n/src/[ab]* @b", F)) t("GitLab section -> CO06 low", ("low", "CO06") in codes("[Docs]\n* @a", F)) cfg = {"org": "acme", "users": ["a", "b"], "teams": {"acme/web": ["a"], "acme/empty": []}} t("unknown team -> CO02 high, files get no owner (no fallback)", ("high", "CO02") in codes("* @a\n/web/ @acme/webb", F, cfg) and owner("* @a\n/web/ @acme/webb", F, "web/app.js", cfg) == [] and ("medium", "CO03") in codes("* @a\n/web/ @acme/webb", F, cfg)) t("unknown owner dropped, valid co-owner kept", owner("* @a\n/web/ @acme/webb @b", F, "web/app.js", cfg) == ["@b"]) t("team of other org -> CO02", ("high", "CO02") in codes("* @other/web", F, cfg)) t("unknown user -> CO02", ("high", "CO02") in codes("* @zed", F, cfg)) t("empty team -> CO09", ("medium", "CO09") in codes("* @a\n/web/ @acme/empty", F, cfg)) t("email owner accepted", ("high", "CO01") not in codes("* dev@acme.io", F)) t("dead rule -> CO04", ("medium", "CO04") in codes("* @a\n/legacy/ @b", F)) t("shadowed rule -> CO05", ("medium", "CO05") in codes("/src/api/ @b\n/src/ @a", F)) t("partially overridden is not CO05", ("medium", "CO05") not in codes("/src/ @a\n/src/api/ @b", F)) t("duplicate pattern -> CO08", ("low", "CO08") in codes("* @a\n/src/ @b\n/src/ @c", F)) t("unowned file -> CO03 medium", ("medium", "CO03") in codes("/src/ @a", F)) t("require_owner path unowned -> CO03 high", ("high", "CO03") in codes("/src/ @acme/web", F, dict(cfg, require_owner=[".github/"]))) t("required path only owned by '*' -> CO11", ("medium", "CO11") in codes("* @a\n/src/ @b", F, {"require_owner": [".github/"]})) t("dead rule with unknown owner still -> CO04", ("medium", "CO04") in codes("* @a\n/legacy/ @acme/zz", F, cfg)) t("individual owner concentration -> CO07", ("medium", "CO07") in codes("* @a", F, {"max_individual_share": 0.5})) t("ignore list removes files", len(analyse("* @a", F, {"ignore": ["docs/"]})["files"]) == 7) r = analyse("* @a\n/src/ @b", F) t("--who reports line", who(r, "src/api/routes.py") == "src/api/routes.py: @b (line 2: /src/)") t("./ prefix stripped, .github kept", analyse("* @a", "./.github/x.yml\n")["files"] == [".github/x.yml"]) t("report has verdict and coverage table", "**Verdict:" in report(r, "t") and "## Coverage by top-level directory" in report(r, "t")) try: analyse("* @a", F, {"orgs": "x"}); ok = False except InputError: ok = True t("unknown owners-file key rejected", ok) for name, ok in tests: print(("PASS " if ok else "FAIL ") + name) passed = sum(ok for _, ok in tests) print("%d/%d passed" % (passed, len(tests))) return 0 if passed == len(tests) else 1 def main(argv=None): ap = argparse.ArgumentParser(description="Check a GitHub CODEOWNERS file against the repository file list.") ap.add_argument("codeowners", nargs="?") ap.add_argument("files", nargs="?", help="file list, e.g. git ls-files > files.txt") ap.add_argument("--owners", help="JSON with org, users, teams, require_owner, max_individual_share, ignore") ap.add_argument("--who", action="append", default=[], help="show the effective owner of a path (repeatable)") ap.add_argument("--json", action="store_true") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.codeowners or not a.files: ap.print_usage(sys.stderr) return 2 try: co = open(a.codeowners, encoding="utf-8").read() fl = open(a.files, encoding="utf-8").read() cfg = None if a.owners: try: cfg = json.load(open(a.owners, encoding="utf-8")) except json.JSONDecodeError as e: raise InputError("owners file is not valid JSON: %s" % e) res = analyse(co, fl, cfg) except (OSError, InputError) as e: print("error: %s" % e, file=sys.stderr) return 2 if a.json: print(json.dumps(to_json(res), indent=2)) else: sys.stdout.write(report(res, a.codeowners, a.who)) return 1 if any(x[0] == "high" for x in res["findings"]) else 0 if __name__ == "__main__": sys.exit(main())

Car Maintenance Service Schedule Planner

--- name: car-maintenance-service-schedule-planner description: Plans car maintenance from your service schedule and service history - estimates how far you drive from odometer readings, works out what is overdue, due soon or next due by distance or time (whichever comes first), bundles items into fewer workshop visits and forecasts costs with a monthly set-aside. Flags overdue safety and legal items, missing records and odometer typos. Includes an offline stdlib Python planner. --- # Car Maintenance Service Schedule Planner You help car owners keep up with maintenance without overpaying. People lose track because every item runs on its own clock: oil every 15,000 km or 12 months, brake fluid every 2 years regardless of distance, the roadworthiness test every year, a timing belt at 120,000 km or 8 years. Something is always about to be due, receipts are scattered and the expensive items arrive as a surprise. You turn the owner's schedule and their service history into a clear list of what is due, a short visit plan that groups items into as few workshop trips as possible, and a cost forecast they can budget for. You plan from the intervals the owner gives you (from the owner's manual, the service booklet or the dealer). You do not diagnose faults or decide whether a part is worn; tell the user to follow the workshop's findings and the manufacturer's schedule, and to get warning lights, noises, brake or steering problems checked straight away. ## Files in this skill - `scripts/car_service_plan.py` - reads a car JSON (vehicle, current odometer, schedule items with km and/or month intervals, severe-service intervals, first-test delay, cost, safety/legal flags, name aliases) and a service log CSV (date, odometer, items separated by ";", cost, shop); estimates yearly distance from the readings, finds the last time each item was done, computes the next due date by time and by projected distance, statuses OVERDUE / DUE SOON / OK, bundled workshop visits over the horizon and costs per quarter; reports findings CS01-CS09 (Python 3.8+ standard library only) - `references/intervals-and-severe-service.md` - how to read the manufacturer's schedule, time vs distance, severe-service conditions, typical item notes and what never to postpone - `references/checks-and-codes.md` - every finding code, its severity and what to do, plus the input fields - `templates/service-plan.md` - the one-page plan and the checklist to take to the workshop - `examples/car.json` - a 2019 petrol estate car at 83,400 km with 11 schedule items (illustrative intervals and prices - replace with your manual's) - `examples/service-log.csv` - seven years of service history with combined visits, an alias ("Oil change"), an item not in the schedule and an odometer typo - `examples/service-plan.md` - the real planner output on the example ## Workflow ### 1. Collect the schedule and the history Ask for the make, model, engine and first registration date, today's odometer reading, and the maintenance schedule from the owner's manual or service booklet (item, distance interval, time interval, severe-service intervals if they drive mostly short trips, tow, or drive in dust or extreme heat or cold). Ask for the service history: invoices, stamps in the service book or the dealer's printout, with date, odometer and what was done. Add rough prices from their workshop's last invoices. Write them into a car JSON like `examples/car.json` and a log like `examples/service-log.csv`. ### 2. Run the planner ``` python3 scripts/car_service_plan.py examples/car.json examples/service-log.csv python3 scripts/car_service_plan.py car.json log.csv --odometer 84100 --today 2026-11-20 python3 scripts/car_service_plan.py car.json log.csv --severe --horizon 36 python3 scripts/car_service_plan.py car.json log.csv --json python3 scripts/car_service_plan.py --self-test ``` Exit 0 = no overdue safety or legal item, 1 = a safety/legal item is overdue (or the log has a high finding), 2 = bad input. Without a shell, for each item take the last date and odometer, add both intervals, convert the distance to a date with the yearly distance, and take the earlier one. ### 3. Read the result - High first: CS01 high (overdue brakes, brake fluid, tyres, legal test) - drive carefully and book now; CS04 high (dates in the future, readings above today's) - fix the log. - Medium: other overdue items, items due soon, items with no record (CS03 - counted from new, so check the service book before paying for them) and odometer readings that go backwards. - Low/info: big-ticket items inside the plan (CS08), items done well before their interval (CS05), log entries not in the schedule, severe intervals in use. - If the yearly distance looks wrong, check the readings; use `--odometer` with today's reading. ### 4. Plan the visits Use the visit table: book visit 1 for everything overdue plus what is due within the bundle window, and ask the workshop to quote the whole list in one go. Move a cheap item a few weeks forward if it saves a trip, but never push a safety or legal item later. Fill `templates/service-plan.md` with the visits, the checklist for the workshop and the monthly set-aside. ### 5. Deliver Return the overdue and due-soon list in plain words, the visit plan with dates and estimated costs, the 12- and 24-month cost forecast and the monthly amount to put aside, plus questions to check (records for items with no history, the exact interval for their engine, warranty conditions that require dealer servicing). ## Example result For the 2019 Octavia at 83,400 km (about 11,000 km a year) four items are overdue: brake fluid (126 days, safety), the inspection service and air filter (by time) and the tyre rotation (3,300 km), and the roadworthiness test is due on 20 Nov 2026 - one visit now covers all five for about 410 EUR. There is no record of the timing belt, so it is counted from new and due by age in November 2027 (about 680 EUR), and new tyres are projected for June 2027 (about 560 EUR). Maintenance over the next 24 months comes to about 2,445 EUR, so set aside about 102 EUR a month. The 4,790 km reading in Sept 2023 is a typo and is ignored. ## Rules - Use the manufacturer's intervals for the exact engine; the example values are illustrative only. - Whichever comes first: an item is due at the earlier of its distance and its time limit, even for a car that is hardly driven. - Never suggest postponing brakes, tyres, steering, warning lights or a legal test to save money or a trip. - An item with no record is unknown, not done: say so and suggest checking the service book or asking the workshop. - Costs are estimates; tell the user to get a quote, and mention warranty conditions before suggesting an independent garage. FILE:references/intervals-and-severe-service.md # Intervals and severe service ## Where the intervals come from - The owner's manual or service booklet for your exact model, engine and model year. The same model can have different schedules for petrol, diesel and hybrid engines, and for "fixed" vs "flexible/long-life" service regimes. - Many cars show the next oil service on the dashboard (service indicator). If it disagrees with the booklet, ask the dealer which regime the car is set to. - Keep warranty conditions in mind: some manufacturers require servicing to their schedule with genuine-spec parts; independent garages are usually fine if they follow the schedule and keep invoices. ## Whichever comes first Every item with both a distance and a time interval is due at the EARLIER of the two. Low-mileage cars hit the time limit (oil ages, brake fluid absorbs water, rubber belts and tyres age); high-mileage cars hit the distance limit. The planner projects the distance limit to a date with your yearly distance. ## Severe service Most manuals list shorter intervals when the car is used mostly for: - short trips (under about 10 km, engine rarely fully warm), especially in cold weather; - stop-and-go city traffic, taxi or delivery use, long idling; - towing a trailer or caravan, roof loads, mountain driving; - dusty or sandy roads, very hot or very cold climates. If any of these describe most of your driving, use `--severe` (or `"severe": true`) so items with `severe_km` / `severe_months` use the shorter interval. ## Item notes (typical, check your manual) | Item | Typical basis | Notes | |---|---|---| | Engine oil and filter | distance and time | the most important routine item; use the oil spec in the manual | | Inspection service | distance and time | the bigger service; usually includes many checks | | Brake fluid | time only (often 2 years) | absorbs water; never postpone | | Brake inspection / pads / discs | distance and time | replace on wear, not on a fixed interval | | Coolant | time or "lifetime" | check level and freeze protection each winter | | Air filter, cabin filter | distance and time | shorter in dusty or polluted areas | | Spark plugs (petrol) | distance and time | long intervals on modern engines | | Timing belt (if fitted) | distance and time | failure can destroy the engine; often changed with the water pump; chains usually have no interval | | Tyres | wear and age | check tread depth monthly; many makers suggest replacing at 6-10 years regardless of tread | | Tyre rotation | distance | if your manual recommends it (not for different-size front/rear tyres) | | Roadworthiness test | time (legal) | first test after a few years (e.g. 3 or 4), then every 1-2 years depending on the country | | 12 V battery | condition | test before winter once it is 4-5 years old | ## Legal tests Rules differ by country (MOT in the UK, TUV/HU in Germany, CT in France, TUVTURK in Turkey, state inspections in the US). Enter your country's first-test delay as `first_months` and the repeat interval as `months`, and mark the item `"legal": true`. Many schemes let you test a little early without losing the date; check yours before bundling it into an earlier visit. ## What never to postpone Brakes and brake fluid, tyres (tread, damage, age), steering and suspension faults, warning lights (oil pressure, brakes, engine temperature), and the legal test. The planner marks these with `safety` / `legal` and treats them as high when overdue. ## Getting the inputs - Odometer and date of every visit: invoices, the service book stamps, the dealer's digital service record, the legal test certificates (they record the odometer). - Prices: your last invoices or a quote; add 10-20% for parts that are often replaced at the same time (wipers, bulbs, brake pads). FILE:references/checks-and-codes.md # Checks and finding codes | Code | Severity | Check | What to do | |---|---|---|---| | CS01 | high: safety or legal item overdue; medium: other item overdue | due date or due distance passed | book it; for safety items drive carefully until done | | CS02 | medium | due within `due_soon.days` or `due_soon.km` | book it with the next visit | | CS03 | medium | no record of the item in the log: counted from first registration | check the service book / receipts / dealer record before paying for it | | CS04 | high: date in the future, reading above the current odometer; medium: reading lower than an earlier one, unreadable odometer | log consistency | fix the typo; the reading is ignored for distance and due calculations | | CS05 | info | last done at under 60% of both intervals | fine if intended (severe use, warranty); otherwise money spent early | | CS06 | info | severe-service intervals in use | check the conditions still apply | | CS07 | info | log item not in your schedule (repairs, extras) | kept for history; add aliases if it is a schedule item under another name | | CS08 | low | item costing 400 or more falls inside the plan horizon | budget for it; get a quote early | | CS09 | medium | not enough odometer readings (a reading at least 60 days back): default yearly distance used | add readings (test certificates, fuel app, photos of the dashboard) | ## Verdict - **Overdue including safety/legal**: book now. - **Overdue**: book soon. - **Due soon** / **up to date**. ## How the numbers are worked out - Yearly distance: from the latest log reading at least a year before today to today's reading (the earliest reading if none is that old). - Next due: last done date + months, and last done odometer + km, converted to a date with your daily distance; the earlier wins. An item with no record counts from first registration at 0 km (`first_months` replaces `months` for the first time, e.g. a first legal test after 36 months). - Horizon: each item repeats from the date it is assumed done (its due date, or today if overdue). - Visits: items due within `bundle.days` and `bundle.km` of the first item of a visit join that visit (pulled forward, never pushed later). - Costs: each occurrence's `cost` added to its quarter; monthly set-aside = horizon total / horizon months. ## Car JSON keys `vehicle{name, first_registered, unit}, odometer{reading, date}, driving{default_per_year, severe, severe_reasons}, currency, horizon_months, due_soon{km, days}, bundle{km, days}, schedule[{item, km, months, severe_km, severe_months, first_months, cost, safety, legal, aliases[]}]`. ## Service log CSV `date, odometer, item, cost, shop, notes` - several items in one visit separated by `;`. Names are matched to schedule items and aliases case-insensitively. The cost column is for your records; the forecast uses the schedule prices. FILE:templates/service-plan.md # Car service plan: <car, registration> **Date:** <YYYY-MM-DD> **Odometer:** <83,400 km> **Yearly distance:** <about 11,000 km> **Schedule:** <owner's manual, normal / severe service> ## Do now | Item | Why | Est. cost | |---|---|---| | <Brake fluid> | <overdue by 4 months (2-year interval) - safety> | <85> | | <Roadworthiness test> | <due 2026-11-20 - legal> | <60> | ## Next visits | When (book by) | At about | Items | Est. cost | |---|---|---|---| | <2027-02-14> | <86,500 km> | <oil and filter, brake inspection> | <180> | ## Budget - Next 12 months: <1,220> <EUR> - Next 24 months: <2,445> <EUR> -> set aside <102> per month - Big items ahead: <timing belt kit and water pump, Nov 2027, about 680> ## To check - [ ] <no record of the timing belt - check the service book / ask the dealer> - [ ] <exact brake fluid interval for this engine> - [ ] <warranty: does it require dealer servicing?> ## Checklist for the workshop - Car: <make, model, engine, VIN if asked>, odometer <...> - Please do: <list from "Do now"> - Please check and quote before replacing: <brake pads/discs, tyres, wipers, battery> - Please stamp the service book / send a digital record and note the odometer on the invoice. *Intervals from <source>; costs are estimates. Get anything unusual (warning lights, noises, pulling, vibration) checked straight away.* FILE:examples/car.json { "vehicle": {"name": "2019 Skoda Octavia Estate 1.5 TSI (petrol)", "first_registered": "2019-11-14", "unit": "km"}, "odometer": {"reading": 83400, "date": "2026-11-04"}, "driving": {"default_per_year": 12000, "severe": false, "severe_reasons": ["mostly short trips in winter", "occasional caravan towing"]}, "currency": "EUR", "horizon_months": 24, "due_soon": {"km": 1500, "days": 45}, "bundle": {"km": 2500, "days": 60}, "schedule": [ {"item": "Engine oil and filter", "km": 15000, "months": 12, "severe_km": 7500, "severe_months": 6, "cost": 140, "aliases": ["oil service", "oil change"]}, {"item": "Inspection service", "km": 30000, "months": 24, "severe_km": 20000, "cost": 190, "aliases": ["inspection"]}, {"item": "Brake inspection", "km": 20000, "months": 12, "cost": 40, "safety": true}, {"item": "Brake fluid", "months": 24, "cost": 85, "safety": true}, {"item": "Air filter", "km": 60000, "months": 48, "severe_km": 30000, "cost": 45}, {"item": "Cabin filter", "km": 30000, "months": 24, "cost": 40, "aliases": ["pollen filter"]}, {"item": "Spark plugs", "km": 60000, "months": 72, "cost": 160}, {"item": "Tyre rotation", "km": 10000, "cost": 30}, {"item": "Tyres (set of 4)", "km": 45000, "months": 72, "cost": 560, "safety": true}, {"item": "Timing belt kit and water pump", "km": 120000, "months": 96, "cost": 680}, {"item": "Roadworthiness test", "months": 12, "first_months": 36, "cost": 60, "legal": true, "aliases": ["mot", "periodic inspection"]} ] } FILE:examples/service-log.csv date,odometer,item,cost,shop,notes 2020-11-20,11500,Oil service; Brake inspection,165,Main dealer,first service 2021-11-05,22800,Oil service; Brake inspection; Cabin filter,210,Main dealer, 2022-05-28,33900,Oil service; Inspection service; Brake fluid; Air filter,395,Main dealer, 2022-11-08,38000,Roadworthiness test,55,Test centre,passed 2023-06-15,45150,Oil service; Brake inspection; Tyre rotation; Tyres (set of 4),735,QuickFit,new tyres 205/55 R16 2023-09-02,4790,Windscreen chip repair,60,GlassFix, 2023-11-13,49000,Roadworthiness test,55,Test centre,passed 2024-07-01,56900,Oil service; Inspection service; Brake fluid; Spark plugs; Brake inspection,520,Main dealer, 2024-11-12,59800,Roadworthiness test,58,Test centre,advisory: rear wiper 2025-08-20,70100,Oil service; Brake inspection; Cabin filter; Tyre rotation,240,Corner Garage, 2025-11-20,73000,Roadworthiness test,60,Test centre,passed 2026-02-14,75300,Oil change; Brake inspection,150,Corner Garage,dash light came on FILE:examples/service-plan.md # Service plan: 2019 Skoda Octavia Estate 1.5 TSI (petrol) Today 2026-11-04, odometer 83,400 km. You drive about 11,008 km/year (2025-08-20 70,100 -> 2026-11-04 83,400). Normal-service intervals, plan horizon 24 months. Source: examples/service-log.csv. **Verdict: 4 item(s) overdue, including safety/legal items - book a visit now** Next 12 months: about 1,220.00 EUR; next 24 months: 2,445.00 EUR (set aside about 101.88 EUR per month). Findings: 1 high, 6 medium, 2 low, 3 info. ## Items | Item | Interval | Last done | Due by date | Due at km | Next (projected) | Trigger | Status | Est. cost | |---|---|---|---|---|---|---|---|---| | Inspection service | 30,000 km / 24 months | 2024-07-01 at 56,900 | 2026-07-01 | 86,900 | 2026-11-04 | time | **OVERDUE** | 190.00 | | Brake fluid [safety] | 24 months | 2024-07-01 at 56,900 | 2026-07-01 | - | 2026-11-04 | time | **OVERDUE** | 85.00 | | Air filter | 60,000 km / 48 months | 2022-05-28 at 33,900 | 2026-05-28 | 93,900 | 2026-11-04 | time | **OVERDUE** | 45.00 | | Tyre rotation | 10,000 km | 2025-08-20 at 70,100 | - | 80,100 | 2026-11-04 | distance | **OVERDUE** | 30.00 | | Roadworthiness test [legal] | 12 months | 2025-11-20 at 73,000 | 2026-11-20 | - | 2026-11-20 | time | **DUE SOON** | 60.00 | | Engine oil and filter | 15,000 km / 12 months | 2026-02-14 at 75,300 | 2027-02-14 | 90,300 | 2027-02-14 | time | OK | 140.00 | | Brake inspection [safety] | 20,000 km / 12 months | 2026-02-14 at 75,300 | 2027-02-14 | 95,300 | 2027-02-14 | time | OK | 40.00 | | Tyres (set of 4) [safety] | 45,000 km / 72 months | 2023-06-15 at 45,150 | 2029-06-15 | 90,150 | 2027-06-15 | distance | OK | 560.00 | | Cabin filter | 30,000 km / 24 months | 2025-08-20 at 70,100 | 2027-08-20 | 100,100 | 2027-08-20 | time | OK | 40.00 | | Timing belt kit and water pump | 120,000 km / 96 months | no record (counted from new, 2019-11-14) | 2027-11-14 | 120,000 | 2027-11-14 | time | OK | 680.00 | | Spark plugs | 60,000 km / 72 months | 2024-07-01 at 56,900 | 2030-07-01 | 116,900 | 2029-11-18 | distance | OK | 160.00 | ## Workshop visits (items within 60 days / 2,500 km are bundled) | # | Book by | At about | Items | Est. cost | |---|---|---|---|---| | 1 | 2026-11-04 (now) | 83,400 km | Air filter (overdue), Brake fluid (overdue), Inspection service (overdue), Tyre rotation (overdue), Roadworthiness test | 410.00 | | 2 | 2027-02-14 | 86,476 km | Brake inspection, Engine oil and filter | 180.00 | | 3 | 2027-06-15 | 90,125 km | Tyres (set of 4) | 560.00 | | 4 | 2027-08-20 | 92,116 km | Cabin filter, Tyre rotation | 70.00 | | 5 | 2027-11-14 | 94,710 km | Timing belt kit and water pump, Roadworthiness test | 740.00 | | 6 | 2028-02-14 | 97,484 km | Brake inspection, Engine oil and filter | 180.00 | | 7 | 2028-08-27 | 103,365 km | Tyre rotation | 30.00 | | 8 | 2028-11-04 | 105,446 km | Brake fluid, Inspection service | 275.00 | ## Cost forecast by quarter | Quarter | Est. cost | |---|---| | 2026-Q4 | 410.00 | | 2027-Q1 | 180.00 | | 2027-Q2 | 560.00 | | 2027-Q3 | 40.00 | | 2027-Q4 | 770.00 | | 2028-Q1 | 180.00 | | 2028-Q3 | 30.00 | | 2028-Q4 | 275.00 | | **Total 24 months** | **2,445.00** | ## Findings - **HIGH CS01** Brake fluid is overdue by 126 days (safety item) - book it now - **MEDIUM CS01** Air filter is overdue by 160 days - book it now - **MEDIUM CS01** Inspection service is overdue by 126 days - book it now - **MEDIUM CS01** Tyre rotation is overdue by 3,300 km - book it now - **MEDIUM CS02** Roadworthiness test is due soon: 2026-11-20 - **MEDIUM CS03** Timing belt kit and water pump: no record in your log - counted from new; check the service book or receipts - **MEDIUM CS04** row 7: odometer 4,790 on 2023-09-02 is lower than 45,150 on 2023-06-15 - typo or wrong car? reading ignored - **LOW CS08** Timing belt kit and water pump (about 680.00) falls in the plan on 2027-11-14 - budget for it now - **LOW CS08** Tyres (set of 4) (about 560.00) falls in the plan on 2027-06-15 - budget for it now - **INFO CS05** Brake inspection was last done after 5,200 km / 6 months (under 60% of the interval) - fine for severe use, otherwise money spent early - **INFO CS05** Engine oil and filter was last done after 5,200 km / 6 months (under 60% of the interval) - fine for severe use, otherwise money spent early - **INFO CS07** row 7: 'Windscreen chip repair' is not in your schedule - kept in the history only Intervals and prices come from your car file: check them against the owner's manual or service booklet for your exact engine, and follow your workshop if it finds wear earlier. Costs are estimates; tyres and brakes also depend on wear, not only on distance. FILE:scripts/car_service_plan.py #!/usr/bin/env python3 """Car maintenance service schedule planner (stdlib only, Python 3.8+). Reads your car's maintenance schedule (items with distance and/or time intervals, from the owner's manual or service booklet) and your service history (CSV), estimates how far you drive from the odometer readings in the log, and works out for every item when it was last done, when it is next due (distance or time, whichever comes first), what is overdue or due soon, which items can share one workshop visit, and what maintenance will cost over the next months. Usage: car_service_plan.py CAR.json SERVICE_LOG.csv [--odometer N] [--today YYYY-MM-DD] [--severe] [--horizon MONTHS] [--json] car_service_plan.py --self-test Exit: 0 = nothing overdue on a safety/legal item, 1 = a safety or legal item is overdue (or the log has a high finding), 2 = bad input. """ import argparse, calendar, csv, datetime, io, json, sys SEV = {"high": 0, "medium": 1, "low": 2, "info": 3} CAR_KEYS = {"vehicle", "odometer", "driving", "currency", "horizon_months", "due_soon", "bundle", "schedule"} class InputError(Exception): pass def pdate(s, what): try: return datetime.date.fromisoformat(str(s).strip()) except ValueError: raise InputError("%s must be YYYY-MM-DD, got %r" % (what, s)) def add_months(d, m): y, mo = divmod(d.month - 1 + int(m), 12) y += d.year mo += 1 return datetime.date(y, mo, min(d.day, calendar.monthrange(y, mo)[1])) def num(x, what): try: return float(str(x).replace(",", "").replace(" ", "")) except ValueError: raise InputError("%s is not a number: %r" % (what, x)) def fk(x): return "{:,.0f}".format(x) def fm(x): return "{:,.2f}".format(x) # ---------------------------------------------------------------- load def load_car(cfg, odometer=None, today=None, severe=None, horizon=None): if not isinstance(cfg, dict): raise InputError("car file must be a JSON object") bad = set(cfg) - CAR_KEYS if bad: raise InputError("unknown key(s) in car file: %s" % ", ".join(sorted(bad))) v = cfg.get("vehicle") or {} odo = cfg.get("odometer") or {} drv = cfg.get("driving") or {} c = {"name": v.get("name", "Car"), "unit": v.get("unit", "km"), "first": pdate(v["first_registered"], "vehicle.first_registered") if v.get("first_registered") else None, "today": pdate(today or odo.get("date") or datetime.date.today().isoformat(), "today"), "odo": num(odometer if odometer is not None else odo.get("reading"), "odometer reading") if (odometer is not None or odo.get("reading") is not None) else None, "default_per_year": num(drv.get("default_per_year", 12000), "driving.default_per_year"), "severe": bool(drv.get("severe", False)) if severe is None else severe, "severe_reasons": drv.get("severe_reasons", []), "currency": cfg.get("currency", ""), "horizon": int(horizon or cfg.get("horizon_months", 24)), "soon_km": num((cfg.get("due_soon") or {}).get("km", 1500), "due_soon.km"), "soon_days": int((cfg.get("due_soon") or {}).get("days", 45)), "bundle_km": num((cfg.get("bundle") or {}).get("km", 2500), "bundle.km"), "bundle_days": int((cfg.get("bundle") or {}).get("days", 60)), "items": []} if c["odo"] is None: raise InputError("give the current odometer reading (odometer.reading or --odometer)") for i, it in enumerate(cfg.get("schedule") or [], 1): name = it.get("item") if not name: raise InputError("schedule item %d has no 'item' name" % i) km = it.get("severe_km") if c["severe"] and it.get("severe_km") else it.get("km") mo = it.get("severe_months") if c["severe"] and it.get("severe_months") else it.get("months") if not km and not mo: raise InputError("schedule item '%s' needs km and/or months" % name) c["items"].append({"item": name, "km": num(km, name + " km") if km else None, "months": int(mo) if mo else None, "first_months": int(it["first_months"]) if it.get("first_months") else None, "cost": num(it.get("cost", 0), name + " cost"), "safety": bool(it.get("safety")), "legal": bool(it.get("legal")), "severe_used": bool(c["severe"] and (it.get("severe_km") or it.get("severe_months"))), "aliases": [a.lower().strip() for a in it.get("aliases", [])] + [name.lower().strip()]}) if not c["items"]: raise InputError("car file needs a non-empty 'schedule'") return c def load_log(c, text, F): rows = list(csv.DictReader(io.StringIO(text))) if rows and not {"date", "odometer", "item"} <= set(rows[0]): raise InputError("service log needs columns date, odometer, item (has %s)" % ", ".join(rows[0])) entries, readings = [], [] for n, r in enumerate(rows, 2): try: d = pdate(r.get("date"), "date (row %d)" % n) except InputError as e: F.append(("high", "CS04", "row %d: %s - row ignored" % (n, e))); continue if d > c["today"]: F.append(("high", "CS04", "row %d: date %s is in the future - row ignored" % (n, d))); continue odo = None if (r.get("odometer") or "").strip(): try: odo = num(r["odometer"], "odometer (row %d)" % n) except InputError as e: F.append(("medium", "CS04", "%s - distance ignored for this row" % e)) items = [x.strip() for x in (r.get("item") or "").split(";") if x.strip()] entries.append({"row": n, "date": d, "odo": odo, "items": items, "cost": r.get("cost", ""), "shop": r.get("shop", "")}) entries.sort(key=lambda e: (e["date"], e["row"])) last = None for e in entries: if e["odo"] is None: continue if e["odo"] > c["odo"]: F.append(("high", "CS04", "row %d: odometer %s on %s is higher than the current reading %s - typo? reading ignored" % (e["row"], fk(e["odo"]), e["date"], fk(c["odo"])))) e["odo"] = None; continue if last and e["odo"] < last["odo"]: F.append(("medium", "CS04", "row %d: odometer %s on %s is lower than %s on %s - typo or wrong car? reading ignored" % (e["row"], fk(e["odo"]), e["date"], fk(last["odo"]), last["date"]))) e["odo"] = None; continue last = e readings.append((e["date"], e["odo"])) readings.append((c["today"], c["odo"])) return entries, readings def distance_rate(c, readings, F): """km per day from the latest reading at least a year before today (else the earliest).""" end_d, end_o = readings[-1] older = [r for r in readings[:-1] if (end_d - r[0]).days >= 365] start = older[-1] if older else (readings[0] if len(readings) > 1 else None) if not start or (end_d - start[0]).days < 60 or end_o <= start[1]: F.append(("medium", "CS09", "not enough odometer readings to estimate your yearly distance - using the default %s %s/year" % (fk(c["default_per_year"]), c["unit"]))) return c["default_per_year"] / 365.0, "default" rate = (end_o - start[1]) / float((end_d - start[0]).days) return rate, "%s %s -> %s %s" % (start[0], fk(start[1]), end_d, fk(end_o)) # ---------------------------------------------------------------- plan def plan(c, log_text): F = [] entries, readings = load_log(c, log_text, F) rate, basis = distance_rate(c, readings, F) known = {a: it for it in c["items"] for a in it["aliases"]} done = {it["item"]: [] for it in c["items"]} for e in entries: for name in e["items"]: it = known.get(name.lower()) if not it: F.append(("info", "CS07", "row %d: '%s' is not in your schedule - kept in the history only" % (e["row"], name))) continue done[it["item"]].append(e) def date_at_km(km): return c["today"] + datetime.timedelta(days=max(0.0, (km - c["odo"]) / rate)) if rate > 0 else None def km_at_date(d): return c["odo"] + rate * (d - c["today"]).days end = add_months(c["today"], c["horizon"]) rows, occ = [], [] for it in c["items"]: hist = done[it["item"]] last = hist[-1] if hist else None if last: base_d, base_km, base_note = last["date"], last["odo"], "%s at %s" % (last["date"], fk(last["odo"]) if last["odo"] is not None else "?") else: if not c["first"]: raise InputError("no record of '%s' and no vehicle.first_registered to count from" % it["item"]) base_d, base_km, base_note = c["first"], 0.0, "no record (counted from new, %s)" % c["first"] F.append(("medium", "CS03", "%s: no record in your log - counted from new; check the service book or receipts" % it["item"])) months = it["months"] if not last and it["first_months"]: months = it["first_months"] due_d = add_months(base_d, months) if months else None due_km = base_km + it["km"] if (it["km"] and base_km is not None) else None km_d = date_at_km(due_km) if due_km is not None else None cands = [(x, w) for x, w in ((due_d, "time"), (km_d, "distance")) if x] if not cands: due_date, trigger = c["today"], "unknown" else: due_date, trigger = min(cands) overdue = (due_d is not None and due_d < c["today"]) or (due_km is not None and due_km < c["odo"]) soon = not overdue and ((due_d is not None and (due_d - c["today"]).days <= c["soon_days"]) or (due_km is not None and due_km - c["odo"] <= c["soon_km"])) status = "OVERDUE" if overdue else ("DUE SOON" if soon else "OK") if overdue: late = [] if due_d is not None and due_d < c["today"]: late.append("%d days" % (c["today"] - due_d).days) if due_km is not None and due_km < c["odo"]: late.append("%s %s" % (fk(c["odo"] - due_km), c["unit"])) sev = "high" if (it["safety"] or it["legal"]) else "medium" F.append((sev, "CS01", "%s is overdue by %s%s - book it now" % (it["item"], " and ".join(late), " (safety item)" if it["safety"] else (" (legal requirement)" if it["legal"] else "")))) elif soon: F.append(("medium", "CS02", "%s is due soon: %s%s" % (it["item"], due_d if due_d and (due_d - c["today"]).days <= c["soon_days"] else "", (" / at %s %s" % (fk(due_km), c["unit"])) if due_km is not None else ""))) if len(hist) >= 2 and hist[-2]["odo"] is not None and hist[-1]["odo"] is not None: a, b = hist[-2], hist[-1] fr = [] if it["km"]: fr.append((b["odo"] - a["odo"]) / it["km"]) if it["months"]: fr.append(((b["date"] - a["date"]).days / 30.44) / it["months"]) if fr and max(fr) < 0.6: F.append(("info", "CS05", "%s was last done after %s %s / %d months (under 60%% of the interval) - fine for severe use, otherwise money spent early" % (it["item"], fk(b["odo"] - a["odo"]), c["unit"], round((b["date"] - a["date"]).days / 30.44)))) rows.append({"item": it["item"], "last": base_note, "interval": " / ".join(x for x in [("%s %s" % (fk(it["km"]), c["unit"])) if it["km"] else "", ("%d months" % months) if months else ""] if x), "due_date": due_d, "due_km": due_km, "next": max(due_date, c["today"]), "trigger": trigger, "status": status, "cost": it["cost"], "safety": it["safety"] or it["legal"], "flag": "legal" if it["legal"] else ("safety" if it["safety"] else ""), "severe": it["severe_used"]}) # occurrences in the horizon (each one assumed done on its due date) d, k, first = max(due_date, c["today"]), due_km, True guard = 0 while d <= end and guard < 50: guard += 1 occ.append({"item": it["item"], "date": d, "km": km_at_date(d), "cost": it["cost"], "overdue": first and overdue}) first = False nd = add_months(d, it["months"]) if it["months"] else None nk = km_at_date(d) + it["km"] if it["km"] else None cands = [x for x in (nd, date_at_km(nk) if nk is not None else None) if x] if not cands: break d = min(cands) if (it["cost"] >= 400) and any(o["item"] == it["item"] for o in occ): o = next(o for o in occ if o["item"] == it["item"]) F.append(("low", "CS08", "%s (about %s) falls in the plan on %s - budget for it now" % (it["item"], fm(it["cost"]), o["date"]))) if c["severe"]: F.append(("info", "CS06", "severe-service intervals used%s" % ((" (" + ", ".join(c["severe_reasons"]) + ")") if c["severe_reasons"] else ""))) # visits: group occurrences within the bundle window occ.sort(key=lambda o: (o["date"], o["item"])) visits = [] for o in occ: v = visits[-1] if visits else None if v and (o["date"] - v["date"]).days <= c["bundle_days"] and o["km"] - v["km"] <= c["bundle_km"]: v["items"].append(o); continue visits.append({"date": o["date"], "km": o["km"], "items": [o]}) # costs by quarter quarters = {} for o in occ: q = "%d-Q%d" % (o["date"].year, (o["date"].month - 1) // 3 + 1) quarters[q] = quarters.get(q, 0.0) + o["cost"] y1 = sum(o["cost"] for o in occ if o["date"] < add_months(c["today"], 12)) total = sum(o["cost"] for o in occ) F.sort(key=lambda f: (SEV[f[0]], f[1], f[2])) return {"car": c, "rate": rate, "basis": basis, "rows": rows, "occ": occ, "visits": visits, "quarters": quarters, "next12": y1, "total": total, "findings": F, "entries": entries} # ---------------------------------------------------------------- report def report(res, title): c, F = res["car"], res["findings"] cnt = {s: sum(1 for f in F if f[0] == s) for s in SEV} cur = (" " + c["currency"]) if c["currency"] else "" ov = [r for r in res["rows"] if r["status"] == "OVERDUE"] soon = [r for r in res["rows"] if r["status"] == "DUE SOON"] L = ["# Service plan: %s" % c["name"], ""] L.append("Today %s, odometer %s %s. You drive about %s %s/year (%s). %s intervals, plan horizon %d months. Source: %s." % ( c["today"], fk(c["odo"]), c["unit"], fk(res["rate"] * 365), c["unit"], res["basis"], "Severe-service" if c["severe"] else "Normal-service", c["horizon"], title)) L.append("") if any(r["safety"] for r in ov): L.append("**Verdict: %d item(s) overdue, including safety/legal items - book a visit now**" % len(ov)) elif ov: L.append("**Verdict: %d item(s) overdue - book a visit soon**" % len(ov)) elif soon: L.append("**Verdict: nothing overdue, %d item(s) due soon**" % len(soon)) else: L.append("**Verdict: up to date**") L.append("") L.append("Next 12 months: about %s%s; next %d months: %s%s (set aside about %s%s per month). Findings: %d high, %d medium, %d low, %d info." % ( fm(res["next12"]), cur, c["horizon"], fm(res["total"]), cur, fm(res["total"] / c["horizon"]), cur, cnt["high"], cnt["medium"], cnt["low"], cnt["info"])) L += ["", "## Items", "", "| Item | Interval | Last done | Due by date | Due at %s | Next (projected) | Trigger | Status | Est. cost |" % c["unit"], "|---|---|---|---|---|---|---|---|---|"] order = {"OVERDUE": 0, "DUE SOON": 1, "OK": 2} for r in sorted(res["rows"], key=lambda r: (order[r["status"]], r["next"])): L.append("| %s%s | %s | %s | %s | %s | %s | %s | %s | %s |" % ( r["item"], (" [%s]" % r["flag"]) if r["flag"] else "", r["interval"] + (" (severe)" if r["severe"] else ""), r["last"], r["due_date"] or "-", fk(r["due_km"]) if r["due_km"] is not None else "-", r["next"], r["trigger"], "**%s**" % r["status"] if r["status"] != "OK" else "OK", fm(r["cost"]))) L += ["", "## Workshop visits (items within %d days / %s %s are bundled)" % (c["bundle_days"], fk(c["bundle_km"]), c["unit"]), "", "| # | Book by | At about | Items | Est. cost |", "|---|---|---|---|---|"] for i, v in enumerate(res["visits"], 1): L.append("| %d | %s%s | %s %s | %s | %s |" % (i, v["date"], " (now)" if v["date"] == c["today"] else "", fk(v["km"]), c["unit"], ", ".join(o["item"] + (" (overdue)" if o["overdue"] else "") for o in v["items"]), fm(sum(o["cost"] for o in v["items"])))) L += ["", "## Cost forecast by quarter", "", "| Quarter | Est. cost |", "|---|---|"] for q in sorted(res["quarters"]): L.append("| %s | %s |" % (q, fm(res["quarters"][q]))) L.append("| **Total %d months** | **%s** |" % (c["horizon"], fm(res["total"]))) L += ["", "## Findings", ""] L += ["- **%s %s** %s" % (s.upper(), code, m) for s, code, m in F] or ["- none"] L += ["", "Intervals and prices come from your car file: check them against the owner's manual or service booklet for your exact engine, and follow your workshop if it finds wear earlier. Costs are estimates; tyres and brakes also depend on wear, not only on distance."] return "\n".join(L) + "\n" def to_json(res): def j(x): if isinstance(x, datetime.date): return x.isoformat() if isinstance(x, float): return round(x, 2) if isinstance(x, dict): return {k: j(v) for k, v in x.items()} if isinstance(x, list): return [j(v) for v in x] return x return j({"km_per_year": res["rate"] * 365, "items": res["rows"], "visits": [{"date": v["date"], "km": v["km"], "items": [o["item"] for o in v["items"]], "cost": sum(o["cost"] for o in v["items"])} for v in res["visits"]], "quarters": res["quarters"], "next12": res["next12"], "total": res["total"], "findings": [{"severity": s, "code": c, "message": m} for s, c, m in res["findings"]]}) # ---------------------------------------------------------------- self-test def self_test(): tests = [] def t(name, cond): tests.append((name, bool(cond))) def car(**kw): cfg = {"vehicle": {"name": "T", "first_registered": "2020-01-01"}, "odometer": {"reading": 50000, "date": "2026-01-01"}, "schedule": [{"item": "Oil", "km": 15000, "months": 12, "severe_km": 7500, "severe_months": 6, "cost": 100, "aliases": ["oil change"]}]} sched = kw.pop("schedule", None) if sched: cfg["schedule"] = sched cfg.update(kw) return cfg H = "date,odometer,item,cost,shop\n" def run(cfg, log, **kw): return plan(load_car(cfg, **kw), H + log) def row(res, name): return next(r for r in res["rows"] if r["item"] == name) def codes(res): return [(f[0], f[1]) for f in res["findings"]] log = "2025-01-01,40000,Oil,90,X\n" r = run(car(), log) t("rate from readings: 10000 km/year", abs(r["rate"] * 365 - 10000) < 1) t("due by time first (12 months)", row(r, "Oil")["due_date"] == datetime.date(2026, 1, 1) and row(r, "Oil")["trigger"] == "time") t("due today counts as due soon", row(r, "Oil")["status"] == "DUE SOON") r = run(car(), "2025-06-01,40000,Oil,90,X\n") t("distance triggers first when driving a lot", row(r, "Oil")["due_km"] == 55000 and row(r, "Oil")["trigger"] == "distance") r = run(car(), "2024-06-01,30000,Oil,90,X\n") t("overdue by time and distance -> CS01", row(r, "Oil")["status"] == "OVERDUE" and ("medium", "CS01") in codes(r)) sched = [{"item": "Brake fluid", "months": 24, "cost": 80, "safety": True}] r = run(car(schedule=sched), "2023-06-01,30000,Brake fluid,80,X\n2025-01-01,40000,Other,0,X\n") t("overdue safety item -> CS01 high", ("high", "CS01") in codes(r)) t("item not in schedule -> CS07", ("info", "CS07") in codes(r)) r = run(car(), "2025-01-01,40000,oil change,90,X\n") t("aliases match case-insensitively", row(r, "Oil")["last"].startswith("2025-01-01")) r = run(car(), "2025-01-01,40000,Wipers,20,X\n") t("no record -> counted from new, CS03", ("medium", "CS03") in codes(r) and "no record" in row(r, "Oil")["last"]) r = run(car(), "2025-01-01,40000,Oil,90,X\n", severe=True) t("severe intervals used", row(r, "Oil")["due_date"] == datetime.date(2025, 7, 1) and ("info", "CS06") in codes(r)) r = run(car(), "2024-01-01,30000,Oil,90,X\n2024-06-01,20000,Oil,90,X\n2025-01-01,40000,Oil,90,X\n") t("odometer going down -> CS04, reading ignored", ("medium", "CS04") in codes(r)) r = run(car(), "2025-01-01,40000,Oil,90,X\n2027-01-01,60000,Oil,90,X\n") t("future date -> CS04 high", ("high", "CS04") in codes(r)) r = run(car(), "2025-01-01,90000,Oil,90,X\n") t("reading above current odometer -> CS04 high", ("high", "CS04") in codes(r)) r = run(car(), "") t("no readings -> default rate + CS09", ("medium", "CS09") in codes(r) and abs(r["rate"] * 365 - 12000) < 1) r = run(car(), "2025-01-01,40000,Oil,90,X\n2025-04-01,42000,Oil,90,X\n") t("done early -> CS05", ("info", "CS05") in codes(r)) sched = [{"item": "Test", "months": 12, "first_months": 36, "cost": 50, "legal": True}] r = run(car(vehicle={"first_registered": "2024-01-01"}, schedule=sched), "2025-01-01,40000,Other,0,X\n") t("first_months for first test from new", row(r, "Test")["due_date"] == datetime.date(2027, 1, 1)) sched = [{"item": "A", "months": 12, "cost": 100}, {"item": "B", "months": 12, "cost": 50}] r = run(car(schedule=sched), "2025-02-01,41000,A,0,X\n2025-03-15,42000,B,0,X\n") t("items within the bundle window share a visit", len(r["visits"][0]["items"]) == 2) t("horizon repeats yearly items", sum(1 for o in r["occ"] if o["item"] == "A") == 2) t("12-month and total forecast", r["next12"] == 150 and r["total"] == 300) sched = [{"item": "Belt", "km": 120000, "months": 96, "cost": 650}] r = run(car(schedule=sched), "2025-01-01,40000,Other,0,X\n") t("big-ticket item in horizon -> CS08", ("low", "CS08") in codes(r)) t("add_months clamps month end", add_months(datetime.date(2026, 1, 31), 1) == datetime.date(2026, 2, 28)) try: load_car(car(schedule=[{"item": "X", "cost": 1}])); ok = False except InputError: ok = True t("item without interval rejected", ok) try: load_car(dict(car(), colour="red")); ok = False except InputError: ok = True t("unknown key rejected", ok) r = run(car(), log) t("report has verdict, visits and forecast", all(s in report(r, "t") for s in ("**Verdict:", "## Workshop visits", "## Cost forecast"))) for name, ok in tests: print(("PASS " if ok else "FAIL ") + name) passed = sum(ok for _, ok in tests) print("%d/%d passed" % (passed, len(tests))) return 0 if passed == len(tests) else 1 def main(argv=None): ap = argparse.ArgumentParser(description="Plan car maintenance from a schedule and a service log.") ap.add_argument("car", nargs="?") ap.add_argument("log", nargs="?") ap.add_argument("--odometer", type=float) ap.add_argument("--today") ap.add_argument("--severe", action="store_true", default=None, help="use severe-service intervals") ap.add_argument("--horizon", type=int, help="months to plan (default from car file, else 24)") ap.add_argument("--json", action="store_true") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.car or not a.log: ap.print_usage(sys.stderr) return 2 try: try: cfg = json.load(open(a.car, encoding="utf-8")) except json.JSONDecodeError as e: raise InputError("car file is not valid JSON: %s" % e) c = load_car(cfg, a.odometer, a.today, a.severe, a.horizon) res = plan(c, open(a.log, encoding="utf-8-sig").read()) except (OSError, InputError) as e: print("error: %s" % e, file=sys.stderr) return 2 if a.json: print(json.dumps(to_json(res), indent=2)) else: sys.stdout.write(report(res, a.log)) return 1 if any(f[0] == "high" for f in res["findings"]) else 0 if __name__ == "__main__": sys.exit(main())

Design System taste

# Design System taste of a pragmatic design systems engineer - Define design tokens for color, spacing, typography, radius and motion in one source file, and generate CSS variables and platform outputs from it. Confidence: 0.90 - Name tokens by purpose, such as color-text-muted or space-inset-md, not by raw value like gray-500 or 16px. Confidence: 0.85 - Support light and dark themes by swapping semantic token values, never by overriding individual component styles. Confidence: 0.90 - Build components on accessible headless primitives such as Radix UI or React Aria instead of re-implementing focus and keyboard logic. Confidence: 0.85 - Meet WCAG 2.2 AA contrast for every token pairing and check it automatically when tokens change. Confidence: 0.90 - Keep the component API small: a few well-named variants and sizes beat dozens of boolean props. Confidence: 0.85 - Prefer composition with slots or children over configuration objects for complex components like dialogs and menus. Confidence: 0.80 - Forward refs and spread remaining props onto the root element so components work with forms, tooltips and tests. Confidence: 0.85 - Never hard-code colors, spacing or font sizes inside components; lint for raw values with Stylelint or an ESLint rule. Confidence: 0.85 - Document every component in Storybook with usage guidance, do and don't examples, and live controls. Confidence: 0.85 - Run visual regression tests with Chromatic or Playwright screenshots on every pull request. Confidence: 0.80 - Run automated accessibility checks with axe in component tests, and still test keyboard and screen reader flows by hand before release. Confidence: 0.85 - Publish the library as a versioned package with semantic versioning and a changelog generated by Changesets. Confidence: 0.90 - Treat a renamed prop or removed variant as a breaking change, and ship codemods for large migrations. Confidence: 0.75 - Deprecate before removing: mark the old API, log a development-only warning, and remove it in the next major version. Confidence: 0.85 - Ship ESM with tree-shakeable per-component entry points and mark CSS files as side effects correctly. Confidence: 0.80 - Respect prefers-reduced-motion and keep motion tokens short and purposeful. Confidence: 0.80 - Keep icons as a separate package of optimized SVG components with consistent size and stroke tokens. Confidence: 0.75 - Use logical CSS properties like margin-inline-start so components work in right-to-left layouts. Confidence: 0.75 - Keep Figma components and code components in sync by sharing token names and reviewing drift every release. Confidence: 0.70 - Measure adoption by scanning product repositories for library imports and one-off overrides. Confidence: 0.65 - Accept contributions through a short proposal template that covers the use case, API and accessibility before any code. Confidence: 0.70

Parking Ticket Appeal and Evidence Builder (JSON)

{ "role": "Calm, careful parking ticket appeal assistant who helps drivers understand a parking ticket or penalty notice, check it for errors, collect and organize evidence, decide whether to pay or challenge it, and write clear, polite, factual appeal letters within the deadlines, without inventing parking rules, signage, fines, discounts, deadlines, or laws", "task": "Turn my parking ticket details, what happened, my photos and evidence, and the dates I know into a single strict JSON appeal report: a summary, a ticket fact check, an error check of the notice, a grounds assessment, an evidence log, a photo and evidence plan, a pay or appeal decision with the money at stake, a deadline timeline, ready-to-send appeal letters, an escalation path, and a next steps list. Never invent parking rules, signs, fine amounts, early payment discounts, deadlines, or laws.", "context": { "ticket_type": "${ticket_type:penalty charge notice from the city council | private parking charge from a car park operator | police or traffic ticket | not sure}", "ticket_details": "${ticket:issued on Monday at 10:42 on a residential street, reason given was parking in a permit zone without a valid permit, amount 70, reduced to 35 if paid within 14 days}", "issuer": "${issuer:the city council parking services}", "what_happened": "${story:I parked for 20 minutes to drop off furniture at my parents' house, my visitor permit was on the dashboard but had slipped face down under the windshield}", "signs_and_markings": "${signs:one permit zone sign at the end of the street, partly covered by a tree branch, faded bay markings}", "evidence_i_have": "${evidence:a photo of the permit after I found it face down, a receipt for the furniture delivery, and a text from my mother saying I arrived at 10:30}", "evidence_i_can_still_get": "${more_evidence:photos of the sign and markings today, a copy of the visitor permit record, a witness statement from my mother}", "vehicle": "${vehicle:my own car, I am the registered keeper}", "dates_received": "${received:ticket was on the windshield on Monday, no letter by post yet}", "what_i_want": "${want:cancel the ticket, or at least keep the option to pay the reduced amount if the appeal fails}", "country_or_region": "${region:United Kingdom}" }, "ask_first": [ "A clear copy or photo of both sides of the ticket or notice, with the issuer, ticket number, date, time, location, vehicle registration, the rule it says you broke, the amount, any reduced amount, and every deadline printed on it", "Whether it came from a council or other public authority, a private car park operator, or the police, and whether it was left on the car, handed to you, or sent by post", "Exactly what happened, with times, why you parked there, how long you stayed, and whether you had a ticket, permit, blue badge, or payment app session", "What the signs, bay markings, payment machines, and any parking app showed at the time, and whether anything was missing, hidden, broken, or confusing", "All evidence you have and can still get: photos, receipts, app records, permits, witness statements, medical or breakdown records", "Who owns and drives the vehicle, whether it is a company, rental, or lease car, and the outcome you want" ], "rules": [ "Use only my inputs for facts. If something is missing, set it to null, add it to open_questions, and never guess parking rules, sign requirements, fine amounts, discount periods, appeal deadlines, appeal bodies, or laws.", "Ticket fact check: list every printed detail (issuer, ticket number, date, time, location, vehicle registration, make and color, contravention or reason, amount, reduced amount, deadlines) and compare each with what I say really happened. Flag any mismatch or missing detail as a possible error to confirm, never as proof the ticket is invalid.", "Grounds assessment: list the possible grounds my facts support (for example, a valid permit or payment, unclear or missing signs, faded markings, an allowed activity such as loading if the rules allow it, an emergency or breakdown, errors on the notice, or not being the driver or keeper), rate each strong, moderate, or weak with the reason, and mark every rule-based ground as to_confirm with the issuer's published rules or a consumer advice service.", "Evidence plan: tell me what to photograph and how (wide shots of the street and the car's position, close-ups of every sign and marking, the permit or ticket on display, the date and time on each photo), which records to request (permit records, app session history, payment receipts), and how to name and store each file. Never suggest editing photos or creating documents that did not exist.", "Pay or appeal decision: show the full amount, the reduced amount and its deadline if printed, what happens to the reduced amount if I appeal (mark it as to_confirm on the notice or with the issuer), the strength of my grounds, the time it will take, and a clear recommendation with the reason. Never tell me to ignore a ticket or a letter.", "Deadline timeline: list every date from the notice and every step date I give, mark which are deadlines, and add reminders a few days before each one. Do not invent deadlines; if a date is not printed or known, set it to null and add a question.", "Letters must be polite, factual, and short: quote the ticket number, vehicle registration, date, and location, explain what happened in order, state the grounds, list the attached evidence, and say clearly what I am asking for. Include an informal challenge or first appeal, and a formal appeal or representation for the next stage. Never include threats, insults, or claims I cannot back with evidence.", "Escalation path: list the stages in order (for example, informal challenge, formal appeal, independent appeals service or tribunal, payment or court stages) and mark each body and time limit as to_confirm for my region and type of ticket.", "This is practical help, not legal advice. Say so once in disclaimers and suggest a consumer advice service or a lawyer for court letters, large amounts, or a lost vehicle.", "Output only valid JSON matching output_format. No markdown, no comments, no prose outside the JSON." ], "output_format": { "summary": { "issuer": "string", "ticket_type": "public_authority | private_operator | police | unknown", "ticket_number": "string | null", "amount": "number | null", "reduced_amount": "number | null", "key_finding": "string", "recommendation": "appeal | pay_reduced | pay_full | get_advice | need_more_information", "appeal_strength": "strong | moderate | weak | needs_more_evidence", "assumptions": [ "string" ], "open_questions": [ "string" ] }, "ticket_fact_check": [ { "detail": "string", "on_ticket": "string | null", "what_really_happened": "string | null", "matches": "boolean | null", "possible_error": "boolean", "confirm": "boolean" } ], "grounds_assessment": [ { "ground": "string", "facts_supporting": [ "string" ], "evidence_refs": [ "string" ], "strength": "strong | moderate | weak", "reason": "string", "to_confirm": "string | null" } ], "evidence_log": [ { "evidence_id": "string", "type": "photo | receipt | permit | app_record | witness_statement | letter | other", "description": "string", "date_time": "string | null", "shows": "string", "file_name": "string", "have_it": "boolean" } ], "evidence_plan": [ { "item": "string", "how": "string", "by_when": "string", "done": "boolean" } ], "pay_or_appeal": { "full_amount": "number | null", "reduced_amount": "number | null", "reduced_deadline": "string | null", "reduced_amount_kept_during_appeal": "yes | no | to_confirm", "money_at_stake": "number | null", "time_cost": "string", "recommendation": "string", "reason": "string" }, "timeline": [ { "date": "string | null", "event": "string", "deadline": "boolean", "reminder_on": "string | null" } ], "letters": [ { "stage": "informal_challenge | formal_appeal | independent_appeal | other", "to": "string", "subject": "string", "body": "string", "attachments": [ "string" ], "send_by": "string | null", "send_method": "string" } ], "escalation_path": [ { "stage": "number", "action": "string", "body": "string", "trigger": "string", "time_limit_to_confirm": "string" } ], "next_steps": [ { "step": "string", "when": "string", "done": "boolean" } ], "disclaimers": [ "string" ] } }

Family Road Trip Day-by-Day Plan and Packing List (YAML)

role: Practical, calm road trip planner who helps families and friends turn a road trip idea into a realistic day-by-day driving plan, covering routes and driving limits, rest stops, overnight stays, a fuel or charging plan, a budget, a packing list, car checks, entertainment for passengers, and a backup plan for delays, so the trip stays safe, relaxed, and on budget task: > Turn my route idea, my travel dates, my group, my car, my budget, and any bookings I already have into a complete road trip plan as YAML: a summary with the main risks, a route overview, a day-by-day driving plan with realistic driving times and breaks, a rest stop plan, overnight stays, a fuel or charging plan, a budget by category, a pre-trip car check, a packing list by person and by car, a food and snack plan, passenger entertainment, a driver rotation and rest plan, documents and rules to confirm, a delay and breakdown backup plan, and a final departure checklist. inputs: route_idea: ${route:a 7-day loop from our home city through the mountains to the coast and back, about 1400 km in total} travel_dates: ${dates:leaving on Saturday July 12, back home by Friday July 18 evening} group: ${group:two adults, a 7-year-old, a 12-year-old, and a medium-size dog} drivers: ${drivers:both adults can drive, one prefers not to drive at night or in heavy traffic} car: ${car:a 6-year-old petrol station wagon with a roof box, last service 8 months ago} daily_driving_limit: ${limit:no more than 4 hours of driving per day, with a stop at least every 2 hours} budget: ${budget:about 2500 for fuel, tolls, parking, places to stay, food, and activities} bookings_so_far: ${bookings:2 nights booked at a lakeside campsite cabin, nothing else booked yet} places_we_want_to_see: ${places:a mountain pass viewpoint, a waterfall walk, an old harbor town, one beach day} accommodation_preferences: ${stay:pet-friendly cabins, small guesthouses, or apartments with parking, one place with a washing machine} food_needs: ${food:one child is a picky eater, we want to cook simple dinners twice and picnic for lunch most days} constraints: ${constraints:the younger child gets car sick on winding roads, the dog needs a walk every 2 to 3 hours} worries: ${worries:long traffic jams, the car breaking down, the kids getting bored, and the budget running over} ask_first: - Your start and end points, the places you want to see, the total distance if you know it, and whether the route is a loop, one-way, or out and back - Your exact travel dates, any fixed check-in or check-out times, and every booking you already have with its address and cancellation terms - Who is traveling, ages of children, pets, who can drive, any driving limits, and any health needs such as car sickness, medicines, or mobility needs - Your car type, fuel or electric, range on a full tank or charge, roof box or trailer, the date of the last service, and any warning lights or known problems - Your total budget, what is already paid, and which parts (fuel, tolls, parking, stays, food, activities) you want to keep low - Any countries or regions you will cross, and whether you need vignettes, toll passes, low-emission zone stickers, or international documents rules: - Use only my inputs for facts. If something is missing, write it under assumptions and add a question to open_questions. Never invent distances, driving times, toll prices, fuel prices, opening hours, booking availability, or traffic rules. - Mark every distance and driving time as an estimate to check in a current map app, and add a buffer of at least 20 percent to each driving day for traffic, breaks, and slow roads. - Keep each driving day within my daily limit, plan a break at least every 2 hours (or more often for children, pets, or car sickness), and avoid night driving or heavy traffic for drivers who prefer not to. - Plan fuel or charging stops before the tank or battery drops below a quarter, and list a backup stop for each one. Mark every station, charger, and price as to_confirm. - Build the budget from my inputs only, show each category and a reserve of a clearly stated share (suggest 10 to 15 percent), and never present a price as fact. - Mark every toll, vignette, low-emission zone, border, pet travel, child seat, and driving document rule as an item to confirm with the official source for each country or region. Never say a rule does or does not apply. - The pre-trip car check must cover tires and tire pressure with the load, oil and fluids, lights, wipers, brakes, the spare tire or repair kit, the warning triangle and vests where required, and the roof box load limit, and suggest a mechanic check if the car is due for service. - The packing list must split items by person and by car (for example, a first aid kit, car sickness items, a phone holder and chargers, water, snacks, and pet gear), and keep a small easy-to-reach day bag for each day. - Passenger entertainment must fit the children's ages and include screen-free games, rest times, and stops with a short walk or playground, and the dog's walks must be in the stop plan. - The backup plan must cover traffic jams, a breakdown, a flat tire, a child or passenger feeling unwell, bad weather, and a missed booking, with clear actions for each. - This is planning help, not professional or legal advice. Say so in the summary. - Output only valid YAML matching output_format. No prose outside the YAML. output_format: summary: trip: string start_date: string end_date: string total_distance_km_estimate: number driving_days: number total_budget: number reserve: number main_risks: - string status: ready | needs_bookings | needs_decisions | at_risk disclaimer: string assumptions: - string open_questions: - string route_overview: - leg: string from: string to: string distance_km_estimate: number driving_time_estimate: string road_type: string to_check_in_map_app: true day_by_day: - day: number date: string start: string end: string departure_time: string arrival_time_estimate: string driving_hours_with_buffer: number driver: string stops: - stop: string purpose: rest | fuel_or_charging | meal | dog_walk | sightseeing | toilet duration_minutes: number activities: - string overnight: string notes: string overnight_stays: - night: number date: string place: string type: string pet_friendly: boolean parking: boolean booked: boolean cancellation_terms: string cost: number fuel_or_charging_plan: range_km_estimate: number stops: - day: number location: string backup_location: string to_confirm: true budget: categories: - category: string planned: number paid: number remaining: number notes: string reserve: percent: number amount: number total_planned: number total_with_reserve: number over_or_under: number pre_trip_car_check: - check: string when: string done: boolean packing_list: by_person: - person: string items: - string car_kit: - string day_bag: - string pet_gear: - string food_and_snacks: picnic_lunches: - string simple_dinners: - string car_snacks: - string cooler_plan: string passenger_entertainment: - idea: string for_who: string screen_free: boolean driver_rotation: - day: number first_driver: string second_driver: string max_hours_per_driver: number documents_and_rules_to_confirm: - item: string where_to_check: string needed_before: string confirm: true backup_plan: - situation: string first_action: string who_to_call: string plan_b: string departure_checklist: - check: string done: boolean

Photoreal Panther Chameleon on a Mossy Rainforest Branch

A photorealistic macro wildlife photograph of a panther chameleon walking along a thick mossy branch in a misty rainforest, wide landscape 16:9. The chameleon is shown in full side profile facing left, its body bright green with bold orange-red and turquoise bands running along its side, a raised crest on its head, a ridge of small spikes along its back, a turret eye looking forward, and its feet gripping the branch mid-step. Its long tail curls into a tight spiral at the right. The thick, horizontal branch spans the whole frame, covered in green moss and dotted with small clusters of pink star-shaped flowers. Wet, glossy dark-green leaves with fresh dew drops fill the lower corners. Behind, a soft green rainforest background melts into creamy bokeh with round highlights. Shot at eye level with a macro lens, shallow depth of field, sharp scale and skin texture on the chameleon, soft diffused light after rain, calm, vivid, natural mood. No people, no text, no logos.

Pop Art Comic Illustration of a Chrome 1950s Roadside Diner at Night

A pop art comic-style illustration of a gleaming chrome 1950s roadside diner in the desert at night, landscape 4:3, with no text. A streamlined silver diner car with a rounded roof and polished, reflective chrome panels sits in the middle of the frame, with a long row of warm-yellow lit windows and a red-and-white striped awning above them. A turquoise 1950s convertible with tail fins, whitewall tires, and shiny chrome bumpers is parked in front of the diner at the lower left. A tall, blank pink neon sign shape on a dark pole glows at the upper left with no letters on it. A big yellow moon hangs at the upper right in a purple starry night sky, above pink desert mountains, saguaro cacti, and spiky desert plants. A curving desert road with a white edge line sweeps away on the right. Bold black ink outlines, halftone dot shading, flat bright retro colors, punchy comic-book energy. No text, no lettering, no speech bubbles, no logos.

systemd Service Unit Hardening Reviewer

--- name: systemd-service-unit-hardening-reviewer description: Reviews systemd .service units and their drop-ins - flags running as root, secrets in Environment=, shell pipes and redirects in ExecStart, misspelled directives and values systemd silently ignores, settings in the wrong section, weak restart and stop timeouts, network-online ordering, missing [Install], and sandbox options that will break startup. Scores exposure and writes a hardening drop-in. Includes an offline stdlib Python checker. --- # systemd Service Unit Hardening Reviewer You help developers and admins ship systemd service units that start reliably and do not hand an attacker the whole machine. Most unit files are copied from a blog post, run as root, keep a database password in `Environment=`, pipe output with `>>` (which systemd does not understand), and contain a typo that systemd logs once and then silently ignores. Hardening options are added during an incident and then stop the service from starting at all. You read the unit and every drop-in the way systemd merges them, explain what is wrong in plain words, and hand back a corrected unit plus a tested hardening drop-in. You review the text you are given. You cannot see the host: tell the user to confirm with `systemd-analyze verify <file>` and `systemd-analyze security <unit>` on the target machine, and to restart and watch `journalctl -u <unit>` after every change. ## Files in this skill - `scripts/systemd_unit_review.py` - parses a .service file plus drop-in .conf files in order (comments, backslash continuation, repeated keys, empty assignments that reset lists, invalid values that systemd skips), runs checks SD01-SD15 and prints a Markdown report with an exposure score 0-10 and a suggested hardening drop-in; `--json` and `--dropin` outputs (Python 3.8+ standard library only) - `references/directives-and-sandboxing.md` - how systemd merges units and drop-ins, the directives that matter for reliability, every sandboxing option with what it blocks and when it breaks a service - `references/checks-and-codes.md` - every finding code, its severity and the fix - `templates/unit-review.md` - the review summary to send back, with the corrected unit and the rollout steps - `examples/webapp.service` + `examples/webapp-override.conf` - a hand-deployed Node.js API with root, inline secrets, a `>>` redirect, a typo, a CAP_SYS_ADMIN grant and an incident drop-in that breaks start - `examples/worker.service` - a mostly hardened worker with DynamicUser, StateDirectory and LoadCredential - `examples/review-report.md` - the real checker output on both units ## Workflow ### 1. Collect the units Ask for the unit file and every drop-in: `systemctl cat <unit>` prints them all in the order systemd applies them. Ask what the service does (language/runtime, ports, which directories it writes, whether it needs the network at start, whether it forks), the systemd version (`systemctl --version`) and the distribution. ### 2. Run the checker ``` python3 scripts/systemd_unit_review.py examples/webapp.service examples/webapp-override.conf examples/worker.service python3 scripts/systemd_unit_review.py myapp.service override.conf --dropin python3 scripts/systemd_unit_review.py myapp.service --json python3 scripts/systemd_unit_review.py --self-test ``` Files after a .service are its drop-ins until the next .service. Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, merge the drop-ins by hand (later wins, empty list assignment resets) and walk `references/checks-and-codes.md`. ### 3. Read the result - High first: SD01 root, SD03 secrets in the unit or on the command line, SD07 CAP_SYS_ADMIN-class capabilities, SD08 typos in Exec/User/Restart or invalid Type/Restart values (the line is dropped), SD10 shell syntax without a shell, SD14 options that make the service fail (ProtectHome with an app in /home, MemoryDenyWriteExecute with Node/Java). - Medium: restart and stop timeouts, network-online ordering, settings in the wrong section, missing [Install], exposure 5 or more. - Low/info: obsolete targets, duplicated keys, missing resource limits, single sandbox options. ### 4. Fix and harden Fix the high findings in the unit itself (move secrets to `LoadCredential=` or an `EnvironmentFile=` with mode 0600, use a service user or `DynamicUser=yes`, log to stdout instead of `>>`, move the app to /opt or /srv). Add the hardening drop-in from `--dropin` one block at a time, relaxing options the service really needs (write paths, JIT, capabilities), and restart after each step. ### 5. Deliver Fill `templates/unit-review.md`: the verdict, the findings in plain words, the corrected unit, the drop-in, the exposure before and after, and the rollout commands (`daemon-reload`, restart, `systemd-analyze security`, `journalctl -u`). ## Example result The shop API runs as root, has a Postgres password and a live Stripe key in `Environment=`, appends to a log file with `>>` (systemd passes `>>` and `2>&1` to node as arguments) and grants CAP_SYS_ADMIN to bind port 443. `RestartSecs=5` is a typo, so restarts come every 100 ms. The incident drop-in adds `ProtectHome=yes` with the app in /home/deploy and `MemoryDenyWriteExecute=yes` for Node.js - both stop it from starting - and its `Restart=on-faliure` is ignored. 9 high findings, exposure 8.1. The worker is in good shape (exposure 1.2, six optional options to add). ## Rules - Never print or repeat a secret value found in a unit; name the variable and tell the user to rotate it, since it was readable by every local user. - Hardening is tested, not assumed: add options in steps, restart, check the journal; relax one option rather than dropping the whole drop-in. - Prefer `DynamicUser=yes` or a dedicated system user to root; grant only the exact capability needed (CAP_NET_BIND_SERVICE for low ports). - Edit with `systemctl edit <unit>` (drop-ins) instead of changing vendor files under /usr/lib/systemd. - The exposure score is an estimate from this script; the host's `systemd-analyze security` is the reference. FILE:references/directives-and-sandboxing.md # Directives and sandboxing notes ## How systemd builds the unit - Files: the main unit (/etc/systemd/system, else /usr/lib/systemd/system) then drop-ins `<unit>.d/*.conf` in name order. `systemctl cat <unit>` shows them all. - Later assignments win for single-value keys. List keys (After=, Environment=, ExecStartPre=, ReadWritePaths= ...) add up; an empty assignment (`ExecStart=`) resets the list - needed in a drop-in before a new ExecStart=. - An unknown directive or an invalid value is logged once ("Unknown key name", "Failed to parse") and ignored; the unit still loads with the default. That is why typos survive for years. - Lines ending in `\` continue on the next line. `#` and `;` start comments only at the start of a line. - `systemctl daemon-reload` after every edit; `systemd-analyze verify <file>` catches most syntax errors. ## Reliability directives - Type=exec (or simple) for programs that stay in the foreground; notify if the program calls sd_notify; forking only for legacy daemons (add PIDFile=); oneshot for scripts that finish (may have several ExecStart=). - Restart=on-failure + RestartSec=5s for most services. Restart=always also restarts after a clean exit. Start limit (StartLimitIntervalSec=/StartLimitBurst= in [Unit], default 5 in 10 s) stops a crash loop; StartLimitIntervalSec=0 disables it. - TimeoutStopSec= how long a clean stop may take before SIGKILL (default 90 s). infinity hangs shutdowns. - KillMode=control-group (default) kills every process of the service; mixed sends SIGTERM to the main process and SIGKILL to the rest at the timeout. - Network: `Wants=network-online.target` + `After=network-online.target` only if the program fails without the network at start (most servers can bind to 0.0.0.0 without it). - Logs: write to stdout/stderr; journald stores them (`journalctl -u <unit>`). Use LogsDirectory= if a file is required. - [Install] WantedBy=multi-user.target so `systemctl enable` starts it at boot. ## Exec lines are not shell systemd splits the line into words itself: `|`, `>`, `>>`, `2>&1`, `&&`, `;`, `&`, `$(...)` and backticks are passed to the program as arguments. `$VAR` and `${VAR}` are expanded from Environment=. If you need a shell use `ExecStart=/bin/sh -c '...'`, but a small script is easier to read and test. Prefixes: `-` ignore failure, `@` argv0, `+` full privileges, `!` privileges without the user switch (both skip the sandbox). ## Secrets - Environment= values are visible to every local user through `systemctl show` and the unit file (mode 0644). - `LoadCredential=name:/etc/app/secret` copies the file to `$CREDENTIALS_DIRECTORY/name`, readable only by the service (systemd 247+). `SetCredentialEncrypted=` / `systemd-creds` for encrypted ones (250+). - EnvironmentFile=/etc/app/env with owner root and mode 0600 is the portable fallback. - Command-line secrets are visible in `ps` and /proc/<pid>/cmdline. ## Users and capabilities - DynamicUser=yes allocates a transient user at start; combine with StateDirectory=/CacheDirectory=/LogsDirectory= for writable dirs (owned by that user, kept across restarts). Implies ProtectSystem=strict, ProtectHome=read-only, PrivateTmp. - Or a static system user: `useradd --system --no-create-home --shell /usr/sbin/nologin app` and User=app, Group=app. - Port below 1024 as non-root: `AmbientCapabilities=CAP_NET_BIND_SERVICE` and `CapabilityBoundingSet=CAP_NET_BIND_SERVICE`. CAP_SYS_ADMIN is almost root - never for a web app. ## Sandboxing options (what they block, when they break) | Option | Blocks | Breaks when | |---|---|---| | NoNewPrivileges=yes | setuid binaries, privilege gain on exec | the service runs sudo/ping/setuid helpers | | ProtectSystem=strict | writes anywhere except /dev, /proc, /sys, and the listed paths | the service writes outside ReadWritePaths=/StateDirectory=/LogsDirectory=/RuntimeDirectory= | | ProtectHome=yes | /home, /root, /run/user (tmpfs = empty, read-only = visible) | the app, its config or data live in a home directory | | PrivateTmp=yes | other services' /tmp | another process shares files through /tmp | | PrivateDevices=yes | raw devices (/dev/sda, /dev/mem) | the service needs GPUs, serial ports or USB | | ProtectKernelTunables/Modules/Logs=yes | /proc/sys writes, module loading, kernel log | the service tunes sysctls or loads modules | | ProtectControlGroups=yes | cgroup writes | container runtimes | | ProtectClock / ProtectHostname=yes | clock and hostname changes | NTP clients, hostname tools | | RestrictSUIDSGID=yes | creating setuid files | installers | | RestrictNamespaces=yes | creating namespaces | container tools, Chromium sandbox | | RestrictRealtime=yes | realtime scheduling | audio servers | | LockPersonality=yes | changing the execution domain | almost never | | MemoryDenyWriteExecute=yes | writable+executable memory | JIT runtimes: Node.js, Java, .NET, PyPy, LuaJIT, some Python C extensions | | CapabilityBoundingSet= | all capabilities (empty) | anything needing root powers; list only those needed | | SystemCallFilter=@system-service | uncommon syscalls (mount, kexec, ptrace ...) | low-level tools; check the journal for SIGSYS | | SystemCallArchitectures=native | 32-bit syscall ABI tricks | 32-bit binaries | | RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 | netlink, packet, bluetooth sockets | tools that read routing tables (add AF_NETLINK) | | UMask=0077 | world-readable new files | other users must read the files | Rollout: apply in two or three steps (filesystem options, then kernel/namespace options, then syscalls and capabilities), restart, run the health check, read `journalctl -u <unit> -b`, then `systemd-analyze security <unit>`. FILE:references/checks-and-codes.md # Checks and finding codes | Code | Severity | Check | Fix | |---|---|---|---| | SD01 | high (medium for oneshot) | runs as root: no User= and no DynamicUser=, or User=root; `+`/`!` Exec prefixes bypass the user and sandbox (medium) | DynamicUser=yes or a system user; drop the prefix | | SD02 | high: no ExecStart, several ExecStart for a non-oneshot; low: command not an absolute path | ExecStart sanity | one absolute ExecStart; empty `ExecStart=` first in a drop-in to replace it | | SD03 | high | secret-looking variable (PASSWORD, SECRET, TOKEN, API_KEY, PRIVATE_KEY, DSN) or a URL with user:password in Environment=; `--password=` style secrets on the command line | LoadCredential= or EnvironmentFile= with mode 0600; rotate the leaked secret | | SD04 | medium: Restart=no for a long-running service; low: no RestartSec (100 ms default); high: oneshot with Restart=always/on-success; info: Restart=always with the default start limit | restart policy | Restart=on-failure, RestartSec=5s | | SD05 | medium: After= and Wants= of network-online.target not paired; low: obsolete syslog.target / network.service | ordering | add the missing half | | SD06 | medium if exposure >= 5, else low | sandboxing options missing (weighted exposure score) | the `--dropin` output, tested step by step | | SD07 | high: CAP_SYS_ADMIN, CAP_SYS_MODULE, CAP_SYS_PTRACE, CAP_SYS_RAWIO; medium: CAP_DAC_OVERRIDE, CAP_NET_ADMIN, CAP_SETUID/SETGID; low: others | dangerous capabilities in AmbientCapabilities / CapabilityBoundingSet | keep only what is needed | | SD08 | high: unknown Exec*/User*/Restart* directive or invalid Type/Restart value; medium: other unknown directive, invalid value, bad boolean, line without `=`, assignment before a section, unknown section | systemd logs a warning and ignores the line | fix the spelling (suggestion shown) | | SD09 | medium | directive in the wrong section (StartLimitBurst in [Service], WantedBy in [Service], old StartLimitInterval) | move it | | SD10 | high: pipes, redirects, `&&`, `;`, `&` or `$( )` in an Exec line without `/bin/sh -c`; medium: nohup / --daemon with Type=simple/exec; low: Type=forking without PIDFile | systemd does not use a shell | a script, `sh -c`, or foreground mode | | SD11 | medium: no WantedBy/RequiredBy/Alias; low: WantedBy=default.target or graphical.target for a system service | enable at boot | WantedBy=multi-user.target | | SD12 | medium: TimeoutStopSec=infinity/0, KillMode=none; low: KillMode=process | stop behaviour | TimeoutStopSec=30s, KillMode=mixed | | SD13 | low | the same single-value key twice in one file | keep one | | SD14 | high: ProtectHome=yes/tmpfs with an app, working dir or env file under /home or /root; MemoryDenyWriteExecute with node/java/dotnet/pypy/bun/deno; medium: ProtectSystem=strict with a write path not in ReadWritePaths/StateDirectory/LogsDirectory/RuntimeDirectory | options that break the service | move the app, add the write path, drop the option | | SD15 | info | no MemoryMax/MemoryHigh/TasksMax/CPUQuota | add limits from observed usage | ## Exposure score Weights (sum 10): run as non-root 2.0, ProtectSystem=strict 1.0 (full/yes counts half), NoNewPrivileges 0.8, ProtectHome 0.6, CapabilityBoundingSet without dangerous caps 0.6, PrivateTmp 0.5, PrivateDevices 0.5, ProtectKernelTunables 0.4, ProtectKernelModules 0.4, RestrictNamespaces 0.4, SystemCallFilter 0.4, RestrictAddressFamilies 0.4, ProtectControlGroups 0.3, RestrictSUIDSGID 0.3, MemoryDenyWriteExecute 0.3, ProtectKernelLogs 0.2, ProtectClock 0.2, RestrictRealtime 0.2, UMask 0077/0027 0.2, ProtectHostname 0.1, LockPersonality 0.1, SystemCallArchitectures=native 0.1. Rating: under 2 OK, under 5 MEDIUM, under 8 EXPOSED, 8 or more UNSAFE. ## Verdict - **N high finding(s) - fix before deploying** - **works, but exposure X - add the hardening drop-in** (no high, exposure 5 or more) - **looks good** FILE:templates/unit-review.md # systemd unit review: <unit name> **Host:** <distro, systemd version> **Runtime:** <Node.js 20 / Go binary / Python> **Reviewed:** <YYYY-MM-DD> **Verdict:** <9 high findings - fix before deploying> **Exposure:** <8.1 before -> 1.5 after> ## Must fix | # | Problem | Why it matters | Fix | |---|---|---|---| | 1 | <runs as root> | <an exploit owns the machine> | <DynamicUser=yes + CAP_NET_BIND_SERVICE for port 443> | | 2 | <secret STRIPE_SECRET_KEY in Environment=> | <readable by every local user - rotate it> | <LoadCredential=stripe:/etc/shop-api/stripe> | ## Should fix - <Restart/RestartSec, network-online pairing, [Install], stop timeout> ## Corrected unit ```ini <full corrected .service file> ``` ## Hardening drop-in (`systemctl edit <unit>`) ```ini <drop-in from --dropin, adjusted for this service> ``` ## Rollout 1. Rotate the leaked secrets; put the new ones in /etc/<name>/ (mode 0600). 2. `systemd-analyze verify /etc/systemd/system/<unit>` 3. `systemctl daemon-reload && systemctl restart <unit>`; check `journalctl -u <unit> -b` and the health endpoint. 4. `systemd-analyze security <unit>` - expect <exposure>. 5. Roll back: `systemctl revert <unit>` removes the drop-ins. ## Open questions - [ ] <which directories does it write?> - [ ] <does it need the network at start?> FILE:examples/webapp.service # /etc/systemd/system/shopapi.service - Node.js shop API, deployed by hand in 2023 [Unit] Description=Shop API (Node.js) After=network-online.target syslog.target StartLimitBurst=3 [Service] Type=simple WorkingDirectory=/home/deploy/shop-api Environment=NODE_ENV=production PORT=443 Environment="DATABASE_URL=postgres://shop:Winter2024@db.internal:5432/shop" Environment=STRIPE_SECRET_KEY=sk_live_EXAMPLE_not_a_real_key ExecStartPre=/usr/bin/npm run migrate ExecStart=/usr/bin/node server.js >> /var/log/shop-api.log 2>&1 Restart=always RestartSecs=5 AmbientCapabilities=CAP_NET_BIND_SERVICE CAP_SYS_ADMIN TimeoutStopSec=infinity ProtectSystem=full PrivateTmp=yes FILE:examples/webapp-override.conf # /etc/systemd/system/shopapi.service.d/override.conf - added during an incident [Service] ProtectHome=yes MemoryDenyWriteExecute=yes Restart=on-faliure FILE:examples/worker.service # /etc/systemd/system/thumbnailer.service - image thumbnail worker [Unit] Description=Thumbnail worker Wants=network-online.target After=network-online.target StartLimitIntervalSec=60 StartLimitBurst=5 [Service] Type=exec ExecStart=/usr/local/bin/thumbnailer \ --queue redis://127.0.0.1:6379/2 \ --out /var/lib/thumbnailer DynamicUser=yes StateDirectory=thumbnailer LoadCredential=s3-key:/etc/thumbnailer/s3-key Restart=on-failure RestartSec=5s TimeoutStopSec=30s NoNewPrivileges=yes ProtectSystem=strict ProtectHome=yes PrivateTmp=yes PrivateDevices=yes ProtectKernelTunables=yes ProtectKernelModules=yes ProtectControlGroups=yes RestrictSUIDSGID=yes RestrictNamespaces=yes LockPersonality=yes CapabilityBoundingSet= SystemCallFilter=@system-service SystemCallArchitectures=native RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 MemoryMax=1G TasksMax=128 [Install] WantedBy=multi-user.target FILE:examples/review-report.md # systemd unit review | Unit | Description | Type | Runs as | Restart | Exposure (0-10) | High | Medium | Low | Info | |---|---|---|---|---|---|---|---|---|---| | `examples/webapp.service + examples/webapp-override.conf` | Shop API (Node.js) | simple | root | always | 8.1 UNSAFE | 9 | 4 | 2 | 1 | | `examples/worker.service` | Thumbnail worker | exec | DynamicUser | on-failure | 1.2 OK | 0 | 0 | 1 | 0 | ## examples/webapp.service + examples/webapp-override.conf **Verdict: 9 high finding(s) - fix before deploying** | Sev | Code | Where | Finding | Fix | |---|---|---|---|---| | high | SD01 | examples/webapp.service | runs as root (no User= or DynamicUser=) - a bug or exploit in the service owns the whole machine | add DynamicUser=yes, or create a system user (useradd --system --no-create-home <name>) and set User=/Group= | | high | SD03 | examples/webapp.service:11 | DATABASE_URL contains a URL with an embedded password | move the credential out of the unit (LoadCredential= / EnvironmentFile= 0600) | | high | SD03 | examples/webapp.service:12 | secret STRIPE_SECRET_KEY is written in the unit file - unit files are world-readable and shown by `systemctl show` | use LoadCredential=stripe_secret_key:/etc/<name>/stripe_secret_key (read from $CREDENTIALS_DIRECTORY) or EnvironmentFile=/etc/<name>/env with mode 0600 | | high | SD07 | examples/webapp.service:17 | grants CAP_SYS_ADMIN - close to full root | remove it; to bind ports below 1024 only CAP_NET_BIND_SERVICE is needed | | high | SD08 | examples/webapp-override.conf:5 | invalid value Restart=on-faliure - systemd ignores the line and keeps the default (did you mean on-failure?) | use one of: always, no, on-abnormal, on-abort, on-failure, on-success, on-watchdog | | high | SD08 | examples/webapp.service:16 | unknown directive RestartSecs= (ignored by systemd) - did you mean RestartSec=? | rename to RestartSec= | | high | SD10 | examples/webapp.service:14 | ExecStart= uses shell syntax (pipes, redirects, &&, ;, & or $( )) but systemd does not run a shell - the symbols are passed as plain arguments | wrap it: ExecStart=/bin/sh -c '...' or better move the logic into a script; log to stdout (journald) instead of >> file | | high | SD14 | examples/webapp-override.conf:3 | ProtectHome=yes but the service uses /home/deploy/shop-api - it cannot see it and will fail to start | move the app out of /home (e.g. /opt/<name>, /srv/<name>) or use ProtectHome=read-only with ReadWritePaths= for the exact directory | | high | SD14 | examples/webapp-override.conf:4 | MemoryDenyWriteExecute=yes with a JIT runtime (/usr/bin/node) - it will crash on start | remove MemoryDenyWriteExecute= for this service | | medium | SD05 | examples/webapp.service:4 | After=network-online.target without Wants=network-online.target - the ordering does nothing unless something else pulls the target in | add Wants=network-online.target | | medium | SD06 | examples/webapp.service | 19 sandboxing option(s) missing: User, NoNewPrivileges, ProtectSystem, PrivateDevices, ProtectKernelTunables, ProtectKernelModules, ProtectKernelLogs, ProtectControlGroups, ProtectClock, ProtectHostname, RestrictSUIDSGID, RestrictNamespaces, RestrictRealtime, LockPersonality, CapabilityBoundingSet, SystemCallFilter, SystemCallArchitectures, RestrictAddressFamilies, UMask | add the suggested drop-in (systemctl edit <name>), restart, and test the service | | medium | SD11 | examples/webapp.service | no [Install] WantedBy= - `systemctl enable` does nothing, so the service will not start at boot | add [Install] WantedBy=multi-user.target | | medium | SD12 | examples/webapp.service:18 | stop timeout infinity - a hung service blocks shutdown and restarts forever | set TimeoutStopSec=30s (or what a clean shutdown really needs) | | low | SD04 | examples/webapp.service:15 | Restart=always without RestartSec= (default 100ms) - a crash loop hammers the machine and hits the start limit fast | add RestartSec=5s | | low | SD05 | examples/webapp.service:4 | After=syslog.target is obsolete | remove it (journald is always available; use network-online.target) | | info | SD15 | examples/webapp.service | no resource limits (MemoryMax=, TasksMax=, CPUQuota=) - a leak can starve the host | add MemoryMax= and TasksMax= sized from normal usage | Suggested drop-in (test after applying; relax an option if the service needs it): ```ini # /etc/systemd/system/<name>.service.d/hardening.conf (systemctl edit <name>) [Service] # or User=<service account>; a non-root user needs AmbientCapabilities=CAP_NET_BIND_SERVICE for ports below 1024 DynamicUser=yes NoNewPrivileges=yes # currently full; add ReadWritePaths=/StateDirectory= for paths it writes ProtectSystem=strict PrivateDevices=yes ProtectKernelTunables=yes ProtectKernelModules=yes ProtectKernelLogs=yes ProtectControlGroups=yes ProtectClock=yes ProtectHostname=yes RestrictSUIDSGID=yes RestrictNamespaces=yes RestrictRealtime=yes LockPersonality=yes # empty = no capabilities; or list only what you need, e.g. CAP_NET_BIND_SERVICE CapabilityBoundingSet= SystemCallFilter=@system-service SystemCallArchitectures=native RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 UMask=0077 # then: systemctl daemon-reload && systemctl restart <name> && systemd-analyze security <name> ``` ## examples/worker.service **Verdict: looks good (exposure 1.2)** | Sev | Code | Where | Finding | Fix | |---|---|---|---|---| | low | SD06 | examples/worker.service | 6 sandboxing option(s) missing: ProtectKernelLogs, ProtectClock, ProtectHostname, RestrictRealtime, MemoryDenyWriteExecute, UMask | add the suggested drop-in (systemctl edit <name>), restart, and test the service | Suggested drop-in (test after applying; relax an option if the service needs it): ```ini # /etc/systemd/system/<name>.service.d/hardening.conf (systemctl edit <name>) [Service] ProtectKernelLogs=yes ProtectClock=yes ProtectHostname=yes RestrictRealtime=yes # not for JIT runtimes (Node.js, Java, .NET, PyPy) MemoryDenyWriteExecute=yes UMask=0077 # then: systemctl daemon-reload && systemctl restart <name> && systemd-analyze security <name> ``` Exposure is this script's weighted estimate, not the systemd-analyze number; run `systemd-analyze security <unit>` and `systemd-analyze verify <file>` on the target host to confirm. FILE:scripts/systemd_unit_review.py #!/usr/bin/env python3 """systemd service unit hardening reviewer (stdlib only, Python 3.8+). Reads one or more systemd .service unit files (and drop-in .conf files, applied in the order given) the way systemd does - sections, comments, backslash line continuation, repeated keys, empty assignments that reset a list - and reviews them for reliability and security problems: running as root, secrets in Environment=, shell syntax in Exec lines without a shell, unknown or misspelled directives and values, directives in the wrong section, restart and timeout policy, network-online ordering, missing [Install], sandboxing gaps, dangerous capabilities and options that will stop the service from starting. Prints an exposure score (0 = locked down, 10 = wide open, in the spirit of `systemd-analyze security`) and a suggested hardening drop-in. Usage: systemd_unit_review.py UNIT.service [DROPIN.conf ...] [--json] [--dropin] systemd_unit_review.py --self-test Exit: 0 = no high findings, 1 = at least one high finding, 2 = bad input. """ import argparse, difflib, json, re, sys SEV = {"high": 0, "medium": 1, "low": 2, "info": 3} UNIT_KEYS = {"Description", "Documentation", "Requires", "Requisite", "Wants", "BindsTo", "PartOf", "Upholds", "Conflicts", "Before", "After", "OnFailure", "OnSuccess", "PropagatesReloadTo", "ReloadPropagatedFrom", "JoinsNamespaceOf", "RequiresMountsFor", "OnFailureJobMode", "IgnoreOnIsolate", "StopWhenUnneeded", "RefuseManualStart", "RefuseManualStop", "AllowIsolate", "DefaultDependencies", "CollectMode", "FailureAction", "SuccessAction", "JobTimeoutSec", "JobRunningTimeoutSec", "StartLimitIntervalSec", "StartLimitBurst", "StartLimitAction", "RebootArgument", "SourcePath", "ConditionPathExists", "ConditionPathIsDirectory", "ConditionFileNotEmpty", "ConditionHost", "ConditionVirtualization", "ConditionKernelCommandLine", "ConditionACPower", "ConditionUser", "ConditionGroup", "AssertPathExists", "AssertFileNotEmpty", "ConditionEnvironment", "ConditionSecurity"} SERVICE_KEYS = {"Type", "ExitType", "RemainAfterExit", "GuessMainPID", "PIDFile", "BusName", "ExecStart", "ExecStartPre", "ExecStartPost", "ExecCondition", "ExecReload", "ExecStop", "ExecStopPost", "RestartSec", "RestartSteps", "RestartMaxDelaySec", "TimeoutStartSec", "TimeoutStopSec", "TimeoutAbortSec", "TimeoutSec", "TimeoutStartFailureMode", "TimeoutStopFailureMode", "RuntimeMaxSec", "WatchdogSec", "Restart", "RestartMode", "SuccessExitStatus", "RestartPreventExitStatus", "RestartForceExitStatus", "RootDirectoryStartOnly", "NonBlocking", "NotifyAccess", "Sockets", "FileDescriptorStoreMax", "USBFunctionDescriptors", "OOMPolicy", "OpenFile", "ReloadSignal", # exec "WorkingDirectory", "RootDirectory", "RootImage", "User", "Group", "DynamicUser", "SupplementaryGroups", "PAMName", "UMask", "Environment", "EnvironmentFile", "PassEnvironment", "UnsetEnvironment", "StandardInput", "StandardOutput", "StandardError", "SyslogIdentifier", "LogLevelMax", "LogRateLimitIntervalSec", "LogRateLimitBurst", "Nice", "OOMScoreAdjust", "CPUSchedulingPolicy", "IOSchedulingClass", "LimitNOFILE", "LimitNPROC", "LimitCORE", "LimitMEMLOCK", "LimitAS", "LimitFSIZE", "CapabilityBoundingSet", "AmbientCapabilities", "NoNewPrivileges", "SecureBits", "ProtectSystem", "ProtectHome", "RuntimeDirectory", "StateDirectory", "CacheDirectory", "LogsDirectory", "ConfigurationDirectory", "RuntimeDirectoryMode", "StateDirectoryMode", "RuntimeDirectoryPreserve", "ReadWritePaths", "ReadOnlyPaths", "InaccessiblePaths", "ExecPaths", "NoExecPaths", "TemporaryFileSystem", "BindPaths", "BindReadOnlyPaths", "PrivateTmp", "PrivateDevices", "PrivateNetwork", "PrivateUsers", "PrivateIPC", "PrivateMounts", "ProtectHostname", "ProtectClock", "ProtectKernelTunables", "ProtectKernelModules", "ProtectKernelLogs", "ProtectControlGroups", "ProtectProc", "ProcSubset", "RestrictAddressFamilies", "RestrictNamespaces", "LockPersonality", "MemoryDenyWriteExecute", "RestrictRealtime", "RestrictSUIDSGID", "RemoveIPC", "SystemCallFilter", "SystemCallArchitectures", "SystemCallErrorNumber", "DevicePolicy", "DeviceAllow", "IPAddressAllow", "IPAddressDeny", "LoadCredential", "LoadCredentialEncrypted", "SetCredential", "SetCredentialEncrypted", "KeyringMode", "TTYPath", "UtmpIdentifier", "SELinuxContext", "AppArmorProfile", "KillMode", "KillSignal", "SendSIGKILL", "SendSIGHUP", "FinalKillSignal", "RestartKillSignal", # resource control "CPUQuota", "CPUWeight", "MemoryMax", "MemoryHigh", "MemoryLow", "MemoryMin", "MemorySwapMax", "TasksMax", "IOWeight", "Slice", "Delegate", "CPUAccounting", "MemoryAccounting", "IOAccounting", "TasksAccounting", "IPAccounting", "ManagedOOMSwap", "ManagedOOMMemoryPressure"} INSTALL_KEYS = {"Alias", "WantedBy", "RequiredBy", "UpheldBy", "Also", "DefaultInstance"} SECTIONS = {"Unit": UNIT_KEYS, "Service": SERVICE_KEYS, "Install": INSTALL_KEYS} LIST_KEYS = {"Requires", "Wants", "After", "Before", "BindsTo", "PartOf", "Conflicts", "Documentation", "Environment", "EnvironmentFile", "ExecStartPre", "ExecStartPost", "ExecStop", "ExecStopPost", "ExecReload", "ExecCondition", "ReadWritePaths", "ReadOnlyPaths", "InaccessiblePaths", "SupplementaryGroups", "CapabilityBoundingSet", "AmbientCapabilities", "SystemCallFilter", "RestrictAddressFamilies", "DeviceAllow", "LoadCredential", "SetCredential", "WantedBy", "RequiredBy", "Alias", "Also", "BindPaths", "BindReadOnlyPaths", "IPAddressAllow", "IPAddressDeny", "OnFailure", "SuccessExitStatus", "RestartPreventExitStatus", "TemporaryFileSystem", "PassEnvironment", "UnsetEnvironment", "RequiresMountsFor", "StateDirectory", "RuntimeDirectory", "CacheDirectory", "LogsDirectory", "ExecStart", "ConditionPathExists", "AssertPathExists"} VALUES = { "Type": {"simple", "exec", "forking", "oneshot", "dbus", "notify", "notify-reload", "idle"}, "Restart": {"no", "on-success", "on-failure", "on-abnormal", "on-watchdog", "on-abort", "always"}, "ProtectSystem": {"yes", "no", "true", "false", "full", "strict", "1", "0", "on", "off"}, "ProtectHome": {"yes", "no", "true", "false", "read-only", "tmpfs", "1", "0", "on", "off"}, "KillMode": {"control-group", "mixed", "process", "none"}, "StandardOutput": None, "NotifyAccess": {"none", "main", "exec", "all"}, } BOOL = {"yes", "no", "true", "false", "1", "0", "on", "off"} BOOL_KEYS = {"NoNewPrivileges", "PrivateTmp", "PrivateDevices", "PrivateNetwork", "PrivateUsers", "ProtectKernelTunables", "ProtectKernelModules", "ProtectKernelLogs", "ProtectControlGroups", "ProtectHostname", "ProtectClock", "LockPersonality", "MemoryDenyWriteExecute", "RestrictRealtime", "RestrictSUIDSGID", "RemoveIPC", "DynamicUser", "RemainAfterExit", "PrivateIPC", "PrivateMounts", "DefaultDependencies"} TRUE = {"yes", "true", "1", "on"} SECRET_RE = re.compile(r"(PASS(WORD|WD)?|SECRET|TOKEN|API_?KEY|PRIVATE_?KEY|CREDENTIALS?|DSN)", re.I) SHELL_RE = re.compile(r"(\|\||&&|(?<![\\])[|;]|>>?|<|\$\(|`|(?:^|\s)&\s*$|\s&$)") DANGER_CAPS = {"CAP_SYS_ADMIN": "high", "CAP_SYS_MODULE": "high", "CAP_SYS_PTRACE": "high", "CAP_DAC_OVERRIDE": "medium", "CAP_SYS_RAWIO": "high", "CAP_NET_ADMIN": "medium", "CAP_SETUID": "medium", "CAP_SETGID": "medium", "CAP_CHOWN": "low", "CAP_SYS_CHROOT": "low"} # (directive, wanted value test, weight, recommended line) - weights sum to 10.0 HARDEN = [ ("User", None, 2.0, "DynamicUser=yes|or User=<service account>; a non-root user needs AmbientCapabilities=CAP_NET_BIND_SERVICE for ports below 1024"), ("NoNewPrivileges", "bool", 0.8, "NoNewPrivileges=yes"), ("ProtectSystem", "strict", 1.0, "ProtectSystem=strict"), ("ProtectHome", "home", 0.6, "ProtectHome=yes"), ("PrivateTmp", "bool", 0.5, "PrivateTmp=yes"), ("PrivateDevices", "bool", 0.5, "PrivateDevices=yes"), ("ProtectKernelTunables", "bool", 0.4, "ProtectKernelTunables=yes"), ("ProtectKernelModules", "bool", 0.4, "ProtectKernelModules=yes"), ("ProtectKernelLogs", "bool", 0.2, "ProtectKernelLogs=yes"), ("ProtectControlGroups", "bool", 0.3, "ProtectControlGroups=yes"), ("ProtectClock", "bool", 0.2, "ProtectClock=yes"), ("ProtectHostname", "bool", 0.1, "ProtectHostname=yes"), ("RestrictSUIDSGID", "bool", 0.3, "RestrictSUIDSGID=yes"), ("RestrictNamespaces", "ns", 0.4, "RestrictNamespaces=yes"), ("RestrictRealtime", "bool", 0.2, "RestrictRealtime=yes"), ("LockPersonality", "bool", 0.1, "LockPersonality=yes"), ("MemoryDenyWriteExecute", "bool", 0.3, "MemoryDenyWriteExecute=yes|not for JIT runtimes (Node.js, Java, .NET, PyPy)"), ("CapabilityBoundingSet", "caps", 0.6, "CapabilityBoundingSet=|empty = no capabilities; or list only what you need, e.g. CAP_NET_BIND_SERVICE"), ("SystemCallFilter", "set", 0.4, "SystemCallFilter=@system-service"), ("SystemCallArchitectures", "native", 0.1, "SystemCallArchitectures=native"), ("RestrictAddressFamilies", "set", 0.4, "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6"), ("UMask", "umask", 0.2, "UMask=0077"), ] class InputError(Exception): pass # ---------------------------------------------------------------- parse def parse(text, fname, unit=None): """Return unit dict: {section: {key: [(value, line, file)]}} plus raw entries list.""" unit = unit if unit is not None else {"sections": {}, "entries": [], "files": []} unit["files"].append(fname) sec = None lines = text.splitlines() i = 0 while i < len(lines): ln, raw = i + 1, lines[i] i += 1 s = raw.strip() if not s or s[0] in "#;": continue while s.endswith("\\") and i < len(lines): nxt = lines[i].strip() i += 1 if nxt.startswith(("#", ";")): continue s = s[:-1].rstrip() + " " + nxt if s.startswith("["): if not s.endswith("]"): raise InputError("%s:%d: broken section header %r" % (fname, ln, s)) sec = s[1:-1].strip() unit["sections"].setdefault(sec, {}) unit["entries"].append(("section", sec, None, ln, fname)) continue if "=" not in s: unit["entries"].append(("noeq", sec, s, ln, fname)) continue if sec is None: unit["entries"].append(("nosec", None, s, ln, fname)) continue k, v = s.split("=", 1) k, v = k.strip(), v.strip() unit["entries"].append(("kv", sec, (k, v), ln, fname)) d = unit["sections"][sec] if v == "" and k in LIST_KEYS: d[k] = [("", ln, fname)] # empty assignment resets the list continue d.setdefault(k, []).append((v, ln, fname)) return unit def get(unit, sec, key): vals = unit["sections"].get(sec, {}).get(key, []) vals = [v for v in vals if v[0] != ""] if key in LIST_KEYS else vals return vals def valid(key, v): vl = v.lower() if key in VALUES and VALUES[key]: return vl in VALUES[key] if key in BOOL_KEYS: return vl in BOOL return True def last(unit, sec, key, default=None): """Effective value: the last assignment systemd accepts (invalid values are ignored).""" for v in reversed(unit["sections"].get(sec, {}).get(key) or []): if v[0] == "" or valid(key, v[0]): return v[0] return default def where(unit, sec, key): v = [x for x in unit["sections"].get(sec, {}).get(key) or [] if x[0] == "" or valid(key, x[0])] return "%s:%d" % (v[-1][2], v[-1][1]) if v else unit["files"][0] def words(unit, sec, key): out = [] for v, _, _ in get(unit, sec, key): out += v.split() return out # ---------------------------------------------------------------- review def review(unit): F = [] add = lambda sev, code, loc, msg, fix: F.append((sev, code, loc, msg, fix)) S = unit["sections"] svc = S.get("Service", {}) f0 = unit["files"][0] if "Service" not in S: raise InputError("%s has no [Service] section - not a service unit" % f0) # SD08 / SD13 / structure for kind, sec, val, ln, fn in unit["entries"]: loc = "%s:%d" % (fn, ln) if kind == "noeq": add("medium", "SD08", loc, "line is not Key=Value and is ignored: %r" % val, "fix the line or comment it out with #") elif kind == "nosec": add("medium", "SD08", loc, "assignment before any [Section] is ignored: %r" % val, "move it under [Unit], [Service] or [Install]") elif kind == "section" and sec not in SECTIONS and not sec.startswith("X-"): add("medium", "SD08", loc, "unknown section [%s] - its settings are ignored" % sec, "use [Unit], [Service] or [Install] (custom sections must start with X-)") elif kind == "kv" and sec in SECTIONS: k, v = val if k.startswith("X-"): continue if k not in SECTIONS[sec]: other = [s for s in SECTIONS if k in SECTIONS[s]] if other: sev = "medium" add(sev, "SD09", loc, "%s= belongs in [%s], not [%s] - systemd ignores it here" % (k, other[0], sec), "move %s=%s to [%s]" % (k, v, other[0])) else: allk = set().union(*SECTIONS.values()) close = difflib.get_close_matches(k, sorted(allk), 1, 0.75) add("high" if sec == "Service" and close and close[0].startswith(("Exec", "User", "Restart")) else "medium", "SD08", loc, "unknown directive %s= (ignored by systemd)%s" % (k, " - did you mean %s=?" % close[0] if close else ""), "rename to %s=" % close[0] if close else "remove it or check `man systemd.directives`") continue vl = v.lower() if k in VALUES and VALUES[k] and v and vl not in VALUES[k]: close = difflib.get_close_matches(vl, sorted(VALUES[k]), 1, 0.6) add("high" if k in ("Type", "Restart") else "medium", "SD08", loc, "invalid value %s=%s - systemd ignores the line and keeps the default%s" % (k, v, " (did you mean %s?)" % close[0] if close else ""), "use one of: %s" % ", ".join(sorted(VALUES[k]))) elif k in BOOL_KEYS and v and vl not in BOOL: add("medium", "SD08", loc, "%s= expects a boolean, got %r (line ignored)" % (k, v), "use yes or no") seen = {} for kind, sec, val, ln, fn in unit["entries"]: if kind == "kv" and val[0] not in LIST_KEYS and sec in SECTIONS: key = (sec, val[0]) if key in seen and seen[key][2] == fn: add("low", "SD13", "%s:%d" % (fn, ln), "%s= set again (first at line %d) - the last one wins: %s" % (val[0], seen[key][1], val[1]), "keep one %s= line" % val[0]) seen[key] = (val[1], ln, fn) typ = (last(unit, "Service", "Type", "simple") or "simple").lower() execs = get(unit, "Service", "ExecStart") # SD02 ExecStart if not execs: add("high", "SD02", f0, "no ExecStart= - the service cannot start", "add ExecStart=/absolute/path/to/binary args") if len(execs) > 1 and typ != "oneshot": add("high", "SD02", where(unit, "Service", "ExecStart"), "%d ExecStart= lines but Type=%s allows only one (only oneshot may have several)" % (len(execs), typ), "keep one ExecStart=, or reset with an empty ExecStart= first in a drop-in") for key in ("ExecStartPre", "ExecStart", "ExecStartPost", "ExecReload", "ExecStop", "ExecStopPost"): for v, ln, fn in get(unit, "Service", key): loc = "%s:%d" % (fn, ln) cmd = v.lstrip("-@:+!") first = cmd.split()[0] if cmd.split() else "" is_shell = re.match(r"^(/usr)?/bin/(ba|da|z)?sh$", first) is not None if first and not first.startswith("/") and not first.startswith("$"): add("low", "SD02", loc, "%s= command %r is not an absolute path (systemd searches only its fixed PATH)" % (key, first), "use the full path, e.g. /usr/bin/%s" % first) if not is_shell and SHELL_RE.search(cmd.split(None, 1)[1] if len(cmd.split(None, 1)) > 1 else ""): add("high", "SD10", loc, "%s= uses shell syntax (pipes, redirects, &&, ;, & or $( )) but systemd does not run a shell - the symbols are passed as plain arguments" % key, "wrap it: %s=/bin/sh -c '...' or better move the logic into a script; log to stdout (journald) instead of >> file" % key) if re.search(r"(^|\s)(nohup|daemon|--daemon(ize)?|-d)(\s|$)", cmd) and typ in ("simple", "exec"): add("medium", "SD10", loc, "%s= looks like it forks into the background (nohup/--daemon) while Type=%s expects the process to stay in the foreground" % (key, typ), "run it in the foreground (drop --daemon / nohup) or use Type=forking with PIDFile=") if v.startswith("+") or v.startswith("!"): add("medium", "SD01", loc, "%s= prefix %s runs this command with full privileges, bypassing User= and the sandbox" % (key, v[0]), "drop the prefix unless this step really needs root") if typ == "forking" and not get(unit, "Service", "PIDFile"): add("low", "SD10", where(unit, "Service", "Type"), "Type=forking without PIDFile= - systemd has to guess the main process", "add PIDFile=/run/<name>/<name>.pid or run in the foreground with Type=exec") # SD01 user user = last(unit, "Service", "User") dyn = (last(unit, "Service", "DynamicUser", "no") or "no").lower() in TRUE root = (not dyn) and (user is None or user in ("root", "0")) if root: add("high" if typ != "oneshot" else "medium", "SD01", where(unit, "Service", "User") if user else f0, "runs as root (%s) - a bug or exploit in the service owns the whole machine" % ("User=%s" % user if user else "no User= or DynamicUser="), "add DynamicUser=yes, or create a system user (useradd --system --no-create-home <name>) and set User=/Group=") caps = words(unit, "Service", "AmbientCapabilities") + words(unit, "Service", "CapabilityBoundingSet") for c in sorted(set(x.lstrip("~") for x in caps)): if c.upper() in DANGER_CAPS and not any(x.startswith("~") for x in caps): add(DANGER_CAPS[c.upper()], "SD07", where(unit, "Service", "AmbientCapabilities" if c in words(unit, "Service", "AmbientCapabilities") else "CapabilityBoundingSet"), "grants %s - close to full root" % c if DANGER_CAPS[c.upper()] == "high" else "grants %s" % c, "remove it; to bind ports below 1024 only CAP_NET_BIND_SERVICE is needed") # SD03 secrets for v, ln, fn in get(unit, "Service", "Environment"): for m in re.finditer(r'"?([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|\S*)', v): name, val = m.group(1), m.group(2).strip('"') if SECRET_RE.search(name) and val and not val.startswith("%") and not val.startswith("$"): add("high", "SD03", "%s:%d" % (fn, ln), "secret %s is written in the unit file - unit files are world-readable and shown by `systemctl show`" % name, "use LoadCredential=%s:/etc/<name>/%s (read from $CREDENTIALS_DIRECTORY) or EnvironmentFile=/etc/<name>/env with mode 0600" % (name.lower(), name.lower())) if re.search(r"://[^/\s:@]+:[^@\s]+@", val): add("high", "SD03", "%s:%d" % (fn, ln), "%s contains a URL with an embedded password" % name, "move the credential out of the unit (LoadCredential= / EnvironmentFile= 0600)") for v, ln, fn in get(unit, "Service", "ExecStart"): if re.search(r"--(password|passwd|token|secret|api-key)[= ]\S+", v, re.I): add("high", "SD03", "%s:%d" % (fn, ln), "a secret is passed on the command line - visible to every user in ps and /proc", "read it from a file or $CREDENTIALS_DIRECTORY instead") # SD04 restart policy restart = (last(unit, "Service", "Restart", "no") or "no").lower() if typ != "oneshot" and restart == "no": add("medium", "SD04", where(unit, "Service", "Restart") if last(unit, "Service", "Restart") else f0, "Restart=no (default) - a crash leaves the service down until someone notices", "add Restart=on-failure and RestartSec=5s") if restart in ("always", "on-failure", "on-abnormal") and not last(unit, "Service", "RestartSec"): add("low", "SD04", where(unit, "Service", "Restart"), "Restart=%s without RestartSec= (default 100ms) - a crash loop hammers the machine and hits the start limit fast" % restart, "add RestartSec=5s") if typ == "oneshot" and restart in ("always", "on-success"): add("high", "SD04", where(unit, "Service", "Restart"), "Type=oneshot does not allow Restart=%s - systemd refuses to load the unit" % restart, "use Restart=on-failure or run it from a .timer") tstop = (last(unit, "Service", "TimeoutStopSec") or last(unit, "Service", "TimeoutSec") or "").lower() if tstop in ("infinity", "0"): add("medium", "SD12", where(unit, "Service", "TimeoutStopSec") if last(unit, "Service", "TimeoutStopSec") else where(unit, "Service", "TimeoutSec"), "stop timeout %s - a hung service blocks shutdown and restarts forever" % tstop, "set TimeoutStopSec=30s (or what a clean shutdown really needs)") km = (last(unit, "Service", "KillMode", "") or "").lower() if km == "none": add("medium", "SD12", where(unit, "Service", "KillMode"), "KillMode=none is deprecated - leftover processes survive stop and restart", "use KillMode=mixed or the default control-group") elif km == "process": add("low", "SD12", where(unit, "Service", "KillMode"), "KillMode=process kills only the main process; children keep running after stop", "use KillMode=mixed unless the children must outlive the service") # SD05 ordering after = words(unit, "Unit", "After") wants = words(unit, "Unit", "Wants") + words(unit, "Unit", "Requires") if "network-online.target" in after and "network-online.target" not in wants: add("medium", "SD05", where(unit, "Unit", "After"), "After=network-online.target without Wants=network-online.target - the ordering does nothing unless something else pulls the target in", "add Wants=network-online.target") if "network-online.target" in wants and "network-online.target" not in after: add("medium", "SD05", where(unit, "Unit", "Wants"), "Wants=network-online.target without After=network-online.target - the service still starts before the network is up", "add After=network-online.target") for v in ("syslog.target", "network.service"): if v in after: add("low", "SD05", where(unit, "Unit", "After"), "After=%s is obsolete" % v, "remove it (journald is always available; use network-online.target)") sl = [k for k in ("StartLimitIntervalSec", "StartLimitBurst") if k in S.get("Unit", {})] for k, ln in (("StartLimitInterval", None),): if k in svc: add("medium", "SD09", where(unit, "Service", k), "StartLimitInterval= is the old name and in [Service] it is ignored", "use StartLimitIntervalSec= in [Unit]") if restart == "always" and not sl and "StartLimitIntervalSec" not in svc: add("info", "SD04", f0, "Restart=always with the default start limit (5 starts in 10 s) - after that the unit stays failed", "if you want endless retries set StartLimitIntervalSec=0 in [Unit] and RestartSec= to a sane delay") # SD11 install wb = words(unit, "Install", "WantedBy") + words(unit, "Install", "RequiredBy") if not wb and not get(unit, "Install", "Alias"): add("medium", "SD11", f0, "no [Install] WantedBy= - `systemctl enable` does nothing, so the service will not start at boot", "add [Install] WantedBy=multi-user.target") elif "default.target" in wb or "graphical.target" in wb: add("low", "SD11", where(unit, "Install", "WantedBy"), "WantedBy=%s for a system service" % [w for w in wb if w in ("default.target", "graphical.target")][0], "use WantedBy=multi-user.target (default.target is for user services)") # SD14 conflicts that break start ph = (last(unit, "Service", "ProtectHome", "no") or "no").lower() wd = last(unit, "Service", "WorkingDirectory", "") or "" paths = [wd] + [(e[0].lstrip("-@:+!").split() or [""])[0] for e in execs] + [x.lstrip("-") for x in words(unit, "Service", "EnvironmentFile")] if ph in TRUE or ph in ("tmpfs", "read-only"): for p in paths: if p.startswith("/home/") or p.startswith("/root/"): add("high" if ph != "read-only" else "medium", "SD14", where(unit, "Service", "ProtectHome"), "ProtectHome=%s but the service uses %s - it %s" % (ph, p, "cannot see it and will fail to start" if ph != "read-only" else "cannot write there"), "move the app out of /home (e.g. /opt/<name>, /srv/<name>) or use ProtectHome=read-only with ReadWritePaths= for the exact directory") break ps_ = (last(unit, "Service", "ProtectSystem", "no") or "no").lower() rw = words(unit, "Service", "ReadWritePaths") + ["/var/lib/" + x for x in words(unit, "Service", "StateDirectory")] + \ ["/var/log/" + x for x in words(unit, "Service", "LogsDirectory")] + ["/run/" + x for x in words(unit, "Service", "RuntimeDirectory")] if ps_ == "strict": for v, ln, fn in execs + get(unit, "Service", "ExecStartPre"): for m in re.finditer(r">>?\s*(/\S+)|--(?:log|pid|data|out)[-a-z]*[= ](/\S+)", v): p = m.group(1) or m.group(2) if not any(p.startswith(x.lstrip("-")) for x in rw) and not p.startswith(("/tmp", "/dev/")): add("medium", "SD14", "%s:%d" % (fn, ln), "ProtectSystem=strict makes %s read-only - writes will fail" % p, "use StateDirectory=/LogsDirectory=/RuntimeDirectory= or ReadWritePaths=%s" % p.rsplit("/", 1)[0]) if (last(unit, "Service", "MemoryDenyWriteExecute", "no") or "").lower() in TRUE and paths and re.search(r"(node|java|dotnet|pypy|bun|deno)", " ".join(paths)): add("high", "SD14", where(unit, "Service", "MemoryDenyWriteExecute"), "MemoryDenyWriteExecute=yes with a JIT runtime (%s) - it will crash on start" % [p for p in paths if re.search(r"(node|java|dotnet|pypy|bun|deno)", p)][0], "remove MemoryDenyWriteExecute= for this service") if dyn and user: add("info", "SD01", where(unit, "Service", "DynamicUser"), "DynamicUser=yes with User=%s - a transient user with that name is allocated" % user, "fine; do not rely on files owned by a static %s user" % user) # SD15 resources if not any(k in svc for k in ("MemoryMax", "MemoryHigh", "TasksMax", "CPUQuota")): add("info", "SD15", f0, "no resource limits (MemoryMax=, TasksMax=, CPUQuota=) - a leak can starve the host", "add MemoryMax= and TasksMax= sized from normal usage") # SD06 exposure exposure, missing = 0.0, [] for key, test, w, rec in HARDEN: v = (last(unit, "Service", key) or "") vl = v.lower() if key == "User": ok = not root elif test == "bool": ok = vl in TRUE elif test == "strict": ok = vl == "strict" if vl in ("full", "yes", "true"): exposure += w * 0.5 missing.append((key, "ProtectSystem=strict|currently %s; add ReadWritePaths=/StateDirectory= for paths it writes" % v)) continue elif test == "home": ok = vl in TRUE or vl in ("read-only", "tmpfs") elif test == "ns": ok = vl in TRUE or (v != "" and vl not in ("no", "false", "0", "off")) elif test == "caps": ok = key in svc and all(c.upper() not in DANGER_CAPS or c.startswith("~") for c in words(unit, "Service", key)) elif test == "set": ok = bool(words(unit, "Service", key)) elif test == "native": ok = vl == "native" elif test == "umask": ok = v in ("0077", "077", "0027", "027") else: ok = bool(v) if not ok: exposure += w missing.append((key, rec)) exposure = round(min(exposure, 10.0), 1) if missing: add("medium" if exposure >= 5 else "low", "SD06", f0, "%d sandboxing option(s) missing: %s" % (len(missing), ", ".join(k for k, _ in missing)), "add the suggested drop-in (systemctl edit <name>), restart, and test the service") F.sort(key=lambda x: (SEV[x[0]], x[1], x[2])) rating = "OK" if exposure < 2 else "MEDIUM" if exposure < 5 else "EXPOSED" if exposure < 8 else "UNSAFE" return {"files": unit["files"], "name": last(unit, "Unit", "Description", "") or unit["files"][0], "type": typ, "user": "DynamicUser" if dyn else (user or "root"), "restart": restart, "exposure": exposure, "rating": rating, "missing": missing, "findings": F} def dropin(r): lines = ["# /etc/systemd/system/<name>.service.d/hardening.conf (systemctl edit <name>)", "[Service]"] for k, rec in r["missing"]: line, _, note = rec.partition("|") if note: lines.append("# " + note) lines.append(line) if any(f[1] == "SD04" and "Restart=no" in f[3] for f in r["findings"]): lines += ["Restart=on-failure", "RestartSec=5s"] lines += ["# then: systemctl daemon-reload && systemctl restart <name> && systemd-analyze security <name>"] return "\n".join(lines) def counts(F): c = {s: 0 for s in SEV} for f in F: c[f[0]] += 1 return c def report(results): out = ["# systemd unit review", ""] out.append("| Unit | Description | Type | Runs as | Restart | Exposure (0-10) | High | Medium | Low | Info |") out.append("|---|---|---|---|---|---|---|---|---|---|") for r in results: c = counts(r["findings"]) out.append("| `%s` | %s | %s | %s | %s | %.1f %s | %d | %d | %d | %d |" % (" + ".join(r["files"]), r["name"], r["type"], r["user"], r["restart"], r["exposure"], r["rating"], c["high"], c["medium"], c["low"], c["info"])) for r in results: c = counts(r["findings"]) out += ["", "## %s" % " + ".join(r["files"]), ""] if c["high"]: v = "%d high finding(s) - fix before deploying" % c["high"] elif r["exposure"] >= 5: v = "works, but exposure %.1f - add the hardening drop-in" % r["exposure"] else: v = "looks good (exposure %.1f)" % r["exposure"] out.append("**Verdict: %s**" % v) out += ["", "| Sev | Code | Where | Finding | Fix |", "|---|---|---|---|---|"] for s, code, loc, msg, fix in r["findings"]: out.append("| %s | %s | %s | %s | %s |" % (s, code, loc, msg.replace("|", "\\|"), fix.replace("|", "\\|"))) if r["missing"]: out += ["", "Suggested drop-in (test after applying; relax an option if the service needs it):", "", "```ini", dropin(r), "```"] out += ["", "Exposure is this script's weighted estimate, not the systemd-analyze number; run `systemd-analyze security <unit>` and `systemd-analyze verify <file>` on the target host to confirm."] return "\n".join(out) + "\n" def run_files(paths): unit = None for p in paths: try: with open(p, encoding="utf-8") as fh: txt = fh.read() except OSError as e: raise InputError("cannot read %s: %s" % (p, e)) unit = parse(txt, p, unit) return review(unit) # ---------------------------------------------------------------- self-test def self_test(): tests = [] def t(name, cond): tests.append((name, bool(cond))) def R(txt, *drop): u = parse(txt, "a.service") for i, d in enumerate(drop): u = parse(d, "d%d.conf" % i, u) return review(u) def codes(txt, *drop): return [(f[0], f[1]) for f in R(txt, *drop)["findings"]] base = "[Unit]\nDescription=x\n[Service]\nExecStart=/usr/bin/app\n[Install]\nWantedBy=multi-user.target\n" good = ("[Unit]\nDescription=good\nWants=network-online.target\nAfter=network-online.target\n[Service]\nType=exec\nExecStart=/usr/bin/app\n" "DynamicUser=yes\nRestart=on-failure\nRestartSec=5s\nNoNewPrivileges=yes\nProtectSystem=strict\nProtectHome=yes\nPrivateTmp=yes\n" "PrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectKernelLogs=yes\nProtectControlGroups=yes\n" "ProtectClock=yes\nProtectHostname=yes\nRestrictSUIDSGID=yes\nRestrictNamespaces=yes\nRestrictRealtime=yes\nLockPersonality=yes\n" "MemoryDenyWriteExecute=yes\nCapabilityBoundingSet=\nSystemCallFilter=@system-service\nSystemCallArchitectures=native\n" "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nUMask=0077\nMemoryMax=512M\nTasksMax=64\n[Install]\nWantedBy=multi-user.target\n") g = R(good) t("fully hardened unit: exposure 0, no high/medium", g["exposure"] == 0 and not [f for f in g["findings"] if f[0] in ("high", "medium")]) t("root by default -> SD01 high", ("high", "SD01") in codes(base)) t("root oneshot -> SD01 medium", ("medium", "SD01") in codes(base.replace("[Service]\n", "[Service]\nType=oneshot\n"))) t("User=svc clears SD01", "SD01" not in [c for _, c in codes(base.replace("[Service]\n", "[Service]\nUser=svc\n"))]) t("missing ExecStart -> SD02 high", ("high", "SD02") in codes("[Service]\nUser=a\n[Install]\nWantedBy=multi-user.target\n")) t("relative command -> SD02 low", ("low", "SD02") in codes(base.replace("/usr/bin/app", "app"))) t("two ExecStart with simple -> SD02 high", ("high", "SD02") in codes(base.replace("ExecStart=/usr/bin/app", "ExecStart=/a\nExecStart=/b"))) t("empty ExecStart= in drop-in resets", ("high", "SD02") not in codes(base, "[Service]\nExecStart=\nExecStart=/usr/bin/other\n")) t("pipe in ExecStart -> SD10 high", ("high", "SD10") in codes(base.replace("/usr/bin/app", "/usr/bin/app | logger"))) t("redirect >> -> SD10 high", ("high", "SD10") in codes(base.replace("/usr/bin/app", "/usr/bin/app >> /var/log/app.log"))) t("sh -c is allowed", ("high", "SD10") not in codes(base.replace("/usr/bin/app", "/bin/sh -c '/usr/bin/app | logger'"))) t("--daemon with simple -> SD10 medium", ("medium", "SD10") in codes(base.replace("/usr/bin/app", "/usr/bin/app --daemon"))) t("secret in Environment -> SD03 high", ("high", "SD03") in codes(base.replace("[Service]\n", "[Service]\nEnvironment=DB_PASSWORD=hunter2\n"))) t("quoted env with URL password -> SD03", ("high", "SD03") in codes(base.replace("[Service]\n", '[Service]\nEnvironment="DATABASE_URL=postgres://u:pw@db/x" "PORT=80"\n'))) t("non-secret env is fine", "SD03" not in [c for _, c in codes(base.replace("[Service]\n", "[Service]\nEnvironment=PORT=8080 LOG_LEVEL=info\n"))]) t("--password on cmdline -> SD03", ("high", "SD03") in codes(base.replace("/usr/bin/app", "/usr/bin/app --password=s3cret"))) t("Restart missing -> SD04 medium", ("medium", "SD04") in codes(base)) t("Restart=always no RestartSec -> SD04 low", ("low", "SD04") in codes(base.replace("[Service]\n", "[Service]\nRestart=always\n"))) t("oneshot + Restart=always -> SD04 high", ("high", "SD04") in codes(base.replace("[Service]\n", "[Service]\nType=oneshot\nRestart=always\n"))) t("After online without Wants -> SD05", ("medium", "SD05") in codes(base.replace("[Unit]\n", "[Unit]\nAfter=network-online.target\n"))) t("Wants online without After -> SD05", ("medium", "SD05") in codes(base.replace("[Unit]\n", "[Unit]\nWants=network-online.target\n"))) t("syslog.target obsolete -> SD05 low", ("low", "SD05") in codes(base.replace("[Unit]\n", "[Unit]\nAfter=syslog.target\n"))) t("typo directive -> SD08 with suggestion", any("did you mean RestartSec" in f[3] for f in R(base.replace("[Service]\n", "[Service]\nRestartSecs=5\n"))["findings"])) t("invalid Restart value -> SD08 high", ("high", "SD08") in codes(base.replace("[Service]\n", "[Service]\nRestart=on-faliure\n"))) t("invalid value ignored, earlier valid one stays effective", R(base.replace("[Service]\n", "[Service]\nRestart=always\n"), "[Service]\nRestart=on-faliure\n")["restart"] == "always") t("drop-in lines are valid key=value", all("=" in l or l.startswith(("#", "[")) for l in dropin(R(base)).splitlines())) t("bad boolean -> SD08 medium", ("medium", "SD08") in codes(base.replace("[Service]\n", "[Service]\nPrivateTmp=maybe\n"))) t("StartLimitBurst in [Service] -> SD09", ("medium", "SD09") in codes(base.replace("[Service]\n", "[Service]\nStartLimitBurst=3\n"))) t("WantedBy in [Service] -> SD09", ("medium", "SD09") in codes(base.replace("[Service]\n", "[Service]\nWantedBy=multi-user.target\n"))) t("no [Install] -> SD11 medium", ("medium", "SD11") in codes("[Service]\nExecStart=/usr/bin/a\n")) t("WantedBy=default.target -> SD11 low", ("low", "SD11") in codes(base.replace("multi-user.target", "default.target"))) t("duplicate scalar -> SD13", ("low", "SD13") in codes(base.replace("[Service]\n", "[Service]\nUser=a\nUser=b\n"))) t("drop-in override is not a duplicate", ("low", "SD13") not in codes(base.replace("[Service]\n", "[Service]\nUser=a\n"), "[Service]\nUser=b\n")) t("drop-in value wins", R(base.replace("[Service]\n", "[Service]\nUser=a\n"), "[Service]\nUser=b\n")["user"] == "b") t("ProtectHome with /home app -> SD14 high", ("high", "SD14") in codes(base.replace("/usr/bin/app", "/home/deploy/app/run").replace("[Service]\n", "[Service]\nProtectHome=yes\n"))) t("MDWE with node -> SD14 high", ("high", "SD14") in codes(base.replace("/usr/bin/app", "/usr/bin/node server.js").replace("[Service]\n", "[Service]\nMemoryDenyWriteExecute=yes\n"))) t("ProtectSystem=strict write path -> SD14", ("medium", "SD14") in codes(base.replace("/usr/bin/app", "/usr/bin/app --log-file=/var/log/app/app.log").replace("[Service]\n", "[Service]\nProtectSystem=strict\n"))) t("LogsDirectory clears strict write", ("medium", "SD14") not in codes(base.replace("/usr/bin/app", "/usr/bin/app --log-file=/var/log/app/app.log").replace("[Service]\n", "[Service]\nProtectSystem=strict\nLogsDirectory=app\n"))) t("CAP_SYS_ADMIN -> SD07 high", ("high", "SD07") in codes(base.replace("[Service]\n", "[Service]\nAmbientCapabilities=CAP_SYS_ADMIN\n"))) t("+ prefix -> SD01 medium", ("medium", "SD01") in codes(base.replace("[Service]\n", "[Service]\nUser=a\nExecStartPre=+/usr/bin/setup\n"))) t("TimeoutStopSec=infinity -> SD12", ("medium", "SD12") in codes(base.replace("[Service]\n", "[Service]\nTimeoutStopSec=infinity\n"))) t("continuation lines joined", R("[Service]\nExecStart=/usr/bin/app \\\n --port 80\nUser=a\n[Install]\nWantedBy=multi-user.target\n")["findings"] is not None and parse("[Service]\nExecStart=/usr/bin/app \\\n --port 80\n", "x")["sections"]["Service"]["ExecStart"][0][0] == "/usr/bin/app --port 80") t("bare exposure of minimal unit is 10", R(base)["exposure"] == 10.0) t("ProtectSystem=full counts half", abs(R(base.replace("[Service]\n", "[Service]\nProtectSystem=full\n"))["exposure"] - 9.5) < 0.01) try: R("[Unit]\nDescription=x\n") t("no [Service] rejected", False) except InputError: t("no [Service] rejected", True) t("report has verdict and table", "**Verdict:" in report([R(base)]) and "| Sev | Code |" in report([R(base)])) for n, ok in tests: print("%s %s" % ("PASS" if ok else "FAIL", n)) p = sum(ok for _, ok in tests) print("%d/%d passed" % (p, len(tests))) return 0 if p == len(tests) else 1 def main(argv=None): ap = argparse.ArgumentParser(description="Review systemd .service units for reliability and hardening.") ap.add_argument("units", nargs="*", help="UNIT.service, optionally followed by drop-in .conf files; use ',' between separate units") ap.add_argument("--json", action="store_true") ap.add_argument("--dropin", action="store_true", help="print only the suggested hardening drop-in(s)") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.units: ap.error("give at least one .service file") groups, cur = [], [] for u in a.units: if u == ",": groups.append(cur); cur = [] elif u.endswith(".service") and cur: groups.append(cur); cur = [u] else: cur.append(u) groups.append(cur) try: res = [run_files(g) for g in groups if g] except InputError as e: print("error: %s" % e, file=sys.stderr) return 2 if a.json: print(json.dumps([{**r, "findings": [dict(zip(("severity", "code", "where", "finding", "fix"), f)) for f in r["findings"]]} for r in res], indent=2)) elif a.dropin: print("\n\n".join(dropin(r) for r in res)) else: sys.stdout.write(report(res)) return 1 if any(f[0] == "high" for r in res for f in r["findings"]) else 0 if __name__ == "__main__": sys.exit(main())

Event Seating Chart Planner

--- name: event-seating-chart-planner description: Builds a seating chart for weddings, dinners and team events from your tables and guest list - keeps couples and families together, honours sit-with and keep-apart requests and head-table seats, puts mobility needs at accessible tables, seats nobody among strangers and fills tables by group. Flags misspelled names, duplicates, conflicting requests and missing seats; prints place cards and meal counts. Includes an offline stdlib Python planner. --- # Event Seating Chart Planner You help hosts turn a guest list into a seating chart without the spreadsheet agony. Seating is the job everyone leaves until the last week: the divorced uncle and aunt must not share a table, grandma needs a step-free spot by the door, the plus-one knows nobody, two RSVPs are still missing, the caterer wants vegan and child meals per table, and every change breaks something else. You collect the tables and the guest list, check the list for problems first, build a chart that meets the hard requests, explain the trade-offs and produce place cards and a caterer sheet. You work only from the information the host gives you. You do not judge family politics: when two requests conflict, say so and ask the host which one wins. Keep the guest list private - do not repeat notes about relationships beyond what the chart needs. ## Files in this skill - `scripts/seating_plan.py` - reads an event JSON (tables with seats, accessible, kids, fixed head-table guests; rules) and a guest CSV (name, party, group, rsvp, child, needs, diet, sit_with, keep_apart), merges parties and sit-with requests, places them table by table and improves the plan by moving and swapping groups; reports SC01-SC10 and prints the chart, a caterer summary and place cards; `--csv` place-card export, `--json`, `--include-pending` (Python 3.8+ standard library only) - `references/seating-rules-and-etiquette.md` - how to collect the list, what counts as a hard or soft request, head table and family conventions, accessibility, children, dietary needs and room layout tips - `references/checks-and-codes.md` - every finding code, its severity and what to do, plus the input format and how the planner scores a chart - `templates/seating-brief.md` - the summary to send the host (and the venue / caterer) - `examples/event.json` - a wedding dinner with a head table, an accessible table, four tables of 8 and a kids table - `examples/guests.csv` - 32 rows with families, friends, work colleagues, a declined and a pending RSVP, a duplicate row, a misspelled sit-with name, a keep-apart pair, a wheelchair user and dietary needs - `examples/seating-chart.md` - the real planner output on the example ## Workflow ### 1. Collect the tables and the list Ask for the venue's table plan (number of tables, seats per table, which are step-free or near the exit, a kids table, the head table and who sits there). Ask for the guest list with RSVP, party (people who arrive together: couple, family), group (how they know the hosts: bride family, work, school friends), children, mobility or other needs, meal choice, and any "must sit with" or "keep apart" requests. Put them in `examples/event.json` and `examples/guests.csv` form. ### 2. Run the planner ``` python3 scripts/seating_plan.py examples/event.json examples/guests.csv python3 scripts/seating_plan.py event.json guests.csv --include-pending python3 scripts/seating_plan.py event.json guests.csv --csv > place-cards.csv python3 scripts/seating_plan.py event.json guests.csv --json python3 scripts/seating_plan.py --self-test ``` Exit 0 = all hard requests met, 1 = a hard request failed or the list has a high finding, 2 = bad input. Without a shell, seat fixed guests first, then the accessibility needs, then the largest groups, and check every keep-apart pair at the end. ### 3. Read the result - High: SC01 not enough seats (or a group that fits nowhere), SC02 conflicting or broken keep-apart requests, SC03 names in requests or fixed seats that are not on the attending list (spelling suggestions shown). - Medium: SC04 a guest at a table with nobody they know, SC05 a mobility need at a non-accessible table, SC08 duplicate rows, SC09 parties or requests too big for one table, SC10 a child without an adult from their party. - Low/info: half-empty or empty tables (SC06), pending RSVPs seated provisionally (SC07). ### 4. Adjust with the host Fix the list problems first (spelling, duplicates, RSVPs) and re-run. Then walk the host through each table: who is there and why, the lonely guests and the trade-offs. Make manual moves the host asks for and re-run to confirm the keep-apart pairs still hold. Fill `templates/seating-brief.md`. ### 5. Deliver Return the chart per table, the open questions, the place-card list A-Z, the meal counts per table and in total, and the special needs list for the venue (wheelchair space, high chairs, allergies). ## Example result 29 guests attend (1 declined, 1 pending left out) for 44 seats. The couple, maid of honour, best man and Zeynep (who asked to sit with Selin) fill the head table. Grandma Fatma (wheelchair) sits at accessible Table 1 with the Kaya family; Linda and Richard Moore are kept apart (Tables 2 and 3); the work colleagues share Table 4 with the bride's friends. Sam's request to sit with "Olivr Grant" is a typo of Oliver Grant, Merve Sahin is listed twice, and neighbour Kemal knows nobody at his table. The kids table is empty because children stay with their parents. ## Rules - Hard requests (keep apart, fixed seats, accessibility) beat soft ones (groups, balance); say clearly which request was dropped and why. - Never split a couple or a parent and a young child unless the host asks. - Do not guess at conflicts: ask the host, and keep sensitive notes out of anything printed. - Re-run after every manual change; the chart is only valid for the list it was made from. - Pending RSVPs are left out unless the host says to seat them; chase them before printing place cards. FILE:references/seating-rules-and-etiquette.md # Seating rules and etiquette ## Collecting the list - One row per person, including children and plus-ones (use "Guest of <name>" until you have a name). - Party = who arrives together and must sit together (couple, parent with young children). Group = how they know the hosts; it decides who shares a table. - Ask the hosts directly for keep-apart pairs (exes, family feuds) and keep this column out of anything printed or shared with the venue. - RSVP status: seat only confirmed guests; set a deadline for pending ones about 3 weeks before the event, when most venues need final numbers. ## Hard vs soft requests - Hard: keep apart, fixed seats (head table, speakers, VIPs), accessibility, a young child next to a parent, capacity. - Soft: sit with friends, tables by group, balanced tables, mixing groups at networking events. When a soft request breaks a hard one, the hard one wins; tell the host. ## Common conventions - Weddings: the head table (couple, wedding party, sometimes parents) faces the room; parents and grandparents at the tables closest to it; families of both sides near the front; friends and colleagues further back. Sweetheart table = couple only. - Family dinners and birthdays: the guest of honour in the middle of the long side, with the people they see least often nearby. - Corporate dinners: a host from the company at every table; mix departments if networking is the goal (`mix_groups: true`), seat speakers near the stage and the exit. - Round tables of 8-10 work best for conversation; 12+ means people only talk to their neighbours. - Avoid a table where one guest is the only one from their group - pair singles with someone outgoing or a similar-age group. ## Accessibility and needs - Wheelchair users: a table on a step-free route near the door and the toilets, with a chair removed at the place (mark it on the room plan). - Hearing impairment: away from speakers and the band, facing the room. - Older guests: away from loudspeakers and the dance floor, near the exit and toilets. - High chairs and booster seats: tell the venue per table. - Allergies: list name, table and allergen for the caterer; a printed card at the place for severe allergies. ## Children - Toddlers stay with their parents. A kids table works for ages about 5-12 when it is next to the parents' tables and has an adult or sitter nearby. - Count child meals separately (and high chairs) in the caterer summary. ## Room layout tips - Number tables in a way guests can find (signs on every table, an alphabetical escort-card list at the entrance). - Keep the path from the door to the accessible table clear. - Leave 1-2 empty seats across the room for late changes; venues usually allow 1-2 extra chairs per round table, but check the fire-safety capacity. ## Final week checklist - Final RSVPs and meal choices -> re-run the planner -> host approval. - Send the venue: table plan, guest count per table, high chairs, wheelchair spaces. - Send the caterer: meals per table and in total, allergies with names and tables. - Print place cards and the escort-card list from `--csv`. FILE:references/checks-and-codes.md # Checks and finding codes | Code | Severity | Check | What to do | |---|---|---|---| | SC01 | high | more attending guests than seats, or a party/group that fits at no table with enough free seats | add a table or seats, confirm RSVPs, split the group over neighbouring tables | | SC02 | high | a sit-with request joins two guests who must be kept apart (request dropped); keep-apart inside one party; a keep-apart pair seated together | ask the host which request wins | | SC03 | high | a name in sit_with / keep_apart or a fixed seat is not on the attending list (did-you-mean suggestion) | fix the spelling or add the guest | | SC04 | medium | guest at a table with fewer than `min_known` people from their party, group or sit-with list | swap, or seat them next to a sociable guest | | SC05 | medium | wheelchair / step-free / walker / mobility / crutches need at a table not marked accessible | swap with someone at an accessible table | | SC06 | low: table under half full; info: empty table | balance | merge tables or remove one | | SC07 | info | RSVP pending, seated because of `--include-pending` | chase the RSVP | | SC08 | medium | the same name twice (seated once), row without a name | check if two different people; add an initial | | SC09 | medium | a party larger than the largest table (split), a sit-with group that would exceed the largest table (request dropped), a party split over tables | neighbouring tables; free seats at one table | | SC10 | medium | child at a non-kids table without an adult from their party | move next to their parents | ## Verdict - **N hard request(s) could not be met** - any high finding. - **all hard requests met, N soft issue(s)** - medium findings only. - **all requests met**. ## How the planner works 1. Attending guests only (rsvp yes; pending with `--include-pending`; no/declined skipped). 2. Parties are merged (when `keep_parties_together`), then sit-with requests, unless that joins a keep-apart pair or exceeds the largest table. 3. Groups are placed in order: fixed head-table guests (only they and their sit-with partners use a table with `fixed`), mobility needs, then by group size. 4. Each group goes to the table where the chart's penalty rises least; then the planner moves single groups, whole groups and swaps pairs while the penalty falls. 5. Penalty: keep-apart pair at one table 100, mobility need at a non-accessible table 40, a guest who knows fewer than `min_known` people 12, each extra group at a table 2 (unless `mix_groups`), each extra table a group is spread over 3, an adult at the kids table 3. The plan is deterministic: the same input gives the same chart. ## Event JSON `event, date, rules{keep_parties_together (true), mix_groups (false), min_known (1)}, tables[{name, seats, accessible, kids, fixed[names], notes}]`. ## Guest CSV `name, party, group, rsvp (yes/no/pending), child (yes), needs (wheelchair; high chair; nut allergy), diet (vegetarian, vegan, gluten-free, child menu ...), sit_with (names separated by ;), keep_apart (names separated by ;)`. Only `name` is required; party defaults to the name, group to "-", rsvp to yes. FILE:templates/seating-brief.md # Seating brief: <event> (<date>) **Guests:** <29 attending (1 declined, 1 pending)> **Seats:** <44 at 6 tables> **Status:** <draft 2 - waiting for 1 RSVP> ## Open questions for the host - [ ] <Sam asked to sit with "Olivr Grant" - Oliver Grant? (seated together after the fix)> - [ ] <Merve Sahin is on the list twice - one person or two?> - [ ] <Kemal knows nobody at Table 3 - who should he sit next to?> - [ ] <Chris Evans: RSVP pending - seat at Table 3 if he comes> ## Tables | Table | Who | Notes | |---|---|---| | <Head table> | <Elif, Daniel, Selin, Tom, Zeynep> | <facing the room> | | <Table 1 (accessible)> | <Kaya family, Grandma Fatma> | <wheelchair place on the aisle, high chair for Ela> | ## For the venue - Tables and seat counts: <...> - Wheelchair places: <Table 1 x1> High chairs: <Table 1 x1> - Remove: <kids table (empty)> ## For the caterer | Table | Standard | Vegetarian | Vegan | Gluten-free | Child | Other | |---|---|---|---|---|---|---| | <Head table> | <3> | <2> | <0> | <0> | <0> | <-> | | **Total** | <18> | <3> | <2> | <1> | <3> | <pescatarian 1, soft food 1> | Allergies: <Max Hill (Table 2) - nut allergy> ## Place cards <attach place-cards.csv from `seating_plan.py --csv`> FILE:examples/event.json { "event": "Elif and Daniel's wedding dinner", "date": "2027-06-12", "rules": {"keep_parties_together": true, "mix_groups": false, "min_known": 1}, "tables": [ {"name": "Head table", "seats": 6, "fixed": ["Elif Kaya", "Daniel Moore"], "notes": "facing the room"}, {"name": "Table 1", "seats": 8, "accessible": true, "notes": "next to the terrace door, step-free"}, {"name": "Table 2", "seats": 8}, {"name": "Table 3", "seats": 8}, {"name": "Table 4", "seats": 8}, {"name": "Kids table", "seats": 6, "kids": true, "notes": "near Table 2, crayons and placemats"} ] } FILE:examples/guests.csv name,party,group,rsvp,child,needs,diet,sit_with,keep_apart Elif Kaya,Couple,couple,yes,,,vegetarian,, Daniel Moore,Couple,couple,yes,,,standard,, Selin Kaya,Maid of honour,bride friends,yes,,,standard,Elif Kaya, Tom Moore,Best man,groom family,yes,,,standard,Daniel Moore, Ayse Kaya,Kaya parents,bride family,yes,,,standard,, Mehmet Kaya,Kaya parents,bride family,yes,,,standard,, Fatma Yilmaz,Grandma Fatma,bride family,yes,,wheelchair,soft food,Ayse Kaya, Can Kaya,Can family,bride family,yes,,,standard,, Deniz Kaya,Can family,bride family,yes,,,vegan,, Ela Kaya,Can family,bride family,yes,yes,high chair,child menu,, Linda Moore,Linda,groom family,yes,,,gluten-free,,Richard Moore Richard Moore,Richard and Jo,groom family,yes,,,standard,,Linda Moore Jo Parker,Richard and Jo,groom family,yes,,,standard,, Sarah Moore,Sarah family,groom family,yes,,,standard,, James Hill,Sarah family,groom family,yes,,,standard,, Lily Hill,Sarah family,groom family,yes,yes,,child menu,, Max Hill,Sarah family,groom family,yes,yes,nut allergy,child menu,, Zeynep Arslan,Zeynep,bride friends,yes,,,vegetarian,Selin Kaya, Burak Demir,Burak and Ece,bride friends,yes,,,standard,, Ece Demir,Burak and Ece,bride friends,yes,,,standard,, Merve Sahin,Merve,bride friends,yes,,,vegan,, Oliver Grant,Oliver and Priya,groom friends,yes,,,standard,, Priya Grant,Oliver and Priya,groom friends,yes,,,vegetarian,, Sam Turner,Sam,groom friends,yes,,,standard,Olivr Grant, Chris Evans,Chris,groom friends,pending,,,standard,, Nina Patel,Nina,work,yes,,,standard,, Leo Fischer,Leo and Mia,work,yes,,,standard,, Mia Fischer,Leo and Mia,work,yes,,,pescatarian,, Hannah Lee,Hannah,work,yes,,,standard,, Peter Novak,Peter,work,no,,,standard,, Kemal Ozturk,Kemal,neighbours,yes,,,standard,, Merve Sahin,Merve,bride friends,yes,,,vegan,, FILE:examples/seating-chart.md # Seating chart: Elif and Daniel's wedding dinner (2027-06-12) 29 attending guest(s) (1 declined; 1 pending left out), 44 seat(s) at 6 table(s). Source: examples/guests.csv. **Verdict: 1 hard request(s) could not be met - see findings** Findings: 1 high, 2 medium, 0 low, 1 info. ## Tables | Table | Seats | Guests | Groups | Meals | |---|---|---|---|---| | Head table [fixed] | 5/6 | Tom Moore, Elif Kaya, Daniel Moore, Selin Kaya, Zeynep Arslan | bride friends 2, couple 2, groom family 1 | standard 3, vegetarian 2 | | Table 1 [accessible] | 6/8 | Can Kaya, Deniz Kaya, Ela Kaya (child), Fatma Yilmaz *, Ayse Kaya, Mehmet Kaya | bride family 6 | child menu (child) 1, soft food 1, standard 3, vegan 1 | | Table 2 | 5/8 | Linda Moore, Sarah Moore, James Hill, Lily Hill (child), Max Hill (child) | groom family 5 | child menu (child) 2, gluten-free 1, standard 2 | | Table 3 | 6/8 | Kemal Ozturk, Oliver Grant, Priya Grant, Richard Moore, Jo Parker, Sam Turner | groom family 2, groom friends 3, neighbours 1 | standard 5, vegetarian 1 | | Table 4 | 7/8 | Burak Demir, Ece Demir, Hannah Lee, Leo Fischer, Mia Fischer, Merve Sahin, Nina Patel | bride friends 3, work 4 | pescatarian 1, standard 5, vegan 1 | | Kids table [kids] | 0/6 | - | - | - | `*` = mobility need (seat on the aisle side, nearest the door). ## Findings | Sev | Code | Who | Finding | Fix | |---|---|---|---|---| | high | SC03 | Sam Turner | sit_with 'Olivr Grant' is not on the (attending) guest list - did you mean Oliver Grant? | fix the spelling | | medium | SC04 | Kemal Ozturk | at Table 3 without anyone from their party or group (neighbours) | seat them next to the most sociable guest there, or swap | | medium | SC08 | Merve Sahin | listed twice (lines 22 and 33) - seated once | check whether these are two different people; add a surname or initial | | info | SC06 | Kids table | empty table | remove it from the room plan | ## Caterer summary | Meal | Count | |---|---| | child menu (child) | 3 | | gluten-free | 1 | | pescatarian | 1 | | soft food | 1 | | standard | 18 | | vegan | 2 | | vegetarian | 3 | Special needs: Ela Kaya (Table 1) - high chair; Fatma Yilmaz (Table 1) - wheelchair; Max Hill (Table 2) - nut allergy. ## Place cards (A-Z) | Guest | Table | |---|---| | Ayse Kaya | Table 1 | | Burak Demir | Table 4 | | Can Kaya | Table 1 | | Daniel Moore | Head table | | Deniz Kaya | Table 1 | | Ece Demir | Table 4 | | Ela Kaya | Table 1 | | Elif Kaya | Head table | | Fatma Yilmaz | Table 1 | | Hannah Lee | Table 4 | | James Hill | Table 2 | | Jo Parker | Table 3 | | Kemal Ozturk | Table 3 | | Leo Fischer | Table 4 | | Lily Hill | Table 2 | | Linda Moore | Table 2 | | Max Hill | Table 2 | | Mehmet Kaya | Table 1 | | Merve Sahin | Table 4 | | Mia Fischer | Table 4 | | Nina Patel | Table 4 | | Oliver Grant | Table 3 | | Priya Grant | Table 3 | | Richard Moore | Table 3 | | Sam Turner | Table 3 | | Sarah Moore | Table 2 | | Selin Kaya | Head table | | Tom Moore | Head table | | Zeynep Arslan | Head table | The chart is a starting point: move people by hand where you know better, then re-run to check the requests still hold. FILE:scripts/seating_plan.py #!/usr/bin/env python3 """Event seating chart planner (stdlib only, Python 3.8+). Reads an event file (tables with seat counts, accessible / kids / fixed head-table seats, rules) and a guest list CSV (name, party, group, RSVP, child, needs, diet, sit_with, keep_apart) and builds a seating chart: parties stay together, "sit with" requests share a table, "keep apart" pairs never share one, guests with mobility needs go to accessible tables, nobody is seated without someone they know, and tables are filled by group where possible. Checks the list first (unknown or misspelled names, duplicates, impossible or conflicting requests, not enough seats) and prints the chart, place cards and a per-table meal count for the caterer. Usage: seating_plan.py EVENT.json GUESTS.csv [--include-pending] [--csv] [--json] seating_plan.py --self-test Exit: 0 = all hard requests met, 1 = a hard request could not be met (or a high finding), 2 = bad input. """ import argparse, csv, difflib, io, json, sys SEV = {"high": 0, "medium": 1, "low": 2, "info": 3} EVENT_KEYS = {"event", "date", "tables", "rules"} TABLE_KEYS = {"name", "seats", "accessible", "kids", "fixed", "notes"} RULE_KEYS = {"keep_parties_together", "mix_groups", "min_known"} MOBILITY = ("wheelchair", "step-free", "walker", "mobility", "crutches") W_APART, W_ACCESS, W_LONELY, W_GROUP, W_SPREAD = 100, 40, 12, 2, 3 class InputError(Exception): pass def norm(s): return " ".join(str(s or "").split()).lower() def split_list(s): return [x.strip() for x in str(s or "").replace(",", ";").split(";") if x.strip()] # ---------------------------------------------------------------- load def load_event(cfg): if not isinstance(cfg, dict) or not isinstance(cfg.get("tables"), list) or not cfg["tables"]: raise InputError("event file must be a JSON object with a non-empty \"tables\" list") bad = set(cfg) - EVENT_KEYS if bad: raise InputError("unknown key(s) in event file: %s" % ", ".join(sorted(bad))) rules = cfg.get("rules") or {} badr = set(rules) - RULE_KEYS if badr: raise InputError("unknown rule(s): %s" % ", ".join(sorted(badr))) tables, names = [], set() for i, t in enumerate(cfg["tables"], 1): badt = set(t) - TABLE_KEYS if badt: raise InputError("table #%d: unknown key(s) %s" % (i, ", ".join(sorted(badt)))) name = str(t.get("name") or "Table %d" % i) if name in names: raise InputError("table name %r used twice" % name) names.add(name) seats = t.get("seats") if not isinstance(seats, int) or seats < 1: raise InputError("table %s: seats must be a positive whole number, got %r" % (name, seats)) tables.append({"name": name, "seats": seats, "accessible": bool(t.get("accessible")), "kids": bool(t.get("kids")), "fixed": [str(x) for x in t.get("fixed") or []], "notes": t.get("notes", "")}) return {"event": cfg.get("event", "Event"), "date": cfg.get("date", ""), "tables": tables, "together": rules.get("keep_parties_together", True), "mix": bool(rules.get("mix_groups", False)), "min_known": int(rules.get("min_known", 1))} def load_guests(text, include_pending=False): rows = list(csv.DictReader(io.StringIO(text))) if not rows: raise InputError("guest list is empty") cols = {c.strip().lower() for c in rows[0].keys() if c} if "name" not in cols: raise InputError("guest list needs a 'name' column") guests, skipped, F, seen = [], {"no": 0, "pending": 0}, [], {} for ln, r in enumerate(rows, 2): r = {(k or "").strip().lower(): (v or "").strip() for k, v in r.items()} name = " ".join(r.get("name", "").split()) if not name: F.append(("medium", "SC08", "line %d" % ln, "row without a name skipped", "fill in the name or delete the row")) continue rsvp = norm(r.get("rsvp") or "yes") if rsvp in ("no", "declined", "n"): skipped["no"] += 1 continue if rsvp in ("pending", "maybe", "?", "invited", ""): if not include_pending: skipped["pending"] += 1 continue if norm(name) in seen: F.append(("medium", "SC08", name, "listed twice (lines %d and %d) - seated once" % (seen[norm(name)], ln), "check whether these are two different people; add a surname or initial")) continue seen[norm(name)] = ln needs = [norm(x) for x in split_list(r.get("needs"))] guests.append({"name": name, "party": r.get("party") or name, "group": r.get("group") or "-", "child": norm(r.get("child")) in ("yes", "y", "true", "1", "child"), "needs": needs, "mobility": any(any(m in n for m in MOBILITY) for n in needs), "diet": norm(r.get("diet")) or "standard", "sit_with": split_list(r.get("sit_with")), "keep_apart": split_list(r.get("keep_apart")), "line": ln, "pending": rsvp != "yes" and rsvp not in ("y", "accepted")}) return guests, skipped, F # ---------------------------------------------------------------- plan class DSU: def __init__(self, n): self.p = list(range(n)) def find(self, a): while self.p[a] != a: self.p[a] = self.p[self.p[a]] a = self.p[a] return a def union(self, a, b): self.p[self.find(a)] = self.find(b) def plan(ev, guests, F=None): F = list(F or []) add = lambda sev, code, who, msg, fix: F.append((sev, code, who, msg, fix)) idx = {norm(g["name"]): i for i, g in enumerate(guests)} allnames = [g["name"] for g in guests] def resolve(who, ref, kind): j = idx.get(norm(ref)) if j is None: close = difflib.get_close_matches(ref, allnames, 1, 0.7) add("high", "SC03", who, "%s %r is not on the (attending) guest list%s" % (kind, ref, " - did you mean %s?" % close[0] if close else ""), "fix the spelling" if close else "add the guest or remove the request") return j n = len(guests) seats = sum(t["seats"] for t in ev["tables"]) maxt = max(t["seats"] for t in ev["tables"]) if n > seats: add("high", "SC01", "-", "%d guests but only %d seats (%d short)" % (n, seats, n - seats), "add a table or seats, or confirm the RSVPs") dsu = DSU(n) party_of = {} for i, g in enumerate(guests): party_of.setdefault(norm(g["party"]), []).append(i) if ev["together"]: for p, mem in party_of.items(): if len(mem) > maxt: add("medium", "SC09", guests[mem[0]]["party"], "party of %d is larger than the largest table (%d) - it is split" % (len(mem), maxt), "seat the party on neighbouring tables") for a, b in zip(mem, mem[1:]): if (mem.index(b)) % maxt: dsu.union(a, b) else: for a, b in zip(mem, mem[1:]): dsu.union(a, b) apart = set() for i, g in enumerate(guests): for ref in g["keep_apart"]: j = resolve(g["name"], ref, "keep_apart") if j is not None and j != i: apart.add(tuple(sorted((i, j)))) # sit_with links, refusing those that would exceed the largest table or join a keep-apart pair for i, g in enumerate(guests): for ref in g["sit_with"]: j = resolve(g["name"], ref, "sit_with") if j is None or j == i: continue a, b = dsu.find(i), dsu.find(j) if a == b: continue size = sum(1 for k in range(n) if dsu.find(k) in (a, b)) clash = [p for p in apart if {dsu.find(p[0]), dsu.find(p[1])} == {a, b}] if clash: x, y = clash[0] add("high", "SC02", g["name"], "asks to sit with %s, but %s and %s must be kept apart - the request is dropped" % (guests[j]["name"], guests[x]["name"], guests[y]["name"]), "ask the host which request wins") continue if size > maxt: add("medium", "SC09", g["name"], "sitting with %s would make a group of %d (largest table %d) - request dropped" % (guests[j]["name"], size, maxt), "seat them on neighbouring tables") continue dsu.union(i, j) for x, y in sorted(apart): if dsu.find(x) == dsu.find(y): add("high", "SC02", guests[x]["name"], "must be kept apart from %s but they are in the same party - cannot be met" % guests[y]["name"], "change the party or the request") links = set() for i, g in enumerate(guests): for ref in g["sit_with"]: j = idx.get(norm(ref)) if j is not None: links.add((i, j)); links.add((j, i)) def knows(a, b): ga, gb = guests[a], guests[b] return (norm(ga["party"]) == norm(gb["party"]) or (ga["group"] == gb["group"] and ga["group"] != "-") or (a, b) in links) clusters = {} for i in range(n): clusters.setdefault(dsu.find(i), []).append(i) cl = list(clusters.values()) T = ev["tables"] fixed_at = {} for ti, t in enumerate(T): for nm in t["fixed"]: j = idx.get(norm(nm)) if j is None: close = difflib.get_close_matches(nm, allnames, 1, 0.7) add("high", "SC03", t["name"], "fixed seat for %r who is not on the attending list%s" % (nm, " - did you mean %s?" % close[0] if close else ""), "fix the name in the event file") else: fixed_at[j] = ti assign = {} load = [0] * len(T) reserved = {ti for ti, t in enumerate(T) if t["fixed"]} def pen_table(ti, members): p = 0 mem = set(members) for x, y in apart: if x in mem and y in mem: p += W_APART groups = {} for m in members: g = guests[m] if g["mobility"] and not T[ti]["accessible"]: p += W_ACCESS groups[g["group"]] = groups.get(g["group"], 0) + 1 if not ev["mix"]: p += W_GROUP * max(0, len(groups) - 1) for m in members: g = guests[m] known = sum(1 for o in members if o != m and knows(m, o)) if known < ev["min_known"]: p += W_LONELY if T[ti]["kids"]: p += sum(3 for m in members if not guests[m]["child"]) return p def members_of(ti): return [m for c, t in assign.items() if t == ti for m in cl[c]] def total(): p = sum(pen_table(ti, members_of(ti)) for ti in range(len(T))) spread = {} for c, ti in assign.items(): for m in cl[c]: if guests[m]["group"] != "-": spread.setdefault(guests[m]["group"], set()).add(ti) return p + W_SPREAD * sum(len(v) - 1 for v in spread.values()) gsize = {} for g in guests: gsize[g["group"]] = gsize.get(g["group"], 0) + 1 order = sorted(range(len(cl)), key=lambda c: (-any(i in fixed_at for i in cl[c]), -any(guests[i]["mobility"] for i in cl[c]), -gsize[guests[cl[c][0]]["group"]], guests[cl[c][0]]["group"], -len(cl[c]), cl[c][0])) unseated = [] for c in order: size = len(cl[c]) fx = [fixed_at[i] for i in cl[c] if i in fixed_at] cands = [fx[0]] if fx else range(len(T)) best = None for ti in cands: if load[ti] + size > T[ti]["seats"] or (T[ti]["fixed"] and not fx and ti in reserved): continue assign[c] = ti delta = total() del assign[c] key = (delta, -(load[ti] > 0), ti) if best is None or key < best[0]: best = (key, ti) if best is None: unseated.append(c) continue assign[c] = best[1] load[best[1]] += size # local search: move or swap clusters while it lowers the penalty (deterministic) fixed_cl = {c for c in assign if any(i in fixed_at for i in cl[c])} improved, rounds = True, 0 while improved and rounds < 50: improved, rounds = False, rounds + 1 cur = total() for c in sorted(assign): if c in fixed_cl: continue for ti in range(len(T)): if ti == assign[c] or load[ti] + len(cl[c]) > T[ti]["seats"] or ti in reserved: continue old = assign[c] assign[c] = ti new = total() if new < cur: load[old] -= len(cl[c]); load[ti] += len(cl[c]); cur = new; improved = True else: assign[c] = old # move every cluster of one group (from all tables) to one table for gname in sorted({guests[cl[c][0]]["group"] for c in assign if c not in fixed_cl}): block = [c for c in assign if c not in fixed_cl and guests[cl[c][0]]["group"] == gname] for b in range(len(T)): if b in reserved: continue old = {c: assign[c] for c in block} moving = sum(len(cl[c]) for c in block if old[c] != b) if not moving or load[b] + moving > T[b]["seats"]: continue for c in block: assign[c] = b new = total() if new < cur: for c in block: if old[c] != b: load[old[c]] -= len(cl[c]); load[b] += len(cl[c]) cur = new; improved = True break for c in block: assign[c] = old[c] # move a whole group block (all clusters of one group at one table) to another table for a in range(len(T)): groups_here = sorted({guests[cl[c][0]]["group"] for c, x in assign.items() if x == a and c not in fixed_cl}) for gname in groups_here: block = [c for c, x in assign.items() if x == a and c not in fixed_cl and guests[cl[c][0]]["group"] == gname] bsize = sum(len(cl[c]) for c in block) for b in range(len(T)): if b == a or b in reserved or load[b] + bsize > T[b]["seats"]: continue for c in block: assign[c] = b new = total() if new < cur: load[a] -= bsize; load[b] += bsize; cur = new; improved = True break for c in block: assign[c] = a for c in sorted(assign): for d in sorted(assign): if d <= c or c in fixed_cl or d in fixed_cl or assign[c] == assign[d] or assign[c] in reserved or assign[d] in reserved: continue a, b = assign[c], assign[d] if load[a] - len(cl[c]) + len(cl[d]) > T[a]["seats"] or load[b] - len(cl[d]) + len(cl[c]) > T[b]["seats"]: continue assign[c], assign[d] = b, a new = total() if new < cur: load[a] += len(cl[d]) - len(cl[c]); load[b] += len(cl[c]) - len(cl[d]); cur = new; improved = True else: assign[c], assign[d] = a, b seat = {} for c, ti in assign.items(): for i in cl[c]: seat[i] = ti for c in unseated: add("high", "SC01", ", ".join(guests[i]["name"] for i in cl[c]), "no table with %d free seats together - not seated" % len(cl[c]), "add seats or split the group across neighbouring tables") # findings on the result for x, y in sorted(apart): if x in seat and y in seat and seat[x] == seat[y]: add("high", "SC02", guests[x]["name"], "seated at %s together with %s although they must be kept apart" % (T[seat[x]]["name"], guests[y]["name"]), "move one of them by hand") for i, g in enumerate(guests): if i not in seat: continue ti = seat[i] if g["mobility"] and not T[ti]["accessible"]: add("medium", "SC05", g["name"], "needs %s but %s is not marked accessible" % ("/".join(g["needs"]), T[ti]["name"]), "swap with a guest at an accessible table") mem = [m for m, t in seat.items() if t == ti and m != i] known = [m for m in mem if knows(i, m)] if len(known) < ev["min_known"]: add("medium", "SC04", g["name"], "at %s without anyone from their party or group (%s)" % (T[ti]["name"], g["group"]), "seat them next to the most sociable guest there, or swap") if g["child"] and not T[ti]["kids"] and not any(norm(guests[m]["party"]) == norm(g["party"]) and not guests[m]["child"] for m in mem): add("medium", "SC10", g["name"], "child seated without an adult from their party", "move next to their parents or to the kids table") if g["pending"]: add("info", "SC07", g["name"], "RSVP still pending - seated provisionally", "chase the RSVP before printing place cards") for ti, t in enumerate(T): used = sum(1 for i in seat if seat[i] == ti) if 0 < used < t["seats"] / 2: add("low", "SC06", t["name"], "only %d of %d seats used" % (used, t["seats"]), "merge with another table or take it out") if used == 0: add("info", "SC06", t["name"], "empty table", "remove it from the room plan") for p, mem in party_of.items(): ts = {seat[i] for i in mem if i in seat} if len(ts) > 1 and len(mem) <= maxt: add("medium", "SC09", guests[mem[0]]["party"], "party split over %s" % ", ".join(T[x]["name"] for x in sorted(ts)), "free seats at one table and move them together") F.sort(key=lambda x: (SEV[x[0]], x[1], x[2])) return {"seat": seat, "tables": T, "guests": guests, "findings": F, "penalty": total(), "seats": seats} # ---------------------------------------------------------------- output def report(ev, r, skipped, src): G, T, seat = r["guests"], r["tables"], r["seat"] c = {s: 0 for s in SEV} for f in r["findings"]: c[f[0]] += 1 hard = [f for f in r["findings"] if f[0] == "high"] out = ["# Seating chart: %s%s" % (ev["event"], (" (%s)" % ev["date"]) if ev["date"] else ""), "", "%d attending guest(s) (%d declined; %s), %d seat(s) at %d table(s). Source: %s." % ( len(G), skipped["no"], ("%d pending seated provisionally" % sum(1 for g in G if g["pending"])) if any(g["pending"] for g in G) else "%d pending left out" % skipped["pending"], r["seats"], len(T), src), ""] v = ("%d hard request(s) could not be met - see findings" % len(hard)) if hard else ("all hard requests met, %d soft issue(s) to look at" % c["medium"] if c["medium"] else "all requests met") out += ["**Verdict: %s**" % v, "", "Findings: %d high, %d medium, %d low, %d info." % (c["high"], c["medium"], c["low"], c["info"]), ""] out += ["## Tables", "", "| Table | Seats | Guests | Groups | Meals |", "|---|---|---|---|---|"] for ti, t in enumerate(T): mem = sorted((i for i in seat if seat[i] == ti), key=lambda i: (norm(G[i]["party"]), G[i]["child"], G[i]["line"])) tags = [x for x in ("accessible" if t["accessible"] else "", "kids" if t["kids"] else "", "fixed" if t["fixed"] else "") if x] names = ", ".join(G[i]["name"] + (" (child)" if G[i]["child"] else "") + (" *" if G[i]["mobility"] else "") for i in mem) or "-" groups = {} meals = {} for i in mem: groups[G[i]["group"]] = groups.get(G[i]["group"], 0) + 1 k = G[i]["diet"] + (" (child)" if G[i]["child"] else "") meals[k] = meals.get(k, 0) + 1 out.append("| %s%s | %d/%d | %s | %s | %s |" % (t["name"], " [%s]" % ", ".join(tags) if tags else "", len(mem), t["seats"], names, ", ".join("%s %d" % kv for kv in sorted(groups.items())) or "-", ", ".join("%s %d" % kv for kv in sorted(meals.items())) or "-")) out += ["", "`*` = mobility need (seat on the aisle side, nearest the door).", ""] out += ["## Findings", "", "| Sev | Code | Who | Finding | Fix |", "|---|---|---|---|---|"] for s, code, who, msg, fix in r["findings"]: out.append("| %s | %s | %s | %s | %s |" % (s, code, who, msg.replace("|", "\\|"), fix.replace("|", "\\|"))) meals = {} for i in seat: k = G[i]["diet"] + (" (child)" if G[i]["child"] else "") meals[k] = meals.get(k, 0) + 1 out += ["", "## Caterer summary", "", "| Meal | Count |", "|---|---|"] for k, v_ in sorted(meals.items()): out.append("| %s | %d |" % (k, v_)) notes = [(G[i]["name"], T[seat[i]]["name"], ", ".join(x for x in G[i]["needs"])) for i in sorted(seat, key=lambda i: G[i]["name"]) if G[i]["needs"]] if notes: out += ["", "Special needs: " + "; ".join("%s (%s) - %s" % n for n in notes) + "."] out += ["", "## Place cards (A-Z)", "", "| Guest | Table |", "|---|---|"] for i in sorted(seat, key=lambda i: norm(G[i]["name"])): out.append("| %s | %s |" % (G[i]["name"], T[seat[i]]["name"])) out += ["", "The chart is a starting point: move people by hand where you know better, then re-run to check the requests still hold."] return "\n".join(out) + "\n" def run(event_path, guests_path, include_pending=False): try: ev = load_event(json.load(open(event_path, encoding="utf-8"))) text = open(guests_path, encoding="utf-8-sig").read() except (OSError, ValueError) as e: raise InputError("cannot read input: %s" % e) guests, skipped, F = load_guests(text, include_pending) return ev, plan(ev, guests, F), skipped # ---------------------------------------------------------------- self-test def self_test(): tests = [] def t(name, cond): tests.append((name, bool(cond))) H = "name,party,group,rsvp,child,needs,diet,sit_with,keep_apart\n" def P(tables, rows, pending=False, **rules): ev = load_event({"tables": tables, "rules": rules}) g, sk, F = load_guests(H + rows, pending) return plan(ev, g, F), g def codes(r): return [(f[0], f[1]) for f in r["findings"]] def tab(r, g, name): i = [k for k, x in enumerate(g) if x["name"] == name][0] return r["seat"].get(i) T2 = [{"name": "A", "seats": 4}, {"name": "B", "seats": 4}] rows = "Ann,P1,work,yes\nBob,P1,work,yes\nCid,P2,family,yes\nDee,P2,family,yes\nEve,P3,work,yes\nFay,P4,family,yes\n" r, g = P(T2, rows) t("parties stay together", tab(r, g, "Ann") == tab(r, g, "Bob") and tab(r, g, "Cid") == tab(r, g, "Dee")) t("groups fill tables", tab(r, g, "Eve") == tab(r, g, "Ann") and tab(r, g, "Fay") == tab(r, g, "Cid")) t("clean plan has no high/medium", not [f for f in r["findings"] if f[0] in ("high", "medium")]) r, g = P(T2, "Ann,P1,work,yes,,,,,Bob\nBob,P2,work,yes\nCid,P3,work,yes\nDee,P4,work,yes\n") t("keep_apart respected", tab(r, g, "Ann") != tab(r, g, "Bob") and ("high", "SC02") not in codes(r)) r, g = P(T2, "Ann,P1,work,yes,,,,Dee\nBob,P2,family,yes\nCid,P3,family,yes\nDee,P4,friends,yes\n") t("sit_with respected", tab(r, g, "Ann") == tab(r, g, "Dee")) r, g = P(T2, "Ann,P1,work,yes,,,,Bob,Bob\nBob,P2,work,yes\n") t("sit_with vs keep_apart conflict -> SC02 high", ("high", "SC02") in codes(r)) r, g = P(T2, "Ann,P1,work,yes,,,,,Bob\nBob,P1,work,yes\n") t("keep apart inside one party -> SC02", ("high", "SC02") in codes(r)) r, g = P(T2, "Ann,P1,work,yes,,,,Bobb\nBob,P2,work,yes\n") t("misspelled name -> SC03 with suggestion", any(f[1] == "SC03" and "did you mean Bob" in f[3] for f in r["findings"])) r, g = P([{"name": "A", "seats": 2}], "Ann,P1,w,yes\nBob,P2,w,yes\nCid,P3,w,yes\n") t("not enough seats -> SC01 high", ("high", "SC01") in codes(r)) r, g = P(T2, "Ann,P1,w,yes\nAnn,P1,w,yes\nBob,P1,w,yes\n") t("duplicate -> SC08 and seated once", ("medium", "SC08") in codes(r) and len(g) == 2) r, g = P(T2, "Ann,P1,w,no\nBob,P2,w,pending\nCid,P3,w,yes\nDee,P3,w,yes\n") t("declined and pending excluded", len(g) == 2) r, g = P(T2, "Bob,P2,w,pending\nCid,P3,w,yes\n", pending=True) t("--include-pending seats pending -> SC07", len(g) == 2 and ("info", "SC07") in codes(r)) r, g = P([{"name": "A", "seats": 4}, {"name": "B", "seats": 4, "accessible": True}], "Ann,P1,w,yes\nBob,P2,x,yes,,wheelchair\n") t("wheelchair -> accessible table", tab(r, g, "Bob") == 1) r, g = P([{"name": "A", "seats": 4}, {"name": "B", "seats": 4}], "Ann,P1,w,yes\nBob,P2,x,yes,,wheelchair\n") t("no accessible table -> SC05", ("medium", "SC05") in codes(r)) r, g = P(T2, "Ann,P1,work,yes\nBob,P1,work,yes\nZed,P9,gym,yes\n") t("lonely guest -> SC04", ("medium", "SC04") in codes(r)) r, g = P([{"name": "Head", "seats": 4, "fixed": ["Bride", "Groom"]}, {"name": "B", "seats": 4}], "Bride,C,couple,yes\nGroom,C,couple,yes\nBest,Best,groom family,yes,,,,Groom\n") t("sit_with partner counts as someone they know", ("medium", "SC04") not in codes(r) and tab(r, g, "Best") == 0) r, g = P([{"name": "A", "seats": 4}, {"name": "B", "seats": 4}, {"name": "C", "seats": 4}], "A1,a1,fam,yes\nA2,a1,fam,yes\nA3,a1,fam,yes\nW1,w1,work,yes\nB1,b1,fam,yes\nB2,b1,fam,yes\nB3,b1,fam,yes\nW2,w2,work,yes\n") t("group split by greedy is pulled together", tab(r, g, "W1") == tab(r, g, "W2")) r, g = P([{"name": "A", "seats": 3}, {"name": "B", "seats": 3}], "A1,Big,w,yes\nA2,Big,w,yes\nA3,Big,w,yes\nA4,Big,w,yes\n") t("party bigger than a table is split -> SC09", ("medium", "SC09") in codes(r) and len(r["seat"]) == 4) r, g = P([{"name": "Head", "seats": 2, "fixed": ["Cid"]}, {"name": "B", "seats": 4}], "Ann,P1,w,yes\nBob,P1,w,yes\nCid,P3,w,yes\n") t("fixed seat honoured", tab(r, g, "Cid") == 0) r, g = P([{"name": "Head", "seats": 2, "fixed": ["Cyd"]}, {"name": "B", "seats": 4}], "Cid,P3,w,yes\n") t("fixed seat typo -> SC03", ("high", "SC03") in codes(r)) r, g = P([{"name": "A", "seats": 10}, {"name": "B", "seats": 10}], "Ann,P1,w,yes\nBob,P1,w,yes\n") t("half-empty and empty tables -> SC06", ("low", "SC06") in codes(r) and ("info", "SC06") in codes(r)) r, g = P([{"name": "A", "seats": 4}, {"name": "Kids", "seats": 4, "kids": True}], "Mum,F,fam,yes\nTim,F,fam,yes,yes\nLia,G,fam,yes,yes\nDad,G,fam,yes\n") t("children stay with their party by default", tab(r, g, "Tim") == tab(r, g, "Mum")) r, g = P(T2, "Ann,P1,w,yes,,,vegetarian\nBob,P1,w,yes,,,\n") t("diet counted", "vegetarian 1" in report({"event": "x", "date": ""}, r, {"no": 0, "pending": 0}, "x")) r, g = P([{"name": "A", "seats": 2}, {"name": "B", "seats": 2}], "Ann,P1,w,yes,,,,Bob;Cid\nBob,P2,w,yes\nCid,P3,w,yes\n") t("sit_with group larger than any table -> SC09", ("medium", "SC09") in codes(r)) for bad, name in (({"tables": []}, "no tables"), ({"tables": [{"name": "A", "seats": 0}]}, "zero seats"), ({"tables": [{"name": "A", "seats": 4}, {"name": "A", "seats": 4}]}, "duplicate table"), ({"tables": [{"name": "A", "seats": 4, "colour": "red"}]}, "unknown table key")): try: load_event(bad); t("rejected: " + name, False) except InputError: t("rejected: " + name, True) try: load_guests("first,last\nA,B\n"); t("rejected: no name column", False) except InputError: t("rejected: no name column", True) r, g = P(T2, rows) rep = report({"event": "x", "date": ""}, r, {"no": 0, "pending": 0}, "x") t("report has verdict, tables and place cards", "**Verdict:" in rep and "## Tables" in rep and "## Place cards" in rep) for n, ok in tests: print("%s %s" % ("PASS" if ok else "FAIL", n)) p = sum(ok for _, ok in tests) print("%d/%d passed" % (p, len(tests))) return 0 if p == len(tests) else 1 def main(argv=None): ap = argparse.ArgumentParser(description="Build a seating chart from tables and a guest list.") ap.add_argument("event", nargs="?") ap.add_argument("guests", nargs="?") ap.add_argument("--include-pending", action="store_true", help="seat guests whose RSVP is pending") ap.add_argument("--csv", action="store_true", help="print name,table CSV (place cards)") ap.add_argument("--json", action="store_true") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.event or not a.guests: ap.error("give EVENT.json and GUESTS.csv") try: ev, r, skipped = run(a.event, a.guests, a.include_pending) except InputError as e: print("error: %s" % e, file=sys.stderr) return 2 G, T = r["guests"], r["tables"] if a.json: print(json.dumps({"tables": [{"name": t["name"], "seats": t["seats"], "guests": [G[i]["name"] for i in sorted(r["seat"]) if r["seat"][i] == ti]} for ti, t in enumerate(T)], "unseated": [g["name"] for i, g in enumerate(G) if i not in r["seat"]], "findings": [dict(zip(("severity", "code", "who", "finding", "fix"), f)) for f in r["findings"]]}, indent=2)) elif a.csv: w = csv.writer(sys.stdout, lineterminator="\n") w.writerow(["name", "table", "diet"]) for i in sorted(r["seat"], key=lambda i: norm(G[i]["name"])): w.writerow([G[i]["name"], T[r["seat"][i]]["name"], G[i]["diet"]]) else: sys.stdout.write(report(ev, r, skipped, a.guests)) return 1 if any(f[0] == "high" for f in r["findings"]) else 0 if __name__ == "__main__": sys.exit(main())

Train Delay Compensation Claim (JSON)

{ "role": "Calm, careful passenger-rights assistant who helps train travelers understand a delay or cancellation, gather evidence, check whether compensation or a refund may apply under the rules for their region, write clear factual claim letters, and track deadlines — without inventing laws, amounts, deadlines, or airline/rail policies", "task": "Turn my train trip details, the delay or cancellation facts, tickets and receipts, and what the operator already offered into a single strict JSON compensation claim report: a summary, a trip and disruption fact check, a rights checklist marked to_confirm for my region, an eligibility assessment, an evidence log and plan, a claim-amount worksheet with every figure marked estimate or to_confirm, a deadline timeline, ready-to-send claim letters and emails, an escalation path, and next steps. Practical help only. Never invent passenger-rights rules, compensation amounts, deadlines, or laws. This is not legal advice.", "context": { "region": "${region:EU/EEA train journey under EU rail passenger rights | UK domestic or international | US Amtrak or other US carrier | other / not sure}", "trip": "${trip:outbound high-speed train from City A to City B on 12 March, ticket bought online, reserved seat, arrived 2 hours 40 minutes late}", "disruption_type": "${type:long delay on arrival | cancellation | missed connection because of a delay | denied boarding / no seat | partial cancellation}", "operator": "${operator:the mainline rail operator named on my ticket}", "what_happened": "${story:the train sat outside the station for 90 minutes with no clear updates, then crawled in; I missed my last connecting bus home and paid for a taxi}", "ticket_details": "${ticket:e-ticket PDF, booking reference ABC123, paid 89 EUR, flexible fare, passenger name matches my ID}", "delay_length": "${delay:arrived 2 hours 40 minutes after the scheduled arrival time on the ticket}", "care_received": "${care:one bottle of water offered after 60 minutes; no meal voucher; no hotel}", "expenses": "${expenses:taxi home 35 EUR with receipt; meal at station 12 EUR with card statement}", "operator_offer_so_far": "${offer:an email offering 25 percent voucher credit toward a future ticket; I have not accepted it}", "deadlines_I_know": "${deadlines:I think I have months to claim but I am not sure; disruption was 5 days ago}", "goal": "${goal:cash compensation or a refund if that fits the rules, plus reimbursement of reasonable extra costs; I prefer cash over a voucher}", "documents_I_have": "${docs:e-ticket PDF, booking confirmation email, photos of the delay board, taxi receipt, bank statement line for the meal}" }, "ask_first": [ "Your region or route (EU/EEA, UK, US, or other), the operator name on the ticket, and whether the journey was domestic or international.", "Scheduled and actual departure and arrival times, delay length at arrival, and whether a connection was missed.", "Ticket type (flexible, non-flex, season, rail pass), price paid, booking reference, and passenger name match.", "What the operator already offered (voucher, cash, rebooking, nothing) and whether you accepted anything.", "Extra costs with receipts (taxi, hotel, meals) and any care provided on board or at the station.", "Any claim deadline printed on the ticket email or operator site that you have already seen (mark unknown if not)." ], "rules": [ "Never invent passenger-rights laws, compensation percentages, fixed euro/dollar amounts, claim deadlines, or operator policies. Mark every legal or policy point as to_confirm with the official operator and the official passenger-rights source for that region (for example EU rail passenger rights materials, UK rail ADR/ombudsman pages, or the US carrier's published contingency plan).", "Treat EU261-style air rules as NOT applying to trains. If the user mentions a flight, say this prompt is for rail and point them to use a flight-specific claim helper instead.", "US-aware means: note that US rail compensation is largely carrier-policy and DOT consumer guidance based, not a single EU-style fixed delay scale — mark every amount and deadline to_confirm with the carrier.", "Never present a compensation figure as guaranteed. Use estimate or to_confirm only.", "Prefer cash reimbursement language when the user prefers cash; list voucher offers as optional alternatives to evaluate, not as advice to accept.", "Be polite, factual, and brief in all letter bodies. No threats, no invented case law, no fake statute citations.", "If facts are missing, set fields to null and add open_questions instead of guessing.", "Always include clear disclaimers that this is practical organizing help, not legal advice, and that the user should confirm rights and deadlines with official sources or a qualified adviser if the claim is large or disputed." ], "output_format": { "summary": { "operator": "string", "region": "string", "disruption_type": "long_delay | cancellation | missed_connection | denied_boarding | other", "delay_minutes": "number | null", "ticket_price": "number | null", "currency": "string | null", "key_finding": "string", "recommendation": "file_compensation_claim | request_refund | negotiate_better_than_voucher | accept_offer_after_confirming | get_advice | need_more_information", "claim_strength": "strong | moderate | weak | needs_more_evidence", "assumptions": [ "string" ], "open_questions": [ "string" ] }, "trip_fact_check": [ { "detail": "string", "on_ticket_or_record": "string | null", "what_really_happened": "string | null", "matches": "boolean | null", "confirm": "boolean" } ], "rights_checklist": [ { "item": "string", "applies_guess": "likely | unlikely | unknown", "reason": "string", "official_source_to_confirm": "string", "status": "to_confirm" } ], "eligibility_assessment": [ { "ground": "string", "facts_supporting": [ "string" ], "evidence_refs": [ "string" ], "strength": "strong | moderate | weak", "reason": "string", "to_confirm": "string | null" } ], "evidence_log": [ { "evidence_id": "string", "type": "ticket | booking_email | photo | receipt | bank_statement | operator_message | witness | other", "description": "string", "date_time": "string | null", "shows": "string", "file_name": "string", "have_it": "boolean" } ], "evidence_plan": [ { "item": "string", "how": "string", "by_when": "string", "done": "boolean" } ], "claim_amount_worksheet": { "ticket_price": "number | null", "possible_delay_compensation_estimate": "number | null", "extra_costs_total": "number | null", "extra_costs_breakdown": [ { "item": "string", "amount": "number | null", "receipt": "boolean", "reimbursable_guess": "likely | unlikely | unknown" } ], "operator_offer_value": "number | null", "operator_offer_type": "cash | voucher | rebooking | none | unknown", "money_at_stake_estimate": "number | null", "currency": "string | null", "all_figures_status": "estimate_or_to_confirm", "notes": "string" }, "timeline": [ { "date": "string | null", "event": "string", "deadline": "boolean", "reminder_on": "string | null", "confirm_with": "string | null" } ], "letters": [ { "stage": "first_claim | follow_up | reject_voucher_ask_cash | escalation_adr_or_regulator | other", "to": "string", "subject": "string", "body": "string", "attachments": [ "string" ], "send_by": "string | null", "send_method": "email | web_form | post | app | to_confirm" } ], "escalation_path": [ { "stage": "number", "action": "string", "body": "string", "trigger": "string", "time_limit_to_confirm": "string" } ], "next_steps": [ { "step": "string", "when": "string", "done": "boolean" } ], "disclaimers": [ "string" ] } }

Community collection: awesome-chatgpt-prompts (CC0, refreshed hourly from GitHub).