@f
developer. github star. head of AX at automattic.com for spacefast.com, builder of prompts.example.vn

A fill-in template for clean, Notion-style black-and-white editorial illustrations: swap in a subject, outfit, action and facial expression to get flat monochrome line art with a subtle hand-drawn feel on a clean white background.
A simple black-and-white illustration of a [subject] in [outfit], [doing action], with a [facial expression] expression, in a Notion-style minimalist editorial aesthetic, clean line art, flat monochrome design, simple shapes, subtle hand-drawn feel, minimal detail, expressive posture, clean white background, neat modern layout, soft playful character style
Opinionated Kotlin Multiplatform preferences: share logic not UI by default, thin expect/actual, Ktor and SQLDelight in common code, coroutines and Flow, clean Swift interop and fast CI.
# Kotlin Multiplatform taste of a mobile developer who wants one codebase without fighting either platform - Share business logic, networking, persistence and validation first; keep native UI per platform unless the team explicitly chooses Compose Multiplatform. Confidence: 0.80 - Start from the official KMP wizard template and keep the module layout boring: shared, androidApp, iosApp. Confidence: 0.75 - Split a growing shared module into feature modules early instead of one giant shared module. Confidence: 0.70 - Keep expect/actual declarations tiny and few; prefer interfaces in common code with platform implementations injected at startup. Confidence: 0.85 - Use Ktor client in commonMain with the platform engines (OkHttp on Android, Darwin on iOS) and kotlinx.serialization for JSON. Confidence: 0.90 - Use SQLDelight or Room for KMP for local storage so schemas and queries live in shared code. Confidence: 0.80 - Use kotlinx-datetime instead of platform date APIs in shared code. Confidence: 0.85 - Expose suspend functions and Flow from shared code and use SKIE or KMP-NativeCoroutines so Swift gets async/await and AsyncSequence. Confidence: 0.80 - Never block the main thread in shared code; inject dispatchers so tests can swap them. Confidence: 0.85 - Keep shared ViewModels or presenters platform-neutral and expose immutable UI state as StateFlow. Confidence: 0.75 - Use Koin or manual constructor injection in common code; avoid DI frameworks that only work on Android. Confidence: 0.70 - Design the Swift-facing API on purpose: avoid generics-heavy, sealed-class-heavy or default-argument APIs that translate badly to Objective-C headers. Confidence: 0.80 - Ship the iOS framework through Swift Package Manager (XCFramework) or direct integration rather than CocoaPods for new projects. Confidence: 0.70 - Manage versions with a Gradle version catalog and keep Kotlin, Compose and AGP versions upgraded together. Confidence: 0.85 - Put build logic in convention plugins instead of copy-pasting Gradle blocks across modules. Confidence: 0.75 - Write most tests in commonTest with kotlin.test and run them on both JVM and iOS simulator targets. Confidence: 0.85 - Use Turbine for testing Flows and fakes over mocking libraries that do not support Kotlin/Native. Confidence: 0.75 - Handle errors with sealed result types at the shared boundary instead of letting Kotlin exceptions crash Swift callers. Confidence: 0.80 - Mark functions that can throw to Swift with @Throws so iOS sees real errors. Confidence: 0.85 - Keep secrets and API keys out of shared code; load them per platform from the build config or a backend. Confidence: 0.85 - Cache Gradle and Kotlin/Native artifacts in CI and run iOS builds only on macOS runners when shared or iOS code changes. Confidence: 0.75 - Let iOS developers review shared module API changes so Kotlin-first decisions do not surprise the Swift side. Confidence: 0.70
Opinionated Drizzle ORM preferences: schema in TypeScript, drizzle-kit migrations in git, explicit relations, typed queries, transactions, prepared statements and Zod schemas generated from tables.
# Drizzle ORM taste of a TypeScript developer who likes to see the SQL - Define the schema in TypeScript with drizzle-orm table builders, split into one file per domain and re-exported from a single schema index. Confidence: 0.85 - Generate SQL migrations with drizzle-kit generate, review the SQL by hand and commit it; never use push against production. Confidence: 0.95 - Use drizzle-kit push only on throwaway local or preview databases where losing data is fine. Confidence: 0.80 - Keep drizzle.config.ts small and read the database URL from the environment, never from a committed file. Confidence: 0.90 - Apply migrations in a separate deploy step with the migrator, not on every app boot in every serverless instance. Confidence: 0.85 - Name columns in snake_case in the database and camelCase in TypeScript using the casing option instead of hand-mapping each one. Confidence: 0.75 - Give every table a primary key, created_at and updated_at with database defaults, and use timestamp with time zone. Confidence: 0.85 - Declare foreign keys with references() and an explicit onDelete behavior so the database enforces integrity. Confidence: 0.90 - Add indexes in the table definition for every foreign key and every column you filter or sort on. Confidence: 0.85 - Define relations() for the relational query API and use db.query with "with" for nested reads instead of manual joins. Confidence: 0.75 - Use the SQL-like select builder with explicit joins when you need aggregates, window functions or precise control. Confidence: 0.80 - Select only the columns you need instead of returning whole rows, especially for list endpoints. Confidence: 0.80 - Infer types with $inferSelect and $inferInsert rather than writing duplicate interfaces by hand. Confidence: 0.90 - Generate Zod schemas from tables with drizzle-zod and refine them for API validation. Confidence: 0.75 - Wrap multi-step writes in db.transaction and pass the tx object down instead of the global db. Confidence: 0.90 - Use the sql template tag for raw fragments, which keeps values parameterized; never build SQL with string concatenation. Confidence: 1.00 - Use prepared statements with placeholders for hot queries on long-running servers. Confidence: 0.65 - Use returning() on inserts and updates instead of a second read query. Confidence: 0.80 - Use onConflictDoUpdate for upserts and back it with a real unique index. Confidence: 0.85 - Pick the driver that matches the runtime (node-postgres for servers, the Neon or other HTTP driver for edge and serverless) and keep it in one db module. Confidence: 0.80 - Keep queries in small repository or data-access functions so route handlers never build queries inline. Confidence: 0.70 - Run integration tests against a real Postgres (container or branch database) with migrations applied, not against mocks. Confidence: 0.85 - Seed local data with a typed seed script checked into the repo. Confidence: 0.70
Opinionated payments integration preferences: hosted checkout first, idempotency keys, webhooks as the source of truth, integer money, test clocks, reconciliation and careful refund handling.
# Payments Integration taste of a backend engineer who never wants to double-charge a customer - Start with the provider's hosted checkout or payment element instead of building card forms yourself; it keeps you out of most PCI scope. Confidence: 0.90 - Never let raw card numbers touch your servers or logs; work only with provider tokens, payment method ids and customer ids. Confidence: 1.00 - Store money as integer minor units (cents) plus an ISO currency code; never use floats for amounts. Confidence: 1.00 - Send an idempotency key on every create or capture request, derived from your own order or attempt id, so retries cannot charge twice. Confidence: 0.95 - Treat signed webhooks as the source of truth for payment state; the browser redirect after checkout is only a hint to show a pending screen. Confidence: 0.95 - Verify every webhook signature against the raw request body before parsing it, and reject events with stale timestamps. Confidence: 1.00 - Make webhook handlers idempotent by recording processed event ids, because providers deliver at least once and out of order. Confidence: 0.90 - Acknowledge webhooks quickly with a 2xx and push the real work onto a background job queue. Confidence: 0.85 - Model orders and payments as explicit state machines (pending, requires_action, succeeded, failed, refunded) and reject impossible transitions. Confidence: 0.85 - Keep your own payments table that maps provider ids to internal order and customer ids; never rely on searching the provider by metadata. Confidence: 0.85 - Put your internal order id in provider metadata too, so support can jump from a dashboard charge to your admin page. Confidence: 0.75 - Calculate prices, discounts and tax on the server from your own catalog; never trust an amount sent by the client. Confidence: 1.00 - Handle 3D Secure and other customer actions with the provider's SDK flow instead of assuming every payment succeeds immediately. Confidence: 0.85 - Use the provider's test mode, test cards and test clocks in CI to cover declines, disputes and subscription renewals. Confidence: 0.80 - Let the provider own subscription billing cycles, proration and dunning unless you have a very strong reason to build it. Confidence: 0.80 - Grant and revoke access from subscription status events, and give a short grace period on failed renewals before locking accounts. Confidence: 0.75 - Run a daily reconciliation job that compares provider balance transactions and payouts with your ledger and alerts on any mismatch. Confidence: 0.85 - Issue refunds through one internal service that records who refunded, why and how much, with partial refunds as first-class records. Confidence: 0.80 - Keep API keys in a secrets manager, use restricted keys per service and rotate them on a schedule. Confidence: 0.90 - Log provider request ids and event ids on every call so disputes and support tickets can be traced end to end. Confidence: 0.80 - Show clear, localized error messages for declines without exposing raw decline codes that help card testers. Confidence: 0.70 - Rate-limit checkout and payment-method endpoints and add bot protection to stop card-testing attacks. Confidence: 0.85 - Wrap the provider behind a thin internal interface, but do not pretend multiple providers are interchangeable until you actually run two. Confidence: 0.65

Photoreal sunny afternoon in a quiet living room corner: a walnut record player playing a black record with a plain mustard label, a teak sideboard with record sleeves, a trailing pothos, headphones, and golden light through a sheer linen curtain. Step 1 of the Turntable Afternoon workflow.
A photorealistic photograph of a quiet living room corner on a sunny afternoon, centered on a vintage record player that is playing a record. The turntable has a warm walnut wood plinth, a brushed aluminum platter with a black rubber mat and a slim silver tonearm resting on the record, its stylus in the groove. The black vinyl record has a plain mustard-yellow center label with a single thick dark red stripe across it and no text, so its rotation is easy to see. The turntable stands on a low mid-century teak sideboard. Next to it: a small stack of record sleeves in plain muted colors (olive, rust, cream) leaning against the wall with no readable text, a ceramic pot with a trailing pothos plant spilling over the edge of the sideboard, and a pair of over-ear headphones lying on the wood. Behind the sideboard, a tall window with a sheer white linen curtain lets in warm golden sunlight that falls across the turntable in soft diagonal stripes; a few fine dust motes float in the light beam. A small framed abstract print with simple colored shapes hangs on the wall above. Warm afternoon light against the cool, soft shadows in the room. 50 mm lens at seated eye level, slightly above the height of the turntable, turntable a little left of center, everything sharp. Calm, nostalgic, slow-Sunday mood, natural colors. No people, no hands, no animals or pets, no screens, no readable text, labels or logos. Landscape 16:9.

A straight-on photo of a hand-embroidered Uzbek suzani on a plaster wall: ivory cotton with six large crimson sun medallions, winding vines with tulips and carnations in saffron, teal and indigo, a rosette border, and glossy raised silk stitches in soft raking daylight.
A detailed straight-on photograph of a traditional Uzbek suzani, a large hand-embroidered textile from Central Asia, hung flat on a pale plaster wall. The background cloth is an ivory cotton with a soft natural texture. Across it, bold embroidered motifs in silk thread cover most of the surface: six large circular red "sun" medallions arranged in two columns, each filled with concentric rings of crimson, deep madder red and dark plum, outlined in black, with small star-like rosettes at their centers. Between the medallions, curving vines with serrated leaves in olive and teal green wind across the cloth, sprouting small tulips, carnations and round buds in saffron yellow, salmon pink and indigo blue. A wide border runs around all four edges, filled with a repeating pattern of smaller red rosettes and leafy scrolls, framed by a narrow dark indigo band. The embroidery is done in dense couching and chain stitches, so every motif has a slightly raised, glossy surface; up close you can see individual stitches, small irregularities from handwork and a few places where the silk has faded a little with age. Soft, even daylight from a window on the left gives a gentle raking light that shows the texture of the stitches, with a faint soft shadow where the textile hangs slightly away from the wall at the top corners. Rich, warm, crafted Silk Road folk-art mood, natural colors, everything sharp. No people, no hands, no furniture in front, no readable text, letters, signatures or logos. Portrait 3:4.

