# Apple Health (Salud) KuentaGYM does not read Apple Health. Your iPhone posts it. An iOS automation in [Health Auto Export](https://www.healthexportapp.com/) (HAE) reads Apple Health and POSTs its JSON export to your KuentaGYM profile. The **Salud** screen — the heart button in Home's header, next to the gear: the tab bar keeps its five tabs so its raised Start button stays centred — draws whatever arrived, as read-only cards; `api/vitals.js` does the arithmetic; `frontend/src/lib/vitals-view.js` decides which number each card shows. Nothing here is an input. There is no way to type a step count into this screen, and the workouts the watch records are shown as a list rather than merged into your workout history — they carry no sets and no weights, so folding them in would put entries into your progression, your PRs and the recovery model that nothing in them can support. --- ## 1. Connect it Signed in as the profile that should own the data (a guest has no profile to post to — Salud says so), open **Salud → ⚙**, and: 1. **Create an ingest key.** It is created on first use and shown once — copy it. 2. Note the endpoint: `https://your-instance/api/vitals/ingest`. 3. In Health Auto Export on the iPhone: **Automations → New Automation → REST API**. - **URL**: the endpoint above. - **Add Headers** → `Authorization` = `Bearer ` (`X-Ingest-Key: ` works too, if you would rather keep the header plain.) - **Export Format**: `JSON` - **Export Version**: `2` - **Data Type**: `Health Metrics` (add `Workouts` as a second automation, or include both) - **Summarize Data**: `On` - **Time Grouping**: `Hours` (or `Days` if you only ever want one number a day) - **Date Range**: `Previous 7 Days` (not `Today` — see below) - **Sync Cadence**: whatever you like — 5 minutes, hourly, once a day. 4. **Manual Sync → Export** once, to prove it works. It runs in the foreground, so it works even while iOS is being cautious about background time. One automation per profile: the key *is* the profile. Two people, two phones, two keys, two files — neither can see the other's, and the URL is the only thing they share. ### Why those settings | Setting | Value | Why | | --- | --- | --- | | Summarize Data | On | Sends aggregates instead of every sample. Smaller payloads, and the numbers on the cards are the ones Apple already summarised. | | Time Grouping | Hours | Each sync carries the hours of the day, so the day is the **sum of its hours** and the detail sheet can draw the day hour by hour. Every hour is replaced by the next report of it, so a five-minute cadence is still safe (see §2). `Days` is the smaller option: one total per day, exact, and with nothing behind it to look into. | | Date Range | Previous 7 Days | How much history exists at all. With `Today` (the default) every sync carries today only, and yesterday is never in the file — the cards then have a single day to draw. `Previous 7 Days` re-sends the last week every time, which also fills in a sync missed while the phone was locked or in Low Power Mode. | | Export Version | 2 | The current payload shape (`{"data":{"metrics":[…]}}`). Version 1 is also accepted. | Apple's own limits apply and cannot be worked around: HAE cannot read Health data while the phone is locked, and iOS decides when background runs happen. Opening the app (or tapping the Automations widget) is what makes a sync happen on demand. That is a limitation of iOS, not of this endpoint. --- ## 2. Why a 5-minute automation does not double-count This is the part worth understanding, because it is the part that goes wrong. A five-minute automation re-sends overlapping windows: with **Date Range = Today** each run carries the entire day so far, and appending would count it again every five minutes. With **Date Range = Since Last Sync** the windows are disjoint, and *replacing* would throw away everything but the last five minutes. The same endpoint has to survive both without knowing which one the phone is configured for, so the rule is chosen per payload, from the payload's own shape: | The payload looks like | What the receiver does | Safe with | | --- | --- | --- | | Every datapoint sits exactly on midnight (`00:00:00`) — HAE's **Days** grouping, i.e. a **total** per day | The day it names is **replaced** by it, in full. A day total only ever supersedes another day total, so re-sending the same day all afternoon converges on the day's total instead of accumulating. | Overlapping windows, disjoint windows, manual re-exports, first sync of a year of history. | | Every datapoint sits exactly on the hour (`HH:00:00`) — HAE's **Hours** grouping, i.e. a **total** per hour | That **hour** is replaced, for the same reason: the hour in progress grows on every run. The day is then recomputed as the sum of its hours, so the day total and the hourly detail can never disagree. The hours are what the detail sheet draws (kept for 7 days; the day aggregates live on). | Overlapping windows, disjoint windows, and switching an automation from `Days` to `Hours` mid-day. | | Anything else — real sample timestamps, or Minute grouping | Each sample is identified by its **instant plus its numbers** and stored once, in its own hour. A repeat is skipped and reported back as `duplicates`; a genuinely new sample is added. | Overlapping windows (repeats detected) and disjoint ones (new samples add). | | **Two devices in one hour** (an Apple Watch and an iPhone both recording the walk) | The hour keeps each source's aggregates apart and shows **one** of them — the source that reported most in that hour, then the newest, then the largest. Not a sum: HealthKit de-duplicates the same walk, and adding both is what turns 946 steps into 1,700. The choice is per hour, which is what makes the disjoint case right too — an hour only the phone recorded is the phone's hour, and nothing competes with it. | A metric with a single source, or one whose payload has no `source` at all, behaves exactly as it did: one source, which is the bucket. | The hour rule is decided from the **whole payload**, never from a single timestamp: a five-minute automation also produces samples that land exactly on the hour, and reading one of those as an hour total would wipe the hour it belongs to. Day keys come from the date **the phone wrote**, never from the server's clock. HAE stamps each sample with its own local offset, so grouping by a server-local date would slide every evening's steps into the next day for anyone not on UTC. The one configuration neither rule rescues is **Minute** grouping with an overlapping window: the minute still in progress is re-sent with a larger value each time, so it is a new sample by the union rule and gets added twice. The error is bounded by one partial minute of the cheapest metric — a handful of steps, a few hundredths of a kcal — and grouping by `Days` (or `Hours`) removes it entirely. Being explicit about that is better than a cleverer rule that silently miscounts a whole day. What every sync answers with is the receipt: how many points arrived, how many were recognised as already stored, and what the profile holds now. ```json { "ok": true, "ts": 1756900000000, "received": { "metrics": 12, "points": 40, "duplicates": 288, "workouts": 1 }, "stored": { "metrics": 24, "days": 190, "workouts": 37 } } ``` --- ## 3. What is stored, and where One file per profile: `data/vitals-.json`, mode 0600, written atomically. It is deliberately **not** part of `state-.json`: - the phone writes it while the browser writes the state document, and one file would have the two fighting over the same revision counter; - the state document is pushed back to the server by every client, so a year of heart rate would round-trip through `localStorage` on every device; - a reader that only wants the health data needs no merge logic to find it. Inside, numbers are kept **per day and per field, generically**: ```json { "v": 1, "updatedAt": 1756900000000, "last": { "ts": 1756900000000, "metrics": 12, "points": 40, "duplicates": 288, "workouts": 1 }, "metrics": { "heart_rate": { "units": "bpm", "sources": ["Apple Watch"], "days": { "2026-09-03": { "n": 24, "lastTs": 1756900000000, "f": { "Avg": { "n": 24, "sum": 1665.6, "min": 55, "max": 96, "last": 72, "avg": 69.4 } }, "h": { "08": { "n": 1, "lastTs": 1756900400000, "f": { "Avg": { "n": 1, "sum": 62, "min": 62, "max": 62, "last": 62 } } } } } }, "seen": { "2026-09-03 09:05:00 +0200|Avg:70": 1756900000000 } } }, "workouts": [ { "name": "Walking", "start": 1756900000000, "durMin": 60, "avgHr": 128, "fields": {} } ] } ``` The server does not decide what "steps today" means. A counter's day is its `sum`, a rate's is its `avg`, a gauge's is its `last` — and all four are stored, because which one a *card* shows is a presentation rule, and it lives in `vitals-view.js` with the labels. That is also why a metric HAE ships next year shows up without a server change: an unrecognised name still lands in `f` under whatever HAE called it, gets a humanised label and a card of its own under **Other**. Bounds, all enforced on write: | Kept | Limit | Why | | --- | --- | --- | | Days per metric | 400 | A little over a year, so "this time last year" still exists. | | Hours per day | 7 days | Detail is what makes the file grow (24 buckets × every metric × every day of a year); it is also only interesting for the last few days, which is what the detail sheet opens. The day aggregates underneath keep the full 400. | | Dedupe ledger per metric | 72 h | A repeat can only be recent — the next automation run is minutes away, not days. | | Workouts | newest 300 | A wrist that records every walk produces thousands a year; nobody scrolls past the last few hundred. | | Request body | 32 MB | A full-history export with Summarize off is tens of megabytes. Over it: `413` with a readable message. The bundled web container allows this **one route** the bigger body (`web/nginx.conf.template`); every other `/api` path stays at 5 MB. Behind your own reverse proxy, raise `client_max_body_size` there too, or it is your proxy's 413 the phone sees. | **Salud → ⚙ → Delete the health data** removes this file. Your workouts, routines, account, passes and ingest key are untouched, so the phone needs no re-configuring to sync again. To start over on **one** measurement instead — "these steps look wrong" — open the metric's card and use **Reset this measurement**: that metric's days and hours go, everything else stays, and with a Date Range of a week or more the next sync rebuilds it from Apple Health. Because a day total *replaces* the day it names, a re-sync corrects the stored past as well: there is no separate "recalculate" step to run. --- ## 3b. The second opinion (optional) Salud can also carry a **judgment** about the profile's own numbers: how ready the person is to train hard, whether the week calls for easing off, which body part looks least recovered, and which health metric deserves attention. It is answered by [Jev](https://typesafe.ai), TypeSafe's "System One" model, which is not a chat model — it takes a state and a set of typed questions and answers them with a value **and the probability it put there**, in one request. That is the whole point of using it here rather than a text model: "62% probable" can be argued with, and "take a deload week" cannot. It is served through the **OpenCode Zen** gateway, so one account covers this and anything else configured against that gateway. Off unless a key is set; with no key the card does not exist. ```bash JEV_API_KEY=… # or OPENCODE_API_KEY JEV_MODEL=jev-1.13 # jev-1.13-free for the gateway's free tier JEV_BASE_URL=https://opencode.ai/zen JEV_MAX_PER_DAY=12 # per profile, per day — every ask costs a request JEV_MIN_INTERVAL_MS=600000 # ten minutes between asks JEV_DISABLED= # a fleet operator's kill switch, like COACH_DISABLED ``` What is sent, exactly — this is the part worth reading before turning it on: | Sent | Not sent | | --- | --- | | A week of every health metric the profile has, per field, as the phone wrote them (`qty`, `Avg`, `asleep`…), each day's aggregate folded against the same metric's week | Any identifier: no profile id, no name, no device, no key | | Sets per body part over four weeks and over the last week, sessions in the window, how many days since the last one, average RPE, whether an exercise has stalled (by library name) | Workout titles, routine names, exercise ids, chat, notes | | The newest weigh-in, the four-week change, the target | Anything you typed, **except** the Coach intake's `limitations` | | The intake's goal, experience, days per week and session length — and its `limitations` note, because "bad shoulder" changes the answer | | The sheet behind the card's ⓘ lists the same thing for the profile it is looking at, from the same summary the server just sent, so nobody has to take the table above on faith. All of it goes to the provider you configured, under your own account, and nowhere else — the request is one HTTPS POST from the api container. **It is never on a timer.** A judgment costs a request, so it happens when somebody presses *Ask*. The per-profile daily budget and the ten-minute floor are enforced by the server, not the screen, and the answer is stored in `data/insight-.json` (the answers, the model, the moment, and a digest of the state they were made from). The card says when the data has moved since — after a session is logged or a night arrives, the judgment is marked out of date rather than quietly left looking current. When a judgment is **less than six hours old**, the Coach is given it as `secondOpinion` in its payload: evidence with a confidence attached, for the Coach to read and cite, never an instruction and never a change to the plan. `api/jev.js` has the long version of all of this; the questions it asks live in `buildQuestions` and the reader that tolerates the gateway's response shapes is `parseAnswers`. --- ## 4. Security - **The ingest key is write-only.** It can add to one profile's health file and cannot read a single number out of it: `GET /api/vitals` requires a session. A key that leaks out of a phone is a nuisance, not a disclosure. - **It is its own credential**, not the session token, so rotating it (Salud → ⚙ → Replace the key) invalidates the phone without signing you out anywhere. Lost phone, one tap. - **Per profile.** The key resolves to exactly one account; a payload can never land in somebody else's file. A disabled account's key stops working with the account. - **Compared in constant time** as SHA-256 digests, and refused on length before any hashing. - **CSRF-exempt** by design: the request carries its own credential in a header and has no session to borrow (the same reasoning as `POST /api/pair/redeem`). A browser cannot attach a bearer header on its own, so there is no ambient authority for a hostile page to reach for. - **Audited**: the first sync from a phone, key creation and rotation, a deleted history — plus failed syncs with a reason. Successful syncs are *not* logged: a five-minute cadence would write 288 identical lines a day and bury everything else. Refused requests (bad key) go to the container log instead, so the activity log cannot be filled from the open internet. Health data is not encrypted at rest beyond the file mode — it sits in `./data` next to your workouts, which is the same trust model as the rest of a self-hosted KuentaGYM. **Back up `./data`** and you have backed up your health file too. --- ## 5. Troubleshooting | What you see | What it is | | --- | --- | | `401 invalid ingest key` | Wrong key, a revoked one, or the header is missing `Bearer `. The key is shown in Salud → ⚙; re-copy it rather than retyping. A disabled account also answers 401. | | `400 not a Health Auto Export JSON export` | Export Format is set to **CSV**, or the URL points at something else. Set JSON. | | `413 body too large` | A first sync with everything selected and Summarize off. Turn Summarize Data on, group by Days or Hours, or split the metrics across two automations. Behind your own reverse proxy (Caddy, Cloudflare, a second nginx), raise its body limit for this path as well — the bundled stack already does. | | `200` with `received.points: 0` every time | Working, with nothing to add: bring your phone to Health Auto Export → Manual Sync → Export, and check Date Range covers a day that has data. | | Nothing on the screen | Salud fetches 30 days by default — widen the range. A metric HAE has no samples for is skipped rather than shown as a zero. | | Numbers that look doubled (steps, above all) | The export can carry the same walking twice — once from the Apple Watch and once from the iPhone. Apple Health de-duplicates that; [an export of individual samples does not](https://developer.apple.com/forums/thread/759709). A day total from HAE's own aggregation is the number the Health app shows, so `Time Grouping: Days` is the setting that keeps a card honest; grouping by Hours or Minutes reads the samples instead. | | A card's number is bigger than the Health app's, by about 1.6–1.9× | Two devices recorded the same activity and the Health app de-duplicated it. Nothing to do: the hour keeps its sources apart and shows one of them, and the metric's sheet ends with `… · Apple Watch, iPhone · using Apple Watch` so the number can be checked against the device that produced it. A ratio that *grows* through the day instead means the payload carries running totals rather than per-hour values — see the row below. | | A card's number is bigger than the Health app's (steps above all) | Open the metric's card: **What arrived last** lists how the last payload was stamped, from which sources, what it adds up to and its newest values. A run of *rising* numbers is the tell — those are running totals, not one hour each, and adding them inflates the day. The fix that covers both shapes is already in: a day total the phone declares is the day, and hours are only ever the shape of it (the sheet says so when the two differ). If the receipt shows **one total a day**, the export is already sending what the Health app shows. | | A card shows one day, and its sheet has nothing before it | The automation's **Date Range** is `Today`, so yesterday was never sent. Set it to `Previous 7 Days`; the past cannot be invented server-side. | | The detail sheet says "arrived as one total a day", with no hour list | **Time Grouping** is `Days`: the payload has one number per day and no hours to draw. Set it to `Hours` — the day stays the sum of its hours, so nothing is double-counted, and the hour list appears from the next sync on. | | Steps look half a day behind | HAE cannot read Health while the phone is locked. Open the app (or tap the Automations widget) and the day fills in. | | A metric shows under **Other** | Marketing-free behaviour: the catalogue in `vitals-view.js` covers ~50 metrics by name. Anything else is still stored and still charted — humanised, with every field HAE sent listed in its detail sheet. Add a line to `METRICS` to give it a better label, unit and aggregate. | | Workouts do not appear in History | By design. They are read-only in Salud; see the top of this file. | ## 6. For developers - `api/vitals.js` — parsing, the merge rules of §2, the per-metric receipt of what arrived, retention. Pure; tests in `api/test/vitals.test.js` cover the merge under overlapping, disjoint, day-grouped, hour-grouped, raw, heart-rate, sleep and blood-pressure payloads, plus pruning (days and hours), the day-from-hours projection and timezone handling. - `api/jev.js` — the second opinion: the state that leaves, the questions, the tolerant reader and the budget. Tests in `api/test/jev.test.js` (the state, the questions, every response shape, the privacy claim) and the route against a stub gateway in `api/test/server-insights.test.js`. - `api/server.js` — the eight routes and the ingest key. Route tests in `api/test/server-vitals.test.js` run the real server and check isolation between profiles, that the key cannot read, and that ten re-sends of the same window change nothing. - `frontend/src/lib/vitals-view.js` — the metric catalogue, the card model, the units, the hour rows and the day history the detail sheet lists. Tests beside it. - `frontend/src/views/Health.jsx` — the screen and its two sheets. - Endpoints are documented in `api/openapi.yaml` (tag `health`); rebuild `website/api.html` after changing them.