Loryth Health¶
Health keeps each person's symptoms, episodes, remedies and daily records. All records are private to the signed-in user. It summarizes what was recorded; it does not diagnose or recommend treatment.
Medicines have one dose log and one stock count, whether taken for a symptom or on their own. See Medicines for schedules, stock and phone routes.
Symptoms and episodes¶
A person starts with no symptoms. They name the symptoms they want to track, put them in an order, and archive those they no longer track. Names are trimmed, 1–120 characters, unique for that person ignoring case, including archived names. Archiving keeps history and existing open episodes; it prevents new episodes and remedy uses. Existing episodes may still be edited and ended.
An episode starts and may later end. Each symptom can have one open episode. An episode may start without an intensity reading. Each reading has an aware at timestamp and an intensity from 1 to 10. Omitted reading times default to the episode start on create/details replacement, or now for an appended reading. Readings sort by time. intensity is the latest, peak the highest; both are null before any reading. Peak statistics skip episodes without readings. Finished episodes contribute to duration statistics even without a reading.
tags describe how or where it shows; triggers describe what may have set it off. Each list allows at most 20 labels of 1–40 characters, trimmed and listed once. Matching is case sensitive after trimming. Notes allow 2,000 characters. Suggestions count one occurrence per episode and sort by count descending, then label alphabetically. Suggestions include past episodes of archived symptoms.
API conventions¶
Routes below are relative to /api/v1/health. Successful responses use {"status":"success","data":...}; DELETE returns 204 without a body. UUIDs that are missing or belong to someone else return 404, including nested ids. Unknown request keys are rejected. Domain rule errors return 422 with a string code in detail; field errors use FastAPI's usual list. Event revision conflicts return 409 with {"detail":{"code":"revision_conflict","event":Event}}. Creating or reopening a second open episode returns 409 with code open_episode_exists and the existing event.
| Method and route | Request | Response data |
|---|---|---|
GET /symptoms | — | Symptom[], ordered by order, then creation id |
POST /symptoms | SymptomBody | Symptom, 201 |
GET /symptoms/{uuid} | — | Symptom |
PUT /symptoms/{uuid} | SymptomBody, replaces all editable fields | Symptom |
GET /symptoms/{uuid}/labels | — | {tags:[{label,count}],triggers:[{label,count}]} |
GET /symptoms/{uuid}/episodes?from=&to=&tz= | Inclusive local dates, at most 366 days | EpisodeSummary |
GET /symptoms/{uuid}/episodes/{episode_uuid}/context | — | EpisodeContext |
POST /events | CreateEvent | Event, 201 |
GET /events/{uuid} | — | Event |
PATCH /events/{uuid} | EventUpdate | Event |
DELETE /events/{uuid} | — | 204; remedy uses and doses stay, with the episode link cleared |
SymptomBody is {name,order:0,archived:false}; only name is required. Symptom adds uuid. Archive with PUT; there is no symptom deletion route.
CreateEvent is {type,started_at?,ended_at?,source:"app",details}. source may be app or chat; only watch uploads can create watch events. Times are aware ISO 8601 timestamps. Start defaults to now. Episodes also require symptom_uuid; their details may be omitted entirely.
| Event type | Shape | Details (all store schema_version:1) |
|---|---|---|
episode | Open or finished span | {intensity_updates:[],tags:[],triggers:[],note:null} |
water | Point | {amount_ml} (1–5000) |
coffee | Point | {drink:"Coffee"} |
sleep | Finished span, over 0 and at most 24 hours | {quality:null,stages:null,stage_spans:null} |
stress | Point | {level,note:null}; level 1–5 |
Event has uuid,type,symptom_uuid,started_at,ended_at,details,source,revision, created_at,updated_at,duration_minutes,intensity,peak. symptom_uuid is null for daily tracker events. Point events have no end or duration. Episode durations use now while open. Sleep event duration is the original session's elapsed time.
EventUpdate requires expected_revision and may set started_at, ended_at (null reopens an episode), full replacement details, or intensity_update:{at?,intensity}. Each update increments revision. Deleting an episode clears links on its uses and increments their revisions, keeping doses and stock as recorded.
EpisodeSummary is {from,to,episodes,days,stats,patterns}. episodes are Events with local_date, newest first. days are {date,peak,remedy}, oldest first. remedy means a use that day or linked to an episode starting that day. stats is {episode_days,days_in_range,average_minutes,longest_minutes, median_peak,severe_count,remedy_days}. Severe means peak at least 7. Days in range stop at today. Patterns compare episode days with other recorded days in the 60 days ending at the range end, capped at today. They are null before 8 episode days; missing tracker data never counts as zero. Patterns are {window_days,episode_days,other_days,rows:[{metric,episode_days,other_days}]}; metrics are sleep_before_minutes, coffee_by_14, water_ml_by_14, stress_max.
EpisodeContext is {sleep_minutes,sleep_average_minutes_30d,coffee_count, last_coffee_at,water_ml,latest_stress,uses}. It uses the 24 hours before the episode start, the preceding 30 nights for the sleep average, and all uses linked to that episode. latest_stress is an Event or null.
Remedies and uses¶
A remedy is one of the person's medicines or a short action (1–120 characters), listed for one symptom. The first use adds it to that list; explicitly adding it without using it is also supported. The same medicine or action is listed once per symptom. Actions match ignoring case after trimming.
| Method and route | Request | Response data |
|---|---|---|
GET /symptoms/{uuid}/remedies | — | Remedy[] in creation order |
POST /symptoms/{uuid}/remedies | {medicine_uuid} or {action} | Remedy, 201; an existing match is returned |
GET /symptoms/{uuid}/uses | — | Use[], newest first |
POST /symptoms/{uuid}/uses?tz= | UseBody | Use, 201 |
PATCH /symptoms/{uuid}/uses/{use_uuid}?tz= | {expected_revision,helped?,used_at?} | Use |
DELETE /symptoms/{uuid}/uses/{use_uuid} | — | 204; removes the dose and restores its amount to stock |
UseBody chooses exactly one of remedy_uuid, medicine_uuid, or action. It may add episode_uuid (of the same symptom), used_at (defaults to now), amount (medicine units, default 1, quarter steps 0.25–100), helped (yes, partly, no, unsure, or null), source (app, chat, phone, default app). A use without an episode is allowed. A medicine use creates one as-needed dose through DoseLedger in the same transaction, using the local day of used_at in tz. It can use a scheduled medicine outside its planned times without answering a planned dose. Do not also record that intake through /medicines/doses. An action use has no dose; its amount is ignored.
Use is {uuid,remedy_uuid,episode_uuid,dose_uuid,used_at,helped,amount,revision}. amount is null for an action. PATCH requires expected_revision and at least one of helped or used_at; either may be changed alone or both together. Omitted fields stay unchanged; null helped clears the outcome. used_at must be a non-null, timezone-aware instant. When it changes, a future instant returns 422 used_at_in_future (without a grace period). A time before the linked episode started returns used_at_before_episode; a time after a finished episode ended returns used_at_after_episode. The episode boundaries are inclusive. These errors use a string code in detail and leave the use and dose unchanged. For a medicine use, DoseLedger moves the same dose's taken_at and local day (in tz, default UTC) in the same transaction, preserving its amount and stock. An outcome-only edit keeps the dose's time and day. Every accepted PATCH increments the use revision, including an unchanged value. Stale use revisions return 409 with {"detail":{"code":"revision_conflict","use":Use}}.
Remedy is {uuid,medicine_uuid,name,strength,action,use_count,outcomes, latest_outcome}. Medicine remedies use the medicine's current name and strength; actions use their text as name. outcomes has a count for each of the four answers, with unanswered uses excluded. latest_outcome is the answer from the latest use with an answer, or null. use_count includes unanswered uses. Deleting a medicine or undoing its dose also removes its linked uses.
Days, amounts and sleep¶
Watch day uploads accept steps_hours:[{hour,steps}] alongside the independent daily steps total. Hours are local clock hours 0–23, unique within a day; steps are nonnegative integers. Up to 24 hours are accepted. The phone sums repeated clock hours when daylight saving time ends. Unrecorded hours are absent rather than zero. The daily figure always uses steps, since Health Connect's daily and hourly aggregations can differ.
DayMeasure returns steps_hours sorted by hour alongside heart_rate_hours. Omitted, null or empty uploaded hours replace the previous list with no hours; older watch days return []. The day-range, watch-range and trends responses remain daily summaries. Migration v07-steps-hours.sql adds the nullable JSONB column without changing existing days.
Days take an IANA tz (default UTC). Sleep belongs to the local day it ended; other events to the day they started. GET /days/{date}?tz= returns:
{
date, timezone, events: Event[], episode_spans: Event[],
symptoms: [{uuid,name,order,archived,open_episode: Event|null,
last_ended_at: string|null,episodes: Event[]}],
uses: Use[], totals: DayTotals, measures: DayMeasure|null
}
events are raw records placed on the day, newest first. episode_spans and each symptom's episodes include episodes overlapping the day; counting starts still uses the start date. Every symptom is included, with an open episode from any date. Each symptom's last_ended_at is the end instant of its most recent finished episode before the next local midnight, with no lookback limit. It is null if none exists; open episodes do not count. uses contains that day's uses. Medicines due and taken are fetched separately through GET /medicines/days/{date}?tz=; the day response does not duplicate the medicine scheduling rules.
DayTotals is {water_ml,water_goal_ml,coffee_count,last_coffee_at,sleep, latest_stress,episode_count}. Coffee counts include only saved cups on the requested local day.
GET /days?from=YYYY-MM-DD&to=YYYY-MM-DD&tz=Europe/Athens returns {days:[{date,totals:DayTotals,coffee_at:string[],measures:DayWatch|null}]}. Both dates are required; tz defaults to UTC. The inclusive range must contain 1–31 local calendar days, otherwise it returns 422 with day_range_must_be_1_to_31_days. Entries run oldest first and include empty days. totals uses the same calculations and shape as the single-day route, including the saved water goal and preceding coffee history. Empty days have zero counts and null recorded values; the water goal and usual coffee count can still be present. coffee_at lists the instants of that local day's coffee records, oldest first, or [] when there are none. It sits beside totals; the single-day DayTotals shape is unchanged.
DayWatch is {steps,heart_rate_min,heart_rate_avg,heart_rate_max, exercise_minutes,exercise_sessions,raised}. Missing measurements are null; sessions and raised heart-rate stretches default to []. raised has the same {started_at,ended_at,peak} entries as the single-day route. A missing watch day has measures:null, distinct from a recorded zero steps. The range omits hourly and sampled heart-rate details. All lookups filter by the signed-in person, and load events, watch values, coffee history and settings for the whole range rather than querying each day.
Trends range¶
GET /trends?from=YYYY-MM-DD&to=YYYY-MM-DD&tz=Europe/Athens returns {days:TrendDay[],symptoms:Symptom[],medicines:[{uuid,name}],settings:Settings, first_day:date|null}. Dates are required; tz defaults to UTC. The inclusive range accepts 1–732 local days, otherwise 422 with trends_range_must_be_1_to_732_days. Days are oldest first, including gaps. first_day is the earliest local record day across events, watch readings, doses and remedy uses, independent of the requested range.
TrendDay has date, sleep:{started_at,ended_at,asleep_minutes}|null, naps:[{started_at,ended_at}], steps, heart_rate_min, heart_rate_avg, heart_rate_max, water_ml, coffee_count, feeling, episodes:[{symptom_uuid,uuid,started_at,ended_at}], medicines:[{medicine_uuid,taken,planned}], and as_needed:string[]. Missing amounts/measurements are null. The main night uses the same selection as day totals, with other joined sessions as naps. Episodes appear on every local day they overlap; an end exactly at midnight excludes the following day. A going episode retains a null end. Medicine counts use the existing schedule slots: earlier days before a replan contain recorded timed doses only. A day with no timed doses has no count entry. as_needed names remedy uses and unscheduled intakes, omitting a second copy of a remedy's linked dose. Every lookup filters by the signed-in person. Records load for the whole range, without per-day database queries. No stage spans, hourly heart readings or exercise sessions are included. No database migration is required.
Sleep is a selected night or null. A night has all Event fields, plus segments:Event[], asleep_minutes, awake_minutes. Its start is the first segment's start, its end the last segment's end. Its duration_minutes equals asleep minutes; details.stages holds summed stages, including gaps in awake minutes. Each session's asleep minutes are its elapsed minutes minus its recorded awake minutes, never below zero. Missing stages mean zero recorded awake minutes; unclassified time counts as asleep. Joined nights sum the sessions' asleep minutes. Awake is recorded awake minutes plus gaps. Stages stay null if no segment has stages; awake_minutes still reports gaps. Mixed nights sum known stages only, leaving light, deep and REM minutes as recorded for display.
Watch sessions strictly less than 30 minutes apart join into a night; a session 30 minutes or more away stays separate. Naps do not join the night. Typed app/chat sleep wins (latest end); otherwise the longest watch night wins. This selection is shared by days, watch ranges, episode context and patterns. Raw watch upload and deletion routes retain their session ids, revisions and validation.
PUT /watch/readings accepts optional stage_spans on each sleep item:
{
"sleep": [{
"external_id": "night-1",
"started_at": "2026-11-09T23:00:00Z",
"ended_at": "2026-11-10T07:00:00Z",
"stage_spans": [
{"stage": "light", "started_at": "2026-11-09T23:00:00Z", "ended_at": "2026-11-10T00:00:00Z"},
{"stage": "deep", "started_at": "2026-11-10T00:00:00Z", "ended_at": "2026-11-10T01:00:00Z"}
]
}]
}
Stage timing never rejects a watch upload. Non-list stage_spans values are treated as absent. Entries with an unknown stage, malformed or timezone-naive timestamps, or an end at or before their start are dropped. Stages are awake, light, deep, or rem. Spans are clipped to the session's start and end; those with no time left are dropped. The remaining spans sort by start time. Overlaps move the later span's start to the earlier span's end, dropping it if nothing remains. Only the first 300 surviving spans are kept per session. Adjacent spans, gaps, and partial coverage are allowed. The session is saved with the surviving spans, even when none remain. Session time errors retain their existing per-session skip behavior. The response remains {sleeps_created,sleeps_updated,sleeps_skipped,days_saved}.
Spans are stored in the sleep event's JSON details and returned as details.stage_spans on raw events and every segment of a joined night. The night's own details.stage_spans combines supplied spans in time order, without inventing spans for gaps. Its combined list may exceed 300 when sessions join. Omitted or null spans return null; an empty list remains []. Existing sleeps remain valid without a migration. As with stage totals, re-uploading replaces spans (omission clears them), preserves quality, and increments the revision only when the session changes. Adding or correcting spans is a change.
Span timing is for display; it does not derive or replace stage minute totals, and it does not change the elapsed-minutes-minus-recorded-awake rule above. Event creation and edits also validate supplied spans against the session times.
| Method and route | Request | Response data |
|---|---|---|
PUT /days/{date}/water?tz= | {amount_ml,source:"app"}; 0–20000 ml | DayTotals |
PUT /days/{date}/coffee?tz= | {count,source:"app"}; 0–100 | DayTotals |
PUT /days/{date}/feeling?tz= | {level,source:"app"}; 1 calm to 5 rough | DayTotals |
Only the current local day and earlier days are accepted (day_in_future on a later day). All writes share the per-user lock. Increasing water or coffee adds the difference at now for today, or the final instant of an earlier day. Water increases above 5000 ml are split into records of at most 5000 ml. Lowering a total removes newest records first, shrinking the final water record if needed; remaining record times stay unchanged. Repeated unchanged totals add nothing. Feeling replaces the latest stress record's value and removes other stress records that day; the retained record keeps its time. Sources are app or chat.
GET/PUT /settings reads/replaces {water_goal_ml:2000,bottle_ml:1000,trackers:{water:true,coffee:true,sleep:true,stress:true}}. Bottle size is 1–5000 ml; the goal is 1–20000 ml.
Migration and development¶
v05-symptoms.sql creates a Headache symptom only for users with old headache or medication records. It preserves episode UUIDs, times, readings, notes and revisions, converting the old enums to readable labels. Medication names and dose text become distinct as-needed medicines and strengths; each old event becomes one remedy use and one dose with its original outcome and episode link. Dose days use UTC because the database has no stored user timezone. The stock model requires a count, so migrated medicines start with zero before historical doses are subtracted; low-count alerts are unset. Existing medicines stay intact. Existing glass preferences become the default 1000 ml bottle size; goals stay. There are no routes for the removed headache or medication event types.
Standard DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD configure PostgreSQL. Compose selects database/role health with DB_PASSWORD_HEALTH. IAM is selected by LORYTH_IAM_URL; MCP uses LORYTH_HEALTH_URL. Liveness is /api/v1/health/health. Device key routes are described in Medicines.
From this service run make sync, make format, make lint, make test. To additionally check a private plain SQL production dump in a scratch database:
The test restores into a separate PostgreSQL testcontainer database, compares preserved rows and converted links/outcomes, and prints aggregate counts only. Do not commit a dump or copy its contents into source or test fixtures.
Native notification answers¶
Registered phones use Authorization: Device <key> on GET /device/nudges/plan?tz=, GET /device/nudges/resolve?id=&tz= and POST /device/nudges/answer?tz=. A plan includes three local days of water and coffee candidates, each open episode with its three most-used remedies, and unanswered uses. Resolve returns current figures or null. The phone waits for a connection before displaying an alert.
An answer contains request_id (UUID), id, token, action, and, for remedy_use, remedy_uuid. Actions are bottle, later, coffee, ended, remedy_use, yes, partly, no, pack. A retry with the same request ID returns the saved result. Changed records return 409 nudge_changed. The result includes nudge, current and saved_at. Successful presses remove the notification, with live episodes updating silently after a use or outcome. Notifications offer no Undo; mistakes are corrected in the app.