Photoreal close-up of Turkish coffee brewed the traditional way in hot sand: three hammered copper cezves on a tray of glowing golden sand, thick foam rising in the front one, porcelain cups, rose Turkish delight and a brass grinder in warm café side light.
A photorealistic close-up photograph of Turkish coffee being brewed the traditional way, in hot sand. A wide, shallow hammered copper tray is filled with fine golden sand, heated from below and glowing faintly at the edges. Three small long-handled copper cezves are pushed into the sand at slightly different depths; their brass handles point outward toward the viewer. In the front cezve the dark coffee is just rising, with a thick, velvety, caramel-brown foam swelling gently up to the rim and a few tiny bubbles breaking on its surface. The other two cezves sit a little further back, one with foam just starting to form, one still dark and calm. Beside the tray, on a weathered dark walnut counter: two small white porcelain coffee cups with thin gold rims on matching saucers, a glass of water, a little dish of cubes of rose Turkish delight dusted with powdered sugar, and a hand-cranked brass coffee grinder with fine engraved patterns. A thin curl of steam rises from the front cezve. Warm, low side light from the right, like late afternoon sun through a café window, makes the hammered copper glow and catches every grain of sand; the background falls away into a soft, dark, blurred café interior with a few warm bokeh lights. 85 mm lens, f/2.8, eye level with the cezves, the foam in the front cezve tack-sharp. Rich, warm, inviting coffeehouse mood with natural colors. No people, no hands, no faces, no readable text, signs, labels or logos. Landscape 3:2.
Turn a vague quarter plan into a focused OKR set in YAML: at most 3 objectives with measurable key results (baseline, target, data source, leading indicator), initiatives kept separate, cut ideas with reasons, scoring, and a weekly check-in rhythm that keeps OKRs alive.
1role: >-2 You are a practical OKR coach for startups and small product teams. You help a team turn a3 vague quarter plan into a small set of objectives and measurable key results that people can4 actually remember, influence and check every week. You push back on activity lists disguised5 as key results, on too many objectives, and on numbers nobody can measure yet.67context:8 team: "${team:the 7-person growth and product team of a B2B SaaS startup with 40 employees}"9 company_goal: "${company_goal:reach 1.2 million USD annual recurring revenue by the end of the year, up from 820k today}"10 quarter: "${quarter:Q1 2027, 13 weeks}"...+63 more lines
Get ready for the Q&A after a conference talk: a map of the 15 likely questions, a short answer pattern, model answers for the hardest ones, calm wording for hostile, off-topic or cannot-share questions, a live rehearsal round with feedback and a one-page cheat sheet.
Act as a Conference Talk Q&A Rehearsal Partner. You are an experienced conference speaker and speaking coach who has moderated hundreds of Q&A sessions. You help speakers prepare for the part of a talk they cannot script: the questions from the audience. You know that a good answer is short, honest and useful to the whole room, and that "I don't know, but here is how I would find out" is a perfectly good answer. I want to walk on stage knowing the hardest questions already and feeling calm about the rest. My talk: - Title and topic: Shipping AI Features Without Losing Control, a talk about how a small team added LLM features to a SaaS product with evaluations, guardrails and cost limits - Event and audience: a 600-person developer conference; mostly senior engineers and tech leads, some product managers, a few people from AI vendors - My main message: start with one narrow use case, measure it with real evaluations, and keep a human in the loop until the numbers say otherwise - Length of the Q&A: 10 minutes after a 30-minute talk, with a moderator reading questions from an app and a live microphone - What I am nervous about: questions about cost numbers I cannot share, vendor comparisons, and someone saying our approach is too cautious - What I cannot talk about: customer names, exact revenue, unreleased features - My speaking situation: English is my second language; I get fast and wordy when I am nervous Help me in this order: 1. Quick questions. Ask up to 4 short questions that would change your preparation most (for example the slides' most controversial claim, whether the session is recorded, or who else is speaking on the topic). If I say "skip", continue with sensible assumptions and list them. 2. Question map. Predict the 15 most likely questions for this talk and audience, grouped as: clarifying ("can you go back to..."), deeper technical, skeptical or challenging, "how would this work for us", off-topic, and questions I cannot answer because of my limits. Mark the 5 hardest ones. 3. Answer structure. Teach me one simple pattern for answers under 45 seconds (for example: repeat or rephrase the question, give the direct answer first, one example or number, one sentence that links back to my main message). Show it once with a sample question from the map. 4. Model answers. For the 5 hardest questions, write a model answer in my voice using that pattern, plus a shorter 15-second version for when time is running out. Keep them honest: never invent numbers, and say clearly where I would only be guessing. 5. Difficult situations. Calm, polite wording for: a question I do not understand, a question that is really a long statement, a hostile or "gotcha" question, a question about something I cannot share, a factual mistake I made on a slide that someone points out, a vendor pitching their product at the mic, two people asking at the same time, and silence when nobody asks anything (with 2 "questions I often get" I can ask myself). 6. Bridging without dodging. Show how to move from a question I can only partly answer back to useful ground, and explain the difference between bridging and avoiding the question, so the audience does not feel I am spinning. 7. Rehearsal. Run a live practice round: ask me the questions one at a time, in random order, mixing easy and hard ones, sometimes playing a friendly attendee, a skeptical senior engineer or a rambling commenter. Wait for my answer each time. After each answer, give me exactly 3 short notes: what worked, what to cut, and one sentence I could have said instead. Track my average answer length and tell me if I am getting faster or wordier. 8. Moderator and logistics. A short note I can send the moderator (how I like questions to be read, which topics I cannot discuss, the signal for the last question), and how to handle questions from the app vs. the microphone. 9. After the talk. How to handle the people who come to the stage afterwards, how to promise and actually send follow-up answers, and a 3-line post I can share with links to the slides and the answers I promised. Rules: - Keep everything specific to my talk, audience and limits; no generic public-speaking tips. - Use plain, short sentences because English is my second language, and help me sound natural rather than rehearsed. - Never suggest hiding mistakes, inventing data or attacking the person asking; respectful disagreement is fine. - Remind me to repeat each question into the microphone so the room and the recording can hear it. - End with a one-page Q&A cheat sheet: my answer pattern, the 5 hardest questions with their 15-second answers, 4 polite phrases for difficult moments, my "cannot share" sentence, and 2 self-questions for a silent room.
Turns a nightly sleep diary CSV into clear numbers and patterns: total sleep, time in bed, sleep efficiency, time to fall asleep, regularity, social jet lag between workdays and free days, weekly trends, and flags for late caffeine, long naps, alcohol nights and very short nights. Stdlib Python.
---
name: sleep-diary-pattern-analyzer
description: Turns a nightly sleep diary CSV into clear numbers and patterns: total sleep, time in bed, sleep efficiency, time to fall asleep, regularity, social jet lag between workdays and free days, weekly trends, and flags for late caffeine, long naps, alcohol nights and very short nights. Stdlib Python.
---
# Sleep Diary Pattern Analyzer
You help people who feel they sleep badly look at their own sleep with real numbers instead of impressions. Most people only remember the worst nights. A two- or three-week sleep diary shows what is actually going on: how long they sleep, how much time they lie awake, how much their schedule moves between workdays and weekends, and whether things like late coffee, evening drinks or long naps line up with worse nights. You read the diary, explain the numbers in plain words and suggest a few small, realistic experiments.
You are not a doctor and this is not a diagnosis. A sleep diary is a self-help and conversation tool; sleep clinicians use the same kind of diary, but they combine it with an interview and sometimes tests. Always point people to `references/when-to-get-help.md` when the diary or their description shows warning signs.
## Files in this skill
- `scripts/sleep_diary.py` - reads the diary CSV (times in HH:MM, nights crossing midnight handled automatically), computes per-night time in bed, total sleep, efficiency and sleep midpoint, a summary, a weekly table and flags S01-S10 + E01; `--format text|md|json|csv`, `--since/--until`, `--target-hours`, `--fail-on`, `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/sleep-metrics.md` - what each number means, how it is calculated and typical ranges for adults
- `references/when-to-get-help.md` - warning signs that need a doctor or sleep specialist instead of a spreadsheet, and limits of a diary
- `templates/two-week-sleep-review.md` - a short, friendly review with numbers, patterns and 2-3 experiments
- `examples/sleep_diary.csv` - 3 fictional weeks of an office worker who goes to bed late, drinks coffee in the afternoon on some days and sleeps in on weekends (one row has a typo on purpose)
## Workflow
### 1. Get a diary
If the person has no diary yet, give them the CSV header and ask them to fill one row every morning for at least 14 nights (7 is the minimum for patterns):
```
date,bedtime,sleep_latency_min,awakenings,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type
2026-11-09,23:55,10,2,14,06:50,07:05,0,11:30,0,4,work
```
- `date` = the evening they went to bed (a 00:20 bedtime still belongs to the previous date)
- `bedtime` = when they turned the lights off to sleep; `out_of_bed` = when they actually got up (defaults to `wake_time`)
- `sleep_latency_min` and `awake_min` are guesses, not measurements; rough numbers are fine
- `caffeine_last` = time of the last coffee, tea, cola or energy drink; `quality` = 1 (very bad) to 5 (very good)
- `day_type` = whether the NEXT day is a `work` or `free` day
Data from a sleep tracker or watch works too: export bedtime and wake time and fill the rest by hand.
### 2. Run the analysis
```
python3 scripts/sleep_diary.py sleep_diary.csv
python3 scripts/sleep_diary.py sleep_diary.csv --format md > sleep-review.md
python3 scripts/sleep_diary.py sleep_diary.csv --since 2026-11-16 --target-hours 8
python3 scripts/sleep_diary.py sleep_diary.csv --format csv # per-night table for a spreadsheet
python3 scripts/sleep_diary.py --self-test
```
Exit code 0 = fine (or `--fail-on none`, the default), 1 = flags at or above `--fail-on`, 2 = unreadable file or missing columns.
| Code | Severity | Pattern |
|---|---|---|
| S01 | medium | average sleep efficiency below 85% |
| S02 | medium / high | average total sleep below 7 h / below 6 h |
| S03 | medium | wake-up time varies by more than 60 min (standard deviation) |
| S04 | low / medium | social jet lag of 1 h+ / 2 h+ (free-day sleep midpoint later than on workdays) |
| S05 | medium | average time to fall asleep over 30 min |
| S06 | low | nights with caffeine after 14:00 took 10+ min longer to fall asleep |
| S07 | low | naps over 30 min on 3+ days |
| S08 | low | nights after alcohol had 15+ min more time awake |
| S09 | info | fewer than 7 nights or gaps of 2+ missing nights |
| S10 | medium | 2+ nights with less than 5 h of sleep |
| E01 | medium | rows that could not be read (the line number and reason are shown) |
### 3. Explain and suggest
Use `references/sleep-metrics.md` to explain the numbers in one or two sentences each. Then pick at most three experiments for the next two weeks, linked to the flags, for example:
- S03/S04: the same wake-up time every day, weekends included, within 30-60 minutes; morning daylight soon after waking.
- S06: last caffeine before 14:00 for two weeks, then compare `--since` the start date.
- S07: naps under 30 minutes and before 15:00.
- S01/S05: get up after about 20 minutes awake in bed, do something calm in dim light, return when sleepy.
- S08: compare a few alcohol-free evenings.
The "consistent schedule idea" in the output uses the median workday wake time and `--target-hours`; present it as a starting point, not a rule, and never suggest less than 7 hours in bed on their own.
### 4. Report
Fill `templates/two-week-sleep-review.md`. Keep it kind and concrete; say what went well, too. Repeat the analysis after the experiment period and compare.
## Rules
- Never diagnose (insomnia, sleep apnea, depression, etc.) and never recommend medication, supplements or doses. Refer to a doctor when `when-to-get-help.md` applies.
- Do not recommend strict sleep restriction (shortening time in bed below current sleep) without a clinician; it is a treatment step that needs supervision.
- Diary values are estimates. Talk about patterns over several nights, never about one night.
- Correlation is not cause: "nights with late coffee took longer" is a hint for an experiment, not proof.
- Keep the diary private; it is health data. Do not ask for names or share it outside the conversation.
FILE:references/sleep-metrics.md
# Sleep diary metrics
All values come from the diary, so they are estimates. Look at averages and patterns over at least 7, ideally 14 or more nights.
| Metric | How it is calculated | Typical adult range / meaning |
|---|---|---|
| Time in bed (TIB) | `out_of_bed - bedtime` | Should be close to the sleep you need plus 15-30 min. Much more than that often means lying awake. |
| Time to fall asleep (sleep onset latency) | `sleep_latency_min` | 10-20 min is typical. Regularly over 30 min is a sign of trouble falling asleep (S05). Under 5 min every night can mean sleep debt. |
| Time awake at night (WASO) | `awake_min` | Short awakenings are normal; people rarely remember those under a few minutes. 30+ min per night on average is worth noting. |
| Total sleep time (TST) | `wake_time - (bedtime + latency) - awake_min` | Most adults need 7-9 hours (American Academy of Sleep Medicine, National Sleep Foundation). Below 7 h on average: S02. |
| Sleep efficiency (SE) | `TST / TIB x 100` | 85% or more is usually considered good; below 85% (S01) means a lot of time in bed awake. |
| Sleep midpoint | halfway between falling asleep and waking | A marker of the body clock. Later midpoints = later chronotype or a shifted schedule. |
| Social jet lag | free-day midpoint minus workday midpoint | Like flying one or two time zones every weekend. 1 h+ is common (S04 low), 2 h+ makes Monday mornings much harder (S04 medium). |
| Regularity | standard deviation of bedtime and wake time | Wake time matters most. A spread over 60 min (S03) makes the body clock drift. |
| Quality | the person's 1-5 rating | Subjective, but useful: compare quality with the other numbers. |
## Reading the numbers together
- Short sleep + high efficiency + very short latency: probably not enough time in bed (going to bed too late or getting up very early). Experiment: earlier lights out.
- Normal sleep time + low efficiency + long latency: lots of time awake in bed. Experiments: consistent wake time, get up when awake for long, avoid long naps and late caffeine.
- Good weekday numbers + big social jet lag: the weekend schedule pulls the body clock later; Monday and Tuesday nights then start badly.
- Worse nights after alcohol: alcohol helps people fall asleep but often causes more awakenings in the second half of the night.
## Caffeine and naps
Caffeine has an average half-life of about 5 hours (it varies a lot between people, from about 2 to 10 hours), so an afternoon coffee is still partly active at bedtime. Short naps (10-30 min) before mid-afternoon refresh most people without hurting night sleep; longer or later naps reduce sleep pressure in the evening.
## The "consistent schedule idea"
The script suggests a fixed wake time (the median workday wake time) and a lights-out time that gives `--target-hours` of sleep plus a typical time to fall asleep. It is a starting point for a conversation. Keeping the same wake time every day is the single most useful habit for a regular body clock.
FILE:references/when-to-get-help.md
# When a sleep diary is not enough
A diary helps people notice patterns and try small habit changes. Some situations need a doctor, ideally a general practitioner first, who can refer to a sleep specialist. Recommend getting help, kindly and clearly, when any of these apply:
## See a doctor soon
- Loud snoring with pauses in breathing, gasping or choking at night (noticed by a partner), especially with morning headaches or high blood pressure: possible sleep apnea.
- Strong sleepiness during the day: falling asleep while driving, in meetings or in conversations, even after enough hours in bed.
- Trouble falling or staying asleep at least 3 nights a week for 3 months or more, affecting the day: chronic insomnia has effective treatments, especially cognitive behavioral therapy for insomnia (CBT-I).
- An urge to move the legs in the evening with uncomfortable feelings that get better with movement.
- Acting out dreams, sudden muscle weakness with laughter or strong emotions, or sleep attacks.
- Sleep problems together with low mood, loss of interest, strong anxiety or thoughts of self-harm. If someone mentions thoughts of self-harm, encourage them to contact local emergency services or a crisis line right away.
- Sleep problems that started with a new medication, or that come with pain, breathing problems at night or frequent urination.
- Pregnancy, shift work with accidents or near misses, or a child or teenager with persistent sleep problems: get specific professional advice.
## Never do in this skill
- Diagnose a sleep disorder or rule one out.
- Recommend sleeping pills, melatonin doses, supplements or stopping a prescribed medication.
- Tell someone to drive or work in a safety-critical job when they report strong sleepiness.
## Limits of a diary
- Times are estimates; people often overestimate time awake and underestimate sleep, especially on bad nights.
- Wearable trackers estimate sleep from movement and heart rate; they are fine for bedtime and wake time but not exact for sleep stages.
- A few weeks show habits, not health. Bring the diary and the script's summary to the doctor; clinicians find a filled diary useful.
FILE:templates/two-week-sleep-review.md
# Your sleep review: {{from}} to {{to}} ({{N}} nights)
## The short version
{{2-3 sentences in plain words: how much you sleep, how regular it is, the main pattern, one thing that is already good}}
## Your numbers
| | Your average | Typical range |
|---|---|---|
| Sleep per night | {{6h38}} | 7-9 h |
| Time in bed | {{7h38}} | sleep + 15-30 min |
| Sleep efficiency | {{87%}} | 85% or more |
| Time to fall asleep | {{25 min}} | 10-20 min |
| Wake-up time variation | {{73 min}} | under 60 min |
| Social jet lag | {{1h49}} | under 1 h |
## Patterns we noticed
- {{e.g. On the 7 nights with coffee after 14:00 you needed about 42 minutes to fall asleep, compared with 16 minutes on other nights.}}
- {{...}}
## Experiments for the next two weeks (pick 2-3)
1. {{e.g. Wake up at 06:50 every day, also on weekends (within 30-60 minutes), and get daylight within an hour.}}
2. {{e.g. Last coffee before 14:00.}}
3. {{e.g. Keep naps under 30 minutes and before 15:00.}}
Keep filling the diary, then run the analysis again from {{start date}} and compare.
## Please talk to a doctor if
{{Only if relevant: the warning signs from when-to-get-help.md that apply, written kindly. Otherwise: "Nothing in your diary suggests you need medical help right now, but see a doctor if ..."}}
_This review is based on your own diary estimates and is not medical advice._
FILE:examples/sleep_diary.csv
date,bedtime,sleep_latency_min,awakenings,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type
2026-11-09,23:55,10,2,14,06:50,07:05,0,11:30,0,4,work
2026-11-10,23:10,50,2,14,06:50,07:00,0,16:30,0,2,work
2026-11-11,00:20,15,1,7,06:45,07:00,0,10:00,0,4,work
2026-11-12,23:25,50,1,7,06:50,06:55,40,16:00,0,3,work
2026-11-13,00:55,20,3,50,09:20,09:40,40,08:30,2,3,free
2026-11-14,00:55,10,3,55,09:20,10:00,40,,2,2,free
2026-11-15,00:20,15,2,14,06:45,07:00,0,08:30,0,4,work
2026-11-16,00:20,20,0,0,06:50,07:00,0,,0,4,work
2026-11-17,23:10,40,1,7,06:45,07:00,0,16:30,0,3,work
2026-11-18,23:40,40,1,7,06:45,06:55,0,16:00,0,3,work
2026-11-19,00:20,35,2,14,07:00,07:15,50,16:00,0,2,work
2026-11-20,00:40,10,2,35,09:20,10:00,40,,2,2,free
2026-11-22,23:25,10,2,14,06:45,07:00,0,11:30,0,4,work
2026-11-23,23:40,20,2,14,06:50,07:00,0,08:30,0,4,work
2026-11-24,00:50,40,2,60,06:45,06:55,0,16:30,0,1,work
2026-11-25,01:05,30,1,7,06:45,06:55,0,11:30,0,4,work
2026-11-26,23:25,40,1,7,07:00,07:05,0,16:30,0,2,work
2026-11-27,00:40,20,1,25,10:10,10:30,40,10:00,2,2,free
2026-11-28,01:30,10,3,55,10:10,10:40,50,08:30,2,3,free
2026-11-29,23:40,15,1,7,07:00,07:10,0,10:00,0,4,work
2026-11-30,23:30,15,,10,7:05,,0,,0,,work
2026-12-01,23:15,,1,abc,06:50,07:00,0,09:00,0,4,work
FILE:scripts/sleep_diary.py
#!/usr/bin/env python3
"""sleep_diary.py - turn a simple sleep diary CSV into clear sleep metrics and pattern flags.
One row per night. Required columns: date, bedtime, wake_time. Optional: sleep_latency_min,
awake_min, awakenings, out_of_bed, nap_min, caffeine_last, alcohol_drinks, quality, day_type.
Times are HH:MM (24 h); a night that crosses midnight is handled automatically. date is the
evening you went to bed (YYYY-MM-DD or DD.MM.YYYY). day_type is the NEXT day: work or free.
Per night: time in bed, sleep onset, total sleep time, sleep efficiency, sleep midpoint.
Summary: averages, regularity, workday vs free-day comparison (social jet lag), weekly table,
and flags S01-S10 + E01. Not a medical tool; see references/when-to-get-help.md.
Python 3.8+ standard library only.
Usage:
sleep_diary.py DIARY.csv [--format text|md|json|csv] [--since YYYY-MM-DD] [--until YYYY-MM-DD]
[--target-hours 7.5] [--fail-on high|medium|low|none]
sleep_diary.py --self-test
Exit codes: 0 = no flags at or above --fail-on (default none), 1 = flags at or above it, 2 = bad input.
"""
import argparse, csv, datetime, io, json, statistics, sys
FLAGS = {
"S01": "average sleep efficiency below 85% (a lot of time in bed awake)",
"S02": "average total sleep below the healthy adult range (7 h); below 6 h is high",
"S03": "wake-up time varies a lot (standard deviation over 60 min)",
"S04": "social jet lag: sleep midpoint on free days is 1 h or more later than on workdays (2 h+ is medium)",
"S05": "average time to fall asleep over 30 min",
"S06": "nights with caffeine after 14:00 took clearly longer to fall asleep (10 min+ on average)",
"S07": "long daytime naps (over 30 min) on 3 or more days",
"S08": "nights after alcohol had clearly more time awake (15 min+ on average)",
"S09": "fewer than 7 nights logged, or gaps of 2+ missing nights; patterns are less reliable",
"S10": "2 or more very short nights (under 5 h of sleep)",
"E01": "rows that could not be read",
}
SEV_ORDER = {"high": 3, "medium": 2, "low": 1, "info": 0}
def parse_date(s):
s = (s or "").strip()
for fmt in ("%Y-%m-%d", "%d.%m.%Y", "%d/%m/%Y"):
try:
return datetime.datetime.strptime(s, fmt).date()
except ValueError:
pass
raise ValueError("bad date %r" % s)
def parse_clock(s):
s = (s or "").strip().replace(".", ":")
h, _, m = s.partition(":")
h, m = int(h), int(m or 0)
if not (0 <= h <= 23 and 0 <= m <= 59):
raise ValueError("bad time %r" % s)
return h * 60 + m
def since_noon(clock_min):
"""Minutes since 12:00 on the diary date: 23:30 -> 690, 00:30 -> 750, 07:00 -> 1140.
Assumes bedtimes after 12:00 belong to the evening and times before 12:00 to the next morning."""
return clock_min - 720 if clock_min >= 720 else clock_min + 720
def num(row, key, default=0.0):
v = (row.get(key) or "").strip().replace(",", ".")
try:
return float(v) if v else default
except ValueError:
raise ValueError("bad number %r in %s" % (v, key))
def fmt_clock(m_since_noon):
m = int(round(m_since_noon + 720)) % 1440
return "%02d:%02d" % (m // 60, m % 60)
def hm(minutes):
minutes = int(round(minutes))
sign = "-" if minutes < 0 else ""
minutes = abs(minutes)
return "%s%dh%02d" % (sign, minutes // 60, minutes % 60)
def read_nights(text, since=None, until=None):
nights, errors = [], []
rdr = csv.DictReader(io.StringIO(text))
if not rdr.fieldnames:
raise ValueError("empty file")
cols = {c.strip().lower() for c in rdr.fieldnames if c}
missing = {"date", "bedtime", "wake_time"} - cols
if missing:
raise ValueError("missing required column(s): " + ", ".join(sorted(missing)))
for i, raw in enumerate(rdr, 2):
row = {(k or "").strip().lower(): (v or "").strip() for k, v in raw.items()}
if not any(row.values()):
continue
try:
d = parse_date(row["date"])
if (since and d < since) or (until and d > until):
continue
bed = since_noon(parse_clock(row["bedtime"]))
wake = since_noon(parse_clock(row["wake_time"]))
oob = since_noon(parse_clock(row["out_of_bed"])) if row.get("out_of_bed") else wake
lat, awake = num(row, "sleep_latency_min"), num(row, "awake_min")
onset = bed + lat
if not (bed < wake <= oob) or onset >= wake:
raise ValueError("times out of order (bed %s, wake %s, out of bed %s)" % (row["bedtime"], row["wake_time"], row.get("out_of_bed") or "-"))
tib = oob - bed
tst = wake - onset - awake
if tst <= 0 or tib > 20 * 60:
raise ValueError("implausible night (sleep %.0f min, in bed %.0f min)" % (tst, tib))
caf = row.get("caffeine_last", "")
q = row.get("quality", "")
nights.append({
"date": d.isoformat(), "bedtime": row["bedtime"], "wake_time": row["wake_time"],
"tib_min": tib, "tst_min": tst, "latency_min": lat, "awake_min": awake,
"awakenings": num(row, "awakenings", 0), "efficiency": round(100.0 * tst / tib, 1),
"midpoint": onset + (wake - onset) / 2.0, "wake": wake, "bed": bed,
"nap_min": num(row, "nap_min"), "late_caffeine": bool(caf) and parse_clock(caf) >= 14 * 60,
"alcohol": num(row, "alcohol_drinks") > 0, "quality": int(q) if q else None,
"day_type": (row.get("day_type") or "").lower() or None})
except (ValueError, KeyError) as e:
errors.append({"line": i, "error": str(e)})
nights.sort(key=lambda n: n["date"])
return nights, errors
def mean(xs):
xs = [x for x in xs if x is not None]
return sum(xs) / len(xs) if xs else None
def analyze(nights, errors, target_hours=7.5):
flags = []
def add(code, sev, detail):
flags.append({"code": code, "severity": sev, "detail": detail})
if errors:
add("E01", "medium", "%d row(s): %s" % (len(errors), "; ".join("line %d %s" % (e["line"], e["error"]) for e in errors[:3])))
if not nights:
return {"summary": {"nights": 0}, "nights": [], "weekly": [], "flags": flags}
tst = mean(n["tst_min"] for n in nights)
eff = mean(n["efficiency"] for n in nights)
lat = mean(n["latency_min"] for n in nights)
wake_sd = statistics.pstdev([n["wake"] for n in nights]) if len(nights) > 1 else 0.0
bed_sd = statistics.pstdev([n["bed"] for n in nights]) if len(nights) > 1 else 0.0
work = [n for n in nights if n["day_type"] == "work"]
free = [n for n in nights if n["day_type"] == "free"]
sjl = (mean(n["midpoint"] for n in free) - mean(n["midpoint"] for n in work)) if work and free else None
if eff < 85:
add("S01", "medium", "average efficiency %.1f%%" % eff)
if tst < 360:
add("S02", "high", "average sleep %s" % hm(tst))
elif tst < 420:
add("S02", "medium", "average sleep %s" % hm(tst))
if wake_sd > 60:
add("S03", "medium", "wake time SD %d min" % round(wake_sd))
if sjl is not None and sjl >= 60:
add("S04", "medium" if sjl >= 120 else "low", "free-day midpoint %s later than workdays" % hm(sjl))
if lat > 30:
add("S05", "medium", "average %d min to fall asleep" % round(lat))
lc = [n["latency_min"] for n in nights if n["late_caffeine"]]
nc = [n["latency_min"] for n in nights if not n["late_caffeine"]]
if len(lc) >= 2 and len(nc) >= 2 and mean(lc) - mean(nc) >= 10:
add("S06", "low", "%d min vs %d min to fall asleep (%d late-caffeine nights)" % (round(mean(lc)), round(mean(nc)), len(lc)))
longnaps = [n for n in nights if n["nap_min"] > 30]
if len(longnaps) >= 3:
add("S07", "low", "%d days with naps over 30 min" % len(longnaps))
al = [n["awake_min"] for n in nights if n["alcohol"]]
na = [n["awake_min"] for n in nights if not n["alcohol"]]
if len(al) >= 2 and len(na) >= 2 and mean(al) - mean(na) >= 15:
add("S08", "low", "%d min vs %d min awake at night (%d alcohol nights)" % (round(mean(al)), round(mean(na)), len(al)))
dates = [datetime.date.fromisoformat(n["date"]) for n in nights]
gaps = [(a, b) for a, b in zip(dates, dates[1:]) if (b - a).days >= 3]
if len(nights) < 7 or gaps:
add("S09", "info", "%d nights logged%s" % (len(nights), ("; gaps after " + ", ".join(a.isoformat() for a, _ in gaps)) if gaps else ""))
short = [n for n in nights if n["tst_min"] < 300]
if len(short) >= 2:
add("S10", "medium", "%d nights under 5 h: %s" % (len(short), ", ".join(n["date"] for n in short)))
flags.sort(key=lambda f: (-SEV_ORDER[f["severity"]], f["code"]))
weeks = {}
for n in nights:
y, w, _ = datetime.date.fromisoformat(n["date"]).isocalendar()
weeks.setdefault("%d-W%02d" % (y, w), []).append(n)
weekly = [{"week": k, "nights": len(v), "avg_sleep": hm(mean(x["tst_min"] for x in v)),
"avg_efficiency": round(mean(x["efficiency"] for x in v), 1),
"avg_quality": (round(mean(x["quality"] for x in v), 1) if any(x["quality"] for x in v) else None)}
for k, v in sorted(weeks.items())]
wake_ref = statistics.median([n["wake"] for n in (work or nights)])
summary = {
"nights": len(nights), "from": nights[0]["date"], "to": nights[-1]["date"],
"avg_sleep": hm(tst), "avg_time_in_bed": hm(mean(n["tib_min"] for n in nights)),
"avg_efficiency_pct": round(eff, 1), "avg_latency_min": round(lat), "avg_awake_min": round(mean(n["awake_min"] for n in nights)),
"avg_bedtime": fmt_clock(mean(n["bed"] for n in nights)), "avg_wake_time": fmt_clock(mean(n["wake"] for n in nights)),
"bedtime_sd_min": round(bed_sd), "wake_sd_min": round(wake_sd),
"workday_midpoint": fmt_clock(mean(n["midpoint"] for n in work)) if work else None,
"free_day_midpoint": fmt_clock(mean(n["midpoint"] for n in free)) if free else None,
"social_jet_lag": hm(sjl) if sjl is not None else None,
"avg_quality": round(mean(n["quality"] for n in nights), 1) if any(n["quality"] for n in nights) else None,
"anchor_wake_time": fmt_clock(wake_ref),
"suggested_lights_out": fmt_clock(wake_ref - target_hours * 60 - max(15, min(lat, 30))),
"target_hours": target_hours,
}
return {"summary": summary, "nights": nights, "weekly": weekly, "flags": flags}
def render(res, fmt):
s = res["summary"]
if fmt == "json":
return json.dumps(res, indent=2, default=str)
if fmt == "csv":
b = io.StringIO(); w = csv.writer(b, lineterminator="\n")
w.writerow(["date", "bedtime", "wake_time", "time_in_bed", "sleep", "efficiency_pct", "latency_min", "awake_min", "midpoint", "day_type", "quality"])
for n in res["nights"]:
w.writerow([n["date"], n["bedtime"], n["wake_time"], hm(n["tib_min"]), hm(n["tst_min"]), n["efficiency"], int(n["latency_min"]), int(n["awake_min"]), fmt_clock(n["midpoint"]), n["day_type"] or "", n["quality"] or ""])
return b.getvalue().rstrip("\n")
if not s.get("nights"):
return "No readable nights.\n" + "\n".join(" %s %s" % (f["code"], f["detail"]) for f in res["flags"])
lines = [
("Nights", "%d (%s to %s)" % (s["nights"], s["from"], s["to"])),
("Average sleep", "%s of %s in bed (efficiency %.1f%%)" % (s["avg_sleep"], s["avg_time_in_bed"], s["avg_efficiency_pct"])),
("Falling asleep", "%d min on average; %d min awake during the night" % (s["avg_latency_min"], s["avg_awake_min"])),
("Bedtime / wake time", "%s / %s (variation %d / %d min SD)" % (s["avg_bedtime"], s["avg_wake_time"], s["bedtime_sd_min"], s["wake_sd_min"])),
("Sleep midpoint", "workdays %s, free days %s, social jet lag %s" % (s["workday_midpoint"] or "-", s["free_day_midpoint"] or "-", s["social_jet_lag"] or "-")),
("Quality (1-5)", str(s["avg_quality"] or "-")),
("Consistent schedule idea", "wake at %s every day; lights out around %s for %.1f h of sleep" % (s["anchor_wake_time"], s["suggested_lights_out"], s["target_hours"])),
]
if fmt == "md":
out = ["## Sleep diary summary", "", "| Metric | Value |", "|---|---|"] + ["| %s | %s |" % l for l in lines]
out += ["", "### Weekly", "", "| Week | Nights | Avg sleep | Efficiency | Quality |", "|---|---|---|---|---|"]
out += ["| %s | %d | %s | %.1f%% | %s |" % (w["week"], w["nights"], w["avg_sleep"], w["avg_efficiency"], w["avg_quality"] or "-") for w in res["weekly"]]
out += ["", "### Patterns", ""] + (["- **%s %s** %s - %s" % (f["severity"], f["code"], FLAGS[f["code"]], f["detail"]) for f in res["flags"]] or ["- none"])
out += ["", "_Not medical advice. See when-to-get-help before changing sleep on purpose._"]
return "\n".join(out)
out = ["Sleep diary summary"] + [" %-25s %s" % l for l in lines] + ["", "Weekly"]
out += [" %-9s %d night%s sleep %s efficiency %5.1f%% quality %s" % (w["week"], w["nights"], "" if w["nights"] == 1 else "s", w["avg_sleep"], w["avg_efficiency"], w["avg_quality"] or "-") for w in res["weekly"]]
out += ["", "Patterns"] + ([" %-6s %s %s" % (f["severity"].upper(), f["code"], f["detail"]) for f in res["flags"]] or [" none"])
out += ["", "Not medical advice; see references/when-to-get-help.md."]
return "\n".join(out)
def self_test():
head = "date,bedtime,sleep_latency_min,awake_min,wake_time,out_of_bed,nap_min,caffeine_last,alcohol_drinks,quality,day_type\n"
rows = [
"2026-11-02,23:30,10,10,07:00,07:10,0,09:00,0,4,work",
"2026-11-03,23:45,40,20,07:00,07:15,0,16:30,0,3,work",
"2026-11-04,00:15,15,40,07:00,07:20,45,10:00,2,2,work",
"2026-11-05,23:30,45,15,07:00,07:30,40,17:00,0,3,work",
"2026-11-06,01:30,10,45,09:30,10:00,0,11:00,3,2,free",
"2026-11-07,02:00,10,10,10:30,10:45,60,,0,4,free",
"2026-11-08,23:00,20,10,07:00,07:05,0,08:30,0,4,work",
"2026-11-09,bad,10,10,07:00,,,,,,work",
]
nights, errs = read_nights(head + "\n".join(rows) + "\n")
r = analyze(nights, errs, 7.5)
codes = {f["code"] for f in r["flags"]}
n0 = nights[0]
checks = [
("7 nights read", len(nights) == 7), ("1 error row", len(errs) == 1 and errs[0]["line"] == 9),
("midnight crossing tib", n0["tib_min"] == 460), ("tst", n0["tst_min"] == 430),
("efficiency", n0["efficiency"] == round(100 * 430 / 460, 1)),
("after-midnight bedtime", nights[2]["bed"] == 735 and nights[2]["tst_min"] == 350),
("S04 social jet lag", "S04" in codes), ("S06 late caffeine", "S06" in codes),
("S07 naps", "S07" in codes), ("S08 alcohol", "S08" in codes), ("E01", "E01" in codes),
("S03 wake variation", "S03" in codes), ("no S10", "S10" not in codes),
("clock format", fmt_clock(750) == "00:30" and fmt_clock(1140) == "07:00"),
("hm", hm(430) == "7h10" and hm(-75) == "-1h15"),
("dd.mm.yyyy", parse_date("03.12.2026") == datetime.date(2026, 12, 3)),
("out of order rejected", read_nights(head + "2026-11-02,07:00,10,0,06:00,,,,,,\n")[1] != []),
("md render", render(r, "md").startswith("## Sleep diary summary")),
("csv render", render(r, "csv").count("\n") == 7),
]
bad = [n for n, ok in checks if not ok]
if bad:
print("self-test FAILED:", ", ".join(bad)); print(sorted(codes)); return 1
print("self-test OK: %d checks" % len(checks)); return 0
def main(argv=None):
ap = argparse.ArgumentParser(description="Analyze a sleep diary CSV (stdlib only).")
ap.add_argument("diary", nargs="?")
ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
ap.add_argument("--since"); ap.add_argument("--until")
ap.add_argument("--target-hours", type=float, default=7.5)
ap.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="none")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.diary:
ap.error("give a diary CSV (or --self-test)")
try:
text = sys.stdin.read() if a.diary == "-" else open(a.diary, encoding="utf-8-sig").read()
nights, errors = read_nights(text, parse_date(a.since) if a.since else None, parse_date(a.until) if a.until else None)
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr); return 2
if not 4 <= a.target_hours <= 10:
print("error: --target-hours must be between 4 and 10", file=sys.stderr); return 2
res = analyze(nights, errors, a.target_hours)
print(render(res, a.format))
if a.fail_on == "none":
return 0
return 1 if any(SEV_ORDER[f["severity"]] >= SEV_ORDER[a.fail_on] for f in res["flags"]) else 0
if __name__ == "__main__":
sys.exit(main())
Audits OpenSSH authorized_keys files offline: SHA256 fingerprints like ssh-keygen -lf, weak DSA and short RSA keys, duplicates, missing comments, unrestricted automation keys, expired or loose options, plus keys of people who left or were never known, using an optional owners CSV. Stdlib Python.
---
name: ssh-authorized-keys-auditor
description: Audits OpenSSH authorized_keys files offline: SHA256 fingerprints like ssh-keygen -lf, weak DSA and short RSA keys, duplicates, missing comments, unrestricted automation keys, expired or loose options, plus keys of people who left or were never known, using an optional owners CSV. Stdlib Python.
---
# SSH Authorized Keys Auditor
You help developers, sysadmins and team leads answer a simple question that is surprisingly hard on real servers: who can log in here with a key, and should they still be able to? `authorized_keys` files grow for years. People change laptops and add a new key without removing the old one, contractors finish their projects, a backup host from 2019 still has a 1024-bit RSA key with full shell access, and nobody remembers what `AAAAC3...` without a comment belongs to. You read the files, list every key with its fingerprint, size and owner, and point at the few lines that need action.
You work offline on copies of the files. You never connect to servers, never ask for private keys and never test a key by logging in with it. A finding means "decide about this line", not "this server is compromised".
## Files in this skill
- `scripts/ssh_keys_audit.py` - parses one or more `authorized_keys` files (options with quoted values, key type, base64 blob, comment), computes the SHA256 fingerprint exactly like `ssh-keygen -lf`, reads the real RSA/DSA key size from the blob, and prints findings K01-K12 + E01 with a severity; `--owners` maps keys to people, `--format text|md|json|csv`, `--fail-on` for CI, `--today` for reproducible checks, `--self-test` runs 21 checks (Python 3.8+ standard library only)
- `references/key-types-and-strength.md` - which key types and sizes to accept in 2026, hardware-backed `sk-` keys, and how to replace weak keys without locking anyone out
- `references/authorized-keys-options.md` - `from=`, `command=`, `restrict`, `expiry-time=`, `permitopen=` and friends, with safe patterns for automation keys
- `templates/access-review-report.md` - a short access review report for one server or a fleet
- `examples/authorized_keys` - a fictional `deploy` user on `web-01` with 16 key lines (public keys only; the matching private keys were deleted after generating them)
- `examples/owners.csv` - the owners list for the example, with one person who left and one ended contract
## Workflow
### 1. Collect the files
Copy the files instead of auditing on the live server:
```
scp web-01:/home/deploy/.ssh/authorized_keys ./web-01.deploy.authorized_keys
sudo find /home /root -name 'authorized_keys*' -path '*/.ssh/*' 2>/dev/null # on the server, to find all of them
grep -i AuthorizedKeysFile /etc/ssh/sshd_config /etc/ssh/sshd_config.d/* 2>/dev/null # non-default locations
```
Also check whether `AuthorizedKeysCommand` or SSH certificates (`TrustedUserCAKeys`) are used; keys served that way are not in these files and need a separate review.
### 2. Build or update the owners list (optional, recommended)
`owners.csv` has the columns `match,owner,status,last_review,note`. `match` is either the exact key comment or the `SHA256:` fingerprint (safer, because comments can be edited). `status` is `active`, `left`, `revoked`, `inactive` or `offboarded`. Start with `--format csv` output to get every fingerprint, then fill in owners with the team.
### 3. Run the audit
```
python3 scripts/ssh_keys_audit.py web-01.deploy.authorized_keys
python3 scripts/ssh_keys_audit.py hosts/*.authorized_keys --owners owners.csv --format md > access-review.md
python3 scripts/ssh_keys_audit.py authorized_keys --owners owners.csv --fail-on medium # CI or cron gate
python3 scripts/ssh_keys_audit.py authorized_keys --format csv > key-inventory.csv
python3 scripts/ssh_keys_audit.py --self-test
```
Exit code 0 = nothing at or above `--fail-on` (default high; info never fails), 1 = findings at or above it, 2 = unreadable input or owners file.
| Code | Severity | Meaning |
|---|---|---|
| K01 | high | DSA (`ssh-dss`) key |
| K02 | high | RSA key shorter than 2048 bits |
| K03 | medium | RSA key shorter than `--min-rsa-bits` (default 3072) |
| K04 | medium | the same public key appears more than once (also across files) |
| K05 | low | key without a comment |
| K06 | medium | automation-looking key (ci, deploy, backup, bot, cron, ansible...) with neither `from=` nor `command=` |
| K07 | high | `expiry-time=` already in the past |
| K08 | medium | `command=` key that still allows forwarding or a PTY |
| K09 | high | owner marked left / revoked in the owners file |
| K10 | medium | key not in the owners file |
| K11 | low | owners file review older than `--review-days` (default 365) |
| K12 | info | port forwarding explicitly allowed (`permitopen`, `permitlisten`, `restrict,port-forwarding`) |
| E01 | medium | line that cannot be parsed (truncated paste, bad base64, type mismatch) |
### 4. Decide per finding
Work from high to low with the two reference files:
- K09 and K07: remove the line now, after checking that no running job depends on it; tell the owner's manager.
- K01 and K02: ask the owner for a new Ed25519 key (or `sk-ssh-ed25519` on a hardware key), add it, confirm the login works, then remove the old line.
- K10 and K05: find the owner with the fingerprint (`ssh-keygen -lf`, git history of config management, the team chat). If nobody claims it within the agreed time, disable it by commenting it out first, then remove it.
- K04: keep one line; duplicates often hide a key that was "removed" but still has a second copy.
- K06 and K08: restrict automation keys with `from=` the runner's network and `restrict` plus a forced `command=` when the job only needs one action.
- E01: a broken line is ignored by sshd but often means someone pasted a key wrongly and is now locked out or has a second copy elsewhere.
### 5. Report
Fill `templates/access-review-report.md`: summary counts, the actions table with owner and due date, what was removed, and what is still unknown. Re-run the script after the changes and attach the clean output.
## Rules
- Never ask for, read or store private keys. Public keys and fingerprints are enough for every check here.
- Never remove keys on a live server without a second session open and a tested way back in; removing the wrong key can lock out the only admin.
- Treat the owners file as the source of truth only if someone reviewed it; say when it is old (K11).
- Report what the file says, not guesses about who uses a key. If the owner is unknown, say so.
- Keys in config management (Ansible, Puppet, cloud-init, NixOS) will come back after manual removal; fix them at the source.
FILE:references/key-types-and-strength.md
# Key types and strength (OpenSSH, 2026)
| Type in `authorized_keys` | Verdict | Notes |
|---|---|---|
| `ssh-ed25519` | recommended | Fast, small, fixed 256-bit strength. Default for new keys. |
| `sk-ssh-ed25519@openssh.com` | recommended for admins | Private key lives on a FIDO2 hardware key (YubiKey, SoloKey); a touch is needed for each login. Needs OpenSSH 8.2+ on both sides. |
| `ecdsa-sha2-nistp256/384/521` | acceptable | Fine in practice; some teams prefer Ed25519 for simpler, safer implementations. |
| `sk-ecdsa-sha2-nistp256@openssh.com` | acceptable | Hardware-backed ECDSA for older FIDO keys without Ed25519 support. |
| `ssh-rsa` 3072+ bits | acceptable | Still widely used. 4096 is common. Keep the key, but new keys should be Ed25519. |
| `ssh-rsa` 2048 bits | replace when convenient (K03) | Not broken today, but below the 3072-bit level many policies (NIST, BSI) ask for beyond 2030. |
| `ssh-rsa` below 2048 bits | replace now (K02) | 1024-bit RSA is considered breakable by well-funded attackers. OpenSSH 9.1+ refuses RSA keys below 1024 bits by default (`RequiredRSASize`), and some distributions raise the minimum further. |
| `ssh-dss` (DSA) | replace now (K01) | Fixed 1024-bit size. Disabled by default since OpenSSH 7.0 and removed completely in OpenSSH 10.0; if it still works, the server runs an old or specially configured sshd. |
## The signature algorithm is not the key type
The `ssh-rsa` key type is fine with modern signatures (`rsa-sha2-256`, `rsa-sha2-512`). What OpenSSH 8.8 disabled by default is the old SHA-1 signature algorithm, also called `ssh-rsa`. If very old clients or devices fail to log in after an upgrade, that is usually the reason, not the key itself.
## Fingerprints
`ssh-keygen -lf <file>` prints the size, the SHA256 fingerprint and the comment of every key in a public key or `authorized_keys` file. The fingerprint is the SHA256 hash of the decoded base64 key blob, base64-encoded without `=` padding. The audit script computes the same value, so you can match keys with server logs (`sshd` logs `Accepted publickey for deploy ... SHA256:...`) and with what people see on their laptops (`ssh-keygen -lf ~/.ssh/id_ed25519.pub`).
Older tools show MD5 fingerprints (`ssh-keygen -E md5 -lf ...`, format `aa:bb:...`). Ask for SHA256 to avoid confusion.
## Replacing a weak or old key without lockouts
1. The owner creates a new key on their machine: `ssh-keygen -t ed25519 -C "name@device-2026"` (or `-t ed25519-sk` with a hardware key).
2. They send only the `.pub` file, or the public line, through a channel you trust.
3. Add the new line, keep the old one, and ask them to log in with the new key (`ssh -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes host`).
4. Check the `sshd` log for the new fingerprint, then remove the old line.
5. Update the owners file with the new fingerprint and today's review date.
For automation keys, generate the new key on the machine that uses it (the CI runner, the backup host), never on a laptop, and store the private key only there or in the CI secret store.
## Good comment conventions
Comments are free text and can be changed by anyone who edits the file, so they are hints, not proof. A useful convention is `person-or-service@device-year`, for example `alice@laptop-2026` or `ci-deploy@build-runner`. Match owners by fingerprint when it matters.
FILE:references/authorized-keys-options.md
# authorized_keys options that matter
An `authorized_keys` line is: `[options] keytype base64-key [comment]`. Options are comma-separated; values with spaces or commas are in double quotes, for example `from="10.0.0.0/8,192.168.1.5"`. A line without options gives a full interactive shell with all forwarding allowed, as far as `sshd_config` permits.
## Options checked by the script
| Option | What it does | Typical use |
|---|---|---|
| `from="pattern-list"` | Only accepts the key from matching client addresses or hostnames (CIDR ranges allowed). | Pin automation keys to the CI runner or backup host network. |
| `command="cmd"` | Runs only this command, whatever the client asks for; the original request is in `SSH_ORIGINAL_COMMAND`. | Backup receivers, git-only access, one-purpose jobs. |
| `restrict` | Turns off port, agent and X11 forwarding, PTY allocation and `~/.ssh/rc` in one word (OpenSSH 7.2+). Future restrictions are included automatically. | Start every non-human key with it. |
| `no-port-forwarding`, `no-agent-forwarding`, `no-X11-forwarding`, `no-pty` | The older one-by-one form of `restrict`. | Servers with OpenSSH older than 7.2. |
| `port-forwarding`, `agent-forwarding`, `pty`, `X11-forwarding` | Turn single features back on after `restrict`. | A tunnel key that needs only port forwarding. |
| `permitopen="host:port"` / `permitlisten="port"` | Limit local / remote forwarding to these destinations. | Database tunnels. |
| `expiry-time="YYYYMMDD[HHMM[SS]]"` | sshd refuses the key after this time (OpenSSH 8.2+). | Contractors, temporary support access, break-glass keys. |
| `principals="..."`, `cert-authority` | Used with SSH certificates instead of plain keys. | Fleets that use a CA; review the CA separately. |
## Safe patterns
Human admin with a hardware key:
```
sk-ssh-ed25519@openssh.com AAAA... erin@yubikey
```
CI deploy key that may only run the deploy script from the runner network:
```
from="10.20.0.0/16",restrict,command="/usr/local/bin/deploy.sh" ssh-ed25519 AAAA... ci-deploy@build-runner
```
Backup receiver (only rsync into one directory):
```
restrict,command="/usr/bin/rrsync /srv/backups/web-01" ssh-ed25519 AAAA... backup@backup-02
```
Temporary vendor access for two weeks:
```
expiry-time="20261215",restrict,pty ssh-ed25519 AAAA... vendor-support@contractor
```
Database tunnel only:
```
restrict,port-forwarding,permitopen="localhost:5432" ssh-ed25519 AAAA... db-tunnel@ops
```
## Things that look safe but are not
- `command=` without `restrict` (or the four `no-*` options) still lets the client open port forwards and use agent forwarding: K08.
- Deleting a key from one `authorized_keys` file does not remove it from other users, other servers, golden images or config management.
- `from=` with a hostname depends on reverse DNS; prefer IP ranges.
- An expired `expiry-time` key no longer works, but it shows that the cleanup process is not running: K07.
## sshd_config settings worth checking at the same time
`PubkeyAuthentication yes`, `PasswordAuthentication no`, `PermitRootLogin prohibit-password` or `no`, `AuthorizedKeysFile` (which files are read), `PubkeyAcceptedAlgorithms` (which key types are allowed), and `LogLevel VERBOSE` so logins are logged with the key fingerprint.
FILE:templates/access-review-report.md
# SSH key access review: {{server or fleet}} ({{date}})
Reviewer: {{name}} | Files reviewed: {{count and paths}} | Owners list: {{file, last updated}}
## Summary
- {{N}} keys in {{N}} files; {{N}} high, {{N}} medium, {{N}} low findings
- Key types: {{e.g. 9 ed25519, 2 rsa-4096, 1 rsa-1024, 1 dsa}}
- Verdict: {{clean / actions needed / urgent removals done today}}
## Actions
| # | Finding | Key (comment, fingerprint) | Owner | Action | Due | Done |
|---|---|---|---|---|---|---|
| 1 | {{K09 owner left}} | {{carol@old-macbook, SHA256:...}} | {{manager}} | Remove line | {{today}} | {{yes/no}} |
| 2 | {{K02 RSA 1024}} | {{legacy-backup, SHA256:...}} | {{ops}} | New ed25519 key on the backup host, restrict + command, then remove old | {{date}} | |
| 3 | {{K10 unknown key}} | {{SHA256:...}} | unknown | Ask in {{channel}}; comment out on {{date}}, remove on {{date}} | | |
## Removed today
- {{comment / fingerprint}} - {{reason}} - {{who confirmed}}
## Still unknown
- {{keys nobody claimed yet, and the deadline}}
## Follow-up
- Fix at the source: {{config management repo / image}}
- Next review: {{date}} (re-run `ssh_keys_audit.py --owners owners.csv --fail-on medium`)
FILE:examples/authorized_keys
# /home/deploy/.ssh/authorized_keys on web-01.example.internal (fictional demo; public keys only)
# people
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHFe7WeKd2Owa2Hh2kJr7nzgVZC8s9Ovp1f121uAPFhX alice@laptop-2026
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCnWx5TWWgt37zJmeY9/bLqaQnO0UnBNUQHVfbs5cQdeJ/f/QFHtN2tiK7p0xNF1FhZPFgRsl9UIKjQe3QSSOmX4TIu0y7wWjdfeO160ZQhlPNAh7IK8wvBvFo7g05jwI7P62B+fmvRHz0EL20n7E3fuw9HiRU77sKtdlGvKr/y8mXkFp70FFKtFmQcj53WzHEFCp6KwuJZD4YrI+rcSjULx4ZRyDNF4QJmg4jn1LcUAl7NfyV44Ow0yvZQ5a5d2gKjDbCC3//VINtJrN1eXgp13oFHzFxY3JedFCG0AjxokzIxr8zC/ATsdBPeEV15OQNxwqPb1dSQ/F8n5QznixiwkIi58h7+Zcu3QNhrZNZpjaj7rt+f2cPzMC3CQ+QYp3CmebfATT/tcq4zpVhT5nKPZHuekrxD8BLB1eqk2NNtVqG9bp12kmTcTExk9goR1dVKmGTmiKN4Y6OY5PbLRrVq/vaxBqPZsRt1nmN+tqqk36ONqhAzcSzcTnzMBI0AfzUOj4mmdWcGaJWbO70vMyjKF5gb3OxCecdhw0xwgb5JFiinPVaDZpysA/dViHouz2cBZ6xub5GEqYaitPb6EJnRZWXGAS3Ht+87lnlMTP1Xf6aa93B3b+69CRh0BtpqjDd11SFGHSxAqoGPtM7yWrA0H/mzuCDA5Sh/I5MLJx4kEw== bob@workstation
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3+BmTPsItN0a8fWMCarZW08Kdcm2YJzCJvSc+T38xNvbJapmg4F5GCsw8jI0vuOcTn1h7WV/d0ou/8H4LNinVQ1ozTbjM3FLgXokB5GH05nXsn/uBeiARO/tqQ5/7ZGuOs0im5ubGwwzp113SgsGHQT7vihcwcDSMwYpHQcKOxSPjpN04346VuwA0hUU/CKD8VAg3/Jv4Tx8hPcXMj0iWVTEcXdhGkk9inXgJnTnGKswWvaodO4xo9zz1Ilpt1/vHSasGoDBY69Ix6YelhmQgoNRTZAGUqFR4HbYVS87jlwe2nmBnrswrqHiMphbV0AqCM0dklwiXzxxq/W4yjF9D carol@old-macbook
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBN7PNxyNXn5mvgmJcQJ5XnbF6ecut86YWirOFbgbU4FNdCM926HTQO+WiB5fVv9q4i1Z2IA8T2IlI6OzUjDR4WE= dave@tablet
sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIG51r2VHz7EbQgckgtxTHCvDkHyWF+teUInkAYa6qKV9AAAABHNzaDo= erin@yubikey
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHFe7WeKd2Owa2Hh2kJr7nzgVZC8s9Ovp1f121uAPFhX alice@laptop-2026-copy
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHunuVy30PtFkG0kzjW2DyAijGaDf4mamV1EeC1IVBe9
# automation
from="10.20.0.0/16",restrict ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPayPOBQUnoa7No6o2EaQvGV1rmdcohl25jOvTU+h3pV ci-deploy@build-runner
command="/usr/local/bin/backup-receive",no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC0yY9ApJXN7gLq07iGKSGC5X3mT5xqBjH5XVe35ZhhZ95IGyyV4LyGuoW8W+yHUPj9XbzafPvcaa4r45fmXOY2Avj2IzMdrG3hYBO9w+urhN736J/A5+wSKFAmSShJDbRckmT1Pooph6HBM8AwG2b4iBiV97bQXjbUJoSlQHj4zQ== legacy-backup
ssh-dss AAAAB3NzaC1kc3MAAACBANGlTcoYJTC7HW0TLN7WI3su2R4/ch/LGXEXRJTWSTydXDRgvjEgHmn+2qDu6LmZf1x8KZn9r+WTJTzWVK9N+tcUJ6Cus/7pIy+K8iEfnuSRxbEL7LVWO/web5NCfsvI/ilV5c2ORtyO1LfCdk0qWk12dwb4XYaQAkrWvaNAG+nIAAAAFQCby8zJNfbNH2EiauFTOK4aNABNMwAAAIC6DSRqwEyBsbryPjv57vX3nytJNK+H9VILablLDZguhbtVtnKocmN6zXRm/LYODo/xhGOw5LK6KXA0dPBkrGj3APWwKz3GZvRb3qosyu3NK1FXQQ5N7krys09DCgc0R95jbA6AbJV7poTWQx+16tdCTQnhXQJMWEjyPR+m9zYdfwAAAIBhjRUy5w4g4qZmjef0foRn5UbVPsjioSV72yVsmz5Pu0mBRu9wMMv5U3JS3M6t12S2oy+7Ca3q4QnEqZcgOXU1K4eLFFyKQtiEz0z9py2OHV3ZJYkILYUqcSKHPugFrdWJQhZ6OFKGGVxnn5xplORbirEJgBIHCWHzfeQ23f3JnQ== nagios-check
expiry-time="20261115",restrict ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBGeb7ZdAKvDKvOOZn8CLoctScwVyQuZm3crT8em/UyR vendor-support@contractor
restrict,port-forwarding,permitopen="localhost:5432" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEoW20cIdSsPFUS4NcDnGQl9+ocB6SMvIfKBJod4aXbr db-tunnel@ops
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPzDJ/WTF2UnS6mCm0QG9h/4iTJv+pSS7e7uPGafK/II cron-sync@reports
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7truncated-paste frank@desktop
FILE:examples/owners.csv
match,owner,status,last_review,note
alice@laptop-2026,Alice Kaya (backend),active,2026-09-14,
bob@workstation,Bob Lindqvist (SRE),active,2026-09-14,
carol@old-macbook,Carol Mendes (frontend),left,2026-03-02,left the company 2026-06-30
dave@tablet,Dave Osei (support lead),active,2025-08-20,
erin@yubikey,Erin Novak (security),active,2026-11-01,hardware key
ci-deploy@build-runner,CI pipeline (platform team),active,2026-10-05,
legacy-backup,Backup server (ops),active,2024-11-11,old backup host scheduled for replacement
vendor-support@contractor,Vendor support contract,revoked,2026-11-15,contract ended 2026-11-15
db-tunnel@ops,Ops on-call tunnel,active,2026-10-05,
FILE:scripts/ssh_keys_audit.py
#!/usr/bin/env python3
"""ssh_keys_audit.py - audit OpenSSH authorized_keys files without connecting anywhere.
Reads one or more authorized_keys files (or '-' for stdin), parses options, key type, key blob
and comment, computes the SHA256 fingerprint exactly like `ssh-keygen -lf`, measures RSA key size,
and prints findings K01-K12 (+ E01). Optional --owners CSV maps fingerprints or comments to people
so keys of people who left, unknown keys and overdue reviews are flagged too.
Python 3.8+ standard library only. Never reads private keys; never opens network connections.
Usage:
ssh_keys_audit.py FILE [FILE ...] [--owners owners.csv] [--today YYYY-MM-DD]
[--format text|md|json|csv] [--fail-on high|medium|low|none]
[--min-rsa-bits 3072] [--review-days 365]
ssh_keys_audit.py --self-test
Exit codes: 0 = nothing at or above --fail-on, 1 = findings at or above it, 2 = unreadable input.
"""
import argparse, base64, csv, datetime, hashlib, io, json, re, struct, sys
SEV_ORDER = {"high": 3, "medium": 2, "low": 1, "info": 0}
FLAGS = {
"K01": ("high", "DSA (ssh-dss) key: disabled by default since OpenSSH 7.0 and removed in OpenSSH 10.0"),
"K02": ("high", "RSA key shorter than 2048 bits"),
"K03": ("medium", "RSA key shorter than --min-rsa-bits (default 3072) but at least 2048 bits"),
"K04": ("medium", "same public key appears more than once (in one file or across files)"),
"K05": ("low", "key has no comment, so nobody can tell whose key it is"),
"K06": ("medium", "automation-looking key (comment mentions ci, deploy, backup, bot, cron, ansible...) without from= or command= restriction"),
"K07": ("high", "expiry-time option is in the past (OpenSSH already refuses it, but it is clutter and may hide a gap)"),
"K08": ("medium", "forced command= key still allows forwarding or a PTY (add restrict or no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty)"),
"K09": ("high", "owners file marks this key's owner as left/revoked"),
"K10": ("medium", "key not found in the owners file (unknown key)"),
"K11": ("low", "last review in the owners file is older than --review-days (default 365)"),
"K12": ("info", "agent forwarding or port forwarding explicitly enabled with permitopen/permitlisten - check that it is intended"),
"E01": ("medium", "line could not be parsed (bad base64, unknown type, type mismatch inside the blob)"),
}
KEY_TYPES = {"ssh-ed25519", "ssh-rsa", "ssh-dss", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521",
"sk-ssh-ed25519@openssh.com", "sk-ecdsa-sha2-nistp256@openssh.com"}
CERT_SUFFIX = "-cert-v01@openssh.com"
AUTOMATION = re.compile(r"\b(ci|cd|deploy|deployer|backup|bot|cron|ansible|jenkins|runner|github-actions|gitlab|terraform|svc|service)\b", re.I)
RESTRICT_ALL = {"no-port-forwarding", "no-agent-forwarding", "no-x11-forwarding", "no-pty"}
def split_options(s):
"""Split the leading options field of an authorized_keys line. Returns (options list, rest)."""
opts, cur, i, inq = [], "", 0, False
while i < len(s):
ch = s[i]
if ch == "\\" and inq and i + 1 < len(s):
cur += s[i:i + 2]; i += 2; continue
if ch == '"':
inq = not inq; cur += ch
elif ch == "," and not inq:
opts.append(cur); cur = ""
elif ch in " \t" and not inq:
opts.append(cur); return [o for o in opts if o], s[i:].strip()
else:
cur += ch
i += 1
raise ValueError("options field without a key")
def read_string(blob, off):
if off + 4 > len(blob):
raise ValueError("truncated blob")
(n,) = struct.unpack(">I", blob[off:off + 4])
if off + 4 + n > len(blob):
raise ValueError("truncated blob")
return blob[off + 4:off + 4 + n], off + 4 + n
def mpint_bits(b):
b = b.lstrip(b"\x00")
return 0 if not b else (len(b) - 1) * 8 + b[0].bit_length()
def parse_line(line):
"""Return dict(options, type, blob_b64, comment, bits, fingerprint) or raise ValueError."""
s = line.strip()
first = s.split(None, 1)[0]
if first in KEY_TYPES or first.endswith(CERT_SUFFIX):
options, rest = [], s
else:
options, rest = split_options(s)
parts = rest.split(None, 2)
if len(parts) < 2:
raise ValueError("missing key data")
ktype, b64 = parts[0], parts[1]
comment = parts[2].strip() if len(parts) > 2 else ""
if ktype not in KEY_TYPES and not ktype.endswith(CERT_SUFFIX):
raise ValueError("unknown key type %r" % ktype[:40])
try:
blob = base64.b64decode(b64, validate=True)
except Exception:
raise ValueError("invalid base64 key data")
inner, off = read_string(blob, 0)
if inner.decode("ascii", "replace") != ktype:
raise ValueError("key type %s does not match blob type %s" % (ktype, inner.decode("ascii", "replace")[:40]))
bits = None
if ktype == "ssh-rsa":
_e, off = read_string(blob, off)
n, off = read_string(blob, off)
bits = mpint_bits(n)
elif ktype == "ssh-dss":
p, off = read_string(blob, off)
bits = mpint_bits(p)
elif "nistp" in ktype:
bits = int(re.search(r"nistp(\d+)", ktype).group(1))
elif "ed25519" in ktype:
bits = 256
fp = "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=")
return {"options": options, "type": ktype, "blob_b64": b64, "comment": comment, "bits": bits, "fingerprint": fp}
def opt_map(options):
m = {}
for o in options:
k, _, v = o.partition("=")
m.setdefault(k.lower(), []).append(v.strip('"') if v else True)
return m
def load_owners(path):
rows = []
with open(path, newline="", encoding="utf-8") as f:
for r in csv.DictReader(f):
rows.append({k.strip().lower(): (v or "").strip() for k, v in r.items() if k})
need = {"match", "owner", "status"}
if rows and not need <= set(rows[0]):
raise ValueError("owners CSV needs columns match,owner,status (optional: last_review,note)")
return rows
def find_owner(key, owners):
for r in owners:
m = r["match"]
if m.startswith("SHA256:") and m == key["fingerprint"]:
return r
for r in owners:
m = r["match"]
if not m.startswith("SHA256:") and m and m == key["comment"]:
return r
return None
def parse_date(s):
s = s.strip()
for fmt in ("%Y-%m-%d", "%Y%m%d", "%Y%m%d%H%M", "%Y%m%d%H%M%S"):
try:
return datetime.datetime.strptime(s, fmt).date()
except ValueError:
pass
return None
def audit(files, owners=None, today=None, min_rsa=3072, review_days=365):
today = today or datetime.date.today()
keys, flags, seen = [], [], {}
for name, text in files:
for ln, raw in enumerate(text.splitlines(), 1):
if not raw.strip() or raw.lstrip().startswith("#"):
continue
where = "%s:%d" % (name, ln)
try:
k = parse_line(raw)
except ValueError as e:
flags.append({"code": "E01", "severity": FLAGS["E01"][0], "where": where, "key": None, "detail": str(e)})
continue
k["where"] = where
keys.append(k)
om = opt_map(k["options"])
label = k["comment"] or k["fingerprint"][:20]
def add(code, detail):
flags.append({"code": code, "severity": FLAGS[code][0], "where": where, "key": label, "detail": detail})
if k["type"] == "ssh-dss":
add("K01", "ssh-dss %s bits" % k["bits"])
if k["type"] == "ssh-rsa":
if k["bits"] < 2048:
add("K02", "RSA %d bits" % k["bits"])
elif k["bits"] < min_rsa:
add("K03", "RSA %d bits < %d" % (k["bits"], min_rsa))
if k["blob_b64"] in seen:
add("K04", "same key as %s" % seen[k["blob_b64"]])
else:
seen[k["blob_b64"]] = where
if not k["comment"]:
add("K05", k["fingerprint"])
restricted = "from" in om or "command" in om
if k["comment"] and AUTOMATION.search(k["comment"]) and not restricted:
add("K06", "comment %r has no from= or command=" % k["comment"])
if "expiry-time" in om:
d = parse_date(str(om["expiry-time"][0]))
if d and d < today:
add("K07", "expired %s" % d.isoformat())
if "command" in om and "restrict" not in om and not RESTRICT_ALL <= set(om):
missing = sorted(RESTRICT_ALL - set(om))
add("K08", "forced command without " + ",".join(missing))
if {"permitopen", "permitlisten"} & set(om) or ("restrict" in om and {"port-forwarding", "agent-forwarding"} & set(om)):
add("K12", ",".join(sorted(x for x in om if x in ("permitopen", "permitlisten", "port-forwarding", "agent-forwarding"))))
if owners is not None:
o = find_owner(k, owners)
k["owner"] = o["owner"] if o else None
if o is None:
add("K10", k["fingerprint"])
else:
st = o["status"].lower()
if st in ("left", "revoked", "inactive", "offboarded"):
add("K09", "%s is %s" % (o["owner"], st))
lr = parse_date(o.get("last_review", "")) if o.get("last_review") else None
if lr is None or (today - lr).days > review_days:
add("K11", "last review %s" % (lr.isoformat() if lr else "never"))
def _w(w):
name, _, ln = w.rpartition(":")
return (name, int(ln) if ln.isdigit() else 0)
flags.sort(key=lambda f: (-SEV_ORDER[f["severity"]], f["code"], _w(f["where"])))
count = {s: sum(1 for f in flags if f["severity"] == s) for s in SEV_ORDER}
types = {}
for k in keys:
t = k["type"] + ("-%d" % k["bits"] if k["type"] == "ssh-rsa" else "")
types[t] = types.get(t, 0) + 1
summary = {"files": len(files), "keys": len(keys), "unparsed": sum(1 for f in flags if f["code"] == "E01"),
"by_type": dict(sorted(types.items())), "findings": count, "today": today.isoformat()}
return {"summary": summary, "keys": keys, "flags": flags}
def render(res, fmt):
s, out = res["summary"], []
if fmt == "json":
keys = [{k: v for k, v in x.items() if k != "blob_b64"} for x in res["keys"]]
return json.dumps({"summary": s, "keys": keys, "flags": res["flags"]}, indent=2)
if fmt == "csv":
b = io.StringIO(); w = csv.writer(b, lineterminator="\n")
w.writerow(["where", "type", "bits", "fingerprint", "comment", "owner", "options"])
for k in res["keys"]:
w.writerow([k["where"], k["type"], k["bits"], k["fingerprint"], k["comment"], k.get("owner") or "", ",".join(k["options"])])
return b.getvalue().rstrip("\n")
f = s["findings"]
head = "%d keys in %d file(s), %d unparsed line(s); findings: %d high, %d medium, %d low, %d info" % (
s["keys"], s["files"], s["unparsed"], f["high"], f["medium"], f["low"], f["info"])
types = ", ".join("%s x%d" % kv for kv in s["by_type"].items())
if fmt == "md":
out += ["## SSH authorized_keys audit (%s)" % s["today"], "", "- " + head, "- key types: " + types, "",
"| Sev | Code | Where | Key | Detail |", "|---|---|---|---|---|"]
out += ["| %s | %s | %s | %s | %s |" % (x["severity"], x["code"], x["where"], x["key"] or "-", x["detail"].replace("|", "/")) for x in res["flags"]]
out += ["", "### Keys", "", "| Where | Type | Bits | Fingerprint | Comment | Owner |", "|---|---|---|---|---|---|"]
out += ["| %s | %s | %s | `%s` | %s | %s |" % (k["where"], k["type"], k["bits"], k["fingerprint"], k["comment"] or "-", k.get("owner") or "-") for k in res["keys"]]
return "\n".join(out)
out += ["SSH authorized_keys audit (%s)" % s["today"], "- " + head, "- key types: " + types, "", "Keys"]
for k in res["keys"]:
out.append(" %-28s %-20s %5s %s %s%s" % (k["where"], k["type"][:20], k["bits"], k["fingerprint"][:27] + "...", k["comment"] or "(no comment)",
(" [" + (k.get("owner") or "unknown") + "]") if "owner" in k else ""))
out += ["", "Findings"]
if not res["flags"]:
out.append(" none")
for x in res["flags"]:
out.append(" %-6s %s %-28s %-24s %s" % (x["severity"].upper(), x["code"], x["where"], (x["key"] or "-")[:24], x["detail"]))
return "\n".join(out)
def self_test():
import os, tempfile
def blob(*parts):
return base64.b64encode(b"".join(struct.pack(">I", len(p)) + p for p in parts)).decode()
ed = blob(b"ssh-ed25519", bytes(range(32)))
ed2 = blob(b"ssh-ed25519", bytes(range(1, 33)))
rsa1k = blob(b"ssh-rsa", b"\x01\x00\x01", b"\x00" + b"\xc3" + b"\x11" * 127)
rsa2k = blob(b"ssh-rsa", b"\x01\x00\x01", b"\x00" + b"\xc3" + b"\x22" * 255)
dss = blob(b"ssh-dss", b"\x00" + b"\x99" * 128, b"\x88" * 20, b"\x77" * 128, b"\x66" * 128)
text = "\n".join([
"# comment line", "",
"ssh-ed25519 %s alice@laptop" % ed,
'from="10.0.0.0/8",no-agent-forwarding ssh-ed25519 %s ci-deploy@runner' % ed2,
"ssh-rsa %s old" % rsa1k,
"ssh-rsa %s mid@host" % rsa2k,
"ssh-dss %s legacy" % dss,
"ssh-ed25519 %s" % ed,
'command="/usr/bin/backup.sh",no-pty ssh-ed25519 %s backup-bot' % blob(b"ssh-ed25519", b"\x05" * 32),
'expiry-time="20250101",restrict ssh-ed25519 %s temp@contractor' % blob(b"ssh-ed25519", b"\x06" * 32),
"ssh-ed25519 !!!notbase64 bad",
"ssh-rsa %s mismatch" % ed,
'restrict,port-forwarding,permitopen="db:5432" ssh-ed25519 %s tunnel@ops' % blob(b"ssh-ed25519", b"\x07" * 32),
"ssh-ed25519 %s deploy@ci" % blob(b"ssh-ed25519", b"\x08" * 32)])
owners = [{"match": "alice@laptop", "owner": "Alice", "status": "active", "last_review": "2026-10-01"},
{"match": "old", "owner": "Olga", "status": "left", "last_review": "2024-01-01"}]
r = audit([("t", text)], owners=owners, today=datetime.date(2026, 12, 3))
codes = [f["code"] for f in r["flags"]]
checks = [
("10 keys parsed", r["summary"]["keys"] == 10),
("2 unparsed", codes.count("E01") == 2),
("rsa 1024 bits", any(k["bits"] == 1024 for k in r["keys"])),
("rsa 2048 bits", any(k["bits"] == 2048 for k in r["keys"])),
("K01 dss", "K01" in codes), ("K02 short rsa", codes.count("K02") == 1), ("K03 2048", codes.count("K03") == 1),
("K04 duplicate", codes.count("K04") == 1), ("K05 no comment", codes.count("K05") == 1),
("K06 unrestricted automation only deploy@ci", [f["key"] for f in r["flags"] if f["code"] == "K06"] == ["deploy@ci"]),
("K07 expired", codes.count("K07") == 1), ("K08 forced command partial", codes.count("K08") == 1),
("K09 left", codes.count("K09") == 1), ("K10 unknown", codes.count("K10") == 8),
("K11 stale review", codes.count("K11") == 1), ("K12 permitopen", codes.count("K12") == 1),
("options with quoted comma", split_options('from="a,b",no-pty ssh-ed25519 X')[0] == ['from="a,b"', "no-pty"]),
("fingerprint format", r["keys"][0]["fingerprint"].startswith("SHA256:") and "=" not in r["keys"][0]["fingerprint"]),
("sorted by severity", [SEV_ORDER[f["severity"]] for f in r["flags"]] == sorted([SEV_ORDER[f["severity"]] for f in r["flags"]], reverse=True)),
("md render", render(r, "md").startswith("## SSH authorized_keys audit")),
("csv render", render(r, "csv").splitlines()[0].startswith("where,type,bits")),
]
bad = [n for n, ok in checks if not ok]
if bad:
print("self-test FAILED:", ", ".join(bad)); print(codes); return 1
print("self-test OK: %d checks" % len(checks)); return 0
def main(argv=None):
ap = argparse.ArgumentParser(description="Audit OpenSSH authorized_keys files (offline, stdlib only).")
ap.add_argument("files", nargs="*", help="authorized_keys files, or - for stdin")
ap.add_argument("--owners", help="CSV with columns match,owner,status[,last_review,note]; match = SHA256 fingerprint or exact comment")
ap.add_argument("--today", help="date for expiry/review checks (YYYY-MM-DD), default today")
ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
ap.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="high")
ap.add_argument("--min-rsa-bits", type=int, default=3072)
ap.add_argument("--review-days", type=int, default=365)
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.files:
ap.error("give at least one authorized_keys file (or --self-test)")
files = []
try:
for p in a.files:
files.append(("stdin", sys.stdin.read()) if p == "-" else (p, open(p, encoding="utf-8", errors="replace").read()))
owners = load_owners(a.owners) if a.owners else None
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr); return 2
today = parse_date(a.today) if a.today else None
if a.today and today is None:
print("error: --today must be YYYY-MM-DD", file=sys.stderr); return 2
res = audit(files, owners, today, a.min_rsa_bits, a.review_days)
print(render(res, a.format))
if a.fail_on == "none":
return 0
lim = SEV_ORDER[a.fail_on]
return 1 if any(SEV_ORDER[f["severity"]] >= lim and f["severity"] != "info" for f in res["flags"]) else 0
if __name__ == "__main__":
sys.exit(main())
A timestamped 14-shot, 30-second Seedance storyboard: a white-haired sorceress battles a living ink version of her own shadow through an ancient archive, a fractured sky and a stone altar, with camera moves, VFX and SFX for every shot.
**Title: "The Ink Shadow" (30s, 9:16 or 16:9)** **Shot 1 (00:00-00:02) - WS, Slow Dolly In** In an ancient archive of hanging talismans and bells, a white-haired sorceress paints a glowing sigil on a floating scroll. Her shadow on the wall keeps painting after she stops. VFX: Drifting dust, flickering lantern light. SFX: Paper rustle, soft bells, low hum. **Shot 2 (00:02-00:04) - ECU, Rack Focus** Ink drops rise upward from her brush tip. In the blurred background, her shadow's hand peels off the wall. VFX: Floating ink beads, shadow detaching like wet paint. SFX: Liquid ticks, a distant bell cracking. **Shot 3 (00:04-00:06) - MS, Whip Pan** The shadow tears free as a black ink entity wearing her silhouette. She spins away from its claw and counters with a sweeping brush strike. VFX: Distorted, pulsing ink mist, brush-stroke shockwave. SFX: Whoosh, sharp bell chime. **Shot 4 (00:06-00:08) - CU, Fast Push-in** Her eyes glow cold blue. She flicks her wrist and draws blade-like sigil strokes in mid-air. VFX: Intersecting blue energy lines, afterimage trails. SFX: Sharp air cuts, energy charge. **Shot 5 (00:08-00:10) - WS, Crane Up** Talismans whirl into a vortex and layered sigil rings spin under her feet. The entity slams into the barrier, then sinks through the floor, which turns into a mirror of black ink. VFX: Multi-layer rotating rings, ink-mirror ripples. SFX: Deep resonance, swirling wind. **Shot 6 (00:10-00:13) - MFS, Orbit Tracking** The archive peels away like burning paper, revealing a fractured sky. She steps across floating sigils as her brush stretches into a glowing rune chain that lashes at the entity. VFX: Paper-peel transition, flickering rune-chain light. SFX: Paper tearing, chain clinks. **Shot 7 (00:13-00:16) - LS, Chase Cam** Amid storm clouds and a broken moon, she rides the chain. The entity bursts into a flock of ink crows, and she throws talismans that fold into paper cranes and hunt them. VFX: Rolling clouds, ink crows vs. blue-white paper cranes. SFX: Roaring wind, wing flutter, thunder. **Shot 8 (00:16-00:18) - CU, Lateral Slide** She taps nodes along the chain, lighting hidden purple sigils one by one. The crows are pulled back together into a single body. VFX: Sequential purple node illumination, crows merging. SFX: Light clicks, rising hum. **Shot 9 (00:18-00:20) - MCU, Static** She strikes its forehead in a purple-blue flash and a rotating seal appears on its chest. For one frame, its face becomes hers and smiles. VFX: Flash, rotating seal, face-morph glitch. SFX: Sharp burst, distorted screech, a whisper in her voice. **Shot 10 (00:20-00:22) - WS, Dive Shot** Both streak downward like meteors through the clouds toward an ancient stone altar. VFX: Comet-like trails, cloud shreds. SFX: Air screech, compression. **Shot 11 (00:22-00:24) - WS, Impact (Slow-Motion)** They crash and dust erupts. She slams her palm down and radiating sigils crack across the stone, each fracture glowing for a beat. VFX: Glowing fractures, floating debris. SFX: Heavy impact, stone cracking. **Shot 12 (00:24-00:27) - LS, Slow Pull Back** A massive 3D sigil array rises and forms layered barriers around the entity. She stands calmly outside as it mouths her words back at her. VFX: Expanding geometric barriers, drifting particles. SFX: Low steady resonance, faint echo. **Shot 13 (00:27-00:28) - CU, Static** She forms a hand seal and whispers: "Seal." VFX: Light contracting inward. SFX: Soft chant, energy tightening. **Shot 14 (00:28-00:30) - CU, Fade Out** Eyes closed, she meditates as all light fades. One ink drop falls on the altar, and her shadow on the stone is a half-second late to follow her. VFX: Light dissipating, ink ripple. SFX: Gentle wind, fading echo, silence.

Upload a photo of any city or landmark and turn it into a quiet editorial art print: a realistic 35mm golden-hour photograph on top, a tiny watercolor miniature of the same place below, generous ivory paper space and the caption "CITY IN SOFT LIGHT."
{
"aspect_ratio": "3:4",
"style": "minimalist architectural editorial poster, cinematic photography paired with fine-art print design",
"reference_instructions": {
"use_uploaded_image": true,
"preserve_subject": true,
"preserve_architecture": true,
"preserve_recognizable_landmarks": true,
"preserve_original_composition": false,
"instruction": "Use the uploaded photograph as the primary reference. Accurately preserve the recognizable buildings, architecture, skyline, structures, and distinctive visual identity of the location while transforming it into a sophisticated minimalist poster composition."
},
"composition": {
"layout": "vertical editorial poster",
"structure": "two-part visual composition",
"top_section": {
"size": "approximately 60 percent of the canvas",
"content": "a realistic photographic view of the uploaded location",
"treatment": "warm late-afternoon sunlight, subtle film grain, natural atmospheric perspective, muted cinematic colors",
"framing": "wide architectural composition with the main landmark clearly visible",
"photographic_style": "35mm film photography, realistic textures, natural imperfections, soft sunlight and gentle shadows"
},
"middle_section": {
"transition": "large uninterrupted area of warm ivory textured paper",
"spacing": "generous negative space",
"divider": "no visible hard border, clean separation between photograph and artwork"
},
"bottom_section": {
"size": "approximately 35 percent of the canvas",
"content": "a miniature artistic reconstruction of the same cityscape or architecture",
"placement": "small, centered horizontally and positioned within the lower half",
"scale": "tiny architectural diorama-like composition surrounded by expansive empty space",
"style": "soft watercolor, gouache, muted architectural illustration, slightly faded vintage print",
"details": "retain the recognizable silhouettes and relative positions of the important structures while simplifying minor details"
}
},
"background": {
"color": "warm cream, ivory, pale beige",
"texture": "subtle fine-grain handmade paper texture, delicate fibers, vintage print imperfections",
"appearance": "matte, elegant, tactile, minimal"
},
"color_palette": {
"primary": [
"warm ivory",
"sand beige",
"muted terracotta",
"dusty blue",
"soft gray",
"faded olive"
],
"saturation": "low to moderate",
"grading": "warm nostalgic film color grading"
},
"typography": {
"text": "CITY IN SOFT LIGHT.",
"placement": "centered beneath the miniature illustration",
"font_style": "elegant serif typography",
"letter_spacing": "wide tracking",
"font_size": "small and understated",
"color": "muted dark brown",
"alignment": "center",
"additional_text": "none"
},
"visual_mood": [
"quiet",
"nostalgic",
"minimalist",
"architectural",
"poetic",
"editorial",
"museum-quality"
],
"lighting": {
"photographic_section": "soft golden-hour sunlight",
"illustration_section": "diffused warm light",
"shadows": "gentle and natural"
},
"rendering": {
"photorealism": "high in the upper photograph",
"illustration": "painterly and subtly imperfect in the lower miniature",
"texture": "visible paper grain throughout",
"quality": "premium art print, refined visual storytelling, sophisticated design magazine aesthetic"
},
"constraints": [
"Do not invent or replace the main architecture",
"Do not distort recognizable buildings",
"Keep the upper photograph realistic",
"The lower illustration must depict the same location as the photograph",
"The lower illustration should be significantly smaller than the upper photograph",
"Maintain large amounts of negative space",
"Avoid clutter",
"Avoid excessive decorative elements",
"Avoid modern graphic design clutter",
"No borders",
"No watermark",
"No extra text",
"No logos"
]
}Opinionated Supabase preferences: migrations in git, Row Level Security on every table, generated types, server-side auth, Edge Functions, storage policies and safe key handling.
# Supabase App taste of a full-stack developer who treats Postgres as the real backend
- Manage the schema with Supabase CLI migrations checked into git; never change production tables in the dashboard. Confidence: 0.95
- Run the local stack with supabase start and test every migration locally before pushing it. Confidence: 0.85
- Enable Row Level Security on every table in exposed schemas, including tables you think nobody can reach. Confidence: 1.00
- Write separate RLS policies per operation (select, insert, update, delete) instead of one broad "for all" policy. Confidence: 0.80
- Wrap auth.uid() in a select inside policies and index the columns policies filter on, so RLS stays fast on large tables. Confidence: 0.80
- Test RLS policies with pgTAP or SQL tests that act as different roles and users. Confidence: 0.80
- Never ship the service role key to the browser or a mobile app; use it only in server code and Edge Functions. Confidence: 1.00
- Generate TypeScript types with supabase gen types after each migration and commit them with the schema change. Confidence: 0.85
- Use @supabase/ssr with cookie-based sessions for server-rendered apps, and check the user with getUser() on the server, not getSession(). Confidence: 0.85
- Keep user profile data in a public profiles table keyed by the auth user id, created by a trigger on auth.users. Confidence: 0.80
- Put multi-row business logic in Postgres functions called through rpc, so it runs in one transaction. Confidence: 0.80
- Mark functions security invoker by default and use security definer only with a fixed search_path and a written reason. Confidence: 0.85
- Keep private tables and helper functions in a schema that is not exposed through the API. Confidence: 0.80
- Use Edge Functions for webhooks, third-party API calls and secrets, not for plain CRUD that RLS already covers. Confidence: 0.80
- Store files in private storage buckets with policies tied to the object path, such as a folder per user id. Confidence: 0.85
- Serve private files through short-lived signed URLs rather than making buckets public. Confidence: 0.85
- Subscribe to Realtime only on the tables and filters a screen needs, and remember RLS applies to what clients receive. Confidence: 0.75
- Select only the columns you need in queries instead of select('*'), and paginate with range(). Confidence: 0.80
- Seed local and preview databases from seed.sql with fake data; never copy production data down. Confidence: 0.85
- Use branching or a separate staging project for preview deployments, never the production database. Confidence: 0.80
- Turn on point-in-time recovery for production and practice a restore before you need one. Confidence: 0.75
- Review the Security and Performance Advisors in the dashboard after every schema change. Confidence: 0.75Opinionated Python web scraping preferences: APIs before HTML, polite rate limits, httpx and selectolax, Playwright only when needed, resilient parsing, validation and storing raw pages.
# Python Web Scraping taste of a data engineer who wants scrapers that are polite and boring to maintain - Look for an official API, a sitemap, an RSS feed or the JSON endpoint the page itself calls before parsing any HTML. Confidence: 0.90 - Read the site's terms and robots.txt first, and skip sources that clearly forbid automated access. Confidence: 0.85 - Use httpx with a shared client, connection pooling, timeouts on every request and HTTP/2 when the site supports it. Confidence: 0.85 - Send an honest User-Agent with a contact URL or email instead of pretending to be a browser. Confidence: 0.75 - Rate-limit per domain (for example one request per second by default) and add jittered exponential backoff on 429 and 5xx responses. Confidence: 0.90 - Respect Retry-After headers and stop the run when error rates spike instead of hammering a struggling site. Confidence: 0.85 - Parse HTML with selectolax or lxml and CSS selectors; reach for BeautifulSoup only for small scripts or very broken markup. Confidence: 0.70 - Use Playwright only when content truly needs JavaScript, and block images, fonts and trackers to keep it fast. Confidence: 0.80 - Prefer stable hooks like ids, data attributes and JSON-LD over long positional XPath or styling class names. Confidence: 0.85 - Save the raw response (HTML or JSON) with its URL and fetch time before parsing, so you can re-parse without re-fetching. Confidence: 0.85 - Keep fetching and parsing as separate steps with parser functions that take a string and return plain data, easy to unit test. Confidence: 0.85 - Write parser tests against saved fixture pages and refresh the fixtures when the site changes. Confidence: 0.80 - Validate every scraped record with Pydantic and send records that fail validation to a reject file instead of dropping them silently. Confidence: 0.85 - Normalize prices, dates, currencies and whitespace at parse time into typed fields, keeping the original text alongside. Confidence: 0.75 - Make runs resumable and idempotent: track visited URLs and upsert records by a stable natural key. Confidence: 0.85 - Use conditional requests (ETag, If-Modified-Since) and skip pages that have not changed since the last run. Confidence: 0.70 - Use asyncio with a bounded semaphore for concurrency, never an unbounded gather over thousands of URLs. Confidence: 0.80 - Reach for Scrapy when a project crawls many sites or needs pipelines and scheduling, not for a one-page script. Confidence: 0.65 - Never scrape behind a login or collect personal data unless you have clear permission and a reason to keep it. Confidence: 0.90 - Alert when the record count or the share of empty fields drops sharply; that is how you notice the layout changed. Confidence: 0.85 - Log each request with URL, status code, duration and retry count in structured form. Confidence: 0.75 - Pin dependencies and run scrapers on a schedule in CI or a small container, not from someone's laptop cron. Confidence: 0.75
Opinionated debugging preferences: reproduce first, shrink the failing case, read the real error, bisect, use debuggers and logs deliberately, and lock every fix in with a test.
# Debugging taste of an engineer who would rather prove a cause than guess one - Reproduce the bug reliably before changing any code; a fix for a bug you cannot reproduce is a guess. Confidence: 0.95 - Write down the exact steps, inputs, versions and environment that trigger the bug in the ticket before you start digging. Confidence: 0.85 - Read the full error message and the whole stack trace, starting from the first frame in your own code, before searching the web. Confidence: 0.90 - Shrink the failing case to the smallest input or code path that still fails; most causes become obvious once the noise is gone. Confidence: 0.90 - Turn the reproduction into a failing automated test first, then make it pass, and keep that test forever. Confidence: 0.90 - Use git bisect when something used to work; let the history find the breaking commit instead of reading diffs by hand. Confidence: 0.85 - Change one thing at a time and re-run; never stack several speculative fixes and hope one of them helped. Confidence: 0.90 - State a hypothesis out loud (or in the ticket) before each experiment, and note what result would disprove it. Confidence: 0.75 - Reach for a real debugger with breakpoints and watch expressions over adding a dozen print statements. Confidence: 0.70 - When printing is the right tool, log the values and their types with clear labels, and delete the temporary logs before merging. Confidence: 0.80 - Check your assumptions explicitly with assertions; the bug usually lives in the thing you were sure about. Confidence: 0.85 - Compare a working and a broken environment side by side (config, env vars, dependency versions, data) instead of staring at code. Confidence: 0.80 - Verify you are running the code you think you are running: clear caches, rebuild, and confirm the version or commit in the logs. Confidence: 0.85 - Look at the actual data in the database, queue or API response; do not debug from what the data is supposed to look like. Confidence: 0.85 - Treat flaky tests as real bugs, usually timing, ordering or shared state, and never just add retries to hide them. Confidence: 0.85 - For race conditions, add structured logs with timestamps and request or thread ids, then reconstruct the order of events. Confidence: 0.75 - Read the source of the library or framework when its behavior surprises you; docs describe intent, code describes reality. Confidence: 0.75 - Time-box solo debugging to about an hour, then explain the problem to a teammate or a rubber duck. Confidence: 0.70 - Fix the root cause rather than the symptom, and search the codebase for the same mistake in other places. Confidence: 0.85 - Never debug in production by editing live code; use feature flags, extra telemetry or a copy of the data instead. Confidence: 0.90 - Write a short note in the pull request on the cause, the fix and how it was verified, so the next person learns from it. Confidence: 0.80 - Add the missing log line, metric or error message that would have made this bug obvious, as part of the fix. Confidence: 0.80

Photoreal winter evening in a stone cottage: logs burning in a fieldstone fireplace under an oak mantel with pillar candles, a green velvet armchair with a knitted throw, tea and an open book on a side table, and a small window onto blue dusk. Step 1 of the Cottage Fireplace workflow.
A photorealistic wide photograph of a cozy stone cottage living room on a winter evening, centered on an open fireplace. The fireplace is built of rough grey fieldstone with a thick dark oak beam as the mantel. Inside, a few split birch and oak logs burn on a black iron grate with bright, lively orange and yellow flames and a bed of glowing red embers. A neat stack of firewood sits in a niche to the right of the hearth, and a black iron poker set hangs on the left. On the mantel: three cream pillar candles of different heights with small steady flames, a sprig of dried pine and a small brass clock without readable numbers. In front of the fire, on a braided wool rug, stand a deep green velvet armchair with a chunky knitted cream throw draped over the arm and a low wooden side table holding a ceramic mug of tea and an open hardcover book lying face down. A small window on the left wall shows deep blue dusk outside and still, snow-covered pine branches; nothing moves outside. The room is lit mainly by the warm firelight, which glows on the stones, the rug and the wooden floorboards, while the corners fall into soft blue-grey shadow. 35 mm lens at seated eye level, a few meters back from the hearth, fireplace slightly right of center, everything sharp. Warm, quiet, safe winter-evening mood, natural colors. No people, no animals, no pets, no Christmas tree or ornaments, no television, no readable text or logos. Landscape 16:9.

A top-down photo of a birch bowl hand-painted in Norwegian rosemaling folk art: cobalt-blue ground, swirling acanthus C- and S-scrolls in red, ochre, green and cream, a central rose with tulips, fine white linework, dot accents and a red rim band, on a weathered grey table.
A detailed top-down photograph of a hand-painted wooden bowl decorated in traditional Norwegian rosemaling, the folk art of decorative "rose painting". The shallow round bowl is turned from birch wood and painted with a deep cobalt-blue background. Inside, flowing acanthus-leaf C-scrolls and S-scrolls swirl around the center in confident brushstrokes of warm red, ochre yellow, soft green and cream, with fine white and black linework outlining each leaf and petal. At the center sits a stylized open rose surrounded by small tulips and round blossoms, each petal shaded from dark to light with a single loaded brushstroke. Tiny dots and teardrop accents fill the gaps, and a thin painted red band with a simple ochre dot pattern runs around the rim. The paint has a slightly glossy varnished sheen, with subtle brush ridges and faint signs of age: a few tiny worn spots on the rim show the pale wood underneath. The bowl rests on a weathered pale grey wooden table, with a folded natural linen cloth and two small dried flower stems at one edge of the frame. Soft, even daylight from above, gentle shadow around the bowl, rich but natural colors, everything sharp from rim to center. Calm, crafted, Scandinavian folk-art mood. No people, no hands, no brushes or paint pots, no readable text, letters, signatures or logos. Square 1:1.

Turn any character into an antique scientific-journal plate: watercolor and ink full-body study with costume details, magnified accessory sketches and sepia handwritten annotations. Fill in [character], [outfit] and [pose].
A detailed character study of [character], illustrated in the style of 19th-century scientific journals, [outfit], [pose], full-body anatomical proportions, delicate ink linework, hand-painted watercolor, natural pigments, detailed costume studies, magnified accessory sketches, fine leader lines, handwritten annotations in sepia ink, elegant scientific plate composition, antique scholarly aesthetic, clean white background
A rapid 14-cut, timestamped 30-second Seedance 2.5 duel scene: a towering samurai duelist fights assassins on a stormy vermilion shrine terrace, rendered as moving gouache concept art, with audio design and inline negatives.
Cinematic 2.5D animation in the style of fully painterly rendering, characters and environments look like gouache concept-art paintings in motion, visible brush texture on skin, cloth and buildings, flat posterized color blocks with hard-edged light shapes, matte finish, soft filmic volumetric lighting, shallow depth of field. NOT flat 2D cartoon, NO bold black outlines, NO cel-shading, NOT glossy CGI, NOT Unreal Engine, NO photorealism, no plastic skin. CHARACTER: Lady Kureha, a 10-heads-tall adult female samurai duelist. Sleek black hair in an architectural looped bun, pointed ears with red tassel earrings, plunging dark-navy halter top with gold bell charms, exposed athletic midriff, draped oversized navy sleeves, asymmetrical high-slit skirt, black geta sandals, wielding a long curved katana. SETTING: The Vermilion Moon Terrace. Stormy coastal wooden platforms and red torii frames over crashing ocean waves under cold midnight moonlight and swaying paper lanterns. CINEMATOGRAPHY & RAPID 14-CUT DUEL CHOREOGRAPHY (EXACTLY 30 SECONDS): 00:00-00:02.0 (Shot 1 | Macro Chimes): Extreme macro close-up on the three gold bell charms at her ribcage vibrating in the gale; a sharp mechanical thumb flick clicks open the katana tsuba with a cold specular glint. 00:02.0-00:04.0 (Shot 2 | Runway Stride): Ground-level tracking shot; black geta heels click rhythmically on wet black-lacquered planks, high-slit skirt parting along her bare leg, oversized navy sleeves billowing wide like dark wings. 00:04.0-00:06.0 (Shot 3 | Face & Gaze): Low-angle push-in on Kureha's face; black bangs whip in the wind, red tassel earrings sway, lips parting into a razor-thin, bloodthirsty smirk. 00:06.0-00:08.0 (Shot 4 | The Ambush): Wide shot; four armored assassins leap from the torii rafters; rain and lanterns swing wildly in the storm. 00:08.0-00:10.5 (Shot 5 | Battoujutsu Crescent): Speed-ramp tracking; Kureha unsheathes her katana in a blinding 360-degree horizontal sweep, carving a flat-painted white crescent wind arc that severs enemy spears in half. 00:10.5-00:12.5 (Shot 6 | Fluid Sidestep): Reverse tight cut; she pivots on one high-heeled sandal, her navy sleeves swirling in slow-motion as an enemy blade grazes inches past her exposed midriff. 00:12.5-00:14.5 (Shot 7 | The Counter Thrust): Low-angle strike; Kureha drives the pommel of her blade into an attacker's jaw with a bone-shattering crack, sending him flying into the stormy sea below. 00:14.5-00:16.5 (Shot 8 | Aerial Cleave): Mid-air tracking cut; she leaps off a wooden balustrade, descending with a two-handed overhead slash that cleanly parts the rain and shatters the wooden decking. 00:16.5-00:18.5 (Shot 9 | Bell Chime Resonation): Extreme macro on the gold bells; the kinetic shockwave rings them with a high-pitched sonic chime that sends a visible distortion wave across the frame. 00:18.5-00:21.0 (Shot 10 | Phantom Dash): Supersonic blur; Kureha weaves through the remaining two foes in a zig-zag dash, leaving flat-painted crimson ribbon trails through the dark. 00:21.0-00:23.5 (Shot 11 | Simultaneous Collapse): Wide shot; Kureha slides to a halt with back turned; both remaining assailants collapse into the surf behind her simultaneously. 00:23.5-00:25.5 (Shot 12 | The Blood Flick): Fluid wrist snap; Kureha flicks rainwater and blood off the steel in one crisp, effortless gesture, her draped sleeves settling heavily. 00:25.5-00:27.5 (Shot 13 | The Sheath Click): Macro on the scabbard mouth; the katana blade smoothly glides home with a distinct metallic *chink*, locking into place. 00:27.5-00:30.0 (Shot 14 | Poster Hero Frame): Locked extreme low-angle hero shot; Kureha stands tall on the terrace edge under the full moon, resting the sheathed nodachi on her shoulder, wind howling through her black hair as the gold bells chime softly in the stillness. Hold for 2.5 seconds. clear three-layer depth: foreground wet balustrades and lantern ropes cropped in silhouette, Kureha fully resolved in midground with maximum value contrast, background crashing ocean breakers and stormy sky dissolved in 80% nocturnal haze. Weighty natural character animation, cloth, long hair, and tassels reacting to violent coastal gales. AUDIO DESIGN: Howling ocean gale, sharp metallic sword draw shing, resonant golden bell chimes, wooden deck foot-clicks, sonic-boom air cleaves, splashing ocean spray, final scabbard click decaying into quiet wind. PROHIBITIONS (INLINE NEGATIVES): Sluggish pacing, less than 14 cuts, male chest, teenager proportions, cute expressions, photorealism, glossy CGI render, smooth 3D plastic skin, anime cel outlines, lineart, camera drift, extra limbs. 100% stylized 2D gouache painting.
Opinionated preferences for handling user file uploads safely: presigned direct uploads, size and type checks, malware scanning, storage keys, image processing and cleanup.
# File Upload Handling taste of a backend engineer who treats every upload as untrusted - Upload large files directly from the browser to object storage with presigned URLs instead of streaming them through the app server. Confidence: 0.90 - Keep presigned upload URLs short-lived (minutes) and scoped to one object key, content type and maximum size. Confidence: 0.90 - Enforce a maximum file size on the server or storage policy, never only in client-side JavaScript. Confidence: 0.95 - Generate storage keys yourself (for example UUIDs under a tenant prefix); never use the user's filename as the path. Confidence: 0.95 - Store the original filename only as sanitized metadata in the database for display and download names. Confidence: 0.85 - Detect the file type from its magic bytes and check it against an allowlist; do not trust the extension or the Content-Type header. Confidence: 0.90 - Keep uploaded files in a private bucket and serve them through short-lived signed download URLs or an authorized proxy. Confidence: 0.90 - Serve user files from a separate domain with Content-Disposition: attachment for risky types so uploaded HTML or SVG cannot run on your origin. Confidence: 0.85 - Scan uploads for malware asynchronously and keep them in a quarantine state until the scan passes. Confidence: 0.80 - Track each upload as a database row with a status (pending, uploaded, scanned, ready, failed) instead of guessing from storage. Confidence: 0.85 - Confirm completion with a server callback or storage event before attaching the file to a record. Confidence: 0.80 - Use multipart or resumable uploads (S3 multipart, tus) for files over roughly 100 MB. Confidence: 0.75 - Re-encode images server-side, strip EXIF metadata including GPS, and generate fixed thumbnail sizes in a background job. Confidence: 0.85 - Reject or carefully sanitize SVG uploads; treat them as code, not images. Confidence: 0.85 - Store a checksum (SHA-256) for each file to detect corruption and deduplicate when it makes sense. Confidence: 0.70 - Set lifecycle rules that delete abandoned pending uploads and incomplete multipart parts after a day or two. Confidence: 0.85 - Delete files from storage when the owning record is deleted, through a background job that retries. Confidence: 0.80 - Rate-limit upload endpoints per user and per IP, and cap total storage per account. Confidence: 0.80 - Never unzip or parse archives and office documents in the request path; do it in a sandboxed worker with size and depth limits. Confidence: 0.85 - Show upload progress and allow cancel in the UI, with clear errors for wrong type or size. Confidence: 0.75 - Log upload metadata (user, key, size, type, status) but never the file content. Confidence: 0.85 - Test uploads with oversized files, renamed executables, polyglot files and filenames with path traversal characters. Confidence: 0.85
Opinionated preferences for writing readable, correct and fast SQL: formatting, CTEs, joins, NULL handling, window functions, parameters and query plans.
# SQL Query Writing taste of a data-minded engineer who wants queries others can read and trust - Write SQL keywords in uppercase and identifiers in snake_case lowercase, one clause per line. Confidence: 0.80 - Put each selected column on its own line with a leading or trailing comma style used consistently across the repo, enforced by sqlfluff. Confidence: 0.75 - Never use SELECT * in application queries or views; list the columns you need. Confidence: 0.90 - Use explicit JOIN ... ON syntax; never comma joins with conditions in WHERE. Confidence: 0.95 - Give every table a short, meaningful alias and qualify every column once more than one table is involved. Confidence: 0.85 - Break long queries into named CTEs that read top to bottom like steps, instead of nesting subqueries three levels deep. Confidence: 0.85 - Check the grain of a query before joining: know what one row means and confirm joins do not fan out rows. Confidence: 0.90 - Prefer EXISTS over IN with a subquery for existence checks, and NOT EXISTS over NOT IN to avoid the NULL trap. Confidence: 0.85 - Treat NULL deliberately: use IS NULL, COALESCE with a documented default and IS DISTINCT FROM for null-safe comparisons. Confidence: 0.90 - Use window functions (ROW_NUMBER, LAG, SUM OVER) for rankings, deduplication and running totals instead of self-joins. Confidence: 0.85 - Filter on half-open date ranges (created_at >= start AND created_at < end) rather than BETWEEN on timestamps. Confidence: 0.90 - Keep predicates sargable: do not wrap indexed columns in functions or casts inside WHERE. Confidence: 0.85 - Always pass values as bound parameters; never build SQL by concatenating user input. Confidence: 1.00 - Use COUNT(*) for row counts and COUNT(column) only when you mean non-null values. Confidence: 0.80 - Put conditions for outer-joined tables in the ON clause, not the WHERE clause, so a LEFT JOIN stays a LEFT JOIN. Confidence: 0.90 - Use CASE expressions with an explicit ELSE so unexpected values are visible instead of silently NULL. Confidence: 0.75 - Add ORDER BY whenever order matters, including with LIMIT; never rely on the natural row order. Confidence: 0.95 - Paginate large result sets with keyset pagination (WHERE id > last_id) instead of big OFFSET values. Confidence: 0.80 - Run EXPLAIN ANALYZE on any query that touches a large table before shipping it, and keep the plan in the pull request. Confidence: 0.80 - Prefer UNION ALL over UNION unless you actually need duplicate removal. Confidence: 0.85 - Write data-changing statements inside a transaction and check the affected row count before committing. Confidence: 0.90 - Comment the business rule behind non-obvious filters, not what the SQL syntax does. Confidence: 0.75 - Keep reusable queries in version-controlled .sql files or views with tests on small fixture data. Confidence: 0.70
Opinionated htmx preferences for server-rendered web apps: hypermedia endpoints, partial templates, swaps, forms, history, CSRF and when to add a little JavaScript.
# htmx Web App taste of a backend developer who wants interactivity without a SPA - Render HTML on the server and use htmx for interactivity before reaching for React or another client-side framework. Confidence: 0.85 - Make every page work as plain links and forms first, then layer hx-get, hx-post and hx-boost on top as progressive enhancement. Confidence: 0.85 - Return HTML fragments from endpoints, never JSON that the client has to turn into markup. Confidence: 0.90 - Keep fragments as small partial templates that the full page template also includes, so there is one source of markup per component. Confidence: 0.90 - Check the HX-Request header on the server to decide between returning a fragment and the full page for the same URL. Confidence: 0.85 - Prefer hx-target with a stable id and hx-swap="outerHTML" so the swapped element can be swapped again later. Confidence: 0.80 - Use hx-push-url for navigation-like swaps so the back button and shareable URLs keep working. Confidence: 0.85 - Put hx-boost="true" on the body or main nav for cheap SPA-like navigation instead of wiring every link by hand. Confidence: 0.70 - Use hx-swap-oob for secondary updates such as a cart count or flash message instead of a second request. Confidence: 0.75 - Trigger client events from the server with the HX-Trigger response header rather than inline script in fragments. Confidence: 0.80 - Show progress with hx-indicator and the htmx-request CSS class; no hand-written loading-state JavaScript. Confidence: 0.85 - Add hx-disabled-elt on submit buttons so double clicks cannot post a form twice. Confidence: 0.80 - Validate forms on the server and re-render the form fragment with inline errors and the user's values kept. Confidence: 0.90 - Use hx-trigger="keyup changed delay:300ms" for live search, and cancel stale requests with hx-sync. Confidence: 0.80 - Send the CSRF token for every non-GET request through hx-headers on the body or a hidden form field. Confidence: 0.95 - Escape all output in templates by default and never swap in user-supplied HTML. Confidence: 0.95 - Return 422 with the re-rendered form on validation errors and configure htmx to swap that response. Confidence: 0.75 - Use HX-Redirect or HX-Location after a successful POST instead of returning a page fragment for the next screen. Confidence: 0.75 - Keep small client-only behavior (toggles, dropdowns, copy buttons) in Alpine.js or a few lines of vanilla JS, not in extra round trips. Confidence: 0.70 - Vendor a pinned htmx file or load it with a subresource integrity hash; no unpinned CDN script tags. Confidence: 0.85 - Avoid hx-on handlers with long inline scripts; move logic into a small named JS function. Confidence: 0.75 - Test endpoints by asserting on returned HTML with a parser, and cover the main flows with Playwright end-to-end tests. Confidence: 0.80 - Reach for a client-side framework only for genuinely app-like screens such as rich editors or offline-first views. Confidence: 0.70

Photoreal winter comfort food: a steaming ceramic bowl of velvety red lentil soup with a red-pepper butter swirl and dried mint, lemon wedges, torn sesame bread, a tulip glass of black tea and scattered lentils on a rustic table in cool window light.
A photorealistic food photograph of a steaming bowl of smooth red lentil soup on a rustic wooden kitchen table on a winter afternoon, seen from a 45-degree angle. The soup is a velvety warm orange, finished with a swirl of melted butter infused with red pepper flakes, a pinch of dried mint and a few drops of olive oil glistening on the surface. Thin wisps of steam rise from the bowl. The bowl is a hand-thrown ceramic bowl with a matte cream glaze and a slightly uneven rim, standing on a folded linen napkin in faded blue. Around it: two lemon wedges on a small plate, a wooden board with a torn round of crusty bread with a golden, sesame-sprinkled crust and a soft open crumb, a vintage spoon resting beside the bowl, a small glass of black tea in a tulip-shaped glass on a saucer, and a few red lentils scattered loosely on the table. Soft cool daylight comes from a window on the left and meets the warm color of the soup; gentle shadows fall to the right. In the softly blurred background, a frosted window pane and the hint of a bare winter branch outside. 50 mm lens, f/2.8, the soup surface and the butter swirl tack-sharp, the bread and tea glass slightly soft. Natural colors, cozy and nourishing winter mood, editorial cookbook style. No people, no hands, no faces, no readable text, labels or logos. Landscape 4:3.