Compare commits

...
363 Commits
Author SHA1 Message Date
Marc-André Bombeck e07527e680 Merge pull request #253 from MBombeck/release/v1.11.2
release/v1.11.2 — Coach-memory controls, privacy hardening, more pinnable metrics
2026-06-04 13:40:35 +02:00
Marc-André BombeckandClaude Opus 4.8 074e3bbdf1 chore(release): v1.11.2 — Coach-memory controls, SSRF hardening, more pinnable metrics
Coach-memory management UI (review/forget durable facts), connect-time
DNS-rebinding pins on user/operator-overridable outbound hosts, eight
additional pinnable dashboard metrics, plus a rollup write-race fix and
fast-path source-priority amortisation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 13:31:25 +02:00
Marc-André BombeckandClaude Opus 4.8 dd3ac3510f test(ssrf): lock the pre-existing moodLog and ntfy host pins
Extend the SSRF pin inventory to also assert the requirePublicHost pins
already present on the user/operator-supplied moodLog push/sync webhooks
and the ntfy sender, so the full set of overridable-host egress points
is CI-guarded and a future edit that drops one reds here.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 13:26:19 +02:00
Marc-André BombeckandClaude Opus 4.8 ba4349eda0 refactor(db): extract the P2002 predicate into one shared helper
The Prisma unique-constraint (P2002) narrowing predicate had been
hand-copied into five call sites. Fold them into a single isP2002 in
src/lib/prisma-errors.ts and import it everywhere (the two step-drain
sites keep their local isUniqueConstraintViolation name via an import
alias). Behaviour-identical; one place to chase a future P2002-semantics
change instead of five.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 13:26:07 +02:00
Marc-André BombeckandClaude Opus 4.8 9c39afa352 fix(settings): per-fact pending state on coach-memory forget
A single shared forgetOne mutation meant forgetOne.isPending disabled
every per-fact forget button during one delete, so the whole list read
as frozen. Track the in-flight fact id via the mutation variables so
only the row being deleted disables and shows the spinner.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 13:26:00 +02:00
Marc-André BombeckandClaude Opus 4.8 2763a64b83 fix(dashboard): hide iOS-pin-only widgets from the web settings list
The eight v1.10 additive HealthKit signals (cardio recovery, six-minute
walk, stair ascent/descent speed, breathing disturbances, wrist
temperature, falls, walking steadiness) are writable dashboard widget
ids so the native client's Home-pin PUT validates them, but the web
dashboard renders strip tiles via hardcoded per-id blocks and has no
render path for them. Left as-is, the web Settings -> Dashboard list
would offer eight toggles that do nothing on web.

Name them in a new IOS_PIN_ONLY_WIDGET_IDS set (writable-but-not-
web-rendered) and filter that set out of the rendered settings list, so
the toggles never appear on web while the ids stay accepted by the
widgets PUT enum for the native client. Add tests asserting the eight
remain writable (catalogue membership) yet are absent from the web list.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 13:25:55 +02:00
Marc-André BombeckandClaude Opus 4.8 2994954138 test+a11y: fix mocks/expectations for source-priority + dashboard ids; pair coach-memory spinner with motion-reduce
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 13:12:18 +02:00
Marc-André BombeckandClaude Opus 4.8 07c444f938 fix(rollups): treat a concurrent same-partition P2002 as benign
The synchronous DAY rollup hook carries no pg-boss singleton, so two
measurement writes landing on the same (user, type, day) can interleave
their delete-then-insert and the losing createMany trips the per-source
unique index. The peer rewrote the identical source-collapsed partition
— the aggregate is a pure function of the same underlying rows — so the
rollup is already correct. Catch the P2002 in the single-chunk
transactional path, annotate it, and return rather than failing the
recompute. Any other Prisma error still bubbles.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 13:01:54 +02:00
Marc-André BombeckandClaude Opus 4.8 7923d75afe chore: clear v1.11.2 QA-low cleanups
- Drop the unused `now` field from the coach `ExtractOpts` type; fact
  extraction never read it (conversation-summary keeps its own `now`).
- Correct the no-ladder tiebreak docstring in measurement-read: the
  collapse picks the alphabetically smallest source name, matching the
  live-SQL `ORDER BY … source` tiebreak, not max count.
- Replace the hand-inlined canonical-source subquery in the summaries
  rollup-path narrows query with `canonicalMeasurementsFrom(rank, "90 days")`
  for live/rollup parity with its siblings.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 12:59:38 +02:00
Marc-André BombeckandClaude Opus 4.8 0949fadfb0 feat(dashboard): make the v1.10 additive metrics pinnable to Home
Add eight widget ids (cardio recovery, six-minute walk, stair ascent/descent speed, breathing disturbances, wrist temperature, falls, walking steadiness) to the dashboard widget catalogue + default layout (hidden by default) so they can be pinned via the layout PUT.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 12:53:38 +02:00
Marc-André BombeckandClaude Opus 4.8 1f3b0ff5b0 perf(insights): thread source-priority once through graded-series readers
Load the source-priority blob once and pass it into both
readBestGranularityRollups calls. Completes the B3 fast-path threading.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 12:38:25 +02:00
Marc-André BombeckandClaude Opus 4.8 b132abc789 perf(analytics): thread source-priority once through bp-in-target fast path
Load the source-priority blob once and pass it into both BP readers
instead of letting each re-query the user.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 12:34:13 +02:00
Marc-André BombeckandClaude Opus 4.8 b45ca232fa perf(analytics): thread source-priority once through correlations fast path
Load the source-priority blob once and pass it into the three
readRollupBuckets calls instead of letting each re-query the user.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 12:27:56 +02:00
Marc-André BombeckandClaude Opus 4.8 38ef581e7a test(security): inventory guard for the SSRF requirePublicHost pins
Source-grep guard asserting the openai/anthropic/geo outbound sites keep
the unconditional DNS-rebinding pin and the local AI client keeps its
conditional LAN escape hatch — so a future edit can't silently re-open
the SSRF surface.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 12:23:43 +02:00
Marc-André BombeckandClaude Opus 4.8 bd61374351 fix(security): pin DNS-rebinding check on user/operator outbound hosts
Add requirePublicHost to the three outbound safeFetch sites whose host is
user- or operator-controlled and lacked the connect-time pin: the OpenAI
and Anthropic clients (BYO base-URL override) and the IP-geo lookup
(IP_GEO_LOOKUP_URL env). A base URL resolving to a private/metadata
address is now rejected. The LOCAL AI client intentionally stays
conditional (LAN escape hatch). Redirect-follow is already closed by the
safeFetch defaults.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 12:20:23 +02:00
Marc-André BombeckandClaude Opus 4.8 fcb41b8780 feat(coach): settings UI to review and forget what the Coach remembers
Add a 'What the Coach remembers' settings section: lists the user's
durable facts grouped by category with a learned-when stamp, forgets a
single fact or clears all (behind a confirm), and notes the rolling
conversation summary. Consumes the v1.11.1 CoachFact routes via the
query-key factory; gated on the Coach feature; localised in all six
locales. Closes the API-only gap from v1.11.1.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 12:16:26 +02:00
Marc-André Bombeck 1f3ec16844 Merge pull request #252 from MBombeck/release/v1.11.1
release/v1.11.1 — source-aware vitals + Coach long-term memory
2026-06-04 11:02:16 +02:00
Marc-André BombeckandClaude Opus 4.8 cb8568a2fd chore(release): v1.11.1 — source-aware vitals + Coach long-term memory
Closes the three v1.11.0 follow-ups: cross-source vital de-duplication
(measurement rollups resolve overlapping sources to the priority-ladder
canonical reading across charts, summaries, insights, and the live
fallback), the Coach's rolling encrypted conversation summary, and
durable encrypted personal facts with a list/forget surface.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:56:21 +02:00
Marc-André BombeckandClaude Opus 4.8 7030266220 fix(coach): drop unused version constants, cap stored summary length
Remove the two never-wired *_PROMPT_VERSION exports the dead-code gate
flagged, and consume the summary-length target as a real backstop that
caps the stored rolling summary so a misbehaving provider can't bloat
the encrypted column or the next prompt's history window.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:54:18 +02:00
Marc-André BombeckandClaude Opus 4.8 9b2b137a6c fix(coach,rollups): QA reconcile — decrypt isolation + collapse parity
- conversation-summary: fault-isolate the per-message decrypt in the
  fold loop so one undecryptable historic turn (e.g. mid key-rotation)
  no longer permanently stalls a conversation's summary refresh.
- source collapse: unify the no-ladder tiebreak on alphabetically
  smallest source across the JS reader and the all-time rollup SQL, so a
  ranked vital whose day carries only off-ladder sources resolves to the
  same canonical source on the warm and the live-SQL read paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:38:44 +02:00
Marc-André BombeckandClaude Opus 4.8 8e2e697370 feat(coach): facts management routes (list + forget)
Add the GDPR/trust surface for the durable Coach facts: GET lists the
caller's active facts decrypted, DELETE /[id] soft-deletes one, and a
bulk DELETE clears all — every verb apiHandler + requireAuth +
requireAssistantSurface("coach") + ownership-scoped, with an unknown or
cross-user id collapsing to an idempotent no-op that never leaks
existence. Registered in the OpenAPI contract.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:29:18 +02:00
Marc-André BombeckandClaude Opus 4.8 0a5ba025c8 feat(coach): inject durable facts into the snapshot memory block
buildCoachMemoryBlock gains a third fault-isolated sub-source — the
top-N durable facts — folded under snapshot.memory so they ride the
existing lowest-priority registration and are shed first under the
char budget. Add an EN + DE system-prompt paragraph instructing the
Coach to use facts as the user's own stated, descriptive context —
never as a diagnosis, never invented.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:22:44 +02:00
Marc-André BombeckandClaude Opus 4.8 9a0ea1be56 feat(coach): inject the rolling summary + enqueue memory refresh
fetchConversationWithMessages now returns the decrypted rolling summary
(fail-closed → null), and buildHistoryWindow substitutes it for the dead
placeholder so a long conversation keeps memory of its elided turns.
Once a conversation grows past the turn cap the chat turn fires a
fire-and-forget coach-memory-refresh so the next long turn is fresh,
without adding a provider round-trip to the interactive reply.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:21:19 +02:00
Marc-André BombeckandClaude Opus 4.8 7e29595a71 feat(coach): wire the combined memory-refresh worker queue
Add the coach-memory-refresh pg-boss queue: a fire-and-forget enqueue
contract (coach-memory-shared) and a worker pipeline that runs the
conversation-summary refresh then the fact extraction for one long
conversation, each fault-isolated and budget-gated. Register the queue
in allQueues + a boss.work handler in the worker, with a source-grep
inventory guard so the queue can never ship unregistered.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:18:52 +02:00
Marc-André BombeckandClaude Opus 4.8 5591858f16 feat(coach): conversation-summary + durable-fact compute modules
Add the two background generators behind Coach long-term memory, both
reusing the budget-aware provider chain (runStatusCompletion) with a
local fallback and encrypting their output at rest:

- conversation-summary: folds the turns elided past the history window
  into a rolling natural-language summary, merging into any prior
  summary; short-circuits cheaply until a conversation grows long.
- facts: extracts durable, descriptive personal facts (preferences,
  stated conditions, goals, constraints, context), gated by a Zod
  schema + de-dup + per-user cap; buildCoachFactsBlock ranks the top
  facts for snapshot injection. Never diagnostic, never numeric.

Both are pure/injectable for unit testing and annotate counts only,
never content. Wiring into the queue, route, and snapshot follows.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:16:26 +02:00
Marc-André BombeckandClaude Opus 4.8 54539a801e chore(crypto): rotate summary + fact encrypted columns
Add CoachConversation.summaryEncrypted and CoachFact.factEncrypted to
the key-rotation registry, mirroring the CoachMessage.encryptedContent
Bytes round-trip, so an operator dropping a legacy key re-encrypts the
new Coach-memory columns instead of bricking them.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:12:59 +02:00
Marc-André BombeckandClaude Opus 4.8 01d3afcdaf feat(coach): scaffold conversation-summary + facts storage
Extract the AES-256-GCM Bytes codec from persistence into a shared
bytes-codec module so the conversation summary and the new personal-fact
store reuse one ArrayBuffer-backed implementation. Add the CoachFact
table (migration 0116) for durable, user-scoped facts the Coach extracts
from conversations — encrypted fact text, plain category/confidence/
source for rank-without-decrypt, soft-delete for a reversible forget.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:11:19 +02:00
Marc-André BombeckandClaude Opus 4.8 7c494b60cb feat(rollups): collapse overlapping sources across all read paths
Complete the source-aware rollup read path: the slim summaries slice
(rollup + live), the comprehensive aggregator (both paths, including the
dailyByType correlation feed), and the /api/measurements route (rollup
read + the live date_trunc fallback) now resolve overlapping sources to
the source-priority ladder's canonical reading per (type, day) before
aggregating. A dual-source vital (e.g. WHOOP + Apple Watch resting heart
rate) surfaces one canonical series instead of a blend or a doubled
count; cumulative metrics keep summing per canonical source.

The collapse runs in SQL where the aggregate must stay a single
round-trip (buildSourceRankCase emits a per-user ladder-rank CASE;
canonicalMeasurementsFrom restricts a live read to canonical-source rows)
and in application code (collapseRollupRowsBySource) for the row readers,
both driven by the same resolved ladders so live and rollup agree.

Also widens the enum-literal SQL whitelist to accept digits so VO2_MAX
no longer throws on the typed write-hook recompute or the rank CASE.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 10:05:47 +02:00
Marc-André BombeckandClaude Opus 4.8 d06eec6ace feat(rollups): collapse sources in the DAY + WMY rollup readers
readRollupBuckets and the WEEK/MONTH/YEAR readers now select the source
column and run collapseRollupRowsBySource before composing, so every
rollup consumer (dashboard sparkline, fast-paths, derived metrics, range
deltas) sees one canonical row per bucket. loadUserSourcePriority loads
the ladder blob once; readBestGranularityRollups threads it through each
granularity probe so the per-floor walk never re-queries the user.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 09:37:25 +02:00
Marc-André BombeckandClaude Opus 4.8 cddade3b4f feat(rollups): add source-priority collapse helper for read path
collapseRollupRowsBySource resolves the per-source rollup rows minted by
the source-aware writer down to one row per bucket, using the user's
source-priority ladder (the same ordering the raw-row picker uses). A
metricKeyForType superset maps every overlapping non-cumulative vital
(RHR, HRV-SDNN, SpO2, body/skin temperature, respiratory rate, weight,
body fat, blood pressure, pulse, VO2max, recovery) plus the cumulative
keys onto a SourcePriorityMetricKey. Unlisted sources fall back to the
highest-count row so a bucket never doubles or goes dark.

Wired into the rollup readers in the following commits.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 09:33:30 +02:00
Marc-André BombeckandClaude Opus 4.8 ef74ee13f7 feat(rollups): make measurement rollups source-aware (migration 0115)
Rollup rows were grouped by (type, day) only, so two sources reporting
the same standard vital for one day (e.g. WHOOP + Apple Watch resting
heart rate) were AVG-blended into a single row instead of resolving to
the source-priority ladder's canonical reading.

Re-grain the rollup table to (type, day, source): the writer now groups
by source and delete-then-inserts each affected partition (so a source
that stops reporting a bucket cannot strand a stale row), and the read
path will collapse overlapping sources to the canonical reading in a
follow-up commit. Cumulative metrics (steps, energy) keep summing per
source. Migration 0115 purges the legacy source-blind aggregates; the
boot backfill + read-time self-heal re-mint per-source rows.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 09:29:49 +02:00
Marc-André Bombeck dc9da4fd7c Merge pull request #251 from MBombeck/release/v1.11.0
v1.11.0 — WHOOP, a longitudinal coach, and a clinician-grade record
2026-06-04 05:05:32 +02:00
Marc-André Bombeck 98693cda6a test(e2e): expect three integration pills on mobile after WHOOP card
The WHOOP integration card adds a third status pill on
/settings/integrations. Update the Pixel-5 layout spec to expect three
pills and assert the two connected ones (Withings + moodLog) order-
independently, since WHOOP stays a dormant BYO-keys card until an
operator adds credentials.
2026-06-04 05:00:13 +02:00
Marc-André Bombeck 37cec93d28 test: account for the WHOOP card + narrative route in inventory tests 2026-06-04 04:48:41 +02:00
Marc-André BombeckandClaude Opus 4.8 65c7012590 docs: document the v1.11.0 features
Add WHOOP as a synced provider (per-user BYO-keys OAuth2 + HMAC-signed
webhooks), the longitudinal coach (narrative + per-metric trajectory),
and the read-only FHIR R4 REST API plus the scoped, time-limited
clinician share-link record across README, the self-hosting and ops
runbooks, and a new WHOOP integration page. Note the two optional
WHOOP instance env vars, that migrations 0110-0114 are additive, and
the two known limitations (dual-source standard-vital dedup deferred;
coach durable-memory deferred).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 04:25:22 +02:00
Marc-André Bombeck df5f1d170b chore(release): v1.11.0 — WHOOP provider hub, longitudinal coach, clinician-grade FHIR record 2026-06-04 04:16:57 +02:00
Marc-André Bombeck 1b9f914b8b fix(crypto): cover the WHOOP encrypted columns in key rotation
The rotation registry missed the per-user WHOOP credential columns and
the WhoopConnection token columns, so a key rotation would skip those
rows and leave them undecryptable once the operator drops the old key.
Add whoopClientIdEncrypted / whoopClientSecretEncrypted to the User
field list and a WhoopConnection accessToken / refreshToken pass.
2026-06-04 04:10:16 +02:00
Marc-André Bombeck 7036ff3e0c fix(insights): make the narrative period toggle accessible
Replace the incomplete tablist/tab markup on the week/month toggle with
plain buttons carrying aria-pressed, give them a 44px minimum tap target,
and add a focus-visible ring. The visual treatment is unchanged.
2026-06-04 04:10:16 +02:00
Marc-André Bombeck 153026ea85 fix(clinician): localise measurement-type labels in the shared record view
The clinician view rendered metric names through an English-only humaniser
while the rest of the page was translated, leaving a mixed-language summary for
non-English clinicians. Reuse the doctor-report type-label keys (already present
in every locale) for the per-type label, falling back to the humaniser only for
a type with no key.
2026-06-04 04:10:16 +02:00
Marc-André Bombeck 47ba474569 fix(capabilities): stop advertising a share-scoped FHIR API that is not wired
The capabilities share descriptor exposed scopeable FHIR resourceTypes, but no
/api/fhir/* route honours a share token — those routes require an authenticated
fhir:read Bearer. The share serves the rendered record view only. Drop the
unrouted resourceTypes from the advertised share scope and add an explicit
fhirApi:false flag so an integrator knows the share to FHIR face is not live.
2026-06-04 04:10:16 +02:00
Marc-André Bombeck cd3982a35c fix(integrations): surface the WHOOP dual-source vitals caveat on the connect card
When WHOOP and another source both supply a standard vital (resting heart
rate, blood oxygen, body temperature, respiratory rate, sleep stages), both
values can appear until a future update settles on a single preferred source.
Show this as a calm muted note on the WHOOP card so the known limitation reads
as documented behaviour rather than a bug. New whoopOverlapNote key across all
six locales.
2026-06-04 04:10:16 +02:00
Marc-André Bombeck 7246aa2823 feat(coach): add encrypted conversation-summary columns (migration 0114) 2026-06-04 03:38:19 +02:00
Marc-André Bombeck 462c6e8925 feat(coach): wire short-horizon trajectory into the Coach snapshot
Fold the deterministic short-horizon forecasting engine into the Coach
prompt as a compact, lowest-signal snapshot block. For each in-scope
metric the block carries direction + slope + the projected horizon end
with its widening prediction band, the last observed value, and the
fit's R² / server-computed confidence — read straight from the existing
projection engine, never recomputed. A metric below the fit/history/
staleness floor is omitted; the block is dropped entirely when none
qualify, and it sheds first under prompt-budget pressure.

Add a conditional-projection ground rule so the Coach narrates a
trajectory only when the block is present and only for the metric it
covers: direction and range, always conditional, never a certainty, a
risk score, a diagnosis, or a dated event; absent block means no
projection. The rule lands in the safety-contract matrix across all six
locales and inline in the EN + DE system prompts, with an overclaim
probe asserting a projection is never upgraded. Bump PROMPT_VERSION.
2026-06-04 03:15:39 +02:00
Marc-André Bombeck d99e1f0e8b feat(coach): fold a rolling-profile memory block into the snapshot
Assemble a zero-LLM longitudinal memory block from artefacts already
persisted: the latest period-narrative headline and a per-metric
prior-vs-current band recall. The Coach can now reference what was true
last period instead of re-deriving a cold snapshot every turn.

The block is machine-derived (labels plus numbers only), so it is
unencrypted and adds no model cost. Each sub-source is fault-isolated —
a failing narrative read or context build drops that sub-block and never
sinks the turn. It registers against the lowest-signal cluster so the
budget degrader sheds it first, before any clinical data.
2026-06-04 03:15:09 +02:00
Marc-André Bombeck e1cdbf3e06 chore(api): regenerate OpenAPI for the capabilities FHIR/share descriptors 2026-06-04 02:34:43 +02:00
Marc-André Bombeck 401511d4aa test(whoop): cover WHOOP workout cross-source resolution in the read-time picker
Prove a WHOOP run and the same Apple-Health run inside the 5-minute clustering
window collapse to the APPLE_HEALTH canonical row (richer GPS + HR record),
and a lone WHOOP run survives when no richer source logged the session. The
measurement-side WHOOP/Apple/Withings oracle already lives in
source-priority-whoop-applehealth.test.ts; this closes the workout axis.
2026-06-04 02:34:33 +02:00
Marc-André Bombeck 008160dc72 feat(whoop): settings surface — status, disconnect, credentials, sync routes + connect card
Fill the WHOOP route set beside the OAuth connect/callback: status reports
connection + token expiry + backfill progress, disconnect revokes the stored
tokens and parks the integration, credentials saves/clears the per-user BYO
client id/secret encrypted at rest, sync triggers a manual incremental or full
pull. Add a WHOOP card to Settings -> Integrations mirroring the Withings card
(BYO-keys form, connect/disconnect, status pill, last-sync, backfill notice)
and surface whoop rows in the combined integrations-status envelope so the pill
reflects real failure state. WHOOP lives under the existing integrations
section -- no new slug.
2026-06-04 02:34:33 +02:00
Marc-André Bombeck d4686ea2a6 feat(capabilities): advertise the FHIR REST face and share-link surface
Add a single canonical FHIR_REST_RESOURCE_TYPES catalogue (plus the
$everything operation and honoured search params) to fhir/rest.ts; the
metadata CapabilityStatement and the share-link resource-type enum now
derive from it so the advertised set can never drift from what is routed.

Extend GET /api/meta/capabilities with the FHIR REST descriptor
(restBaseUrl, readScope, resourceTypes, operations, searchParams) and a
clinician-share descriptor (supported, maxDays, resourceTypes, scopeable
sections) — every list sourced from its canonical registry, guarded by
the existing drift assertions. Grow the OpenAPI CapabilitiesResponse to
match.

Fill the clinician test-matrix gap: assert the clinician view never
requests a KVNR / identifier opt-in from the aggregator (default-OFF by
construction) and resolves a rolling window without reaching data older
than the frozen start.
2026-06-04 02:34:33 +02:00
Marc-André Bombeck 93694cacd0 fix(idempotency): scrub hls_ share-link tokens from cached bodies
The body-content secret guard matched hlk_ / hlr_ / sk- but not the
new hls_ clinician share-link prefix, so a response echoing a freshly
minted share token could be persisted to the idempotency cache. Add
hls_ to SECRET_PATTERN alongside the existing token prefixes.
2026-06-04 02:34:33 +02:00
Marc-André Bombeck 01f3374ab0 fix(insights): make TRAJECTORY_TYPES a distinct array, not an alias 2026-06-04 01:56:45 +02:00
Marc-André Bombeck 8e00e1615d fix(settings): add the sharing section icon to the placeholder map 2026-06-04 01:43:55 +02:00
Marc-André Bombeck 4afe1dc6d8 chore(api): regenerate OpenAPI for the trajectory derived metric 2026-06-04 01:40:48 +02:00
Marc-André Bombeck 0be484c8a3 feat(insights): TRAJECTORY forecasting derived metric with a widening band
Add a short-horizon OLS projection over the DAY-native per-day mean
series, extending the existing trendSlope. The fit, residual standard
error and prediction interval are computed at DAY granularity only — the
rollup invariant forbids composing a slope/sd from WEEK/MONTH buckets.

The projection is gated on fit quality (R squared), in-window history and
staleness: below any floor the engine returns insufficient rather than a
weak line, so noise is never extrapolated. The prediction-interval band
widens with the horizon distance from the data centre, so the fan
visibly communicates uncertainty.

Register TRAJECTORY in the derived registry and dispatch (additive,
iOS-forward-compatible; the capabilities endpoint and drift-guard pick it
up automatically). Surface it on the weight detail page as a forecast
band beneath the chart, labelled a projection with the cited method and
a conditional, range-only headline — never a prediction or a dated
event. i18n across all six locales.
2026-06-04 01:40:27 +02:00
Marc-André Bombeck dd1071158f feat(whoop): OAuth connect/callback + HMAC-signed webhook + CSP gating
Connect mints the state nonce into the WhoopOAuthState ledger and redirects
to the WHOOP authorize page; callback verifies the nonce (atomic
delete-first consume, four distinguished reason tags), exchanges the code,
fetches the WHOOP profile for the user id, persists the encrypted
WhoopConnection, and enqueues the self-converging history backfill.

The webhook handler rate-limits per source first, verifies the
WHOOP_WEBHOOK_SECRET path segment, then verifies the HMAC-SHA256 body
signature over the raw bytes (timestamp + body, timingSafeEqual, stale
timestamp reject) before any work. Valid *.updated enqueues the matching
per-resource sync; *.deleted soft-deletes (workouts hard-delete, no
soft-delete column). Unknown users return 200 to stop retries.

CSP gates api.prod.whoop.com to the WHOOP settings surface + /api/whoop/*;
the webhook path joins the public-path allowlist and the path-secret redact
registry. Env wiring adds WHOOP_WEBHOOK_SECRET + WHOOP_REDIRECT_URI to the
compose whitelist and .env.production.example.
2026-06-04 01:40:27 +02:00
Marc-André BombeckandClaude Opus 4.8 be94e43480 feat(share-links): owner share-link management in Settings
Add a Sharing section under Settings (between API and Export) where the owner
creates a read-only clinician share link, sees their active and inactive
links, and revokes one. Create wires to the C4 lifecycle API: it sends the
label, a rolling history window, an expiry (capped at 90 days, validated
before the round trip), an optional scoped FHIR-API toggle, and the FHIR
resource types. The raw token is revealed exactly once on create as a
copy-able `/c/<token>` URL; the list only ever carries the server's safe
projection (no token, since only its hash is stored). Revoke confirms through
an alert dialog and invalidates the list.

RSC page mounts a client island; reads unwrap the envelope and key off the
centralised query factory. New `settings.sharing` / `settings.sections.sharing`
strings land in all six locales.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 01:39:58 +02:00
Marc-André BombeckandClaude Opus 4.8 f4629a17d6 feat(share-links): scrub the share token from logs and harden the /c edge
Register the `/c/` prefix in `PATH_SECRET_PATHS` so the raw `hls_` clinician
share token, which rides as the trailing path segment, is rewritten to
[REDACTED] in `http.path` / `http.route` before any Wide Event or GlitchTip
report leaves the process — the same posture as the Withings webhook path
secret. The resolve path never logs, throws, or annotates the raw token.

Defend the share surface at the edge irrespective of what the RSC emits: the
proxy now sets `Cache-Control: no-store`, `X-Robots-Tag: noindex, nofollow`,
and `Referrer-Policy: no-referrer` on `/c/` responses, so no downstream proxy
caches a scoped record, no crawler indexes the token, and the token-bearing
URL is not leaked in an outbound `Referer`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 01:39:58 +02:00
Marc-André Bombeck 5917bba61c feat(insights): period-narrative summary on the overview
Add a calm "your week / month in review" summary to the Insights
overview, generated from the period-narrative context (deltas, personal
bands, FDR-controlled associations, coincident days).

- New insight_narratives table (migration 0113): one durable row per
  (user, period, locale); generated prose AES-256-GCM at rest following
  the coach-message precedent; labels-only provenance stays plaintext.
- generatePeriodNarrative feeds the context into the provider chain with
  a tight, descriptive-never-causal prompt; an insufficient context
  yields no narrative, a missing provider no-ops, neither fabricates.
- Nightly warm cron on week (Mon) / month (1st) boundaries, budget-gated
  per user; the read-only GET enqueues a single-user warm on a cold read.
- Read route is stale-while-revalidate and never blocks on the provider;
  the card renders plain text (no markdown), a single provenance
  disclosure, and a fixed footprint (no CLS). i18n in all six locales.
2026-06-04 01:21:42 +02:00
Marc-André Bombeck 337f024a87 feat(whoop): pg-boss sync workers + self-converging backfill
Build the WHOOP sync layer on the W2 client, mirroring the Withings
queues. A per-resource sync (recovery/sleep/cycle/workout) pulls since
the last cursor with a 24h overlap on recovery/sleep to absorb WHOOP's
after-the-fact re-scoring, maps via the W2 mappers, and upserts
Measurements with source=WHOOP keyed on (userId,type,source,externalId)
so a re-post overwrites in place. Workouts upsert into Workout with
per-workout strain + HR zones in metadata and kJ->kcal energy.

Token refresh persists BOTH rotated tokens (WHOOP invalidates the prior
access and refresh token on every refresh). A self-converging boot
backfill enqueues one full-history sync per un-backfilled connection and
stamps backfillCompletedAt; the discovery query drops completed accounts,
idempotent across reboots.

Every new queue is registered in the worker's allQueues + cron schedule
(recovery/sleep/workout poll catch-all, cycle poll-only, backfill,
oauth-state sweep). IntegrationStatus gains the whoop key + label.

Tests: rotating-refresh persistence, idempotent measurement upsert,
incremental-window overlap, backfill self-convergence, and a
queue-registration inventory guard.
2026-06-04 01:21:42 +02:00
Marc-André Bombeck 6aa3c75d27 feat(share-links): public clinician view at /c/[token]
A standalone read-only RSC that resolves the path token through the share-token
resolver and renders an owner-scoped clinical summary: provenance header,
clinical vitals and labs, medications with adherence, and a fenced muted card
for the descriptive wellness scores carrying the not-a-clinical-assessment,
not-a-diagnosis disclaimer. KVNR is default off. No app chrome, no coach, no AI,
no session, no markdown — every value renders as escaped text. force-dynamic and
noindex; the page returns a flat 404 for any null resolve.

The route joins the proxy public-path allowlist and the AuthShell standalone
list so it reaches the page bare without a sign-in redirect. New clinicianView
strings land in all six locales.
2026-06-04 01:21:42 +02:00
Marc-André Bombeck 9830ae8027 feat(share-links): public share-token resolver
resolveShareToken hashes a raw hls_ token, looks up the ClinicianShareLink,
enforces not-revoked and not-expired, and returns a ShareContext carrying only
the owner userId plus the frozen scope. It is not an auth primitive: it never
reads a session or sets a cookie, so a share token can authenticate only the
share surface. Unknown / revoked / expired / malformed tokens resolve to null
for a blunt 404. Access counters bump fire-and-forget on a hit.

A token presented on a normal authed route is rejected by construction —
requireAuth reads only the cookie session and Authorization: Bearer (against
ApiToken), never the share header, and an hls_ token has no ApiToken row. The
invariant test locks that boundary.
2026-06-04 01:21:42 +02:00
Marc-André Bombeck ceabf8a54d chore(api): regenerate OpenAPI for the FHIR and share-link routes 2026-06-04 01:05:15 +02:00
Marc-André BombeckandClaude Opus 4.8 57b8fd8ad9 feat(fhir): read-only FHIR R4 REST search routes
GET /api/fhir/{metadata,Patient,Observation,MedicationStatement,
MedicationAdministration} and $everything, returning type:"searchset"
Bundles (total + self/next links, offset paging via _count clamped to 200)
as application/fhir+json, with an OperationOutcome on error. The per-resource
emitters are reused from src/lib/fhir/resources.ts so the document export and
the REST face share one coding source and can never drift. Auth is a narrow
fhir:read scope via requireAuth (cookie sessions also pass); userId is
narrowed from auth. Read-only — no write handlers. Rate-limited per user.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 01:05:06 +02:00
Marc-André BombeckandClaude Opus 4.8 6c3b8be099 feat(share-links): owner clinician share-link lifecycle API
Authenticated owner routes to create, list, and revoke a ClinicianShareLink.
Create mints an hls_ token (192-bit), stores only its HMAC hash, and returns
the raw token exactly once; the scope columns (window, sections, FHIR resource
types, API toggle) are frozen write-once. expiresAt is required and capped at
SHARE_LINK_MAX_DAYS (90). Revoke sets revokedAt and seals a cross-user id as
404. userId is narrowed from auth; rate-limited; strict Zod rejects unknown
keys. This is the owner lifecycle only — the public resolver/view is separate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 01:05:06 +02:00
Marc-André Bombeck 2258cbb489 feat(whoop): WHOOP v2 API client, response classifier, credential resolution
Add the WHOOP integration data layer on copy-of-Withings rails:

- client.ts: hand-rolled fetch over safeFetch (no SDK) — OAuth authorize
  URL / code exchange / rotating-refresh, the four v2 collection fetchers
  (recovery, sleep, cycle, workout) with next_token pagination, single
  body-measurement + profile reads, and the field->Measurement mappers
  (RECOVERY_SCORE/HRV_RMSSD/RESTING_HEART_RATE/OXYGEN_SATURATION/
  SKIN_TEMPERATURE, per-stage SLEEP_DURATION ms->min, SLEEP_NEED/SLEEP_*,
  DAY_STRAIN/ENERGY_EXPENDITURE_KJ, source=WHOOP). Day strain maps to
  DAY_STRAIN and RMSSD to HRV_RMSSD so the device-native values never
  share a bucket with the COMPUTED STRAIN_SCORE / SDNN proxies.
- response-classifier.ts: HTTP-status-driven success/transient/
  reauth_required/persistent verdicts + WhoopApiError, mirroring the
  Withings reason-tag classifier.
- credentials.ts: per-user BYO-key resolution, decrypting the client
  id/secret from the User columns.
- oauth-state.ts: opaque-nonce mint helper + cookie/TTL constants.
- mapping.md: field->Measurement reference, kept in sync with the mappers.

Unit tests cover the classifier, pagination, every fetcher, the mappers
(ms->min, kJ->kcal factor, stage mapping, unscored-record handling), and
credential resolution against mocked WHOOP JSON. No routes / OAuth flow /
sync workers / migration yet.
2026-06-04 01:05:06 +02:00
Marc-André Bombeck 999f2b6b08 feat(insights): period-narrative context assembler
Assemble the structured, provenance-carrying data the period narrative
narrates, without any LLM call. buildPeriodNarrativeContext reads one
bounded window covering the current and prior period of equal length and
delegates to a pure core that produces metric deltas, derived-band
transitions, FDR-surviving correlation drivers, and coincident-deviation
flags as label+number+source beats.

Reuse the rollup-backed daily series, the median ± k·MAD personal band,
and the existing Benjamini-Hochberg correlation engine, so the
descriptive-never-causal contract carries through verbatim — a driver
never enters without clearing the FDR target, and each keeps its
conservative interpretation string unchanged. Gate on data availability:
too little history returns an insufficient shape, never a fabricated
story. Pure core is unit-tested over seeded fixtures.
2026-06-04 01:05:06 +02:00
Marc-André Bombeck 86dea3e176 chore(api): regenerate OpenAPI for the WHOOP measurement types 2026-06-04 00:50:26 +02:00
Marc-André Bombeck fbd45f3044 feat(ai): durable provider-health ledger and credential-expired surfacing
Promote the volatile per-worker last-working cache to a Postgres
provider-health ledger so the fallback chain shares one health signal
across every instance, modelled on the atomic-upsert rate limiter.

The ledger holds a durable negative cache: an auth-class failure
(401/403) benches that provider for a cooldown instead of re-burning the
dead round-trip on every generation; a sustained hard failure backs off
briefly. The local model is never benched — it stays the guaranteed
floor of the chain. Every ledger interaction fails open, so a DB error
falls back to today's chain walk exactly.

When the user's primary provider fails auth-class, the Coach emits a
distinct credential_expired frame that deep-links to reconnect rather
than a generic "try again later".

Adds the provider_health table (migration 0112) and the
errorCredentialExpired copy across all locales.
2026-06-04 00:50:13 +02:00
Marc-André Bombeck 6db3bef413 feat(measurements): add WHOOP source, native score types, and source-priority ladders
Add the WHOOP integration data layer (migration 0111): seven new
MeasurementType values (HRV_RMSSD, DAY_STRAIN, WORKOUT_STRAIN,
SLEEP_PERFORMANCE, SLEEP_EFFICIENCY, SLEEP_CONSISTENCY, SLEEP_NEED,
ENERGY_EXPENDITURE_KJ), a WHOOP MeasurementSource, the WhoopConnection
and WhoopOAuthState models, and the per-user encrypted BYO-key columns
on User. Day-strain takes DAY_STRAIN (not the COMPUTED STRAIN_SCORE) and
RMSSD takes HRV_RMSSD (not the SDNN HEART_RATE_VARIABILITY) so a native
value never shares a bucket with a derived proxy.

Carry the new types through the completeness walls (units, value ranges,
chart tokens, PR direction, categories, list-meta colours/icons/labels,
HealthKit-mapping exclusions) and feed the cross-source picker: recovery
ladder (WHOOP native above the COMPUTED proxy), WHOOP inserted into the
overlapping vital ladders and the workout ladder, plus skinTemperature
and respiratoryRate metric keys.
2026-06-04 00:49:31 +02:00
Marc-André Bombeck 747a62516a refactor(fhir): extract per-resource emitters into resources module
Lift the Observation / MedicationStatement / MedicationAdministration /
Patient / Coverage builders — with their LOINC/ATC/SNOMED/UCUM codings and
the survey-category wellness split — out of build-bundle.ts into a shared
src/lib/fhir/resources.ts. buildFhirDocumentBundle now composes the emitters
so the upcoming FHIR REST search routes reuse the exact same coding logic
instead of a second copy of the mapping.

Pure refactor: the document-bundle output stays byte-identical (the existing
FHIR + export tests pass unchanged). The shared coding constants and option
types re-export from build-bundle so existing import paths keep working.
2026-06-04 00:49:31 +02:00
Marc-André Bombeck f20ad79043 feat(db): add ClinicianShareLink model (migration 0110)
Owner-minted, scoped, time-limited, revocable read view of the health
record for a clinician holding the raw hls_ token. The token is stored
only as an HMAC-SHA256 hash; the scope (range start, sections, resource
types) is frozen at creation and never widened. expiresAt is mandatory
(capped at SHARE_LINK_MAX_DAYS, default 90); only revokedAt, lastAccessAt
and accessCount mutate after mint. Cascades on user delete.

Schema + migration only; no behaviour yet.
2026-06-04 00:49:31 +02:00
Marc-André Bombeck ea3dab33f7 Merge pull request #250 from MBombeck/release/v1.10.4
v1.10.4 — strain honesty label + six-minute-walk reference caveat
2026-06-03 21:42:42 +02:00
Marc-André Bombeck b56f712d4e chore(release): v1.10.4 — strain honesty label + six-minute-walk reference caveat 2026-06-03 21:33:30 +02:00
Marc-André Bombeck 73041b10cd docs(insights): note the Enright 40-80 cohort in the six-minute-walk caveat
The Enright & Sherrill 1998 predicted-distance equation was established on a
40-80 reference cohort; the metric accepts adult ages 18-120, so the
prediction extrapolates outside that range. State it in the user-facing
caveat (all locales) and the norms doc so a younger or older user reads
their percent-of-predicted with that honesty.
2026-06-03 21:33:06 +02:00
Marc-André Bombeck 097af3b84a feat(insights): surface the active STRAIN anchor per score
Carry the per-day STRAIN anchor (personal vs population) from the
strain_trimp_cache row through to the STRAIN WellnessScoreValue read, and
pick the framing line by it on the score-anatomy surface: relative to your
own typical effort once anchored personally, a general reference during
cold start. The method copy was describing both regimes generically and
could not tell the user which one produced this score. Additive read field
— iOS non-breaking.
2026-06-03 21:33:06 +02:00
Marc-André Bombeck a116848276 Merge pull request #249 from MBombeck/release/v1.10.3
v1.10.3 — personalised strain, a daily signal card, deeper derived metrics
2026-06-03 20:18:13 +02:00
Marc-André Bombeck 730c40dfef chore(release): v1.10.3 — personalised strain, a daily signal card, deeper derived metrics 2026-06-03 20:10:17 +02:00
Marc-André Bombeck 1e469d8185 fix(insights): eliminate layout shift on the Today's-signal card
The dynamic loader skeleton reserved 120px while the resolved card's
insufficient (~168px) and fired (~192px) states ran taller, shifting the hero
and everything below it down 48–72px on resolve. Pin a min-h-48 on the card
shell sized to the tallest realistic state, and match both the chunk-loader
skeleton and the in-component CardSkeleton to that footprint (including the
44px provenance header row) so there is zero shift across loading → any state.
Announce the fired state to screen readers via a polite role=status (not the
assertive role=alert), and mark the decorative loader skeleton aria-hidden.
2026-06-03 20:07:46 +02:00
Marc-André Bombeck 17ad93ca5d feat(insights): surface the four new derived metrics as dashboard tiles
The estimated 6-minute-walk band + the three any-user HealthKit baseline
bands (wrist temperature, stair ascent/descent speed) were registered,
provenance-mapped and engine-tested but rendered on no surface. Add a
"Mobility & body" section to the vitals dashboard: the 6MWT passthrough
re-frame (distance + trend always, percent-of-predicted framing only with
the Enright demographics) and a shared baseline-band tile for the three bands.
Every tile is data-availability-gated like the existing ones — absent with no
readings, CoverageMeter while provisional, value + framing + provenance when
ready — and the section heading hides when none resolve. All four tokens ride
the single batched derived request. Derive the sparkline gradient id via
useId() to avoid duplicate-label collisions.
2026-06-03 20:07:46 +02:00
Marc-André Bombeck a31add266f fix(i18n): port STRAIN personal-anchor honesty copy to all locales
The personal-relative-anchor explanation (own recent training-day load vs a
general reference while building history) was EN-only; de/es/fr/it/pl carried
the stale v1.10.0 method+description. Port both strings to all five so the
two-mode honesty distinction is visible regardless of locale. Also correct the
stale strain-score header comment: STRAIN is not excluded from the doctor PDF —
it rides a segregated, disclaimed Wellness-summary section.
2026-06-03 20:07:46 +02:00
Marc-André Bombeck 7ff91fcf55 refactor(insights): drop the unused baseline-capable-type allowlist
The additive HealthKit baselines dispatch via an explicit per-metric type
map, so the allowlist helper and its constant had no consumer.
2026-06-03 20:03:14 +02:00
Marc-André Bombeck 46be440ee8 chore(api): regenerate OpenAPI for the derived series field 2026-06-03 19:48:57 +02:00
Marc-André Bombeck b7cb92d951 fix(insights): compute the sleep midpoint in the user's timezone
The sleep midpoint was minutes-of-day in UTC, so a non-UTC sleeper's
consistency and timing sub-scores drifted with the offset (a 03:00-local
midpoint read as a different clock time than a UTC user's). Resolve the user's
stored zone in computeSleepScore and express the midpoint against it via the
existing tz helpers; reconstructNights takes an explicit tz (UTC default) so
the pure path stays test-pinnable.
2026-06-03 19:48:48 +02:00
Marc-André Bombeck 8806ce4e08 refactor(insights): name the latest-day-mean row cap on the derived readers
The readiness + coincident-deviation latest-day-mean reads cap the row scan
on a dense intra-day day. Lift the bare 50 into a named MAX_LATEST_DAY_ROWS
constant and document the dense-intraday-retention reasoning at both call
sites so the bound is intentional rather than a loose literal.
2026-06-03 19:48:48 +02:00
Marc-André Bombeck 3ca444d23f fix(insights): interpolate age/sex norm bands across bracket boundaries
The age/sex reference tables are coarse decade / paediatric brackets, so a
fractional age read a hard step at a bracket edge (39.9 -> 30s band, 40.0 ->
40s band). Anchor each band at its bracket centre and linearly interpolate a
fractional age between the two adjacent centres; below the youngest centre /
above the oldest centre hold the nearest cited band flat (clamp, never
extrapolate) so the band stays within the span of the two cited brackets and
the standard's provenance stays accurate.
2026-06-03 19:48:48 +02:00
Marc-André Bombeck 99e089ff4c feat(insights): populate the trailing sparkline series on derived metrics
The Derived<T> tile (SparklineDeltaTile) renders a trailing series, but the
engines never filled it, so the inline sparkline was always empty. Each engine
now carries a capped trailing series sourced from the rows it already reads:

- baseline-band metrics (incl. wrist-temperature / stair ascent+descent) ship
  the per-day mean series the band is built from;
- HRV balance reuses the day-mean read it already does for the recent average;
- the wellness scores (recovery / stress / strain) ship their window scores;
- the six-minute-walk band ships its reading series;
- BMI reads a bounded recent-weight set and derives a BMI series at the fixed
  profile height.

All series cap at the last 30 points. The vitals dashboard wires the series
into the baseline, HRV and BMI tiles; the tile already renders >= 2 points and
collapses the sparkline row otherwise.
2026-06-03 19:48:48 +02:00
Marc-André Bombeck e2c7d08bad chore(api): regenerate OpenAPI for the additive derived-metric ids 2026-06-03 19:31:29 +02:00
Marc-André Bombeck efa132b1aa fix(insights): make the score candidate finders deterministic
The recovery / stress / strain nightly finders used distinct + take with no
order, so when more than the cap of users qualified the selected set was
arbitrary across runs. Switch to a grouped query ordered by each user's
newest input first with userId as the stable tiebreak, so the cap takes the
most-recently-active users reproducibly. The strain finder interleaves its
workout and active-energy lists so the merged cap favours recency across both
sources.
2026-06-03 19:31:16 +02:00
Marc-André Bombeck f1ca0e28eb feat(insights): anchor STRAIN to the user's own training load
Map day-total Banister TRIMP to 0-100 against a personal reference -- the
EWMA-smoothed 75th percentile of the user's own training-day TRIMP over a
42-day chronic window -- instead of the fixed population anchor that pinned a
deconditioned or chronic-condition user near 0 regardless of their effort.
Below a 7-training-day cold-start floor the engine falls back to the
population anchor, recorded as anchor: population with lower confidence; at
or above it the personal anchor takes over. Always writes a score row -- no
new null gate. The anchor is derived from the TRIMP input, never the 0-100
output, so there is no circular feedback; rest-day zeros stay out of the
training-day distribution.

Add a server-internal per-(user, day) strain_trimp_cache (day-total TRIMP +
running EWMA reference + anchor) so the chronic window reads cheap cached
values instead of re-integrating 42 days of HR series each night. The cache
is not a Measurement -- it stays out of every user-facing surface, the
doctor PDF, and the FHIR bundle by construction. No backfill: the nightly
idempotent recompute populates the cache forward and self-heals, falling
back to the population anchor until enough personal history accrues.

Keep the Banister/Morton/Tanaka citations and the doctor-PDF exclusion; the
honesty copy now states the scale is relative to the user's typical effort,
with a general reference during cold start.
2026-06-03 19:31:16 +02:00
Marc-André Bombeck 059ba571e3 feat(insights): derived framing for additive HealthKit metrics
Register four new derived metrics for the additive HealthKit signals:

- WRIST_TEMPERATURE_BASELINE, STAIR_ASCENT_SPEED_BASELINE,
  STAIR_DESCENT_SPEED_BASELINE — any-user-baseline personal bands reusing
  the type-generic median +/- k*MAD engine via a new BASELINE_CAPABLE_TYPES
  allowlist. Wrist temperature is a personal-deviation band only (no illness
  or cycle inference); stair speeds are personal trend bands (no population
  cutoff, geometry-confounded).
- SIX_MINUTE_WALK_BAND — passthrough re-frame placing the device-estimated
  distance against the Enright & Sherrill 1998 predicted 6MWD (ATS 2002
  test standard), as percent-of-predicted with a green/yellow/red band;
  band null when age/height/weight/sex are incomplete.

Fall count and the breathing-disturbance index stay trend-only by design,
documented in the registry: fall count is a zero-inflated discrete safety
event, the breathing index is a regulated screening signal where a derived
band would imply a diagnosis.

Note wrist temperature as a deferred correlation outcome channel held
pending a privacy review (cycle-phase inference risk), mirroring the
medication-compliance omission note.

Add provenance + standards entries, method/caveat copy across all six
locales, and tests for the engine routing, the Enright equation, and the
percent-of-predicted band.
2026-06-03 19:29:36 +02:00
Marc-André Bombeck 789ec60d97 feat(insights): elevate coincident-deviation to a dedicated "Today's signal" card
Promote the COINCIDENT_DEVIATION flag from a fire-only tile buried in the
below-the-fold vitals grid to an always-mounted headline card at the top of
the Insights overview. The card renders four calm states off the single
existing derived payload — building-baselines, all-clear, watch, fired — with
no new engine math, route, or schema change.

Keep it calm and clinically safe: at most an amber band, never red, no score,
no chart, no push. Soften a fired flag to the watch tone when the backing
history is thin. The fired/watch states carry the load-bearing "possible
factors, never a cause / not a diagnosis" framing and reuse ProvenanceExplainer
+ CoverageMeter + the band tokens verbatim.

Remove the now-redundant tile, its batch token, and the hasRenderableVital
branch from the vitals grid so the signal is not shown twice.
2026-06-03 19:29:36 +02:00
Marc-André Bombeck fe099acd67 Merge pull request #248 from MBombeck/release/v1.10.2
v1.10.2 — honest AI connection test, consistent insights, retention re-enabled
2026-06-03 09:27:33 +02:00
Marc-André Bombeck 44028b2a6e chore(release): v1.10.2 — honest AI connection test, consistent insights, retention re-enabled 2026-06-03 09:18:55 +02:00
Marc-André Bombeck 9bdf76ea11 fix(settings): localise AI connection-test failure reasons
Return a stable, secret-free reasonCode from /api/ai/test alongside the
English reason, map it to a localised string in the AI settings panel,
and fall back to the plain reason for any unmapped code. A German
operator no longer sees an English failure sentence in an otherwise
localised panel.
2026-06-03 09:17:13 +02:00
Marc-André Bombeck d8f623aea3 fix(measurements): close residual P2002 in the dense intra-day fold
Resolve the canonical daily row deterministically: prefer the row already
carrying the target stats: externalId before falling back to the row on the
canonical local-noon instant, with a stable orderBy tiebreaker. Adopting a
sibling and stamping the target externalId onto it could otherwise collide on
the (userId, type, source, externalId) index with the real canonical row.

Re-anchor the adopted row to local-noon only when that slot is free, so an
externalId row at a tz/DST-shifted instant cannot collide on the measured_at
composite during adopt.

Guard the create against a concurrent insert on the same canonical composite:
catch P2002 outside the transaction (a caught error inside leaves the tx in
the aborted state) and retry the fold once, which then resolves and adopts the
winning row instead of creating a duplicate.

Add a real-Postgres case covering a row already on the canonical instant under
the target stats: externalId plus a fresh out-of-window batch: the fold adopts
in place, no P2002, one canonical row with the correctly folded mean.
2026-06-03 09:17:13 +02:00
Marc-André Bombeck 8456d3bbc3 chore: correct body-cap comments, dockerignore licence posture, stale log copy
- workouts/batch + safeJson: the body cap is a DoS ceiling, not a bound
  the worst-case payload always fits under; an extreme GPS-heavy backlog
  can exceed it and falls back to smaller batches client-side. Note that
  request.text() still buffers the raw body, so the cap bounds the parse
  cost, not the initial read.
- .dockerignore: keep LICENSE / LICENSE.md in the image — AGPL-3.0
  conveys with the software.
- reminder-worker: the dense walk flag is an operator kill-switch now
  that the fold is reworked, not a pending-rework gate.
2026-06-03 09:10:46 +02:00
Marc-André Bombeck 33358c7960 test(medications): pin the GLP-1 card clock off the schedule window
Two assertions depended on the live wall-clock: the card suppresses the
upcoming-injection line while now sits inside a schedule window, so a CI
run during the 08:00-20:00 window rendered the pill instead of the
Next/Recommended-next line. Pin to 07:00 Berlin on a non-scheduled day.
2026-06-03 08:59:31 +02:00
Marc-André Bombeck 0ec5f7552f chore(api): regenerate OpenAPI for the capabilities endpoint 2026-06-03 08:59:31 +02:00
Marc-André Bombeck dbdc99a4a1 fix(insights): return values sub-page back-link to the originating metric
The show-all-readings link now carries the originating metric page as a
sanitised from param, so a weight to show-all drill-in returns to weight
rather than the Insights overview. The param is constrained to an internal
/insights/<slug> path so a crafted value cannot redirect off-site.
2026-06-03 08:56:20 +02:00
Marc-André Bombeck 732e85e4df fix(insights): add scores drill-down back-link and unify back-link styling
The composite-score detail page (/insights/scores/[metric]) gains a leading
back-link to the Insights overview, matching the other drill-down surfaces.
Align the medication detail + history back-links onto the canonical ghost
recipe (-ml-2 w-fit, mr-1 size-4 icon) used by the values and workout-detail
pages, replacing the divergent -ml-2 gap-1 variant.
2026-06-03 08:56:20 +02:00
Marc-André Bombeck 692b091637 feat(insights): unify range controls and part set across bespoke metric pages
Mount MetricRangeControls on the measurement-series bespoke pages (weight,
blood-pressure, pulse, bmi, sleep) so the range selector no longer vanishes
when navigating from a HealthKit metric. Mood, workouts, and medications are
event-driven rather than MeasurementType series, so they document the
omission inline.

Apply the canonical part set where the data supports it: blood-pressure and
sleep gain the diversity nudge + show-all-values foot link. Blood pressure
omits the single-series stat strip (it is sys+dia) and bmi omits the strip /
nudge / show-all entry (it is derived from WEIGHT), each with an inline note.
2026-06-03 08:56:20 +02:00
Marc-André Bombeck 73255f817d refactor(insights): extract shared MetricRangeControls from HealthKit page
Lift the time-range pills + period-over-period delta block out of
HealthKitMetricPage into a standalone MetricRangeControls component that
owns the range pref, the range read, and the direction-sentiment lookup.
The HealthKit scaffold now consumes the shared piece so the bespoke metric
pages can render the identical control.
2026-06-03 08:56:20 +02:00
Marc-André Bombeck 5b5ab5795c fix(settings): guard AI test and regenerate against non-JSON responses
The test and regenerate handlers called res.json() unconditionally. A
proxy-rewritten HTML error page made that throw "Unexpected token '<'",
which leaked into the toast. Both handlers now check the content-type and
wrap the parse, showing a clean message on a non-JSON body. The test
handler also renders the new { ok:false, reason } payload verbatim.
2026-06-03 08:56:20 +02:00
Marc-André Bombeck 564d7dec77 fix(ai): never 5xx from the connection test and report a categorised reason
The connection-test route mapped a provider 5xx to a 502, which a reverse
proxy rewrites to its own HTML error page; the browser's res.json() then
threw "Unexpected token '<'". Every provider-call failure now returns
HTTP 200 with a secret-free { ok:false, providerType, reason }. Reasons
are categorised: credential/auth (401/403, or a 5xx whose body signals an
invalidated/expired session), rate-limit (429), provider server error
(other 5xx) and network/timeout.

The empty-override "test my saved config" path now resolves through the
same provider chain generation uses, instead of the legacy codex->admin
probe that could test a different provider than the one generation runs.

The chain runner already advances past an auth-class failure to the next
enabled provider; add explicit coverage for that on the raw generation
path (401 -> next succeeds, fallback count incremented).
2026-06-03 08:56:19 +02:00
Marc-André Bombeck 192fe45469 feat(api): add GET /api/meta/capabilities discovery endpoint
Expose the server's live id vocabularies (derived-metric ids,
vitals-baseline types, insights layout tile-ids, metric-status ids,
the HealthKit ingest mapping, computed-score types, write allowlist) and
the FHIR coding constants, plus the running contract version, behind
requireAuth (cookie or Bearer, not admin).

Every list is sourced from its canonical server constant / registry, so
the endpoint cannot drift from what the routes actually accept and emit —
retiring the doc-vs-server enum-drift class for the native client. Export
the FHIR ATC/SNOMED URIs and a shared german-ATC default-locale set so the
export route and the discovery surface share one source.

Register the route in the OpenAPI table; drift-guard tests pin
derivedMetricIds to the registry and writeAllowlist to the constant.
2026-06-03 08:56:19 +02:00
Marc-André Bombeck 5ae7aa7570 feat(insights): add load, error, and empty states to the vitals dashboard
Render a skeleton row matching the resolved tile height while the derived
batch loads so the grid reserves its final footprint with no layout shift.
Hide the section heading until there is content (or a skeleton placeholder)
under it, removing the stranded-heading layout shift on empty data. Surface
an inline error message plus a Retry that refetches the shared batch query
when the batch fails, instead of the whole surface silently vanishing. Mark
the tiles container aria-busy while loading and aria-live polite, matching
the insights a11y pattern.
2026-06-03 08:56:19 +02:00
Marc-André Bombeck 786454ee2f fix(ui): repoint medication + admin status colours to theme tokens for light-mode AA
The intake-history taken badge and the admin reminders status glyphs used
bare Tailwind -400/-500 shades chosen for the dark theme. On the white
Alucard light card those land well below WCAG AA (green-400 1.74:1,
red-400 2.77:1, yellow-400 1.53:1). Repoint to the success / destructive /
warning theme tokens (light values 6.1:1 / 5.0:1 / 5.8:1 on white) and pin
the original shades behind dark: so the dark rendering stays identical.
2026-06-03 08:56:19 +02:00
Marc-André Bombeck 48f20f4622 feat(api): cap request-body size on batch and export ingest routes
Apply safeJson's opt-in maxBytes ceiling to the body-accepting batch
and export routes that lacked one. The cap measures the raw text
before JSON.parse, so an over-limit payload returns a clean 413
without buffering onto the heap.

- workouts/batch: reuse the existing 5 MB ceiling so chunked uploads
  with no Content-Length are bounded too.
- measurements/batch: 4 MB — an order of magnitude above a 500-entry
  batch's few-hundred-KB worst case.
- export/health-record: 64 KB — the selection payload is small and
  bounded.

Each cap is a DoS ceiling sized well above any legitimate payload,
never a tight bound on a real batch.
2026-06-03 08:56:19 +02:00
tarantila 81b9606f6f fix(docs): improve README language 2026-06-03 08:11:07 +02:00
tarantila 2795a50eef fix(docker): harden Docker build context 2026-06-03 08:11:05 +02:00
Marc-André Bombeck 64965162c7 feat(measurements): re-enable the dense intra-day retention drain
The v1.10.0.2 kill-switch defaulted the drain OFF after the P2002 fold
collision. With the fold reworked to coexist with the canonical daily row
and integration-tested against real rows, flip the default back ON
(DENSE_INTRADAY_RETENTION_ENABLED=true unless explicitly set to false). The
boot-discovery still defers past the startup storm via the boot-delay so it
never contends for the connection pool on a data-heavy tenant; the nightly
03:50 walk and the per-user handler run again.
2026-06-03 07:41:20 +02:00
Marc-André Bombeck f049eeb8b1 fix(measurements): rework dense intra-day fold to coexist with the canonical daily row
The dense intra-day retention fold minted its daily-mean stats: row with
an externalId-keyed upsert. On real data a row already occupies the
canonical local-noon instant — a sibling daily stats: row or a per-sample
HRV/PULSE reading that fell on noon — so the upsert lookup missed (the
existing row carries a different externalId) and the INSERT then violated
the (user_id, type, measured_at, source, sleep_stage) unique index with
P2002. The mocked unit tests could not surface it.

Resolve the canonical row by the measured_at composite the collision is on
(sleep_stage IS NULL for these continuous types, matched via the
NULLS NOT DISTINCT index) and adopt it in place — refresh the mean, stamp
the canonical stats: externalId, un-tombstone — or create it when absent.
Exclude the adopted row id from the per-sample soft-delete so a noon-instant
sample becomes the daily row instead of being tombstoned.

Add a testcontainer integration test that seeds the colliding shape (a
pre-existing canonical-instant row plus out-of-window per-sample rows) and
pins no-P2002, coexistence, the noon-sample case, idempotency, and the
retention bound. Update the unit coverage for the adopt-in-place path.
2026-06-03 07:41:20 +02:00
Marc-André Bombeck e6ade6b03d Merge pull request #247 from MBombeck/release/v1.10.1
v1.10.1 — consistent medication cards
2026-06-03 07:22:47 +02:00
Marc-André Bombeck b7b7e327ce chore(release): v1.10.1 — consistent medication cards 2026-06-03 07:17:01 +02:00
Marc-André Bombeck 2a584f6210 test(medications): pin card next/last slot symmetry + equal height
Extend the symmetry suite to assert both cards render the byte-identical
next/last slot wrapper (same reserved min-height, spacing, muted colour,
next-then-last order, no em-dash placeholder, no brighter foreground
token) and a constant-height bottom-pinned body across oral / injection
/ GLP-1 / PRN / one-shot, including the compliance-skeleton path. Update
the dose-accent assertions onto text-dose-accent and the GLP-1 rotation
test onto the folded-into-line nudge. Clock stays pinned.
2026-06-03 07:07:48 +02:00
Marc-André Bombeck b3e8f43ab8 fix(medications): make the card identical across every type
Route both the generic and GLP-1 cards through the shared next/last
slot, ending the divergence that made two meds of different types read
differently in the same grid row:

- the GLP-1 card showed last-then-next; both now show next-then-last;
- its next line painted text-foreground/85; both now use the muted token;
- its inner spacing was space-y-1; both now use space-y-3.5;
- it always rendered the next line and printed a literal em-dash when
  there was no next injection; both now gate the line on an actual next
  and drop the placeholder.

Make CardContent a flex column and pin the action row with mt-auto.
Combined with the reserved next/last slot and the constant-height
compliance skeleton, every card body is now equal height, so the pin
aligns the take/skip buttons across a grid row without opening the void
that an unequal-height pin produced before.

Fold the GLP-1 injection-site rotation nudge into the upcoming-injection
line instead of a separate bordered block, so the GLP-1 card keeps the
same row inventory and height as the generic card.

Repoint both cards' dose accent onto text-dose-accent, drop the GLP-1
compliance query's active-only enabled guard so both cards make the same
calls, and share the weekday-label helper.
2026-06-03 07:07:48 +02:00
Marc-André Bombeck 0255dbad7d fix(medications): repoint dose accent onto an AA-safe theme token
The medication cards stamped the upcoming schedule dose with Tailwind
stock text-purple-400, which reads ~3.1:1 on the white Alucard light
card and fails WCAG AA for body text. Add a theme-aware --dose-accent
token: the exact text-purple-400 oklch in dark mode (so the dark card
stays pixel-identical) and a darker AA-safe purple on the light card,
mirroring how the semantic feedback tokens land each tone above AA in
both themes. The cards switch to text-dose-accent in the follow-up
commit.
2026-06-03 07:07:48 +02:00
Marc-André Bombeck e4bec11c2f feat(medications): add shared next/last slot + compliance skeleton card-parts
Extract the medication-card middle slot into a shared
<MedicationNextLastSlot> so the generic and GLP-1 cards render an
identical next/last region — same order (next then last), same
text-muted-foreground colour, same space-y-3.5 spacing, same reserved
min-height, and the same gating (the caller passes a next line only when
one should show; the part never prints a placeholder). A shared
useWeekdayLabel helper collapses the two weekday i18n key families onto
the abbreviated form so the same weekday no longer renders 'Monday' on
one card and 'Mon' on the other.

Add a MedicationComplianceSkeleton that reserves the compliance block's
footprint while the per-card query is in flight or returns null, so a
card without compliance is no longer ~5rem shorter than its grid-row
sibling.
2026-06-03 07:07:48 +02:00
Marc-André Bombeck e1ea0f6645 Merge pull request #246 from MBombeck/fix/disable-dense-retention
v1.10.0.2 — disable intra-day retention drain (P2002 fold collision)
2026-06-03 03:45:37 +02:00
Marc-André Bombeck 7bd66615b6 fix(jobs): disable the dense intra-day retention drain (P2002 fold collision) 2026-06-03 03:39:01 +02:00
Marc-André Bombeck 1bd668ae88 Merge pull request #245 from MBombeck/fix/dense-retention-boot-defer
v1.10.0.1 — defer intra-day retention drain past startup
2026-06-03 02:29:26 +02:00
Marc-André Bombeck 3080828fb7 fix(jobs): defer the dense intra-day retention boot drain past startup to avoid pool exhaustion 2026-06-03 02:22:35 +02:00
Marc-André Bombeck 1fe70b27f5 Merge pull request #244 from MBombeck/release/v1.10.0
v1.10.0 — derived wellness metrics, device-event awareness, deeper ingestion
2026-06-03 01:17:14 +02:00
Marc-André Bombeck 56e9816def test(medications): pin the card clock so window-status and day labels are deterministic 2026-06-03 01:07:36 +02:00
Marc-André Bombeck fbab8cfd30 fix(jobs): break consolidation import cycle that crashed the worker at boot
The reminder worker failed to start in the production bundle with
`ReferenceError: Cannot access 'l' before initialization`, taking every
nightly pg-boss job down with it (score jobs + dense-intraday retention).

Root cause is a value-level import cycle between `consolidation-base.ts`
and `drain-per-sample-cumulative.ts`: each imported values from the other.
The bundler merges the tightly-cyclic pair into one module body and hoists
`DRAIN_CUMULATIVE_CUTOFF_HOURS = CONSOLIDATION_GRACE_CUTOFF_HOURS` ahead of
the constant it reads, so the eager read hits a temporal dead zone. It only
surfaced in the production build because dev/test run the modules unbundled.

Hoist the shared leaf — `CONSOLIDATION_GRACE_CUTOFF_HOURS`, the `PerSampleRow`
shape, and the timezone day-math helpers — into a new dependency-free module
`consolidation-tz.ts`. Both sides now import from the leaf, removing the cycle
at its root. Re-export the moved names from their former homes so every
existing import site resolves unchanged.
2026-06-03 01:01:21 +02:00
Marc-André Bombeck d105849026 fix(fhir): resolve the medication-administration cap per call so an operator override takes effect 2026-06-03 01:00:04 +02:00
Marc-André Bombeck e1d4182a03 test(medications): pin the clock for the next-due day-label assertion 2026-06-03 01:00:04 +02:00
Marc-André Bombeck 8dbfc6989a refactor(measurements): drop the unused score-type set and rhythm-classification enum 2026-06-03 01:00:04 +02:00
Marc-André Bombeck 56e14aa9fa Merge remote-tracking branch 'origin/main' into release/v1.10.0
# Conflicts:
#	CHANGELOG.md
#	docs/api/openapi.yaml
#	package.json
2026-06-03 00:40:41 +02:00
Marc-André Bombeck d43cbf3a3b chore(release): v1.10.0 — derived wellness metrics, device-event awareness, deeper ingestion 2026-06-03 00:08:22 +02:00
Marc-André Bombeck d369b406ac test(insights): align trend-sentiment + gate-inventory tests with the changes
The semantic-token swap means the trend arrow/delta now emit
text-success/text-warning (pixel-identical in dark, AA-safe in light), and
the batched derived route joins the insightStatus allowlist alongside the
single route. Update the trend-card sentiment-colour assertions and the
coach-route gate inventory accordingly.
2026-06-03 00:04:56 +02:00
Marc-André Bombeck 551d352581 feat(insights): surface inputs, method and a cited standard for all 11 derived metrics
Only Sleep and Readiness reached a provenance surface; the other nine
shipped a number with the cited standard buried in a code comment. Give
every derived metric a path to its inputs + method + cited standard:

- Recovery, Stress and Strain get a ScoreAnatomyView detail page and a
  tappable ring (they were read-only dead-ends). Stress surfaces its
  'HRV-derived proxy, NOT an EDA/galvanic measurement' caveat; Strain
  cites the TRIMP load model; Recovery the HRV-guided recovery literature.
- The vitals tiles (baseline, HRV balance, BMI, fitness age, vascular age)
  gain an info explainer affordance carrying the method + standard, since
  they render as tiles with no detail page.
- The coincident-deviation flag gains a dashboard tile (shown only when it
  fired) with the same explainer (median ± k·MAD basis).
- A single standards map (src/components/insights/derived/standards.ts)
  pins each metric's method copy key, standard name and a real linkable URL
  (DOI / WHO / Wikipedia) so the citation a metric exposes stays one source.

Add the per-metric method/caveat/description copy across all six locales.
Map storage units to display symbols so a baseline tile reads '36.6 °C',
not '36.6 celsius'. Show the band word under the strip rings so a value
reads 'low 62', not a bare reddish 62. Drop the empty dashed sparkline
placeholder when no trailing series exists rather than reserving dead
space, and give the tile a series + provenance slot for when one does.
2026-06-03 00:04:56 +02:00
Marc-André Bombeck b92d5cec82 feat(insights): batch the derived-metric reads behind one route
The Insights cold mount fired 14+ independent GET /api/insights/derived
requests — Readiness, Sleep and the vitals baselines are compute-on-visit,
and all of them share one Prisma pool. That is the pool-starvation class
that surfaces as the app hanging then recovering.

Add GET /api/insights/derived/batch?metrics=a,b,c[:type] that resolves the
requested metrics server-side under a bounded p-limit(4) with the profile
loaded once via the shared loadBaselineProfile, returning a map of the same
flat Derived<T> envelope keyed by the request token. Add the useDerivedBatch
hook + the insightsDerivedBatch query-key factory entry; the single-metric
route + hook stay for the per-score detail pages. The single route now also
adopts loadBaselineProfile instead of re-inlining the profile read. Honors
the existing 8s ceiling, retry:0, replace-with-fallback, and warms nothing
on visit. Register the new route in the OpenAPI contract.
2026-06-03 00:04:56 +02:00
Marc-André Bombeck 3f8c8e750c fix(i18n): translate the device-notification namespace for es/fr/it/pl
The entire insights.rhythmEvents namespace — section title, intro, the
load-error, and the medical-adjacent device-detection disclaimer — shipped
the English string verbatim in es/fr/it/pl. The locale-integrity guard only
checks key shape + placeholders, so the copy-paste passed CI while rendering
English on a Spanish/French/Italian/Polish device-notifications card,
disclaimer included. Translate the four keys into real localised copy.
2026-06-03 00:04:56 +02:00
Marc-André Bombeck 60c0ba4483 fix(insights): point derived score-band tokens at the AA-corrected semantic colours
The band primitives (score ring, coverage dots, contributor bars,
provenance chips + standard link, sparkline tint, trend arrow/delta)
painted straight from the raw `--dracula-*` variables, which carry no
`:root.light` override. On the white card the Alucard light theme uses,
the green/orange/yellow cleared roughly 1.1-1.5:1 — under AA — and the
`bg-dracula-yellow` confidence dot read near-invisible. The file comment
claimed they 'track automatically'; they did not.

Point BAND_NUMBER/PROGRESS/BORDER/VAR, the coverage-meter dot tint, the
provenance cyan chips, the sparkline stroke, and sentimentColorClass at
the semantic `--success`/`--warning`/`--destructive`/`--info` tokens
instead. Those alias the same Dracula tones in dark mode (pixel-identical
there, the primary target) but carry the darker AA-safe values under
`:root.light`. Clamp the score-ring provisional caption to one line so a
longer localised string cannot wrap over the ring arc.
2026-06-03 00:04:56 +02:00
Marc-André Bombeck ecf93317dd docs: document the wellness-summary report section and correct the computed-scores note 2026-06-02 23:43:22 +02:00
Marc-André BombeckandClaude Opus 4.8 f170198a83 fix(measurements): validate single-POST source against the writable allowlist
WRITABLE_MEASUREMENT_SOURCES was a dead export whose docblock claimed it
gated the single-entry POST, but the schema only refined out COMPUTED —
WITHINGS and IMPORT stayed client-writable, so a client could attribute a row
to a source the server owns (the Withings webhook / CSV importer) and pollute
the per-source canonical picker. Wire createMeasurementSchema.source to a Zod
enum built from the now-correct {MANUAL, APPLE_HEALTH} allowlist; the enum
subsumes the old COMPUTED refine. Regenerate the OpenAPI contract.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 23:40:24 +02:00
Marc-André BombeckandClaude Opus 4.8 dabdfdf68e fix(insights): confidence reflects real history depth; readiness source folds sleep + mood
The readiness and coincident-deviation composites passed historyDays =
windowDays (a constant) into deriveCoverage, pinning historyFraction to 1 so
a 7-day and a 30-day blend reported identical confidence. Pass the real
distinct-history-days backing the composite (the depth of the
best-supported present contributor) so confidence tracks actual depth.

The readiness provenance source was derived only from RHR/HRV/respiratory, so
a blend backed solely by sleep + mood could mislabel as DAY. Fold the present
sleep + mood provenance in so the source chip matches what actually backed
the headline.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 23:40:24 +02:00
Marc-André BombeckandClaude Opus 4.8 fc6924d52f fix(insights): circular sleep-midpoint distance and explicit efficiency overlap
The sleep-score consistency + timing sub-scores measured the midpoint as a
linear minutes-of-day difference, so a sleeper whose midpoint straddles
midnight (and any night across a DST shift) read a spurious ~24-hour spread
that inflated the SD and timing distance. Measure the midpoint on the
circular 24-hour clock (mod 1440) — a circular mean for the habitual midpoint
and a circular distance for the SD and timing offset.

Efficiency clamped asleep > in-bed (overlapping HealthKit stages) silently to
100, masking a data problem. Handle the overlap explicitly: a small overshoot
caps at the AASM ceiling of 100 (asleep cannot exceed time in bed), a gross
overshoot drops the sub-score because the in-bed denominator is not usable.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 23:40:24 +02:00
Marc-André BombeckandClaude Opus 4.8 cd8e34dac7 fix(insights): place HRV balance against the recent trend, not the band center
computeHrvBalance read recentAvg = baseline.value.center, which is the band
midpoint by construction and therefore always inside [low, high] — so the
"low" and "unbalanced" arms were dead and the card could only ever read
"balanced". Compute recentAvg from the last <= 7 DAY means (the recent
trend) and place that against the longer-window personal band, so a
suppressed recent trend flags "low" and an elevated one flags "unbalanced".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 23:40:24 +02:00
Marc-André BombeckandClaude Opus 4.8 148e6cd600 fix(insights): score the previous day in the nightly score engines
The Recovery/Stress/Strain crons fire in the small hours (04:45-04:55
Europe/Berlin, ~03 UTC) but scored the CURRENT UTC day, only a few hours
old: Strain missed the just-completed day's workouts and Stress saw a
near-empty intra-day SDNN set and falsely gated as insufficient. Score the
day that just ended (now - 1 day) across all three engines and their
measuredAt / externalId day stamps.

Resolve the previous-day key in one place by extracting the shared score-row
helpers the three engines each duplicated: scoreDayKey / scoreMeasuredAt /
scoreExternalId, the idempotent upsertScoreRow, and the cohort runScoreBatch
tally loop into src/lib/insights/score-row.ts; and loadBaselineProfile into
the baseline engine (the three byte-identical profile loaders + the partial
strain variant now route through it). The derived route should adopt
loadBaselineProfile too.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 23:40:24 +02:00
Marc-André Bombeck 78c8177cd3 feat(insights): fold a confidence-gated derived signal into the daily briefing
When a derived wellness score (readiness or recovery) crosses a notability gate
— outside the green band AND confidence at least medium — the insights
generator now appends a SYSTEM CONTEXT block so the briefing can narrate the
shift observationally. Mirrors the GLP-1 plateau detector's append mechanism:
reads the one derived contract, returns null (the common case) at zero token
cost, and instructs the model to frame the signal as an observed pattern, never
a diagnosis or a dose recommendation. Add the readiness/recovery sourceMetric
enum values plus their briefing href + icon + trend-chart mappings.
2026-06-02 23:13:26 +02:00
Marc-André Bombeck 8c24f3ec2a feat(insights): add a wellness-score summary to the doctor report and FHIR export
Surface the server-derived nightly scores (recovery / stress / strain) in the
health-record export without polluting the clinical layer. The aggregator now
emits a wellnessScores summary (latest / avg / min / max / count per score over
the window) built from the already-fetched COMPUTED rows. The PDF renders them
in a clearly-labelled "Wellness summary" section, separate from the clinical
vitals table, with a "descriptive, not a clinical assessment" disclaimer. The
FHIR bundle emits one Observation per score under the survey category with a
text-only concept and the same disclaimer as an Annotation note, so a viewer
never mistakes a band for a diagnosis.
2026-06-02 23:13:26 +02:00
Marc-André Bombeck 3487bdaec8 feat(coach): fold the derived wellness layer into the snapshot as compact summaries
Add a "derived" block to the Coach snapshot: one tiny object per high-signal
derived metric (readiness, recovery, sleep, stress, strain, HRV balance,
cardio-fitness band, vascular-age delta) carrying value + band + confidence +
historyDays — never the raw series. A fully-populated block is ~250 tokens,
comfortably inside the snapshot budget. Insufficient metrics are omitted so the
model never sees no-data noise; each metric's compute is fault-isolated so a
transient failure on one never sinks the turn. Gated on the underlying signals
staying in scope. The system prompt now documents the block and frames the
bands as descriptive composites, not clinical findings.
2026-06-02 23:13:26 +02:00
Marc-André Bombeck d9405e17b9 feat(dashboard): surface the wellness scores as a data-gated ring strip
Add a wellness-scores section to the vitals dashboard: a row of score rings for
Readiness, Recovery, Sleep, Stress, and Strain. Every ring is
data-availability-gated — a score with no underlying data simply does not
render, so the strip never shows an apologetic empty ring. Readiness and Sleep
are tappable and route to their existing score-anatomy detail pages; the
persisted nightly scores render read-only. Every ring reads the one
/api/insights/derived route through the shared useDerivedMetric hook.
2026-06-02 23:13:26 +02:00
Marc-André Bombeck a8daef7376 feat(insights): read the persisted wellness scores through the derived contract
Register RECOVERY_SCORE / STRESS_SCORE / STRAIN_SCORE as derived metrics that
read the nightly-persisted COMPUTED Measurement rows — a passthrough, never a
recompute. The dispatcher routes the three ids to a thin reader that returns
the latest score, a trailing-window trend, and a direction-aware band (stress
and strain invert, so a high stress reads red). This lets every surface — the
dashboard, the Coach snapshot, the doctor report — consume the scores through
the one Derived<T> route + hook rather than each growing its own read path.
Regenerate the OpenAPI enum, which picks up the three ids from the registry.
2026-06-02 23:13:26 +02:00
Marc-André Bombeck 02c50acd46 feat(insights): unify the derived-metric query hook onto one factory key
Two parallel loaders for the generic derived-metric route had grown — a
components-local hook keyed on a 4-element tuple and a hooks/ hook keyed on a
3-or-4-element tuple. Both shared the ["insights","derived",metric,…] prefix
with different tuple shapes, which silently poisons the TanStack cache between
surfaces. Collapse to the single components-local hook (auth-gated, 8 s client
ceiling, retry-free) on the one insightsDerived factory key; the fourth slot is
always present so the metric prefix can no longer carry two shapes.
2026-06-02 23:13:26 +02:00
Marc-André Bombeck c5ba38cebb feat(insights): register the stress, strain, and dense-retention jobs
Wire the two nightly score passes and the dense intra-day retention drain
into the worker. The stress (04:50) and strain (04:55) crons each get a
queue, a schedule, and a single-flight handler; the dense-retention drain
gets a per-user backfill queue with boot discovery (like mean-consolidation)
and folds its steady-state nightly walk onto the existing drain-cumulative
tick, after the daily-mean fold.

A queue not registered in allQueues silently never drains, so a source-grep
guard pins every registration site for all three jobs.
2026-06-02 22:49:43 +02:00
Marc-André Bombeck 6935feda15 feat(insights): compute and store a nightly strain score from workout load
Derive a daily cardio-load proxy from the per-workout heart-rate series
plus active energy. Each workout's HR series scores via Banister's
gender-weighted exponential TRIMP over the fractional heart-rate reserve
(Tanaka age-predicted HRmax, the user's resting HR); the day's TRIMP totals
map to a 0-100 saturating scale. Days with no usable HR series but a
non-trivial active-energy total fall back to an energy-only proxy, with the
path recorded in the result.

Stored as a COMPUTED STRAIN_SCORE row, idempotent per user per day, gated
when neither a usable HR series nor active energy is present.

Standard: Banister 1991; Morton, Fitz-Clarke & Banister 1990 (TRIMP);
Tanaka, Monahan & Seals 2001 (HRmax).
2026-06-02 22:49:43 +02:00
Marc-André Bombeck 57d9cc1674 feat(insights): compute and store a nightly stress score from intra-day HRV
Apple Watch has no electrodermal sensor, so there is no direct stress
measurement to read — what HealthKit does give is discrete SDNN samples
through the day. Derive an honest HRV-through-day PROXY: a suppressed,
below-baseline intra-day SDNN is a recognised marker of higher sympathetic
load. The provenance and label say "HRV-derived proxy" and never imply a
galvanic/EDA reading.

The engine reuses the shared vitals-baseline math (the same SDNN baseline
the wellness index reads), maps the day's below-baseline suppression to a
0-100 score, and stores it as a COMPUTED STRESS_SCORE row — server-owned, a
client can never POST it. It gates and writes nothing below the minimum
intra-day sample floor or without a usable baseline.

Standard: Kim et al. 2018 (HRV and stress meta-analysis); Thayer et al. 2012
(neurovisceral integration). Idempotent per user per day via the nightly job.
2026-06-02 22:49:43 +02:00
Marc-André Bombeck ce2b745cc3 feat(measurements): add a bounded dense intra-day retention tier for HRV/HR
Daytime heart-rate-variability (SDNN) and heart-rate samples need to keep
their intra-day shape long enough for the stress engine to read them, but
the raw per-sample volume must stay bounded. Add a retention tier that
keeps the last 14 days of raw HRV/HR samples and folds everything older to
one daily-mean row via the proven mean-consolidation drain (same idempotent
stats:<HK>:<day> fold, soft-delete, and rollup recompute).

The two dense-tier types are deliberately EXEMPT from the destructive
daily-mean drain allowlist (HIGH_FREQUENCY_MEAN_TYPES) — that drain would
collapse the intra-day shape and soft-delete the raw rows. A regression test
pins both exclusions so a future edit that adds either type to the drain
allowlist fails loudly.

Migration 0108 adds only the partial index that keeps the retention drain's
discovery and per-user scan cheap; the retention bound lives in code so
tuning it never needs a migration.
2026-06-02 22:49:43 +02:00
Marc-André Bombeck 56fc9cefbe docs(meta): sharpen the base SEO description
Replace the generic page description with the self-hosted positioning —
Withings + Apple Health sync, transparent derived wellness metrics, and
AI Insights you own — so the search-result snippet matches the README
and landing copy. OpenGraph and Twitter card descriptions are unchanged.
2026-06-02 22:39:40 +02:00
Marc-André Bombeck 4ddf385211 docs(readme): add wearable-ecosystem positioning and v1.10 derived metrics
Add an honest "Versus WHOOP / Oura / Fitbit ecosystems" subsection that
positions HealthLog on self-hosting, data ownership, multi-provider
aggregation, and the blood-pressure / glucose / medication context the
wrist bands don't hold — without claiming to be or match a wearable
device. Refresh the comparison table with BP+glucose, medication
compliance, derived metrics, and FHIR rows.

Fold the v1.10 derived-metrics tier into the status line, Key Features,
and roadmap: fitness-age, vascular-age delta, HRV balance, sleep score,
readiness and the stored recovery score, and the coincident-deviation
early-strain flag — each computed from the user's own measurements,
citing its inputs, degrading to "not enough data" rather than
fabricating a value. Stress and strain scores stay out of the copy: the
types are reserved but no engine computes them in v1.10.
2026-06-02 22:39:40 +02:00
Marc-André Bombeck 3dcec54726 feat(insights): compute and store a nightly recovery score
Add a recovery-score engine that turns a user's already-stored nightly
signals into a stored 0-100 score. It reuses the readiness blend — the
resting-heart-rate, HRV (SDNN), sleep and respiratory-rate deviation
from the personal baseline, with the null-redistribution the health
score already uses — so the stored series and the live readiness surface
can never drift. The lineage is the recovery-marker literature (Plews
2013, Buchheit 2014): a higher score reads as more recovered. It is a
descriptive wellness proxy, not a clinical or training-recovery
assessment, and it is only stored when enough components are present —
below that floor no row is written rather than a headline from one
signal.

A nightly job computes each eligible user's score and upserts it as a
COMPUTED RECOVERY_SCORE row, idempotent per user per day on the
externalId day key, so a re-fired tick overwrites in place instead of
duplicating. The score is never computed on a page visit. The queue is
registered in the worker's queue inventory, scheduled, and wired to a
handler; a grep guard pins all four points so it cannot silently never
run.
2026-06-02 22:31:21 +02:00
Marc-André Bombeck 33b75361f3 feat(measurements): add a COMPUTED source and first-class score types
Add a server-owned COMPUTED measurement source for rows a server engine
derives rather than a device or a person reports, plus three first-class
0-100 score types — RECOVERY_SCORE, STRESS_SCORE, STRAIN_SCORE (unit
"score", plausibility range 0..100).

COMPUTED is read-only from a client's perspective: it joins the read /
decode enum so the native client can decode the rows it queries and
charts, but every client-facing write surface rejects it exactly like
WITHINGS and IMPORT — the batch ingest allowlist stays {APPLE_HEALTH,
MANUAL} and the single-entry POST 422s a COMPUTED source.

All three score types thread through every type-exhaustiveness site: the
unit + plausibility-range maps, the PR-direction resolver (scores carry
no record direction, like the device events), the category overlay (a
new "scores" cluster), the list-view label / icon / colour maps with
locale strings across all six bundles, and the insight chart-token
allowlist + orphan-enum stripper. They are not clinical vitals, so they
stay out of the doctor-report PDF.

Only the recovery score is computed today; the stress and strain types
are defined now so the engines that compute them later need no schema
change. Migration 0106 is purely additive (ADD VALUE IF NOT EXISTS).
2026-06-02 22:31:21 +02:00
Marc-André Bombeck 51fc48f93c feat(fhir): raise the MedicationAdministration cap to 5000 and make it configurable
Raise the per-export administration ceiling from 1000 to 5000 (~3.5 years
at four doses a day) and resolve it from FHIR_MAX_MEDICATION_ADMINISTRATIONS,
bounded 1..50000 with a fallback to 5000 on an unset or out-of-range value.
The windowed-then-capped newest-first behaviour and the honest-truncation
narrative are unchanged; this only raises the ceiling so it bites far less
often. Add the var to the compose environment whitelist and the production
env example so it reaches the container and check-env stays green.
2026-06-02 22:22:50 +02:00
Marc-André Bombeck e893a43005 feat(fhir): wire the German BfArM ATC locale toggle into the export route
The builder already accepts a germanAtc option that appends the BfArM ATC
URI after the WHO entry. Thread it from the health-record export route: an
explicit germanAtc flag on the selection payload wins, otherwise it derives
from a German-region locale. The WHO coding stays coding[0], byte-identical
and locale-independent, so a WHO-only consumer is unaffected.

Add the optional germanAtc field to the strict export selection schema and
regenerate the OpenAPI contract.
2026-06-02 22:22:50 +02:00
Marc-André Bombeck 9990815efe feat(fhir): add additive SNOMED route and site codings to MedicationAdministration
Emit a SNOMED CT coding alongside the existing .text anchor on the
administration dosage. Route maps ORAL to 26643006 (Oral route) and
INJECTION to 34206005 (Subcutaneous route, the form HealthLog injections
take). Site keys on the eight InjectionSite enum values, collapsing to the
three gross body-region concepts (abdomen 818983003, thigh 68367000, upper
arm 40983000); laterality and the abdominal quadrant stay verbatim in the
.text anchor rather than inventing lateralised concepts.

Referencing concept ids in a FHIR instance is not redistributing the
licensed SNOMED distribution, so this is safe to ship. The .text anchor is
unchanged, so a consumer without a SNOMED binding is unaffected.

Reconcile the dose fixture to the real uppercase enum value the live
builder emits (the previous lowercased value never matched production).
2026-06-02 22:22:50 +02:00
Marc-André Bombeck 95064b405a test(healthkit): cover device-event ingest + the awareness surface
Add mapping tests for the five event classes (verdict resolution,
severity grading, the value-pinned-to-1 contract, unknown-codepoint
fallback, and that a continuous measurement never gets a classification),
the awareness-card gating + device-verdict framing + disclaimer presence,
and the events route narrowing + empty-state contract. Extend the enum,
chart-token and Coach-gate drift guards for the new event types.
2026-06-02 22:10:16 +02:00
Marc-André Bombeck 135141a750 feat(insights): surface device-flagged events as an awareness timeline
Add a timeline of the health notifications the user's device produced on
its own, reachable from the Insights overview. The surface reflects the
device's own decision: each row reads "Your device flagged …" and a
permanent disclaimer states this is not a medical assessment by
HealthLog and that HealthLog does not diagnose any condition.

The surface is data-availability-gated — it un-mounts entirely when the
user has no such events, so an account that never triggered one never
sees an empty or alarming card. Copy renders as plain React text
children; no markdown library is involved.
2026-06-02 22:08:12 +02:00
Marc-André Bombeck a45325af52 feat(healthkit): thread the device-event verdict through batch ingest
Accept the optional HKCategoryValue codepoint on each batch entry and
persist the resolved rhythm_classification on the stored row. The wire
field is additive and ignored for non-event identifiers, so every
existing caller is byte-for-byte unchanged. Regenerate the OpenAPI
contract.
2026-06-02 22:07:45 +02:00
Marc-André Bombeck b06b1cada4 feat(healthkit): add a categorical device-event row class
Add a discrete EVENT row class to the Measurement model for the
device-flagged health notifications a wearable produces on its own —
irregular-rhythm, high/low heart rate, walking-steadiness and
breathing-disturbance alerts.

Following the sleep-stage / glucose-context nullable-context precedent,
this is an additive nullable column on the existing table, not a new
storage paradigm. Five new MeasurementType values carry the event class
and a new rhythm_classification enum column carries the device's own
verdict / severity (migration 0105, with a CHECK that pins the column to
the event types). An event row stores value 1 and the device verdict;
it never participates in trend, rollup, chart or personal-record
analytics.

For the irregular-rhythm class, HealthLog ingests only the
classification RESULT the device's own certified on-device algorithm
already produced. It never ingests a raw ECG waveform, never
re-classifies, and never derives a verdict of its own.

The Apple Health batch ingest maps the five category identifiers, with
the device's HKCategoryValue codepoint resolved to the stored
classification; an unknown codepoint degrades to a fallback verdict
rather than dropping the event.
2026-06-02 22:07:28 +02:00
Marc-André Bombeck 635e64ace7 feat(healthkit): ingest seven additive HealthKit signals end-to-end
Wire seven previously-deferred HealthKit quantity identifiers through
the full pipeline — enum, mapping, plausibility range, category, list-UI
metadata, FHIR coding, and the generic metric-status assessment:

  CARDIO_RECOVERY          heartRateRecoveryOneMinute   bpm
  WRIST_TEMPERATURE        appleSleepingWristTemperature celsius
  FALL_COUNT               numberOfTimesFallen           count
  SIX_MINUTE_WALK_DISTANCE sixMinuteWalkTestDistance     m
  STAIR_ASCENT_SPEED       stairAscentSpeed              m/s
  STAIR_DESCENT_SPEED      stairDescentSpeed             m/s
  BREATHING_DISTURBANCES   appleSleepingBreathingDisturbances count

Each value rides raw on the wire (identity conversion). Fall count is
cumulative (daily SUM); the stair speeds drain to a daily mean; the rest
store as latest per-workout / per-night spot readings. Wrist temperature
and breathing disturbances are flagged privacy-sensitive. The category
sleep-apnea and walking-steadiness EVENT identifiers stay deferred — they
are events, not quantities.

Each new metric gains an Insights sub-page on the shared scaffold with the
generic assessment card, localised across all six locales. Cardio fitness
(VO2 max) — ingested since v1.4.23 but assessment-less — gains its own
/insights/cardio-fitness page so it picks up the assessment instead of
riding as a bare chart-row on the pulse page.

Normal-range anchors are cited where defensible (six-minute walk 400-700 m,
ATS guideline + population reference); the rest defer to the user's own
baseline rather than fabricate a band.

Migration 0104 appends the enum values additively (IF NOT EXISTS, forward-only).
2026-06-02 22:02:50 +02:00
Marc-André Bombeck 30be0c4e0d feat(workouts): accept an optional HR series on the batch contract
Extend POST /api/workouts/batch with an optional per-workout `samples`
array — a route-independent heart-rate series so indoor workouts still
yield a strain-relevant signal. Each entry is `{ t, hr?, speedMs?,
power?, cadence? }`; the array is capped at 30 000 points
(MAX_WORKOUT_HR_SAMPLES), covering a long endurance session sampled at
1 Hz while bounding the largest new workout-side write stream the same
way the 20 000-point route cap bounds the geometry.

Persistence rides the existing route-attachment path: the freshly
written workout id is resolved once (by composite key, or the manual
tuple), then both the route geometry and the HR series attach by FK
with skipDuplicates so a re-submitted batch stays idempotent. A workout
may carry both a GPS route and a canonical HR series, or just one.

GET /api/workouts/{id} returns the series alongside the route. OpenAPI
regenerated.

`samples` keeps first-write-wins/overwrite parity with the workout row
it hangs off: the 1:1 FK plus skipDuplicates means a re-ingest of an
existing workout never duplicates or mutates its series.
2026-06-02 22:02:46 +02:00
Marc-André Bombeck d247f6966a feat(workouts): add a route-independent per-workout heart-rate series
Indoor workouts had no home for their per-sample heart-rate series: it
rode on WorkoutRoute.sampleTimestamps, which only exists when a workout
carries GPS geometry. A treadmill or trainer session therefore lost the
signal the training-strain reader needs.

Add a WorkoutSamples child (workout_samples), 1:1 with the workout like
WorkoutRoute, holding a JSONB `[{ t, hr?, speedMs?, power?, cadence? }]`
array plus a denormalised sample_count. JSONB keeps the self-hosted
Postgres extension-free, mirroring the route table's decision. Migration
0107.

Also retire the stale cross-source workout-dedup marker on the Workout
model: that work landed as the write-time dedupeWorkoutBatch() picker
plus the read-time pickCanonicalWorkoutRows() picker, both resolving the
user's source-priority ladder. The comment now documents the two layers
instead of tracking them as open.
2026-06-02 22:02:46 +02:00
Marc-André Bombeck 14d79ab453 fix(insights): reconcile the derived vitals + composite waves
Resolve the overlap where the vitals tier and the composite tier both extend
the derived-metric registry, dispatch, query-key factory, i18n bundles and the
OpenAPI contract: every derived metric (vitals baseline, fitness/vascular age,
HRV balance, BMI, sleep score, readiness, coincident-deviation) is now wired and
implemented, the dispatch test asserts the full set, and the locale bundles carry
both the vitals and the score-anatomy/composite strings.
2026-06-02 21:25:58 +02:00
Marc-André Bombeck 440f24bff2 fix(medications): drop the bottom-pinned action gap on the cards
The v1.9.0 equal-height change set the card content to a flex column and
pinned the action buttons to the bottom with mt-auto. On a shorter card next
to a taller one in the grid, that opened an empty gap between the content and
the buttons. The cards already stretch to a shared height via the grid, so the
buttons can sit directly after the content: drop the flex column and the
mt-auto wrapper on both card variants. The reserved dose-row slot stays, so the
dose lines still align across the grid; only the gap is gone.
2026-06-02 21:20:02 +02:00
Marc-André Bombeck 95a2a7692f feat(insights): add composite scores, score-anatomy view, and correlation discovery
Build the composite tier of the derived-metrics layer on the shared seam:

- Sleep score — a transparent 0–100 composite from sufficiency, efficiency,
  consistency, timing and composition sub-scores over the per-stage sleep
  rows, reweighting around any sub-score the data cannot support (a legacy
  asleep-only night drops composition gracefully rather than fabricating it).
- Wellness/readiness index — extends the health-score null-redistribution
  blend with resting-HR, HRV (SDNN), sleep, respiratory-rate and mood
  deviation-from-baseline components; returns insufficient below two present
  components so it never headlines from one signal.
- Coincident-deviation flag — counts vitals outside their personal band on
  the latest day and fires when two or more coincide, listing the
  contributing vitals as possible factors, never a cause or a diagnosis.

Each composite cites its standard, carries coverage + confidence +
provenance, and reweights around missing inputs.

Add an FDR-controlled correlation discovery engine behind
GET /api/insights/correlations: it scans a curated behaviour x outcome
matrix, lag-joins each behaviour day to the next day's outcome, runs Pearson
with the exact Student-t p-value, and applies Benjamini-Hochberg control
across every tested pair so only statistically-defensible patterns surface —
each tagged with n, r, p and the adjusted q, framed descriptive not causal.

Add the score-anatomy detail view at /insights/scores/<metric>: a full
score ring, ranked contributor rows each showing its push/pull and weight
share, and the cited-standard provenance explainer — reused by every
composite, mobile-first and accessible.

Regenerate the OpenAPI contract for the new metric values + the correlation
discovery response, and add the i18n keys across all six locales.
2026-06-02 21:19:56 +02:00
Marc-André Bombeck 663a3ee09d feat(insights): add the vitals dashboard + its derived metric tier
Build the Apple-Health-Highlights grid of personal-vital tiles on the
Insights overview, backed by four new pure derived-metric compute
functions over the established seam:

- cardio-fitness band ("Fitness Age" frame) — VO2max placed against the
  FRIEND-registry age/sex norm (Kaminsky 2015), surfaced + trended, never
  re-derived.
- vascular-age delta — Withings vascular-age vs chronological age, a
  relative wellness indicator (Vlachopoulos 2010 PWV framing), no medical
  claim.
- HRV (SDNN) balance — reuses the typical-range engine for the band and
  places the recent average as balanced / above / below; SDNN never
  relabelled RMSSD; cadence-gated.
- BMI from weight + height — exact WHO classification, the fallback when
  no device BMI exists.

Each metric carries coverage + confidence + provenance and cites its
standard through the provenance explainer. The dashboard renders one
SparklineDeltaTile per available vital: an absent vital does not render,
a still-building one shows the honest coverage meter rather than a
headline from too little history. Tiles read the generic
/api/insights/derived route through a TanStack Query hook keyed off the
centralised factory.

Regenerates the OpenAPI contract for the two new metric ids and adds the
vitals copy across all six locales.
2026-06-02 21:17:05 +02:00
Marc-André Bombeck 789eef35c3 Merge pull request #243 from MBombeck/release/v1.9.3
Release v1.9.3 — medication card layout polish
2026-06-02 21:08:33 +02:00
Marc-André Bombeck e7f406ecc7 test(e2e): pin the clock so the medication next-due chip is deterministic
The recurring medication stub schedules an 08:00-09:00 window and the card
derives its header from the real clock. When CI ran inside that window the card
showed the in-window 'take now' pill and correctly suppressed the 'Nächste
Einnahme:' next-due line, so the chip assertion failed depending on wall-clock
time. Pin the clock to a fixed afternoon before rendering the list, putting the
morning window in the past so the next-due line always renders.
2026-06-02 21:02:42 +02:00
Marc-André Bombeck 0c8506d7d4 test(e2e): give the next-due chip assertion the 10s budget the name has
The medication-list next-due line is computed client-side from the schedule
after hydration, so on a loaded CI runner it can appear a beat after the
medication name. The chip assertion used the default 5s timeout while the name
assertion above it uses 10s; align them so the check isn't racing hydration.
2026-06-02 20:52:28 +02:00
Marc-André Bombeck 7b3094eeef chore(release): v1.9.3 — medication card layout polish 2026-06-02 20:36:40 +02:00
Marc-André Bombeck 26fb461cc7 fix(medications): drop the bottom-pinned action gap on the cards
The v1.9.0 equal-height change set the card content to a flex column and
pinned the action buttons to the bottom with mt-auto. On a shorter card next
to a taller one in the grid, that opened an empty gap between the content and
the buttons. The cards already stretch to a shared height via the grid, so the
buttons can sit directly after the content: drop the flex column and the
mt-auto wrapper on both card variants. The reserved dose-row slot stays, so the
dose lines still align across the grid; only the gap is gone.
2026-06-02 20:36:39 +02:00
Marc-André Bombeck 32bc11f968 feat(insights): add the derived-metrics design-system primitives
Build the four reusable presentational components the v1.10 vitals and
score-anatomy surfaces share: a radial score ring, a coverage meter, a
sparkline delta tile, and a provenance explainer. Each extends the
existing dracula band + trend-sentiment vocabulary rather than a new
colour system, and ships its populated, provisional/empty, and stale
states up front so a sparse-data surface never goes blank.

- score-ring: centred tabular-nums number on a Recharts RadialBarChart,
  band-coloured, size prop (sm tile / md / lg anatomy), count-up + sweep
  on mount via a 0 KB requestAnimationFrame hook; role=img aria-label
  restates the number so the ring is never colour-only.
- coverage-meter: CSS-only filled/hollow dots driven by the Derived<T>
  coverage + confidence facets, with an accessible breakdown tooltip
  (present vs required inputs, history days, missing list).
- sparkline-delta-tile: extends the trend-card grammar with an inline
  Recharts area sparkline, a signed period delta, and an age/normal-range
  framing slot.
- provenance-explainer: collapsible Popover (desktop) / bottom-sheet
  (mobile) rendering inputs, plain-language method, and an optional cited
  standard as React text children — no markdown library.

All four read their data off the Derived<T> union as a type-only import
so the client bundle stays free of the server graph. Recharts only, no
new runtime dependency. New i18n keys propagated across all six locales.
2026-06-02 20:14:49 +02:00
Marc-André Bombeck aa281d6649 feat(insights): sharpen the metric-status normalRange with age/sex norms
Thread the reference-range enabler (derived/norms.ts) into the existing
generic assessment path. When lookupNormalRange resolves an age/sex
adjusted band for the metric + profile, the snapshot uses it in place of
the coarse flat registry anchor and tags it normalRangeSource:
age-sex-adjusted; otherwise the flat anchor is kept unchanged. Strictly
additive — a metric with no sharper norm, or a profile missing
demographics, behaves exactly as before.
2026-06-02 20:01:48 +02:00
Marc-André Bombeck 4ad65a5b7d feat(insights): add GET /api/insights/derived + OpenAPI contract
Generic route mirroring the v1.8.7.1 metric-status precedent:
GET /api/insights/derived?metric=<DERIVED_METRIC_ID>[&type=<vital>].
apiHandler + Zod safeParse on the query, closed registry enum (unknown
id 422s via returnAllZodIssues), cookie-or-Bearer auth, userId narrowed
from the session (never a query field). The profile is read once and
passed into the pure compute function. Returns the flat Derived<T> union
in the standard { data, error, meta } envelope so the native client
decodes one stable shape and combines values across metrics.

Register the query + response schemas (DerivedMetricQuery,
DerivedMetricResponse + DerivedCoverage/Confidence/Provenance) and the
path operation in the OpenAPI registry; regenerate docs/api/openapi.yaml.
Add the route to the insights gate inventory (insightStatus-gated, no
Coach prose).

Route tests cover the 200 flat-envelope shape, session-narrowed userId,
422 on an unknown / missing metric, 401 unauthenticated, and the
insufficient flattening (null value + confidence, populated reason).
2026-06-02 20:01:42 +02:00
Marc-André Bombeck 6dac56b659 feat(insights): add the derived-metrics compute foundation
Introduce src/lib/insights/derived/ — the shared, compute-once layer for
derived wellness metrics. Core pieces:

- types.ts: the Derived<T> discriminated union (ok carries value +
  coverage + confidence + provenance; insufficient carries coverage +
  provenance + reason). Client-safe — pure types, no server imports.
- coverage.ts: deriveCoverage() + the buildOk/buildInsufficient terminal
  constructors. Confidence blends the history fraction and the
  input-presence fraction so it drops monotonically as inputs go missing.
- registry.ts: the closed DERIVED_METRIC_ID enum + per-metric metadata
  (inputs, archetype, min-history / min-inputs floors, implemented flag).
- norms.ts: age/sex reference-range tables (VO2max FRIEND registry,
  resting-HR + respiratory-rate by age) behind lookupNormalRange().
  Age + sex only — no ancestry/region ranges.
- baseline.ts: the flagship engine — computeVitalsBaseline() returns the
  personal typical-range band (median +/- k*MAD) for one vital. Center
  reads the composable DAY rollup mean; the spread is DAY-native only
  (the sd/slope/r2-don't-compose invariant), with a per-type bounded
  live-SQL fallback on a coverage miss.
- dispatch.ts: maps a DERIVED_METRIC_ID to its compute function; stubbed
  metrics return an insufficient with reason not_implemented.
- index.ts: the append-only public barrel.

Unit tests cover the coverage model, the Derived<T> ok/insufficient
branching, the norms lookup, the baseline ok / insufficient /
coverage-miss-fallback paths + the composed-vs-raw-DAY band parity, and
the dispatch stub guard.
2026-06-02 20:01:34 +02:00
Marc-André Bombeck 744e8e37ec Merge pull request #242 from MBombeck/release/v1.9.2
Release v1.9.2 — document the medication compliance endpoint
2026-06-02 19:19:23 +02:00
Marc-André Bombeck e2917cb012 chore(release): v1.9.2 — document the medication compliance endpoint 2026-06-02 19:13:24 +02:00
Marc-André Bombeck 9106489196 docs(api): document the medication compliance endpoint
GET /api/medications/{id}/compliance was absent from the OpenAPI document, so
a client generating types from the contract could conflate it with the separate
cadence endpoint (a different shape). Register the route with its exact response
— compliance7/compliance30 summaries, the per-day dailyCompliance grid, and the
two-row complianceDisplay block — documenting that compliance30.totalExpected is
the 30-day denominator and that a per-day glyph is drawn only where due is true.
Handler unchanged; this closes the contract gap.
2026-06-02 19:13:24 +02:00
Marc-André Bombeck cc927f7921 Merge pull request #241 from MBombeck/release/v1.9.1
Release v1.9.1 — no assessment warm on a page visit
2026-06-02 18:47:11 +02:00
Marc-André Bombeck ad471a5110 docs(planning): refresh roadmap and state to the current release line 2026-06-02 18:39:53 +02:00
Marc-André Bombeck fc7386a364 chore(release): v1.9.1 — no assessment warm on a page visit 2026-06-02 18:39:53 +02:00
Marc-André Bombeck 879833b372 fix(insights): stop warming every assessment on an overview visit
Opening the Insights overview fired a once-per-session background warm that
forced the provider to regenerate the comprehensive briefing and every category
and metric assessment at once — a multi-minute burst that contended with
foreground requests and made the app feel unresponsive until it finished. The
nightly pass keeps the caches warm and the per-metric status GETs revalidate
gently on their own, so the warm-on-mount is redundant. Remove it; the manual
'prepare assessments' button remains the explicit on-demand re-warm.
2026-06-02 18:39:53 +02:00
Marc-André Bombeck ed5d453431 Merge pull request #240 from MBombeck/release/v1.9.0
Release v1.9.0 — Insights time-ranges, deeper mood, medication coding, stability
2026-06-02 18:16:10 +02:00
Marc-André Bombeck eb63cd3df3 chore(release): v1.9.0 — Insights time-ranges, deeper mood, medication coding, stability
Insights gain selectable time ranges with period-over-period deltas, and the
mood page adds time-of-day, stability and weight/BP correlation reads. Medications
can carry ATC + RxNorm codes that flow into the health-record export alongside a
MedicationAdministration per acted dose. The connection pool is sized for real
concurrency to remove the under-load stalls, and the medication advanced-settings
page is rebuilt. The standalone /targets page is retired in favour of inline editing.
2026-06-02 18:08:52 +02:00
Marc-André Bombeck a87d6b94e4 fix(insights): keep the server-only rollup readers out of the insights client bundle
The v1.9.0 time-range work imported ANALYTICS_RANGES as a value into the
time-range pills and the insights layout-prefs hook from range-delta.ts.
That module also pulls the rollup readers and the Postgres client, so the
value import dragged pg (dns/fs/net/tls) into the browser bundle and broke
the production build with eight "Module not found" errors.

Move the client-safe pieces — the range list, its type, the per-range
window length, and the period-over-period result shapes — into a new
range-shared module that imports nothing server-side. The insights client
components import from there; range-delta.ts re-exports the same names so
the server route and the OpenAPI registry keep their import paths. The
window-composition logic and the rollup/db imports stay server-side.

No runtime behaviour change — a pure module-boundary split.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 75124e76c1e987d8a022fb39d891049340199b38)
2026-06-02 17:41:33 +02:00
Marc-André Bombeck 1c91abcf2a docs(medications): correct the GLP-1 card equal-height comment
The reserved-slot comment claimed the compliance bars and action row
align "row-for-row across the grid" with a generic sibling. That
overstates it: the GLP-1-only rotation-hint block sits between the
reserved slot and the compliance bars, so the bars are pushed down by
its height and do not share a Y with a generic card's bars. What the
layout actually guarantees is equal card height and a shared bottom
action baseline (`h-full` + `mt-auto`); only the header, the reserved
slot, and the pinned action row align across a mixed-variant row.
Reword the comment to claim exactly that.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 7320c8b1b9f704d22eaba10be42a560594a5ca11)
2026-06-02 17:34:52 +02:00
Marc-André Bombeck ada9006d9c fix(export): cap the FHIR MedicationAdministration count per export
The administration set was windowed only to the report period (up to 730
days). A chronic medication dosed several times a day across that window,
multiplied across several medications, can still materialise thousands of
MedicationAdministration resources into a single Bundle — bounded by the
window but unbounded by dose frequency.

Cap the set at the most-recent 1000 acted intakes overall. The omitted
rows are the oldest in the window, so recent adherence is preserved
intact. When the cap trims rows the aggregator records the original and
included counts and the FHIR document narrative discloses the
truncation, so the export is honest about the omitted history rather
than silently dropping it. Cover the cap in the report aggregator and
the narrative note in the bundle builder.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit c6ce7df2bf6efb5e2c9d948d8f189d95d1289758)
2026-06-02 17:34:52 +02:00
Marc-André Bombeck f0f2caab79 fix(medications): bound the RxNorm code length
The RxCUI field validates against `^\d+$`, which is unbounded — a caller
could submit an arbitrarily long digit string. Add a `.max(20)` ceiling
as defence-in-depth so the column write stays tight; real RxCUIs are at
most a handful of digits. `atcCode` needs no max — its regex already
fixes the length. Regenerate the OpenAPI contract for the new
`maxLength` on both the create and update bodies.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 8b97d35bc375ef3b2e70f938c0d6729a5fa6bccb)
2026-06-02 17:34:52 +02:00
Marc-André Bombeck bfdf0a12a0 fix(medications): route injection-site taps to the nearest quadrant centre
The two stacked abdomen quadrants sit 14 viewBox units apart, yet each
per-dot hit-target was an r=14 transparent circle (Ø=28u), so the
targets overlapped by ~14 units. SVG hit-testing resolves to the
topmost-painted element rather than the nearest centre, so a tap in the
overlap band logged the wrong quadrant — defeating the rotation feature.

Replace the overlapping per-dot hit-circles with a single transparent
overlay that projects the pointer into viewBox space and resolves it to
the nearest site centre (new `nearestSiteAt` helper, constrained to the
effective allowed set). Every pixel now maps to its closest site, so
full-area routing holds without sub-target dead zones, and the abdomen
quadrants can no longer mis-route. Keyboard and assistive-tech users
keep a per-site focusable r=6 circle (non-overlapping at this spacing)
with the Space/Enter handler and aria-label. Add tests asserting a tap
in the former overlap band maps to the nearer quadrant.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit a07988f139b0067e82ccc5ad7e5890e0517fe869)
2026-06-02 17:34:52 +02:00
Marc-André Bombeck 107a111545 fix(insights): polish range pills, zero-delta caption, scrollbar gutter, mood tiles
- Range pills: make the radiogroup a single tab stop with roving tabindex and
  Arrow / Home / End key handling, matching the WAI-ARIA radiogroup pattern.
  Previously every pill was its own tab stop and the arrow keys were dead.
- Range delta caption: render a neutral dash + "no change" for a perfectly
  stable metric instead of a down-arrow with "−0%". Adds the `noChange`
  string across all six locales.
- Scrollbar gutter: scope the document-level `scrollbar-gutter: stable` to the
  body-scrolled shells (login / register / onboarding / legal) via a
  `data-scroll` attribute the shell sets, so the height-locked authenticated
  branch no longer reserves a second, never-painted gutter on classic
  scrollbar platforms.
- Mood tiles: a lone in-target / stability tile now spans full width instead
  of leaving a half-width orphan beside it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 12b434a0c262e29ced1ac0aaf631db6678c3ad05)
2026-06-02 17:34:52 +02:00
Marc-André Bombeck b13721cc97 fix(insights): stop a timed-out warm from evicting its own freshly-warmed caches
The on-demand force-warm bounds the comprehensive briefing with a 45 s
timeout and then warms the per-status + generic-metric caches itself. The
timeout could not cancel the underlying generation, so a comprehensive that
resolved after the timeout reached its own per-status eviction and deleted
the rows the warm passes had just written — leaving the user back on a cold
cache.

Thread an AbortSignal into the comprehensive generation and abort it when the
timeout fires; the generation now bails out before its write + evict once the
signal is aborted, so a late resolve can never undo the warm.

Also align the force-warm gating with the route: the route admits the job on
the per-user assessment surface, so warm the per-status + generic-metric
cards whenever that surface is enabled, even when the global briefing switch
is off. Only the comprehensive briefing stays gated on the briefing switch.

Factor the per-status cache-action shape into a single helper so the key is
built in one place rather than hand-assembled across the generators, the
eviction sweep, and the ingest debounce.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 75e0b5a9129893915f7a213ec96253df19341d15)
2026-06-02 17:34:52 +02:00
Marc-André Bombeck 94415e468e fix(layout): reserve the scrollbar gutter so the nav no longer shifts
The authenticated shell scrolls inside its own `<main>` (the body is height-
locked with `flex h-dvh`), and that `<main>` centres its content with
`mx-auto`. A tall section paints the vertical scrollbar and narrows the
content box; a short one hides it and widens the box, so the whole column —
including the admin/settings sidebar — recentres a few px sideways on every
view switch. The admin "Insights Quality" ↔ "Integrations" toggle was the
visible case.

Reserve the gutter with `scrollbar-gutter: stable` on the `<main>` scroll
viewport, and on `html` for the body-scrolled login / onboarding / standalone
pages. The content box width is now constant whether or not the bar is
painted, so the left nav no longer shifts when a scrollbar appears. The fix is
global: every signed-in route renders inside the same `<main>`, so the same
shift on settings, insights, and dashboard navigation is fixed at once. The
height-locked authenticated body never scrolls the document, so no double
gutter results.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit c1459e5ee42b7f7acbfa933a9eb7d1f5a1c6890a)
2026-06-02 17:10:36 +02:00
Marc-André BombeckandClaude Opus 4.8 6d1587531f test(settings): expect the shortened notifications section label
The settings section reverts to the single-line "Notifications" /
"Benachrichtigungen"; update the shell title assertions to match.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 17:04:40 +02:00
Marc-André Bombeck 170862fdf8 fix(targets): convert glucose targets back to mg/dL on save
The per-metric target editor receives a glucose range already projected
into the user's display unit (mmol/L) along with `unit="mmol/L"`, but it
seeded, validated and saved that value verbatim. HealthLog stores glucose
canonically in mg/dL, so a user on the mmol/L preference either had a
valid target (e.g. 3.9–5.5 mmol/L) rejected by the 40–400 mg/dL bounds,
or — when an override already existed — saw a mg/dL number rendered as if
it were mmol/L and wrote it straight back.

Add `mmolToMgdl` / `toCanonicalMgdl` (the inverse of `convertGlucose`) and
teach the edit sheet to treat the display unit at its boundary: seed the
persisted mg/dL override into the display unit, validate against bounds
expressed in the display unit, and convert the typed value back to
canonical mg/dL before the PUT. A no-op for every non-glucose metric and
for users on the mg/dL preference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 0cc0361058a85f32d7135e5f2fd425c98f62d885)
2026-06-02 17:01:14 +02:00
Marc-André Bombeck 09af60303d feat(medications): redraw the injection-site picker as an anatomical silhouette
Replace the stick-figure outline with a traced front-of-body silhouette,
still an inline SVG so it inherits the theme tokens (currentColor + a
soft currentColor wash) and tints correctly across light/dark and the
zinc/Dracula palettes with no raster asset.

Recalibrate SITE_COORDS onto the new 100x200 viewBox (aspect ≈0.5) using
the iOS client's hands-on fractional coordinates, so both apps land their
dots on the same anatomy. The coordinates double as the Euclidean basis
for the rotation recommender, so picker and recommendation stay in sync.

Dot states: selected (filled), recommended-next (dashed primary ring),
and a new last-used solid ring; hit targets are r=14 on the viewBox
(≈45 CSS px at the rendered scale), clearing the 44px floor. Props,
callbacks, the screen-left=="links" convention and the v1.8.5 site→enum
bridge are unchanged — graphic and coordinates only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 46125c3bbec5573910f41a319ae717d37f39c228)
2026-06-02 17:01:14 +02:00
Marc-André Bombeck 7857aa3dd2 fix(settings): shorten the notifications section label to one line
The notification-channels section heading and the left-nav label both
render `settings.sections.notifications.title`, whose German value
("Benachrichtigungs-Kanäle") is a long compound that wraps to two lines
in the nav rail. Shorten the displayed value to the plain plural across
all six locales (de "Benachrichtigungen"; en "Notifications"; es
"Notificaciones"; fr "Notifications"; it "Notifiche"; pl
"Powiadomienia"). Key id is unchanged; the breadcrumb on the
notification-center page keeps its own wording.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit af437f48b09b9f99b6a80709ddacd565c10132ab)
2026-06-02 17:01:14 +02:00
Marc-André Bombeck d880385635 refactor(targets): retire the standalone Targets page
The standalone /targets (Zielwerte) page is retired. Target editing
moved inline onto the Insights metric pages in v1.8.6 — each metric's
reference panel mounts the editor and writes the same
PUT /api/user/thresholds, reading the same /api/insights/targets
payload. The page carried a deprecation notice and had already dropped
out of the navigation, so removing it is a UI-only change: no data
model, API route, or inline editor moves.

Remove the page and its tests, the components reachable only from it
(target card, per-card coach button, summary header, target prompt /
scope helpers, coach-handoff hook), the now-dead /zielwerte→/targets
proxy redirect, and the orphaned targets.* i18n keys across all six
locales. Repoint the handful of code comments that pointed readers at
the page to the inline Insights panel, and prune the two coach
gate-inventory allowlists plus the queryKey factory guard root that
named the removed files.

The reference panel keeps the range bar, consistency strip, status
pill, edit sheet, and source-link helpers — those are the live editing
surface now.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 7f842c5620087127e980fe22a56133135b7c0531)
2026-06-02 17:01:14 +02:00
Marc-André Bombeck 8c316ee3b0 ops: add a post-deploy version assertion script
scripts/assert-deploy.ts polls /api/version on prod + demo and asserts the
served data.version matches an expected value, printing each target's
buildSha and exiting non-zero on a mismatch or after a bounded retry loop.
This catches the BuildKit layer-cache pitfall where the deploy reports
clean but /api/version still answers the prior release. Run via
`pnpm dlx tsx scripts/assert-deploy.ts <version>` — not bundled into the
standalone image. Document it in the deploy runbook.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit a86a9151ef670846c4b33a1c068da40324393308)
2026-06-02 17:01:14 +02:00
Marc-André Bombeck 4feac6b7e4 fix(insights): gate the assessment warm on insightStatus, not coach
POST /api/insights/pregenerate warms the assessment cards — the comprehensive
insight plus the specialised status cards — all of which the read-only status
GETs gate on the insightStatus surface. It was gating on coach, so a user with
assessments enabled but the Coach disabled got a 403 and could not warm. Move
the gate to insightStatus to match the surface it actually serves, add it to
the route-gate inventory allowlist, and cover the coach-disabled-still-warms
path with a route test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit ec041db6e2c81b95a429625bb765f1f41ebce40b)
2026-06-02 17:01:14 +02:00
Marc-André Bombeck 18cde65af7 docs(openapi): register the six specialised insight status routes
The generic metric-status route set the OpenAPI pattern for the assessment
cards; retrofit the six specialised routes onto it. Add registry entries
for /api/insights/{blood-pressure,pulse,weight,bmi,mood,medication-compliance}-status
mirroring the metric-status envelope (hasProvider/text/cached/updatedAt plus
the preparing + revalidating flags). Medication-compliance carries its richer
summary + per-medication note array as its own schema. Regenerate the YAML.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 91887a13b30e8978e91f615604163331bdc54950)
2026-06-02 17:01:14 +02:00
Marc-André Bombeck 7fa2866154 feat(fhir): emit Coverage on a bare KVNR + add Composition.text
Align the server's `Coverage` emission with the iOS exporter: a
Coverage is now emitted whenever ANY payor signal is present, including
a bare KVNR with no insurer name or IKNR. The KVNR-only case carries the
`subscriberId` with no contained payor Organization; the insurer-known
case is unchanged. A bundle with no payor signal at all still omits
Coverage entirely.

Also add a top-level `Composition.text` narrative (reusing the same
escaped summary the section narrative carries) so a strict
US-Core-style validator sees the document-level narrative it expects.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 22c5ed7fbe02993307c3f04cd0498d199c79cf43)
2026-06-02 16:45:23 +02:00
Marc-André Bombeck ca8781867b feat(fhir): add a MedicationAdministration per acted intake
Emit one `MedicationAdministration` per intake the user actually
actioned — `completed` for a taken dose (`effectiveDateTime = takenAt`),
`not-done` for an explicit skip (`effectiveDateTime = scheduledFor`).
Pending / missed slots and soft-deleted tombstones are never exported,
so the record only asserts administrations that happened.

Each administration reuses the statement's ATC/RxNorm + text concept,
so it is self-describing without a cross-resource reference. A `dosage`
is emitted only when a structured dose Quantity is available (resolved
from the dose-change history in effect at the administration instant) —
a dosage carrying only `.text` would violate the R4 dose-or-rate
invariant. Route + injection site ride along as text-only concepts. The
administrations are referenced from the existing Medications section, so
the document's two-section graph is preserved.

`FhirMedicationAdministration` is new; `FhirDosage` gains `dose`,
`route`, and `site`. The source rows come from the same aggregator the
PDF consumes, keeping FHIR and PDF aligned by construction.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit dd22512f56b7b6dfa42386bbc88d1ced1d71255d)
2026-06-02 16:45:23 +02:00
Marc-André Bombeck 2fcd2e75f5 feat(fhir): emit ATC + RxNorm codings on the medication concept
The health-record export's `MedicationStatement.medicationCodeableConcept`
gains additive `coding[]` entries when the medication carries a stored
code: ATC primary (`http://www.whocc.no/atc`), RxNorm secondary
(`http://www.nlm.nih.gov/research/umls/rxnorm`). The free-text name
stays the `.text` anchor and the concept collapses to exactly the
prior text-only shape when no code is present — the export never
machine-guesses a code, only emits what the user stored.

The aggregator now carries `atcCode` / `rxNormCode` on `medications[]`
and assembles the acted-intake source rows
(`medicationAdministrations`) the administration builder consumes, so
the FHIR export keeps describing the same numbers as the PDF by
construction.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 740c86b3a830efa7e76d69b29ae376addeee6811)
2026-06-02 16:45:23 +02:00
Marc-André Bombeck 0a8c6e307c feat(medications): add optional ATC + RxNorm codes to the medication row
Add two nullable, additive columns to `Medication` (`atc_code`,
`rxnorm_code`) so a user or clinician can assert a drug-classification
code that the health-record FHIR export emits on the medication concept.
Codes are taken verbatim, never machine-guessed: a wrong code is a
clinical-safety problem, an absent one is merely a (conformant)
text-only concept.

- Migration 0103 — additive, nullable, no backfill. Pre-existing rows
  read NULL, which the exporter already treats as "no code".
- Validate on write — ATC `^[A-Z]\d{2}[A-Z]{2}\d{2}$`, RxCUI `^\d+$`;
  422 on a malformed value. Wired field-by-field through the create +
  update routes (no mass assignment); `null` clears a code on update.
- Surface both codes in the medication advanced-settings sheet's Data
  group with a self-saving input, and echo them on the GET/POST/PUT
  response shape. OpenAPI regenerated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 2e0051d42826fa3f043c32e78a34dab7c8050165)
2026-06-02 16:45:23 +02:00
Marc-André Bombeck eff7b42348 feat(medications): collapse the API request examples and quiet the URL
The external-API row was the tallest thing in the advanced-settings sheet:
a full-width endpoint URL block plus an always-expanded 4-9 line request
snippet, on screen for every user whether or not they touch the API.

Collapse the multi-language request examples behind a chevron disclosure,
closed by default — the language picker and the live-interpolated bearer
token now only render once the user opts in, keeping the token-shaped
payload out of the default-visible DOM. De-emphasise the raw endpoint URL
to a muted, single-line truncated `<code>`: the copy button already carries
the full value, so the long absolute URL was redundant noise.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 6310ed49f4523e3210b26c05f2c934748967af88)
2026-06-02 16:45:23 +02:00
Marc-André Bombeck 555138110c feat(medications): give the external API its own settings group
The advanced-settings sheet crammed the external ingest endpoint into the
Data group next to CSV import/export — two unrelated audiences sharing one
frame. Pull `ApiTokensRow` into a dedicated "Externe API" group so the
developer-facing surface reads as a distinct, lowest-frequency block. New
group order: Reminders -> Lifecycle -> Data -> Externe API -> Danger.

The new group reuses the existing `SettingsGroup` bordered-card chrome, so
it stays visually consistent with its siblings. Adds the `externalApi`
group label across all six locales and updates the composition test to pin
the five-block order plus the API row's new home.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit f9f3a1277b5aad1710815511ddf7f6b210a652b2)
2026-06-02 16:45:23 +02:00
Marc-André Bombeck f65181bbf2 feat(insights): surface mood time-of-day, stability, and weight/BP correlations
Render the new mood analyses on the insights surface:

- a four-bar time-of-day chart (morning / afternoon / evening / night),
  shown only when the server marks the pattern reliable
- a stability tile beside the in-target tile, with the descriptive band
- the time-of-day takeaway in the narrative feed (new Clock icon, daypart
  label resolved from the bundle)

Also wire the mood x weight and mood x systolic-blood-pressure scatter
cards. Their Pearson coefficients and points were already computed and
returned by the endpoint but never rendered; they now sit alongside the
sleep / activity / pulse cards, each gated on the same minimum-pairs
threshold so a thin pairing renders an empty state rather than a noisy r.

New i18n keys land EN-first and propagate across de / es / fr / it / pl.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 12902b0cdbc6aa272b6da3c35ba3781f9216cf9f)
2026-06-02 16:45:14 +02:00
Marc-André Bombeck 141c083ff6 feat(insights): add time-of-day and stability mood analyses
Extend the mood-aggregate engine with two pure helpers over the rows it
already fetches:

- computeTimeOfDayAverages buckets every entry into morning / afternoon /
  evening / night in the entry's own timezone (legacy null-tz rows fall
  back to UTC). A spread guard keeps the once-a-day logger — whose entries
  cluster in a single bucket — from producing a misleading daypart claim:
  the pattern is only marked reliable once at least two buckets each clear
  the per-bucket sample floor.
- computeMoodStability maps the population standard deviation of the daily
  means onto a 0-100 score (higher = steadier) with a descriptive,
  non-judgemental band. Sparse loggers below the minimum-days floor get
  null rather than a meaningless number.

Both feed the MoodAggregates object that drives the visible mood page and
the LLM snapshot, so the prose and the charts agree. A new time-of-day
narrative takeaway joins the ranked feed, gated on the same reliability
flag plus the existing effect-magnitude bar.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 685b53c0fd994324c270df2b9a5ac964bb442c82)
2026-06-02 16:45:14 +02:00
Marc-André Bombeck 3694efe6e8 fix(insights): keep the assessment card polling while a stale text revalidates
The stale-while-revalidate path serves the last-good assessment on a cache
miss and returns a terminal payload, so the status hook stopped polling. The
worker warmed a fresh assessment out of band seconds later, but the open card
never picked it up — the stale text stuck until the page remounted.

Add a `revalidating` flag to the read-only miss outcome, set only when
last-good text is served AND a refresh was enqueued (false on the
suppressed-stub branch and when no prior text exists). Thread it through the
generic metric-status generator and the seven specialised generators onto the
wire, type it on the client, and make `nextStatusPollInterval` keep polling on
`preparing || revalidating`. The existing 12-attempt ceiling bounds both
signals, so a persistently failing generation still cannot poll forever.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit c9217534fbdb304c4df1b6eb55fb19e4360b8a10)
2026-06-02 16:45:14 +02:00
Marc-André Bombeck 03925ddece feat(insights): time-range pills with period-over-period deltas on metric pages
Add a 7d / 30d / 90d / 1y segmented control to every HealthKit metric page,
between the stat strip and the chart, with a sentiment-coloured "vs prior
period" delta caption beside it.

New route GET /api/analytics/range?type=<MeasurementType>&range=<7d|30d|90d|1y>
returns the current-window aggregate, the previous comparable window, and the
composed delta. Single metric type by construction, so the read is one
rollup-tier call covering the trailing 2N days sliced into the two halves —
no per-type fan-out, no Prisma-pool burst. Reuses the WMY readers
(readBestGranularityRollups + aggregateWmyBuckets) and the two-window pattern
the year-ago baseline already uses; count/min/max/mean/sum compose across
buckets, SD/slope/r2 stay out (not composable). The cached summaries slice is
untouched so the hottest dashboard cache key never fragments.

The delta caption reuses the dashboard's metric-aware up-good/up-bad colour
logic — extracted from trend-card into a shared trend-sentiment module — with
the metric's good direction sourced from the metric-status registry
(target-band metrics render neutral, matching deviation framing). When the
prior window has no data the caption shows "no prior-period data" rather than
a misleading 0%. The range choice persists across metrics via a localStorage
seam and defaults to 30d so nothing regresses. Cache keyed per (type, range)
through the query-key factory.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit eac87a9f8b144f4d8e7a8b950528a19d5dcf8726)
2026-06-02 16:45:14 +02:00
Marc-André Bombeck f1145c0e91 fix(insights): debounce ingest-driven status invalidation to coalesce the regeneration storm
A constantly-syncing client drips measurement batches every few minutes.
Every batch deleted the dirtied per-metric assessment cache rows and
re-enqueued a regeneration. The per-(user,scope,locale) enqueue singleton
is only 120 s, so it could not coalesce across batches that arrive minutes
apart, and each delete dropped the row a fresh enqueue would otherwise have
found warm — so a metric card regenerated several times an hour and its
assessment felt regenerated on every visit.

Before evicting and re-enqueuing, check whether the scope's cached
assessment was already (re)generated within a 30 min debounce window. A
scope that is fresh is left intact and not re-enqueued; a genuinely stale
or missing scope still refreshes immediately, so correctness holds. A
timeout stub never counts as fresh, so a scope that recently stalled still
retries. One indexed read per user answers it for every candidate scope at
once.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 024baea664490ef0494add78c87492f01e61c6b9)
2026-06-02 16:23:16 +02:00
Marc-André Bombeck 2c6a9f8165 fix(insights): decouple the forced warm sections so a slow comprehensive step cannot starve the rest
The on-demand force-warm ran the comprehensive insight first and only ran
the per-status (7) and generic-metric (~30) assessment passes when that
step returned generated or cached. A slow or stalled comprehensive
generation therefore aborted the entire warm — observed in production as a
102 s run ending with assessments_warmed: 0 — leaving every card cold and
the user back on the lazy 30-60 s on-first-click path.

Give the comprehensive step its own bounded budget and treat a timeout,
error, or skip as non-fatal: the per-status and generic-metric passes now
always run afterwards. Each per-card generator resolves its own provider
chain and bounds its own provider call, so running them after a failed
comprehensive costs a cheap chain-resolve when no provider is configured
and is capped per card otherwise. The result reports each section's
outcome independently, and a timed-out comprehensive is reported distinctly
from a failed one so a partial warm is observable.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit f52f8e9c3b32590f3b085d082418ebdd3a923f1d)
2026-06-02 16:23:16 +02:00
Marc-André Bombeck 4a0ad1fc64 fix(medications): restore equal-height cards and aligned dose rows
The v1.8.6 compliance rework left the last/next-dose and compliance rows in
a plain vertical stack with independently conditional rows. A card missing
its last-dose line (never taken) or its streak flame (zero streak) rendered
shorter, so the dose rows and action buttons drifted out of alignment across
the two-column grid.

Pin the layout on both card variants identically: the Card fills the
stretched grid cell with h-full, the CardContent becomes a flex column, the
next/last-dose pair sits in a reserved min-height slot so a missing line
keeps its footprint, and the intake-actions block is pushed to the bottom
with mt-auto for a shared action baseline. Generic and GLP-1 cards now align
row-for-row regardless of which optional rows render.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit a7e541eeb5123abb63514f56d12b93b0023ce417)
2026-06-02 16:23:16 +02:00
Marc-André BombeckandClaude Opus 4.8 5f8e191e2b fix(compose): set an explicit, tunable database connection_limit
The app pins DATABASE_URL in the compose environment block, which shadows
any connection_limit an operator sets in .env, so Prisma fell back to its
default pool (cpu_count*2+1 — 9 on a 4-core host). A combined web+worker
process starves that pool under background AI and rollup load, leaving
HTTP requests waiting on the pool until they time out. Set connection_limit
explicitly (default 20, override via DB_CONNECTION_LIMIT) plus a pool_timeout
override, so the pool can be sized to the host and its database.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 16:06:55 +02:00
Marc-André Bombeck e9906c8111 Merge pull request #239 from MBombeck/release/v1.8.7.1
v1.8.7.1 — assessments for every HealthKit metric, one-tap pre-generation
2026-06-02 14:40:13 +02:00
Marc-André BombeckandClaude Opus 4.8 a9ed2ed661 chore(release): v1.8.7.1 — assessments for every HealthKit metric, one-tap pre-generation
Adds a plain-language assessment to every HealthKit metric page via a
data-driven generator (archetype templates + per-metric metadata, no
per-metric prompt), a one-tap/auto background pre-generation of all
assessments, and the iOS-facing widening of the Insights layout to the
full metric set. Updates the ChatGPT Codex model-slug ladder so
assessments generate again after the backend rotated its identifiers.
Splits the Targets/Sources settings pages, renames the section to
AI Insights, and applies the metric-detail back-nav, dropdown padding,
heading, and Sources-translation polish.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 14:32:51 +02:00
Marc-André Bombeck 2472579059 feat(insights): warm assessments from the overview page
Wire the on-demand full assessment warm into the Insights overview. A new
useInsightsWarm hook POSTs /api/insights/pregenerate; the cards then fill
through their existing stale-while-revalidate reads with nothing to
invalidate locally.

Two entry points share the one mutation. A background warm fires once per
browser session (sessionStorage-gated) as soon as the overview confirms
the user has data, so a returning user lands on warm caches without
acting; it is silent and tolerates the 429 the server returns while a
warm is already in flight. A manual button ('Prepare assessments') runs
the same warm and shows a toast.

Add the insightsPregenerate mutationKey to the factory and the label +
toast strings across all six locales.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 1273a6253dc0d00c7c7ce774c5fbe352664de2e9)
2026-06-02 14:29:49 +02:00
Marc-André Bombeck bf5052bb01 feat(insights): add on-demand full assessment warm
Add POST /api/insights/pregenerate so every AI assessment text — the
comprehensive insight, the seven specialised status cards, and every
data-bearing generic metric assessment — can be warmed for the calling
user on demand, in the active locale, instead of waiting for the nightly
cron or a lazy first-visit generation.

The route narrows userId from the session/Bearer, runs the assistant
surface gate, and enqueues a forced full-warm job onto the existing
insight-pregenerate queue, returning immediately. A short per-user bucket
(insights-warm:<userId>, one per three minutes) returns 429 on a tight
loop so the bypassed nightly 20h budget cannot be turned into a provider
cost amplifier.

The worker branches on the payload: a job carrying { userId, force }
runs forceWarmUser for that user, skipping the candidate scan and the
20h budget; a scheduled tick with no payload keeps its existing batch
behaviour. forceWarmUser reuses the existing comprehensive generator and
warm helpers — no new generation logic — and stays safe by construction:
the comprehensive generator no-ops without a provider, the generic warm
pass filters to metrics the user has rows for so an empty metric never
reaches the provider, and every write is idempotent.

The queue name and a generator-free enqueue helper move to
insight-pregenerate-shared.ts, mirroring the insight-status-generate
split, so the route enqueues without pulling the generator tree.

Regenerate the OpenAPI contract for the new route.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit e10ae9bfeca544c7e5aecd9102459d97ddfad6db)
2026-06-02 14:29:49 +02:00
Marc-André Bombeck d81ab69dc8 feat(insights): widen the layout tile-id set to the full metric universe
Derive `INSIGHTS_TILE_IDS` from `SUB_PAGE_SLUGS` rather than maintaining a
separate 14-id list. The layout tile-id universe and the routed tab strip
now share one source of truth, so a client can persist a layout covering
every metric page the web exposes (37 slugs + the overview mother page)
instead of tripping a 422 on the ~25 slugs the fixed allow-list did not
know about.

Rebuild `DEFAULT_INSIGHTS_LAYOUT` from the derived id list with an explicit
default-visible set; the long-tail HealthKit, body-composition, mobility,
and audio tiles stay default-invisible. The accepted set stays closed — an
unknown id still 422s — and the legacy German aliases keep round-tripping,
so no persisted layout breaks.

Regenerate the OpenAPI contract and extend the route deck: a PUT carrying
the previously-rejected slugs now succeeds, a full-universe PUT round-trips
through GET, and a genuinely-unknown id still 422s.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 0a161d430533845b0c4c322047701b93aea49a06)
2026-06-02 14:15:31 +02:00
Marc-André Bombeck 2123c63af4 a11y(insights): hide the workouts back-link arrow from assistive tech
The workouts detail back-link's `ArrowLeft` glyph carried no
`aria-hidden`, so a screen reader announced it alongside the link text. Add
`aria-hidden="true"`, matching the sibling values detail page's back-link.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 108c3ff583a707b100570e2999b129055f90c76f)
2026-06-02 14:03:00 +02:00
Marc-André Bombeck 4364f3b509 i18n(settings): translate the source-priority editor body for es/fr/it/pl
Splitting Sources back out into a standalone settings page re-exposed the
source-priority editor body — card title, help text, reorder buttons, the
move-up / move-down ARIA labels, per-metric and device-type controls — which
were still English placeholders for es/fr/it/pl. Provide natural
translations so a non-de/en screen-reader user no longer hears English.

Drop the orphaned `settings.sections.sources.redirectNotice` key from all six
bundles; the redirect it captioned was deleted when Sources became a real
route.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 945d3ed8a6981c23dc51f45c22a1cd3f2625c859)
2026-06-02 14:03:00 +02:00
Marc-André Bombeck 746e002104 fix(insights): re-warm generic metric assessments on measurement ingest
The ingest invalidation path mapped a fresh measurement only to the seven
specialised assessment scopes, so a freshly-synced HealthKit metric's generic
assessment card lagged its real-time data until the nightly warm pass —
an asymmetry against the near-real-time specialised cards.

Add a reverse `MeasurementType → metric id` index to the registry and extend
`invalidateStatusInsightsForTypes` so a reading of a type that backs a
registered generic metric also evicts and re-enqueues the matching
`metric:<ID>` scope, using the same single-locale, singleton-debounced
enqueue as the specialised scopes. Unregistered types and the seven
specialised metrics resolve to no generic scope, so the constant sync cannot
fan out to unwanted cards.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 9bc0f116b46950c8ffa79d127d5dcce32ea644a4)
2026-06-02 14:03:00 +02:00
Marc-André Bombeck bd8a4e7990 refactor(insights): type-check the generic metric previous-context scope
The generic metric-status generator read its previous-context row through an
`as never` cast, because `getPreviousInsightContext` was typed to the seven
specialised scopes only. Widen the helper's `scope` param to a
`PreviousContextScope` union that also accepts the `metric:<ID>-status` scope
form, so the generic call type-checks honestly instead of silently disabling
type checking on the argument. No behaviour change — the helper only
interpolates the scope into the audit action.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 899d59b6fa219a14ba39eacded2e042f0f95c2c5)
2026-06-02 14:03:00 +02:00
Marc-André Bombeck 58b793ee4a fix(insights): correct the active-energy assessment id and share the status card
The active-energy page passed `ACTIVE_ENERGY_BURNED` as `statusMetric`, but
that is the DB MeasurementType, not the registry id the metric-status route
accepts. The route's closed enum only knows `ACTIVE_ENERGY`, so every fetch
422'd and the assessment card silently fell back to its empty body.

Point the page at the `ACTIVE_ENERGY` registry id and type `statusMetric`
(plus the `useInsightMetricStatus` metric param) to the closed
`MetricStatusMetricId` union instead of a bare string, so a future
MeasurementType-vs-registry-id mismatch is a compile error rather than a
silent 422. A typecheck pass over all 29 pages confirms active-energy was the
only diverging one.

Extract a shared `MetricStatusCard` that owns the `useInsightMetricStatus`
hook and the assessment-card wiring, collapsing the duplicated mount block in
the HealthKit metric scaffold and the bespoke sleep page to a single line
each (only the icon differs). Behaviour is unchanged: the card mounts only on
the data-bearing branch, so a source-less account never fires an assessment
round-trip. Add a test asserting the active-energy page wires an accepted
registry id.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 6e371aaeb9698f7b4251c22e1d8f381ddfa70a00)
2026-06-02 14:03:00 +02:00
Marc-André BombeckandClaude Opus 4.8 5827ef58cb refactor(insights): drop the unused metric-to-insight key helper
The identity-cast helper had no caller and tripped the dead-code gate.
Remove it and its now-orphaned type import.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 13:32:30 +02:00
Marc-André Bombeck 78b76d2ac5 feat(settings): split targets and sources, rename AI Insights section
Three related settings changes:

- Split the combined Targets & Sources page back into two pages: Targets
  (/settings/thresholds) owns the per-metric target-range editor and
  Sources (/settings/sources) owns the source-priority and device-type
  ladders. Each is its own left-nav entry and route, served by the
  dynamic [section] route. The former /settings/sources permanent
  redirect is removed since the route now renders the page directly.
- Rename the AI Insights settings section and nav label so the AI nature
  is explicit: 'AI Insights' (EN) / 'KI-Auswertungen' (DE), replacing the
  bare 'Insights' / 'Auswertungen'.
- Each page renders its own h1 heading consistent with sibling settings
  pages.

Drop the now-unused embedded mode from SourcesSection. Update the section
titles and descriptions across all six locale bundles.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 5d8842934b985eb8ce037993a63bb0736ac0c7bd)
2026-06-02 13:26:10 +02:00
Marc-André Bombeck 708d012d28 fix(ui): make select trigger horizontal padding symmetric
The select trigger used pl-3 pr-2 (12 px left, 8 px right), parking the
chevron visibly closer to the right edge than the value text sits from
the left. Use px-3 so both gutters are 12 px; the gap-2 between value and
chevron and the chevron's shrink-0 keep it from crowding or clipping.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit aaea4ea8102d8f74ea039fc6764ee2e3e5474afc)
2026-06-02 13:26:10 +02:00
Marc-André Bombeck ee845946fa fix(insights): place metric detail back-nav above the heading
The metric values subpage (/insights/values/[type]) and the workout
detail page rendered the back link as the first child of SubPageShell,
which paints it below the page heading. Add an optional backLink slot to
SubPageShell that renders above the header — the standard back-nav
placement — and move both pages' back links into it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 72a73a52eb8295c9e70a3456972476b8c4469f07)
2026-06-02 13:26:10 +02:00
Marc-André Bombeck a9aa0b8531 fix(ai): track the ChatGPT Codex backend's current model slugs
The ChatGPT Codex backend rotated its ChatGPT-auth model slugs off the
`-codex` specialist line onto the plain `gpt-5.x` line, so the in-code
default ladder (`gpt-5.3-codex`, `gpt-5-codex`, `gpt-5`, `gpt-4o`) is
now rejected and insight generation fails with a 503 on a fresh deploy
that has no `CODEX_MODEL_FALLBACK_CHAIN` override.

Replace the default ladder with the current accepted set, in order:
`gpt-5.5` (current default across paid tiers), `gpt-5.4` and
`gpt-5.4-mini` (documented fallbacks), `gpt-5.3-codex` (late rung, still
accepted intermittently), `gpt-5.2` (legacy floor). The
fall-through-on-rejection walk, the working-slug cache, and the env
override path are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit bced19de2d4f0788bfd6fa56a78e719347776a1f)
2026-06-02 13:26:10 +02:00
Marc-André Bombeck b1b2e22eeb feat(insights): mount per-metric assessment on HealthKit sub-pages
Add an optional statusMetric prop to HealthKitMetricPage that mounts
InsightStatusCard beneath the chart, pointed at the generic
metric-status route. The card renders only on the data-bearing branch;
the insufficient-data branch keeps the existing empty-state note and
never fires an assessment fetch. Wire statusMetric on the 29
HealthKit metric sub-pages and on the sleep page, which closes the
assessment slot its deferral comment had left open.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 083044201af7715740ec0ee2f14c7240c4999fbf)
2026-06-02 13:26:10 +02:00
Marc-André Bombeck 16b0c349f2 feat(insights): add generic per-metric assessment loader
Add a parameterised query key (insightsMetricStatus) and a
useInsightMetricStatus hook that reads the generic per-metric
assessment route GET /api/insights/metric-status?metric=<id>. The
seven bespoke status routes keep their own keys and hook union; this
one covers the HealthKit metric sub-pages that share a single route
keyed by the metric id. The hook mirrors the existing status loader:
8 s client ceiling, no inline retry, and the bounded preparing poll.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit a3407a2f6c1e9f54c92a6f182db894ae0593e69f)
2026-06-02 13:26:10 +02:00
Marc-André Bombeck e33911e2d4 feat(insights): generic per-metric assessment coverage for HealthKit metrics
Extend the assessment-card system beyond the seven specialised scopes to
the ~30 HealthKit metric pages, without hand-writing a prompt per metric.

- Add a metric-metadata registry keyed by HealthKit id (display name,
  unit, direction, optional normal range, archetype, scope), covering the
  data-bearing HealthKit metrics. The seven specialised metrics keep
  their own scopes and are excluded from the generic set; an unregistered
  id gets no card.
- Add a generic data-driven generator that reuses the existing graded
  snapshot, provider runner, stale-while-revalidate cache, and persist
  path. One prompt template per archetype (physiological-vital,
  activity-fitness, body-composition, mobility-gait,
  environmental-exposure) plus a dedicated sleep template, parameterised
  by metric metadata. Empty-data metrics return an insufficient marker
  with no provider call. Normal ranges use age + sex where the profile
  stores them; no ancestry/region ranges.
- Add GET /api/insights/metric-status?metric=<id>: apiHandler-wrapped,
  Zod-validated against the closed registry id set (422 on unknown),
  read-only with stale-while-revalidate. First insights route with
  OpenAPI coverage; regenerate docs/api/openapi.yaml.
- Route the generic metric:<id> scope through the on-demand status queue
  worker dispatch.
- Extend the nightly warm pass to the generic metric caches for a user's
  data-bearing metrics only (one distinct read gates the set), keeping
  de+en warm and never calling a provider for an empty metric.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
(cherry picked from commit 41453fbdfee60793c16269b9a9e5f04b6c3ea450)
2026-06-02 13:26:10 +02:00
Marc-André BombeckandClaude Opus 4.8 2717297dae docs(contributing): make main the single trunk, retire develop
The long-lived develop branch carried no work absent from main and had
drifted 1216 ahead / 85 behind. Retire it (archived as the tag
archive/develop-pre-v1.5) and rewrite the branch model to match how
releases actually ship: main is the single trunk, releases build on
short-lived release/vX.Y.Z branches off main, merge back, and tag.
This removes the back-merge debt by construction and keeps the tagged
commit on main the single source of the OpenAPI contract.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 12:40:30 +02:00
Marc-André Bombeck 3ea6bde8a3 Merge pull request #238 from MBombeck/release/v1.8.7
v1.8.7 — Instant insight assessments, GLP-1 blood-level chart, tile + caption polish
2026-06-02 10:17:32 +02:00
Marc-André Bombeck d5f75d2e03 chore(release): v1.8.7 — instant insight assessments, GLP-1 blood-level chart, tile + caption polish 2026-06-02 10:11:26 +02:00
Marc-André Bombeck 04615d1bc7 fix(medications): make the drug-level estimate disclaimer clearer
The pharmacokinetic-estimate disclaimer rendered as a low-contrast muted
italic footnote, easy to miss. The curve is a modelled value, never a
measured blood concentration, and that framing must read clearly. Lift it
to a bordered note with stronger text contrast and weight, keeping the
wording unchanged and the tone informative rather than alarming.
2026-06-02 10:10:39 +02:00
Marc-André Bombeck ecf4f06870 fix(dashboard): clip the tile card bound on a pathological value
The headline value span is shrink-0 whitespace-nowrap so it never
truncates a digit — correct. A worst-case very wide value could still
push the card's content past its grid column and break the layout. Add
overflow-hidden to the tile card wrapper so a pathological value clips at
the card bound rather than the grid, without re-introducing truncation of
the number for realistic readings.
2026-06-02 10:10:39 +02:00
Marc-André Bombeck aeb72d1a08 fix(insights): regenerate only the user's locale on a measurement invalidation
The write-path regenerate-on-invalidate enqueued a fresh assessment for
both de and en on every dirtying measurement, while the read-path only
ever serves the user's resolved locale. A frequent Apple-Health sync thus
fanned out two provider calls per scope, half for a language the user
never opens. Resolve the user's locale the way the read-path does
(normalizeLocale of user.locale) and enqueue that single locale. The
nightly warm pass still covers both locales for the rare locale switch.
2026-06-02 10:10:39 +02:00
Marc-André Bombeck ae82b3e484 fix(insights): style the fallback trend caption like the advisor caption
Extract the advisor caption's bordered card + icon + foreground prose
shell into a shared TrendCaptionCard and render the additive-metric
fallback caption through it, so the Trends-row captions read with one
typography instead of the plain muted line standing out below the
chart. The two paths now share a single presentational shell and can't
drift apart.
2026-06-02 10:00:48 +02:00
Marc-André Bombeck be90c4b9ad fix(dashboard): never truncate the tile value, let the unit yield instead
The small KPI tiles in the dashboard strip clipped the numeric value at
narrow widths: the headline value span carried `min-w-0 truncate` while
the unit span was `shrink-0`, so on a dense strip (many tiles → narrow
grid column) the number — not the unit — shrank below its content width
and ellipsis-clipped, rendering "130 mmHg" as a truncated "13…".

Flip the priority. The value span is now `shrink-0 whitespace-nowrap` so
every digit always renders in full on one line, and the unit span takes
`min-w-0 truncate` so it yields when the column is too narrow. The
paired-value font step-down (text-3xl → text-2xl for BP systolic/
diastolic) stays as headroom.

Add guards asserting the value node never carries truncate/min-w-0 and
the full reading (single and paired) renders inside it.
2026-06-02 10:00:48 +02:00
Marc-André Bombeck 9652047e8e fix(medications): order the drug-level chart above the dose-strength curve
Lift the GLP-1 drug-level estimate and the dose-strength (titration)
curve out of the default-closed disclosure on both the medication
detail and history pages so they are visible without a click. Render
the drug-level estimate first — it is the curve the medication concerns
— with the titration curve below it.
2026-06-02 10:00:48 +02:00
Marc-André Bombeck 28af138691 feat(medications): show the GLP-1 drug-level estimate by default
Render the estimated drug-level-in-blood curve for any recognised GLP-1
medication without requiring the Research Mode opt-in. The chart still
self-gates on a recognised brand and on having intake data, and the
pharmacokinetic-estimate disclaimer is now always attached so the curve
reads as a modelled value, not a measured blood concentration.

Drop the now-dead Research-Mode gated-placeholder branch and its copy.
The researchModeEnabled flag is unchanged; it still gates the advanced
settings surface and its acknowledgment dialog.
2026-06-02 10:00:48 +02:00
Marc-André Bombeck 9e8b536ff6 fix(insights): place the mood assessment under the first chart
The mood assessment rendered last on the page, below the target summary,
the calendar, the distribution, the weekday and correlation breakdowns.
Move it directly under the mood chart so the narration sits next to the
trend it describes, matching the other category pages.
2026-06-02 10:00:48 +02:00
Marc-André Bombeck 60f347bf8d feat(insights): serve assessments stale-while-revalidate on a cache miss
A category open whose today-cache had been evicted dropped to the
preparing skeleton even when a perfectly good assessment from an earlier
day was still on record. Read the most recent non-stub assessment for the
scope and serve it instantly while the worker re-warms the cache; only
fall back to the preparing state when no assessment was ever produced.
The user no longer waits on an open if an assessment ever existed.
2026-06-02 10:00:48 +02:00
Marc-André Bombeck f4d5114dcd fix(insights): regenerate cached assessments when a measurement invalidates them
The measurement-sync invalidation deleted the dirtied per-scope
assessment rows and waited for the user's next category open (a cache
miss → a worker round-trip while they wait) or the nightly cron to
re-warm them. Enqueue a debounced regenerate for each dirtied scope
instead, coalesced per (user, scope, locale) through the queue's
singleton key so the constant Apple-Health sync collapses a burst of
samples into one regenerate per scope rather than a job storm.
2026-06-02 10:00:48 +02:00
Marc-André Bombeck a8e7325a08 Merge pull request #237 from MBombeck/release/v1.8.6
v1.8.6 — Compliance two-row return, insights polish, targets deprecation
2026-06-02 00:01:59 +02:00
Marc-André Bombeck cfeb98f0a7 chore(gitleaks): allowlist the trend caption i18n keys 2026-06-01 23:56:19 +02:00
Marc-André Bombeck 9b3cb5ec7e test(e2e): assert the wizard step via the dialog root data attributes 2026-06-01 23:56:19 +02:00
Marc-André Bombeck a4bb4947f9 chore(release): v1.8.6 — compliance two-row return, insights polish, targets deprecation 2026-06-01 23:46:07 +02:00
Marc-André Bombeck b868a72a91 fix(targets): merge the profile-incomplete hint into the deprecation banner
The deprecation notice and the profile-incomplete hint rendered as two
near-identical warning cards stacked on top of each other, so an
incomplete-profile user saw two warning banners. Fold the profile detail
into the single deprecation card as a secondary line beneath the headline
message, shown only when height or age is missing. The page now carries
one warning banner.
2026-06-01 23:43:39 +02:00
Marc-André Bombeck 712c5707ee fix(auth): cap insurerIkNumber length before the digit refine
The insurerIkNumber field went straight to the 9-digit regex refine with
no upper bound, unlike its siblings insurerName and fullName which cap at
120 characters. Add a defensive .max(32) before the transform — well
above the 9 digits the value ever holds — so an oversized string is
rejected at the length gate rather than reaching the regex. The refine
already rejects malformed input; this is hardening for consistency with
the surrounding fields.
2026-06-01 23:43:39 +02:00
Marc-André Bombeck 0ec4a16153 fix(insights): pin category-page heading height and coach icon placement
The relocated diversity-nudge lightbulb is a 44px touch target that only
mounts on pages where readings cluster, so the heading row sat taller on
pages with a nudge than on those without — category-page headings did not
align. Reserve a constant min-height on the heading row so the baseline
holds whether or not the glyph is present.

Split the row into a wrapping left group (title, nudge, badge) and a
shrink-0 Coach icon pinned top-right via justify-between, replacing the
ml-auto member of a single flex-wrap row. A long or wrapped title at
375px can no longer isolate or crowd the Coach icon; it stays cleanly
top-right and the title reflows in the remaining space.
2026-06-01 23:43:39 +02:00
Marc-André Bombeck 3f757f7fc2 fix(medications): name the active wizard step on small screens
On narrow viewports the dot stepper collapsed every per-dot label, so
the user faced an unlabelled row of bullets with no sense of position.
Add a compact caption below the dots that names where they stand ("Step
4 of 8 · How often") on small screens, and let the per-dot labels show
only from the small breakpoint up where there is room. The dots stay
tappable throughout.
2026-06-01 23:43:39 +02:00
Marc-André Bombeck 2c91dc7b75 refactor(medications): share the wizard cadence-line builder
`summariseCadence` and `summariseScheduleDraft` each re-spelled the
cadence phrase, its detail clause, and the interpolation count. Extract
a single `{mode, cadence, subControls}`-shaped helper both call so the
medication-wide and per-schedule summaries can't drift apart, and drop
the now-redundant `summaryKeyForCadence` wrapper. Behaviour is
identical; add coverage pinning the per-schedule summary to the
medication-wide summary's leading cadence segment.
2026-06-01 23:43:39 +02:00
Marc-André Bombeck 4038cfcffe fix(medications): drop the empty streak row from the compliance bars
The streak flame's flex wrapper rendered unconditionally, so a
zero-streak medication left a residual gap below the two compliance bars
from the wrapper's row plus the stack's vertical spacing. Mount the
wrapper only when there is a streak to show.
2026-06-01 23:43:39 +02:00
Marc-André Bombeck a357332a32 refactor(medications): import the shared ComplianceDisplay type on the cards
The generic and GLP-1 medication cards each re-spelled the
`ComplianceDisplay` interface already exported from the compliance lib.
Drop both hand-copies and import the canonical type so a future field
change lands in one place.
2026-06-01 23:43:39 +02:00
Marc-André Bombeck 068cb168d9 fix(medications): clamp compliance expected slots to creation date
`expectedSlotsBetween` walked the full requested window even for a
medication younger than that window. The legacy weekday expander floors
on `startsOn` but not on `createdAt`, so a two-day-old daily med
reported seven expected doses over a seven-day window and thirty over a
thirty-day window — counting days before it existed. Clamp the window
lower bound to `createdAt` so the expected-dose counts, and the window
selection that reads them, reflect the medication's real age. The
displayed rates already clamp independently via `calculateCompliance`,
so only the slot counts change.
2026-06-01 23:43:39 +02:00
Marc-André Bombeck 38867439f3 feat(insights): fold structured mood tags into the tag takeaways
The structured taxonomy tags carry a separate, richer signal than the
free-text tag list: a curated catalog pick with a label key and category,
attached to a mood entry through the tag-link join. The tag-mood takeaway
builder only ever read the flat tags, so the structured tags never reached
the ranked lift/drop pool despite both call sites already passing them.

Merge both axes into one ranked pool. A structured candidate emits its
catalog label key as tagKey, which the feed resolves to the active locale
the same way the weekday key already resolves; flat tags keep their
verbatim label. The lean status snapshot now loads the structured-tag
links too, so the takeaways the model sees match the ones on screen.
2026-06-01 23:43:39 +02:00
Marc-André Bombeck d1e6befa5c fix(insights): render the mood in-target share once
The mood page stacked the in-target tile directly above the narrative
feed, and the feed carried a same-number in-target takeaway built from
the identical share — so the percentage showed twice, one row apart.
Suppress the in-target narrative in the feed whenever the tile renders
(the tile is the canonical surface). The takeaway still rides the API
and LLM snapshot payload unchanged.
2026-06-01 23:43:39 +02:00
Marc-André Bombeck 90586d6279 feat(export): emit a FHIR Coverage resource for the insurer
The health-record FHIR bundle now carries a Coverage resource right
after the Patient. Coverage.status is active, beneficiary references
the Patient, and subscriberId carries the KVNR when present. The payor
is a contained Organization referenced by a local #-ref: its name is
the insurer name and its identifier carries the IKNR under the
http://fhir.de/sid/arge-ik/iknr system.

When the IKNR is absent the Organization keeps its name only; when
neither insurer name nor IKNR is known the Coverage is omitted rather
than emitting an empty payor. The KVNR continues to ride on
Patient.identifier unchanged — Coverage is purely additive.
2026-06-01 23:24:10 +02:00
Marc-André Bombeck b99b07ad38 feat(profile): capture the insurer IK number
Add an optional German insurer institution number (IKNR, 9 digits) to
the user profile, alongside the existing insurer name and KVNR. The
IKNR is a public registry identifier for the institution, not a
per-person quasi-identifier, so it is stored plaintext, matching
insurer_name rather than the encrypted KVNR column.

The profile GET echoes the field; PATCH/PUT accept it via Zod —
optional, empty string maps to null, and a non-empty value must be
exactly 9 digits (422 otherwise, no checksum). The write is built
field-by-field. /api/user/profile gains an OpenAPI registration with
the profile read/write schemas.

Migration 0102 adds the nullable column, NULL-defaulted, forward-only.
2026-06-01 23:24:10 +02:00
Marc-André Bombeck 9ecd798119 chore(targets): keep the EOL note in code, not a planning file 2026-06-01 23:10:22 +02:00
Marc-André Bombeck cd1eaa1a4e chore(targets): deprecate the targets page and drop it from the menu
Target editing now lives inline on the insights pages, so the standalone
targets page is no longer a navigation destination. Remove its sidebar
and bottom-nav (overflow) entries and add a top deprecation banner that
points the user at the insights pages and notes the page will be removed
in a future release.

The page stays routable: the /zielwerte to /targets redirect remains and
the route still renders. Removal later is UI-only because the insights
panel consumes the same targets read and threshold-override write. New
deprecation strings land across all six locales.
2026-06-01 23:07:32 +02:00
Marc-André Bombeck c72715bb62 feat(insights): edit target ranges inline instead of routing to the targets page
The per-metric reference panel on each insights category page now opens
the self-contained target editor in place rather than linking out to the
targets page. The panel mounts the same <TargetEditSheet> the targets
card uses, seeded with the metric's type, unit, and range (plus the
diastolic band for blood pressure); the sheet writes the threshold
override and invalidates the shared targets cache on save, so the panel
repaints without a navigation.

Switch the sheet's targets-cache invalidation to the query-key factory
call so it stays aligned with the centralised key.
2026-06-01 23:07:32 +02:00
Marc-André Bombeck 68517240e1 fix(insights): always caption a briefing-driven trend card
The Trends row charts the metrics the daily briefing flags, but only
the legacy BP / weight / mood triple carried an advisor annotation.
Every additive metric (pulse, sleep, steps, HRV, resting heart rate,
active energy, flights, distance, VO2 max, body temperature) rendered
the chart with empty space underneath because the caption only painted
when a slot carried an annotation key.

Give every chart config a standard one-line description (captionKey)
and render it for slots that carry no advisor annotation, so no card
is ever caption-less. The legacy triple keeps its annotation slot. Add
the caption strings across all six locales and regression tests that
pin a caption on every tile.
2026-06-01 22:59:14 +02:00
Marc-André Bombeck 3f9fd9095f feat(medications): show the GLP-1 dose-strength curve instead of the empty therapy course
The GLP-1 detail disclosure carried a titration block that only ever
rendered the standard EMA *reference* ladder — a static schedule with no
values from the user's own therapy, blank whenever the medication's brand
fell outside the catalog. Replace it with a dose-strength curve over the
user's recorded dose-change history.

The MedicationDoseChange stream is the history of record for titration
(2.5 -> 5 -> 7.5 mg escalation steps). The new curve plots that series as
a step line, carrying the latest dose forward to now so the current
strength anchors the right edge. With a single dose change there is no
escalation to draw, so the surface states the current dose plainly with a
"no titration history yet" caption rather than a flat single-point chart;
with none it shows the empty state. The curve plots only logged facts, so
unlike the estimated-PK drug-level chart it needs no Research-Mode gate.

Drop the now-unused reference-ladder section, its read route, the ladder
helpers, the titration query key, and the orphaned i18n block.
2026-06-01 22:59:14 +02:00
Marc-André Bombeck c1f30466e7 feat(medications): replace the wizard progress bar with a jumpable dot stepper 2026-06-01 22:59:14 +02:00
Marc-André Bombeck 38b12607c2 feat(medications): add a multi-step forward-jump lookahead to the wizard payload 2026-06-01 22:59:14 +02:00
Marc-André Bombeck 308d9c9d6d i18n(medications): add short step labels and jump-navigation copy for the wizard stepper 2026-06-01 22:59:14 +02:00
Marc-André Bombeck 5d2ae7732e feat(api): accept an optional source on the measurements batch endpoint
Add an optional per-entry `source` to POST /api/measurements/batch,
restricted to the {APPLE_HEALTH, MANUAL} subset of MeasurementSource and
defaulting to APPLE_HEALTH when absent so existing web and iOS callers
are unchanged. The standalone iOS client can now tag adopt-on-pair
backfill rows that the user entered by hand as MANUAL instead of having
them mis-attributed to HealthKit.

source is threaded into the (userId, type, source, externalId) dedup
key, the existence probe, and the stats:* overwrite scope, so a MANUAL
row and an APPLE_HEALTH row sharing an externalId are distinct rows and
the stats:* re-post overwrite only touches the matching source.
WITHINGS and IMPORT stay server-owned and are rejected here with 422.

Regenerate the OpenAPI spec and add integration coverage for the
absent-source default, explicit MANUAL, cross-source distinctness, and
the rejected-source 422 path.
2026-06-01 22:54:20 +02:00
Marc-André Bombeck ca4425b2e0 fix(medications): make the danger zone a symmetric matched pair
Replace the space-y-4 + interleaved-separator danger card, whose two
rows the outer group double-framed into unequal spacing, with one
tinted card: divide-destructive/20 dividers, equal py-3 per row, and
two identical destructive buttons for a true matched pair.
2026-06-01 22:54:20 +02:00
Marc-André Bombeck 795898bb0a fix(medications): rebuild the advanced-settings sheet as a single column
Drop the lg:grid-cols-2 data|reminders grid that read as overloaded.
The sheet now narrows from 4xl to 2xl and stacks four bordered section
cards in most-used-first order: Reminders, Lifecycle, Data, Danger. One
spacing rule throughout — space-y-4 between cards, divide-y plus py-3
rows inside each card, with the SettingsGroup card owning the dividers
so no row interleaves its own separator.
2026-06-01 22:54:20 +02:00
Marc-André Bombeck a3b34bc0cf chore(mood): drop the notes timeline from the insights page
The notes timeline display comes off the mood insights surface; note
capture on the entry form stays. Add a structural guard that the
timeline component is gone, the insights sections no longer render it,
and the narrative feed and in-target tile take its place.
2026-06-01 22:51:10 +02:00
Marc-André Bombeck ac51cfdc18 feat(mood): add a ranked narrative takeaway feed
Surface plain-language takeaways above the mood charts: the weekday dip
and peak, the overall trend direction, the weekend-vs-weekday effect,
the strongest tag-to-mood lift and drop, the in-target share, and the
current logging streak. Each takeaway is threshold-gated — every minimum
sample count and minimum effect size is a named constant, and a takeaway
only renders once its bar is cleared, so the feed never falls back to
filler. The list is ranked by effect size and capped.

The takeaways are pure helpers computed from the existing mood
aggregates, so the same feed reaches both the insights endpoint and the
mood snapshot the model reasons over — what the page shows matches what
the model is sent. Also promote the previously snapshot-only in-target
percentage to a visible headline tile.
2026-06-01 22:51:10 +02:00
Marc-André Bombeck 3ecfa3a898 fix(mood): truncate long notes in the entries table
A long free-text note forced the mood entries table into horizontal
scroll. Cap the note column width, clamp the note to two lines, and
surface the full text on hover through a tooltip. The complete note
stays editable in the entry sheet.
2026-06-01 22:51:10 +02:00
Marc-André Bombeck 6e61713fc6 fix(insights): move coach-ask to the header and de-emphasise the assessment border
The Coach launch sat at the foot of every category page; move it into the
sub-page header as an icon-only button at heading height, top-right, so
"ask the coach" reads as a header action and the page no longer ends on a
stray button. The shared shell mounts it (gated on the Coach flag plus the
per-user opt-out), so every category page picks it up and the foot
instance is dropped. Also drop the purple left accent on the assessment
("Einschätzung") card — the coloured rule made it read as restless against
the calmer surrounding cards.
2026-06-01 22:50:59 +02:00
Marc-André Bombeck 4935a9b000 feat(insights): surface the diversity hint as a heading lightbulb
The measurement-diversity nudge used to render as an inline note block on
each category page; read in context it looked like a data finding rather
than a tip and confused. Move it onto the heading as a small Lightbulb
glyph that only mounts when the spread is genuinely lopsided; the hint
text it used to show inline now lives in a hover / focus Tooltip with an
accessible name. The sub-page shell carries the glyph in the heading row,
drops the removed explainer trigger, and normalises the foot-of-page
"show all readings" control to the standard secondary-button height.
2026-06-01 22:50:59 +02:00
Marc-André Bombeck 0e9fa7bf80 fix(insights): drop the question-mark explainer circle from the heading
The round `?` popover next to each category heading read as restless
beside the title and duplicated copy already shown inline. Remove the
`MetricExplainer` trigger entirely; the static one- to two-sentence
definition stays as the muted caption directly beneath the heading, so
the definition is still always visible without a tap. The bundle keeps
the per-metric Title leaf for stable key pairs even though only the Body
caption now renders.
2026-06-01 22:50:59 +02:00
Marc-André Bombeck e5b873833a fix(medications): restore the two-row compliance display, scaled to cadence
v1.8.5 swapped the long-standing 7-/30-day compliance rows for a per-dose
adherence timeline on sparse-cadence medications. The timeline breaks the
card layout and reads as restless, so every medication is back to two
percentage rows.

The two windows are no longer hardcoded — they scale with the dosing
cadence. selectComplianceWindows walks a 7/30 -> 30/90 -> 90/365 ladder and
returns the densest rung whose both windows clear MIN_STABLE_DOSES realised
expected doses, so a daily med stays on 7/30, a weekly med steps up to
30/90, and a rolling 35-day injection lands on the widest 90/365 rung. When
even the top rung can't clear the floor (a brand-new or very rare med) the
widest rung is returned so the card still shows two honest rows. The row
labels follow the chosen windows via a parametrised complianceWindow string.

The compliance percentage math is unchanged: each row is the existing
cadence-aware calculateCompliance over the selected window. compliance7 /
compliance30 stay on the wire verbatim for iOS and the Health Score.

- compliance.ts: replace the timeline display with selectComplianceWindows +
  the window ladder; buildComplianceDisplay now returns the two scaled rows
- remove the dose-adherence-timeline component and its now-dead strings
- medication-compliance-bars: parametrise the row labels on the day-counts
- switch the standard and GLP-1 cards back to the always-two-row bars
2026-06-01 22:44:13 +02:00
Marc-André Bombeck 6c44d4a2c1 Merge pull request #236 from MBombeck/release/v1.8.5
v1.8.5 — Insights reference panels, mood depth, injection tracking
2026-06-01 21:42:03 +02:00
Marc-André Bombeck 0fe2ac6d51 chore(api): regenerate the OpenAPI spec for 1.8.5 2026-06-01 21:36:40 +02:00
Marc-André Bombeck bdacd78b0a chore(release): v1.8.5 — Insights reference panels, mood depth, injection tracking 2026-06-01 21:21:02 +02:00
Marc-André Bombeck 6a2762ec35 fix(a11y): raise the target status-pill text contrast to AA
The status pill painted full-saturation Dracula green/orange/red text on
a 12-14% same-hue tint. That fails WCAG AA (4.5:1) for the out tone on
the muted insights reference panel in dark mode (3.87:1) and for every
tone on a white card in light mode (1.2-2.7:1), since the pill used the
raw Dracula palette rather than the theme-aware feedback tokens.

Switch the pill to dedicated theme-aware tokens (status-pill-in/near/out)
and a 10% tint: dark mode keeps Dracula green/orange and lifts the out
tone off #ff5555 to a lighter red; light mode adopts the darker
AA-corrected family already used for the chart and destructive colours.
All three tones now clear 4.5:1 on both bg-card and bg-muted/30 in both
themes (worst case 4.62:1).
2026-06-01 21:17:09 +02:00
Marc-André Bombeck 0b10932c53 docs(insights): pin the median window contract across the summary paths
DataSummary.median carries two windows under one field name: the SQL
summaries-slice path windows PERCENTILE_CONT to the trailing 90 days,
while the JS summarize() takes the median over the full series it is
handed (a caller-defined window). No user-visible bug today — the stat
strip only reads the 90-day SQL path — but a future consumer reading
summary.median off a summarize()-derived payload would silently get a
different number. Document the window on the type and at both call sites
so the divergence is explicit; the percentile algorithm matches, only
the window differs.
2026-06-01 21:17:09 +02:00
Marc-André Bombeck 146867b09f fix(insights): show one adjust-target link for the glucose panel group
The blood-glucose reference panel fans out to up to four per-context
panels (fasting / postprandial / random / bedtime), each previously
emitting its own identical "Adjust target range" link to /targets — so
the page stacked up to four copies of the same link. Lift the link to
the group wrapper and render it once; keep the per-panel link for the
non-glucose single-panel path.
2026-06-01 21:17:09 +02:00
Marc-André Bombeck b10569dc44 fix(insights): give the mood distribution chart a zero-bucket track
A mood level with no days painted a zero-height bar with no affordance,
reading as missing rather than "0". Add a faint full-height track behind
each bar so empty buckets stay legible; the coloured bar paints over the
track for the populated levels.
2026-06-01 21:17:02 +02:00
Marc-André Bombeck bd0b284201 fix(a11y): enlarge mood tag chips to the 44px tap target
The structured-tag picker chips and the side-effect chips sat at 32px
(min-h-8), under the 44px minimum and a fat-finger risk on a phone where
they wrap tightly. Bump both to min-h-11 with matched padding so the tap
target clears 44px without loosening the visual density.
2026-06-01 21:17:02 +02:00
Marc-André Bombeck baa1ff250c refactor(insights): table-drive the mood correlations
The five mood-metric correlations and the measurement query's type
filter were two hand-kept copies of the same channel list. Introduce a
CORRELATION_METRICS map and single-source both the correlations object
and the fetch filter from it so they cannot drift.
2026-06-01 21:17:02 +02:00
Marc-André Bombeck 78d3478ad2 fix(mood): return tag keys from create and update
The list GET surfaces tagKeys per entry but the create and update
responses omitted it, so a client hydrating from the response body
showed an empty tag set until the next refetch. Read the persisted
link keys back inside the write transaction and include them in both
response bodies.
2026-06-01 21:17:02 +02:00
Marc-André Bombeck d5580917cc fix(mood): write tag links inside the entry transaction
The mood entry was committed before createTagLinks/replaceTagLinks ran,
so a tag-link failure 5xx'd after the entry already existed and a client
retry minted a duplicate entry. Wrap the entry write and the tag-link
write in one $transaction and thread the tx client through both helpers
so they commit or roll back together.
2026-06-01 21:17:02 +02:00
Marc-André Bombeck fcf5114620 chore(mood): drop the superseded tag-taxonomy seeder
The structured tag catalog is seeded directly by migration
0101_v185_mood_tag_taxonomy and served from Postgres via the
/api/mood/tags route, so the parallel TypeScript copy had no
importer and tripped the knip gate.
2026-06-01 21:17:02 +02:00
Marc-André Bombeck a5c894b58e i18n(medications): translate the injection-site strings for es/fr/it/pl
The injection-site / log-dialog / settings cluster shipped translated in
de and en but verbatim English in es, fr, it and pl, so those users saw
English copy in the medication wizard, the log-injection-site dialog and
the settings injection card. Localise the eleven keys and drop the two
orphaned injection-rotation keys in the same bundles.
2026-06-01 21:16:56 +02:00
Marc-André Bombeck 6bc51249ba chore(i18n): drop two orphaned injection-rotation keys
medications.injectionRotationOverviewTitle and
medications.injectionRotationNextSuggested have no t() reference anywhere
in the tree — leftovers from an injection-rotation overview that did not
land. Remove them so the bundle carries only live keys.
2026-06-01 21:16:56 +02:00
Marc-André Bombeck f29ac6d96e fix(a11y): give the injection-site picker a visible focus state and accessible names
The SVG site picker painted its focus ring as the stroke of a transparent
hit-target circle — effectively invisible on the muted body map, a WCAG
2.4.7 risk — and conveyed the recommended next site only through the
dashed ring (no screen-reader cue). Track keyboard focus and paint a
contrasting halo on the filled dot, and fold the recommendation into the
recommended site's aria-label so the rotation guidance reaches assistive
tech. Adds injectionSiteRecommendedAriaLabel across all six locales.
2026-06-01 21:16:56 +02:00
Marc-André Bombeck ad693cd862 refactor(medications): extract the compliance slot-context builders
expectedSlotCountForDay and expectedSlotsBetween each rebuilt the same
canonical-schedule and recurrence-context literals inline, differing only
by id prefix and count-vs-collect. Extract toRecurrenceCtx and
toCanonicalSchedule so both share one adapter; behaviour identical.
2026-06-01 21:16:56 +02:00
Marc-André Bombeck 7e7702d6c9 refactor(medications): single-source the injection-site allow check
resolveInjectionSiteForWrite reimplemented the effectiveAllowedSites(...)
.includes(...) membership test inline, duplicating the isSiteAllowed
helper that already wraps it. Call isSiteAllowed so the write-path guard
and the helper share one definition.
2026-06-01 21:16:56 +02:00
Marc-André Bombeck fef88787e9 fix(medications): surface a multi-day-overdue first rolling dose
A rolling cadence with no intake logged anchors its first dose at
startsOn ?? createdAt. When that anchor falls on a prior calendar day
the dose is overdue by a day or more, but nextOccurrenceAfter floored
the search window to the start of the user's current day and dropped it
— so the dashboard showed no next-due and the reminder worker, which
shares this engine, emitted nothing. Clamp the floor to the first-dose
day in the no-intake branch so a multi-day-overdue start dose surfaces
as overdue. The post-intake re-anchor (lastIntakeAt + N) is unaffected.
2026-06-01 21:16:56 +02:00
Marc-André Bombeck b5e98533b8 fix(export): move HealthKit placeholder codes off the LOINC namespace
Six HealthKit metrics without a published LOINC term were coded under
http://loinc.org, which fails FHIR R4 conformance (a non-LOINC code must
not sit in the LOINC namespace). Route any HKQuantityTypeIdentifier code
onto a shared custom CodeSystem (https://healthlog.dev/fhir/CodeSystem/healthkit),
keeping the raw HealthKit identifier as the code so the export stays
byte-aligned with the native client's exporter.
2026-06-01 20:46:49 +02:00
Marc-André Bombeck 0f7ca61e2f feat(insights): port the target reference panel onto the category pages
Grow the per-category insights target summary from a one-line range card
into a compact reference panel that surfaces the band range, the verbal
status, the guideline source, the in-target share, the 30-day average,
the range bar and the 7-day consistency strip — all from the Targets
data already on the wire, reading the same shared cache. Extract the
status pill and the source-link resolver into shared primitives so the
Targets card and the insights panel can never disagree, and wire blood
glucose into the summary with its per-context split and unit conversion.
2026-06-01 20:42:40 +02:00
Marc-André Bombeck 5de9ddb0cc feat(insights): drive the Trends charts from the daily briefing
The overview Trends row used to render a fixed BP / weight / mood
triple regardless of what the day's data surfaced. It now mirrors the
daily briefing: the row charts exactly the metrics the briefing flags,
in the briefing's priority order, deduped and capped at three. When no
briefing is available — cold mount, a web-only account with no
findings, or a pre-briefing cached payload — selection falls back to
the legacy BP / weight / mood triple so the row never paints empty.

Selection lives in `trend-chart-select.ts` as a pure, unit-tested
mapping from each briefing `sourceMetric` to a chart descriptor
(series, colour, unit, title key). Adherence-context findings
(compliance, GLP-1 plateau) have no standalone trend series and are
skipped so the next finding fills the slot. Annotations stay on the
legacy triple; additive HealthKit metrics render chart-only. The chart
set is derived from the briefing payload already on the page, so there
is no new blocking call.
2026-06-01 20:26:31 +02:00
Marc-André Bombeck 6ce09cc76d feat(insights): stat strip, range band, all-readings subpage, diversity nudge
Add the data-value features to the insights category pages on top of the
density pass:

- Stat strip: lead each metric page with min / max / median / mean,
  read from the already-fetched analytics summaries slice (no new
  network). Median is now computed in both summary producers — exact in
  the live path, a windowed PERCENTILE_CONT in the rollup-tier slim
  slice. The thin HealthKit pages mount it too for parity; no AI
  assessment is added there.
- Range band: shade an Apple-Health-style min-max area around the daily
  mean line where the data supports it (non-cumulative metrics). The
  daily-aggregate read now emits per-day min / max from the rollup
  buckets; the band rides the existing target-range toggle.
- All readings: a dedicated per-metric subpage at /insights/values/<type>
  reusing the measurement list pinned to one type (pagination + inline
  edit/delete). A clear entry button mounts at the foot of each
  category page.
- Diversity nudge: a gentle hint when a metric's readings cluster on one
  weekday or time of day, computed from a bounded, cached timestamp
  window — non-blocking, self-gating.

All new reads stay cache-friendly and off the navigation path.
2026-06-01 20:26:26 +02:00
Marc-André Bombeck cf649f72ce feat(mood): structured tag taxonomy + note capture and timeline
Add the Category -> Tag taxonomy the mood surface was missing and the
free-text note the web form could never write, then surface both on the
Insights mood page.

Schema (migration 0101): a global MoodTagCategory -> MoodTag catalog
plus a MoodEntryTagLink join, seeded with a default five-category set
(i18n-keyed labels, Lucide icons). Purely additive — the legacy flat
MoodEntry.tags JSON column, the GLP-1 quick-tags, and the Telegram /
MoodLog sync are untouched; an entry can carry both axes.

Capture: the mood-logging form and the edit sheet gain a Textarea for
the note (model + API already accepted it) and an icon-chip picker over
the taxonomy catalog (GET /api/mood/tags). Create / update resolve the
picked keys to links; unknown keys drop silently against the catalog.

Insights: a structured-tag breakdown (icon + per-tag avg-mood lift) and
a notes timeline join the existing distribution / weekday / flat-tag
sections. The aggregate extension also fixes the flat-tag axis, which
read the raw JSON string and so never populated.

i18n across all six locales. Tests cover the taxonomy aggregation, the
note round-trip, the structured-tag schema, and the notes timeline.
2026-06-01 20:25:42 +02:00
Marc-André Bombeck b99a015266 feat(medications): make injection-site tracking and rotation real
The injection_site column on intake events was read across several
surfaces but never written, so site tracking was effectively dead. Wire
it end-to-end as a per-medication opt-in, gated on an INJECTION delivery
form and default off.

- Schema: add medications.track_injection_sites + allowed_injection_sites
  and users.global_excluded_injection_sites (migrations 0099, 0100;
  additive, defaulted, no backfill).
- Intake write path: accept an optional injectionSite on the per-med,
  status-toggle, and bulk intake routes. Persist it only on a taken
  injection with tracking enabled, validated against the medication's
  effective allowed set (per-med allowed sites minus the user-level
  global exclusion, deny wins) — a disallowed site returns 422 (the bulk
  route skips the entry).
- Rotation: extend the least-recently-used recommender with an allowed
  filter; the picker disables sites outside the effective set.
- UI: per-medication tracking toggle + allowed-sites editor in the dose
  wizard step, a skippable post-dose site prompt on both medication
  cards, and a Settings card for the user-level global exclusion.
- Contract: injectionSite is additive on the intake request; OpenAPI
  regenerated. New GET/PATCH /api/auth/me/injection-site-prefs.

The site capture is always optional and never blocks logging a dose.
2026-06-01 20:25:34 +02:00
Marc-André Bombeck 84e592b17e feat(insights): enrich the mood page with calendar, distribution, weekday, and correlation views
Lift the mood aggregates the AI status generator already computes —
tag frequency + per-tag average, in-target share, and the
mood × metric Pearson correlations — into a shared
`mood-aggregates.ts` so the prose and the new charts read off one
implementation. `mood-status.ts` now consumes the shared helpers
instead of its own inline copies.

Add a cached `/api/mood/insights` endpoint that returns the
pre-computed shapes (summary, heatmap, distribution, weekday, tags,
correlations) behind a 60-second server cache and a bounded 365-day
read — a cheap read-only path, never a synchronous model call. The
bucket invalidates alongside the mood-analytics cache on a mood write.

Render the shapes on the mood Insights page:

- a calendar heatmap forked from the compliance heatmap, coloured by
  the same mood-score bands as the line chart, with an adaptive
  window (30 days until ~90 days of history, then 90, then a full
  year past 180 days) so the grid is never mostly empty;
- a mood distribution bar chart (share of days per level);
- average mood by weekday with a best/toughest-day callout;
- a tag / trigger breakdown (frequency bars + per-tag average);
- mood vs. sleep / activity / pulse correlation cards reusing the
  existing scatter chart.

Add the supporting i18n keys across all six locales.
2026-06-01 19:54:26 +02:00
Marc-André Bombeck 1fcc5ba96b feat(medications): adapt the compliance display to cadence density
A rolling 7-/30-day percentage is meaningful for daily and weekday
medications but noise for sparse cadences: a med dosed every few weeks
has at most one expected dose in a 7-day window, so the bar swings
between 0 and 100 off a single sample.

Decide the display server-side from expected-dose density. When the
30-day window holds at least four expected doses the percentage bars
stay; below that the card swaps to an uptime-style per-dose timeline
where each cell is one expected dose — taken, missed, skipped or
upcoming — with a "last N doses" summary and a dose-indexed streak.

The compliance route returns an additive complianceDisplay block
(mode, expected7/30, the dose timeline, the summary) alongside the
existing compliance7/30 fields, which the iOS client and the Health
Score read unchanged. Read-path only; no schema change.

- compliance.ts: add expectedSlotsBetween and buildComplianceDisplay
  over the canonical recurrence engine
- dose-adherence-timeline: plain flex cells reusing the heatmap colour
  tokens and tap-to-pin tooltip
- switch the standard and GLP-1 cards on the server-decided mode
2026-06-01 19:54:26 +02:00
Marc-André Bombeck 93790aa043 feat(measurements): consolidate gait/mobility HealthKit metrics nightly
Extend the daily-mean consolidation to cover the high-frequency
gait/mobility metrics that previously mapped to no consolidation set and
piled up at sampling granularity: walking asymmetry, walking
double-support, walking steadiness, and walking heart-rate average. The
correct daily reduction for these is the mean, matching the Health-app
display; all four stay disjoint from the cumulative (sum) set.

Fold the daily-mean drain onto the existing nightly cumulative-drain tick
so new high-frequency spot samples no longer accumulate raw between worker
reboots. The two passes share one concurrency-1 cron, keeping the
maintenance window a single sequential walk. Boot-time discovery stays as
the back-fill for accounts that accumulated raw rows before this shipped.

Recompute the affected day's rollup bucket after the consolidation
commits, the same way the ingest path does, so a rollup-covered read
reflects the single consolidated row rather than a stale mean derived from
the now soft-deleted per-sample rows.

Regular heart-rate / pulse stays raw: it is a discrete clinical reading
and feeds correlation and scatter analytics. No schema change.
2026-06-01 19:54:26 +02:00
Marc-André Bombeck 5771b36899 feat(insights): tighten category-page density and balance the overview hero
Polish the Insights surfaces for a denser, more deliberate rhythm.

Category pages:
- Collapse the double caption under the heading. The explainer
  definition and the description paragraph used to stack, so every
  metric page opened with two near-duplicative muted lines before any
  data. Keep the explainer body as the single caption; render the
  description only when no explainer is set.
- Tighten the header gap (space-y-1.5) and the block rhythm
  (space-y-4 md:space-y-5) so the heading-to-first-data distance
  shrinks by roughly one text block.
- Demote the target summary from a full bordered card to an inline
  band (bg-muted/30 rounded-lg px-3 py-2). One line of range text no
  longer reserves the card primitive's py-4/py-6 shell padding.
- Close the gap under the assessment heading. The card primitive's
  gap-4/gap-6 flex gap floated the title well above its prose; override
  to gap-2 md:gap-3 with py-4/py-5 across every status variant.

Overview hero:
- Condense the "ask the coach" band — denser prompt chips and a
  bottom-pinned strip so the left column stops out-running the
  Health Score card.
- Give the Health Score breakdown more vertical presence (looser row
  rhythm, taller component bars) so the right column fills the row
  height instead of leaving the bottom empty.
2026-06-01 19:54:26 +02:00
Marc-André Bombeck d660279c97 fix(medications): stop the wizard showing each time-of-day suggestion twice
The schedule wizard's time-of-day step rendered the four suggested times
twice: once as the icon chips from the step itself, and again as the
labelled preset row built into the chip component below. Add an opt-out
on the chip component and pass it from the step so only the icon-based
suggestions remain. The period is still conveyed by the icon plus an
aria-label; the offered times and selection logic are unchanged. The
preset row stays on by default for every other caller.
2026-06-01 19:37:58 +02:00
Marc-André Bombeck ddb08b048a fix(medications): stop the delete confirm hanging in a spinner
Deleting a medication from the danger zone awaited a prefix-invalidate of
the "medications" key bundle before navigating. That bundle covers the
detail page's own active query, so the invalidation refetched the just-
deleted resource, hit a 404, retried with backoff, and never resolved —
the confirm button spun forever even though the delete had persisted.

Evict the detail query before invalidating, navigate to the list first,
then fire-and-forget the dependent-bundle invalidation. The busy state is
also cleared on the failed-response path. The detail query opts out of
retries so a deleted-resource refetch never burns a backoff cycle.
2026-06-01 19:36:33 +02:00
Marc-André Bombeck b3f61d0c75 fix(medications): surface the first rolling dose at the start date
Rolling schedules anchored next-due on start + N days when no intake had
been logged yet, which skipped the dose due AT the start date and
suppressed its reminder (the worker shares this engine). The +N cadence
now begins only after the first intake is logged: with no intake the
first dose is due at startsOn (or createdAt). A past start date with no
intake surfaces the dose as due/overdue rather than rolling it forward —
nextOccurrenceAfter floors the rolling search to the start of the user's
day so an overdue or due-earlier-today dose stays visible.

The post-intake re-anchor (lastIntakeAt + N) and the endsOn cap are
unchanged; PRN, one-shot, RRULE and legacy cadences are unaffected.
2026-06-01 19:35:11 +02:00
dependabot[bot] eea6385bc5 chore(deps): Bump actions/setup-node from 4 to 6 (#222)
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 4 to 6.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-01 18:00:21 +02:00
dependabot[bot] b1cc1f86f5 chore(deps): Bump gitleaks/gitleaks-action from 2 to 3 (#221)
Bumps [gitleaks/gitleaks-action](https://github.com/gitleaks/gitleaks-action) from 2 to 3.
- [Release notes](https://github.com/gitleaks/gitleaks-action/releases)
- [Commits](https://github.com/gitleaks/gitleaks-action/compare/v2...v3)

---
updated-dependencies:
- dependency-name: gitleaks/gitleaks-action
  dependency-version: '3'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-01 18:00:16 +02:00
Marc-André Bombeck 16fdc75513 chore(release): v1.8.4 — medication card accuracy + Insights polish
The medication card reads the schedule engine's next-due (fixes
interval/one-time schedules that never advanced after a dose), logging a
dose confirms itself, Insights status polling is bounded, each Insights
category explains itself inline, medication history shows each dose's
origin, and an idempotent migration adds the app_settings columns that
were only ever applied ad-hoc.
2026-06-01 17:37:11 +02:00
Marc-André Bombeck 65bbedd83d fix(seed): repair demo seed against the current schema
Two gaps stopped a fresh demo seed:

- medication_intake_events gained a NOT NULL updated_at column in the
  v1.7.0 sync keyset work. The raw INSERTs omitted it; set it alongside
  created_at on every intake row so the seed does not lean on the
  column's migration-only default.

- app_settings carried four columns on the schema (default_locale plus
  the telegram/ntfy/web-push global toggles) that never landed in the
  migration history — applied via db push to existing environments but
  never committed. A database built from migrations alone is missing
  them, and the admin settings read path selects default_locale, so a
  fresh deploy reports "column default_locale does not exist" on first
  read. Add an idempotent ADD COLUMN IF NOT EXISTS drift-fix migration
  mirroring 0025_user_locale_drift_fix: a no-op where the columns exist,
  a clean add on a migrations-only build.

Verified end to end against a fresh Postgres 16 built from the full
migration set: the seed completes and re-runs cleanly.
2026-06-01 17:31:45 +02:00
Marc-André Bombeck 65cfa2b83a fix(insights): bound the status preparing-poll to a fixed ceiling
The per-metric status cards and the inline medication-compliance query
poll the read-only status route every 4 s while the payload reports
preparing:true. A configured provider whose generation persistently
fails leaves preparing pinned true, so an open Insights page would poll
indefinitely — steady battery and network draw on a screen the user has
walked away from.

Cap the poll at 12 attempts (~48 s) through a shared
nextStatusPollInterval helper both call sites route through. Past the
ceiling the card settles on its existing static / empty state. The happy
path is unchanged: a generation that lands within a couple of intervals
clears preparing and stops the timer exactly as before, and a terminal
no-provider payload never carried preparing so it stays terminal.
2026-06-01 17:31:45 +02:00
Marc-André Bombeck 8dced00188 feat(medications): label each intake history row with its logging origin
The intake history surfaced the coarse IntakeSource enum directly, so a
dose logged from the iOS app showed nothing meaningful. Map the enum to
the practical client it represents — WEB to Web, API to iOS App,
REMINDER to Reminder, IMPORT to Import — and render it as a muted
"via {origin}" caption on each intake row next to the status. No schema
or API change; the source value already rides the existing intake
response. Tighten the en/de labels that read "External API" and
"Telegram / Reminder" into the same origin vocabulary across all six
locales.
2026-06-01 17:31:02 +02:00
Marc-André Bombeck c2808a9c70 feat(insights): show the metric explainer inline under each category heading
The per-category explainer text only lived behind the "?" popover next to
the heading. Render the same localised definition inline as a muted caption
directly beneath the title, where the short scaffold line already sits, so
the one- to two-sentence definition is discoverable without a tap.

Both surfaces read the identical insights.subPage.explainer.<metric>Body
key, so there is no duplicated copy and all six locales stay covered. The
"?" glyph stays in place as the always-available pointer to the same text.
HealthkitMetricPage already forwards explainerMetric to the shell, so every
routed metric sub-page picks up the inline caption from this one change.
2026-06-01 17:31:02 +02:00
Marc-André BombeckandClaude Opus 4.8 0e3a8f9cd3 fix(medications): read next-due from the server and confirm intake actions
Two fixes on the medication cards.

Next-due: the card recomputed "next intake" client-side from
`daysOfWeek` + `windowStart` alone, ignoring rolling intervals, RRULE,
one-shot doses, and the last-intake anchor. A rolling medication (e.g. a
35-day interval) showed "tomorrow" and never re-anchored after a dose.
`GET /api/medications` already returns `nextDueAt` per medication,
computed by the canonical recurrence engine anchored on the last intake.
Both card variants now render that value directly: the generic card
drops its `getNextOccurrenceTimestamp` walker, and the GLP-1 card drops
its weekly-only predictor that hardcoded a 7-day step. The day-label and
window-range rendering are unchanged; only the timestamp source moves to
the server. `nextDueAt` is threaded through the list page's medication
type into both cards.

Intake confirmation: tapping Taken / Skipped now raises a toast naming
the medication ("… recorded as taken" / "… skipped"), so the action has
clear feedback. The next-intake line refreshes on the invalidated list
query, which the next-due fix above makes accurate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 17:31:02 +02:00
Marc-André Bombeck 96f0b225fd chore(release): v1.8.3 — Insights no longer block the interface
Per-category Insights assessments are served read-only from cache and
generated out of band, the client request is capped, the overnight warm
pass keys on the shown language, a stalled model is briefly remembered,
and Insights/dashboard stream a loading skeleton — so opening and
switching Insights categories stays responsive instead of freezing.
2026-06-01 09:11:36 +02:00
Marc-André Bombeck 35800becbb fix(insights): make per-category status cards read-only so navigation never blocks on the LLM
Opening an Insights category page froze the whole UI: the per-metric
status card fired a cold, uncapped LLM fetch on mount with no client
abort, so the request hung up to the server's 60s ceiling and the
pending/resolve re-renders thrashed the tab strip and ate touch events.
Timeouts were never negatively cached, so every visit re-blocked.

Fix the class holistically:

- Bound every status GET on the client. The shared use-insight-status
  hook and the inline medication-compliance query now wrap fetch in an
  8s AbortController and stop retrying inline; navigation can no longer
  await an uncapped round-trip.

- Make the status routes read-only. On a cache miss the generator
  enqueues an out-of-band pg-boss job (insight-status-generate) and
  returns a preparing envelope; the client polls a bounded interval
  until the worker warms the cache. Models the dashboard snapshot's
  ready/preparing pattern. The queue is registered in the worker
  allQueues loop + a boss.work handler, with a guard test.

- Fix the nightly warm-pass regression: warm every supported locale
  (the client reads against the active UI locale, not the persisted
  User.locale) and warm on a cached comprehensive outcome too (its
  write still evicts the per-status caches). Add a short-TTL negative
  cache on the timeout path so a transient provider stall no longer
  makes every subsequent visit re-block or re-enqueue.

- Add loading.tsx for the insights segment + the root so any future
  RSC await streams a skeleton instead of blocking the transition.

- Stabilise the advisor regenerate callback so a status-query flip
  can't re-render the memoised tab strip mid-gesture.

New i18n key insights.assessmentPreparing across all six locales.
2026-06-01 08:59:59 +02:00
Marc-André Bombeck 6a603ad587 chore(release): v1.8.2 — one intake row per dose slot
Guarantees a single intake entry per scheduled dose: intake writes snap
to the canonical slot instant and update in place rather than inserting a
sibling row, a re-sync can no longer clear a recorded dose, concurrent
logs converge, and a one-time startup pass collapses existing duplicates.
2026-06-01 08:33:20 +02:00
Marc-André Bombeck 710902a43c fix(medications): harden the slot upsert against races, downgrades, and double-decrements
Review of the slot-convergence change surfaced gaps that could mis-record
a dose. Fold the write logic into one shared `applyCanonicalSlotWrite`
used by both intake routes and close them:

- Concurrency: catch the unique-key race on insert and converge by
  re-finding the slot row and updating it, instead of returning 500 (and
  dropping the tap) or leaving a duplicate.
- No downgrade: a pending projection echo replayed onto a slot already
  marked taken or skipped is a no-op — it never clears `takenAt`. A
  recorded dose is immutable, so an offline re-sync cannot flip a taken
  dose back to missed.
- Inventory: decrement a medication's remaining count only on a genuine
  pending→taken transition, not on an idempotent re-post.
- Deterministic slot-row selection: prefer an existing actioned row, then
  the pending row, ordered by createdAt then id.
- Snap instant: derive the canonical instant via the same `localHmAsUtc`
  the projector and reminder worker mint with, so the value is identical
  by construction across a DST transition rather than only test-pinned.
- Cleanup job: isolate each slot's collapse in its own try/catch and
  guard the instant-normalisation against a tombstone collision, so one
  slot can no longer dead-letter a user's whole dedup pass.
2026-06-01 08:32:42 +02:00
Marc-André Bombeck 5047eb7a20 fix(medications): collapse pre-existing duplicate dose-slot rows at boot
The write-path convergence stops new duplicate slot rows, but accounts
that already accrued a pending + taken pair for one dose keep an inflated
expected count, a phantom taken marker, and a suppressed "due now" prompt
until the bad rows are cleared.

Add a boot-time, idempotent cleanup queue (mirroring the existing
backfill queues): discover only the users holding a same-slot duplicate,
then per medication snap every live intake to its canonical slot, keep
the most-actioned row per slot (taken over skipped over pending),
normalise its instant, soft-delete the losers, and recompute the
affected compliance rollups. Rows that resolve to no scheduled slot
(PRN / as-needed) are never collapsed. A second pass is a no-op.

Registered in the worker's queue list with a static guard test, after a
prior incident where a queue was built but never registered and silently
never ran.
2026-06-01 08:12:48 +02:00
Marc-André Bombeck 0d7d08f616 fix(medications): converge intake writes onto one row per scheduled slot
A twice-daily medication ended up with two rows for one dose slot: the
projector / reminder worker mints a pending row (source REMINDER) at the
slot's `localHmAsUtc` instant, while a "taken" write from the per-med or
bulk intake route inserted a fresh row (source WEB / API). Because
`source` is part of the `(userId, medicationId, scheduledFor, source)`
unique key — and the written instant could drift by a minute from the
projected one — the two rows coexisted: one taken, one still pending and
overdue. The card then read the slot as taken, counted 100%, and
suppressed the "due now" prompt for a dose the user had not taken.

Resolve every scheduled intake write to the slot's canonical instant
before writing and upsert in place, source-agnostic:

- `resolve-slot-instant.ts` snaps an incoming instant to the nearest
  scheduled slot for that day (enumerated through the canonical
  recurrence engine, so PRN and cyclic off-weeks resolve to no slot) and
  anchors it on the same `localHmAsUtc` the projector and worker use.
  Off-slot and as-needed writes resolve to null and keep insert semantics.
- The per-med and bulk routes look up the existing row at the canonical
  `(userId, medicationId, scheduledFor)` ignoring source and update it in
  place — mirroring the status-toggle route — instead of inserting a
  sibling. The bulk per-entry response gains an additive `updated` status.
- The reminder worker's missed-dose mint now skips a slot that already
  carries an actioned row (taken or skipped) from any source, not only an
  existing pending REMINDER row.

PRN / as-needed writes are unaffected. Regression tests pin the collapse
(exact and one-minute drift), the PRN exemption, and the worker guard.
2026-06-01 08:06:37 +02:00
Marc-André Bombeck 4578078cc1 chore(release): v1.8.1 — multi-time medication compliance
Closes the two surfaces the 1.7.3 multi-time compliance fix did not
reach: the today-tile projection now mints one pending dose per
scheduled time, and the compliance heatmap classifies each dose against
its nearest scheduled time instead of the first window.
2026-06-01 07:27:50 +02:00
Marc-André Bombeck 7f7bf75e34 fix(medications): classify each time-of-day slot in the compliance heatmap
The History compliance heatmap matched each taken intake event to the
closest schedule by `windowStart` alone, ignoring `timesOfDay`. For a
twice-daily medication stored as one schedule row with
`timesOfDay = ["07:00","19:00"]` and `windowStart = "07:00"`, the evening
dose matched the lone 07:00 window and classified as very-late (~12h),
painting the day's cell orange even when both doses were taken on time —
so the heatmap never recovered to green for single-row multi-time
schedules.

Expand every schedule into its effective dose slots (its `timesOfDay`,
else `[windowStart]`) and classify each event against the nearest slot's
window — the slot time anchoring a window that spans the schedule's
`windowEnd − windowStart` duration, overnight spans included. Single-time
schedules collapse to one slot at `windowStart` and stay byte-identical.
The denominator already routed through the canonical engine; only the
numerator's timing classification is corrected.
2026-06-01 07:26:47 +02:00
Marc-André Bombeck fcb517df87 fix(medications): fan out the today-tile projector over every time-of-day
The today-window projector minted a single pending intake row per
schedule, anchored at `windowStart`, dropping a schedule's first-class
`timesOfDay`. A twice-daily medication stored as one schedule row with
`timesOfDay = ["07:00","19:00"]` therefore surfaced only its morning
dose in the today tile and the "Erfassen" sheet, and the event-count
compliance rollup recorded one expected dose per day instead of two — a
perfectly adherent user read 50% the moment the second dose was logged,
and deleting then re-adding one dose left the rate stuck at 50%.

Fan the projection out over every `timesOfDay` entry, mirroring the
reminder worker's per-slot mint and dedup against the
`(userId, medicationId, scheduledFor, source)` unique index. Absent
first-class `timesOfDay` the projector still emits one slot at
`windowStart`, byte-stable against the worker's legacy single-window row.

Adds regression coverage across the projector (dashboard summary), the
legacy compliance walker, and the cadence expansion pinning the
single-row twice-daily case at the correct two-dose-per-day shape.
2026-06-01 07:26:26 +02:00
Marc-André Bombeck 869f13612a Merge v1.8.0 Insights release into main
# Conflicts:
#	CHANGELOG.md
#	docs/api/openapi.yaml
#	package.json
2026-05-31 23:00:08 +02:00
Marc-André Bombeck 3743f91bce chore(release): v1.7.3 — health-record pdf fixes + multi-time compliance 2026-05-31 22:49:16 +02:00
Marc-André Bombeck 013ad5d967 fix(compliance): expand multi-time legacy schedules through the canonical engine
A medication whose schedule row carried multiple timesOfDay plus a legacy
daysOfWeek (and no rrule / rollingIntervalDays) reported 50% compliance for a
fully-adherent 2x/day dose. The expected-slot denominator always ran the
canonical recurrence engine and counted both daily slots, but the numerator
only delegated to the engine for rrule / rolling / one-shot / non-SCHEDULED
rows; a plain-legacy row fell to the local cadence walker, which emitted a
single windowStart slot per day and ignored timesOfDay. 1 taken / 2 expected
read as 50 percent.

Route expandScheduleSlots through the engine for every schedule shape whenever
a medication context is supplied, so the numerator and denominator read the
same source of truth. Harden the context-less legacy walker to iterate
timesOfDay as well, mirroring the engine's legacy branch, so the single
remaining non-engine path stays correct for multi-time rows. Drop the now-dead
expander gate helper.

Add regression guards: a 2x/day legacy row reports 2/2 through
calculateCompliance, and expectedSlotCountForDay agrees with
buildCadenceTimeline on the slot count for an identical schedule.
2026-05-31 22:47:44 +02:00
Marc-André Bombeck aed83b7747 fix(report): keep modules together, label the chart time axis, fix glyph stretch
Four layout defects in the clinical PDF renderer:

- Stretched lines: the built-in Helvetica is WinAnsi-encoded, so glyphs
  outside it (the trend arrows the summary injects, the superscript-two in
  kg/m2) resolved to the .notdef box at a fallback advance width and stretched
  the surrounding words. Route every drawn string (direct text, wrapped
  paragraphs, and autoTable cells) through a central WinAnsi sanitiser that
  maps the offenders onto safe equivalents. Embedding a Unicode TTF so the
  arrows render as true glyphs is a documented follow-up.

- The sparkline dropped each reading's timestamp and plotted on an index
  axis, so a trend gave no sense of its time span. Plot points by their real
  timestamp and print the first/last dates under the baseline.

- No consistent bottom safe area: scattered y > 240 magic numbers and tables
  with no bottom margin let content run into the footer. Introduce a single
  contentMaxY derived from the page height, footer band, and bottom margin;
  every break check and every autoTable bottom margin refers to it.

- Modules tore mid-block. Add an ensureSpace guard called before each module
  heading and a per-line guard in every free-text loop; give the short
  titration and side-effect tables rowPageBreak: avoid.
2026-05-31 22:47:44 +02:00
Marc-André Bombeck c6e782cdb8 fix(report): pass the in-app locale through to the pdf export
The health-record export panel sent no locale, so the server resolved the
report language from the browser's Accept-Language header. A German user on
an English-default browser got an English doctor report.

Send the active in-app locale from the panel, and on the server resolve
most-specific-first: explicit selection, then the healthlog-locale cookie
(what the user actually chose in the UI), then Accept-Language as the
weakest fallback.
2026-05-31 22:47:44 +02:00
Marc-André Bombeck 6842b52346 chore(release): v1.8.0 — insights data-driven assessments, embedded targets, explainers 2026-05-31 22:46:18 +02:00
Marc-André Bombeck 67a72b1023 perf(insights): parallelise the nightly per-user assessment warm pass
The warm pass forced the seven per-metric status generators strictly
back to back per user, so a fully configured account paid ~7× one LLM
round-trip serially. Bound the inner pass with a small `p-limit(3)` so
the cards warm a few at a time without saturating the Prisma pool or
fanning out an unbounded number of provider calls. The per-user budget
gate still bounds total cost per night.
2026-05-31 22:43:24 +02:00
Marc-André Bombeck c775861d8c fix(insights): invalidate per-metric assessment caches on measurement edit and delete
The targeted status-insight invalidator only fired on insert and batch
ingest, so editing or deleting a reading left the affected per-metric
assessment cards serving their pre-mutation text for the rest of the day.
Add the fire-and-forget invalidation to the single-measurement PUT
(covering both the old and the new type when an edit re-types a row),
the single-measurement DELETE, and the iOS by-external-ids
reconciliation DELETE (keyed off the distinct types it tombstoned).
2026-05-31 22:43:24 +02:00
Marc-André Bombeck eee6ab2e7e refactor(insights): wire the WMY rollup tier into status snapshots and share generator helpers
Read the MONTH / YEAR rollup tier for the monthly / yearly slices of the
focused single-metric status snapshots (weight, pulse, bmi,
blood-pressure) via `buildGradedSeriesWithRollups`, so the coarse tiers
finally earn their write amplification. BMI has no tier of its own, so it
scales the WEIGHT tier by 1 / heightCm² (`scaleGradedSeries`) — an exact
linear transform. The multi-metric general overview and the tier-less
mood / adherence series keep their bounded in-memory fold.

Fix the coverage-miss path that returned an always-empty monthly / yearly
slice: the bounded ~90-day recent read can never supply those slices, so
on a cold-tier miss the builder now folds the full history in memory
rather than shipping empty coarse arrays when years of raw history exist.
Excludes tombstoned rows from both reads.

Lift the byte-identical `round`, `normalizeSummaryText`,
`normalizeLocale`, `summarizeSeries`, the `{summary}`-envelope parse, and
the cache-row persist block out of the seven generators into
`status-shared.ts`. Drop the per-medication expectation in the compliance
generator: the prompt returns only `{summary}`, so the per-med cards are
server-side placeholders rather than a dead model-authored branch. Remove
the unused `summarizeGradedSeries` export.

Behaviour is unchanged on the in-memory path; the rollup path is exact
where the tier composes (count / min / max / mean) and the payload stays
under the snapshot char cap.
2026-05-31 22:43:24 +02:00
Marc-André Bombeck 75380d5f39 fix(insights): lift explainer popover body to 12px + correct target-summary doc
Two small polish items on the insights category surface.

The desktop explainer popover body rendered at 11px while the mobile
sheet used the larger `text-sm`, an uncomfortable and asymmetric read.
Lift the popover body to `text-xs` (12px) so both surfaces sit on the
type scale.

The `MetricTargetSummary` docstring claimed both the range and the
in-target share are hidden when the route flags `insufficientData`. The
range stays visible — only the share is suppressed. Correct the comment
to match the code.
2026-05-31 22:35:02 +02:00
Marc-André Bombeck 36d5c79526 test(insights): pin explainerMetric props against the en.json explainer keys
`<MetricExplainer>` resolves its copy through a template literal
(`insights.subPage.explainer.${metric}{Title,Body}`), so the static
call-site coverage guard never sees these keys — a typo in an
`explainerMetric` prop would paint the raw key path with no CI signal.

Walk every `explainerMetric="…"` value under `src/app/insights/**` plus
the shared healthkit-metric-page scaffold and assert each resolves a
Title and Body leaf in messages/en.json. Also pin the literal-only prop
contract and a non-empty match count so a future rename can't silently
disable the guard. The locale-integrity test then carries the EN
guarantee to the other five bundles.
2026-05-31 22:35:02 +02:00
Marc-André Bombeck 05097df1ee feat(insights): give every category page a metric explainer + normalise keys to english
Two parts to the explainer surface, landed together because they share
the same i18n block and page props.

Coverage: every routed insights category page now passes an
`explainerMetric` prop, so the heading-side `?` glyph is present on all
37 pages instead of 13. The 24 newly covered metrics — body
composition (body water, bone/fat/muscle/lean mass, fat-free mass,
visceral fat), mobility (flights, walking distance/speed/steadiness,
asymmetry, double-support, step length, walking heart rate),
cardiovascular (pulse-wave velocity, vascular age), hearing
(environmental + headphone levels, loud-sound events), respiratory
rate, daylight, blood glucose, and skin temperature — each gain a one
to two sentence layperson definition grounded in standard clinical
references, shipped in all six locales.

Keys: the explainer key segments were a German/English mix
(`blutdruck`, `puls`, `gewicht`, `schlaf`, `stimmung`, `medikamente`
alongside English ones). Rename them to English to match the
naming-convention ADR — `bloodPressure`, `pulse`, `weight`, `sleep`,
`mood`, `medications` — across every locale, and update the
`explainerMetric` prop values that reference them. These are i18n key
segments, not route slugs, so the slug contract is untouched.
2026-05-31 22:35:02 +02:00
Marc-André Bombeck 8f120cfdef fix(insights): generalise the data-gating threshold across metric kinds
The hard '~5 measurement points' floor did not fit mood (counted in
entries) or medication adherence (counted in scheduled doses). Re-word
the gate as 'a few measurement points/entries/events' and note that the
unit depends on the metric. Also fix the gating-field path: the recency
field lives at dataCoverage.newestMeasurementDaysAgo, not on summary.
2026-05-31 22:32:20 +02:00
Marc-André Bombeck f683e8fd6d feat(insights): add a calm support pointer for sustained low mood
The mood card noted persistent low phases but offered no gentle path to
support. When mood stays clearly low for several days, the model now
offers an autonomy-preserving pointer toward talking it through with a
trusted person or a professional — never alarming, never a diagnosis, no
emergency tone. The safety-contract matrix does not cover this pathway
and does not reach the per-metric assessment prompts, so it lives here.
2026-05-31 22:32:20 +02:00
Marc-André Bombeck 0e9e9bc4ba fix(insights): weight 30-day adherence over the noisy 7-day window
For an infrequent schedule such as a weekly injection, the 7-day
compliance figure is dominated by a single dose: one miss swings the
percentage sharply and reads as a collapse it is not. Tell the model to
lean on compliance30 as the load-bearing value when schedulesPerDay is
low and treat compliance7 as a rough pointer only. Output stays {summary}.
2026-05-31 22:32:20 +02:00
Marc-André Bombeck 4c873ebb37 fix(insights): give the overall assessment its own length budget
The overall-status card summarises up to six metrics, but it inherited
the single-metric 30-60 word budget, which forced the model to either go
generic or overrun. Grant the section an explicit 3-5 sentence / 50-80
word budget and cap it at naming two metrics by name, with the rest
mentioned only when they deviate notably from their own mean.
2026-05-31 22:32:20 +02:00
Marc-André Bombeck d29b11cdf4 refactor(insights): split bmi and weight assessment focus
The bmi and weight cards produced near-identical trend text for a user
with both metrics, since bmi is weight scaled by a constant. Re-aim each
card so they carry distinct information: bmi now centres on WHO-band
placement (call out a band crossing or a near-boundary value against the
person's own baseline), and weight stays on the continuous trend and
pace (kg/week, plateau, milestone). Each defers the other concern to its
sibling card.
2026-05-31 22:32:20 +02:00
Marc-André Bombeck 262a3ad70a docs(insights): document english tile-id contract + naming ADR
Regenerate `docs/api/openapi.yaml` so the `InsightsLayoutBody` enum
carries the canonical English tile ids first, then the
accepted-but-deprecated legacy German ids, with the normalisation +
deprecation spelled out in the schema description. Add ADR 0001 fixing
the convention — localised UI copy, English internal identifiers — and
the non-breaking alias strategy. Add an iOS coordination note covering
the new canonical ids, the continued acceptance of the legacy ids, and
the recommended migration path.
2026-05-31 22:12:25 +02:00
Marc-André Bombeck 607dd9e5df feat(insights): accept legacy german tile ids as aliases
The tile-layout enum migrates from German to English to match the route
slugs. The contract on `GET/PUT /api/insights/layout` stays
non-breaking for clients that persisted the old German ids (the iOS
layout sync among them):

- the Zod enum is built from `ACCEPTED_INSIGHTS_TILE_IDS` (canonical
  English plus the legacy German aliases), so a PUT carrying old ids
  validates rather than tripping a 422;
- `normalizeInsightsTileId` collapses each legacy id onto its canonical
  English replacement on both the read path (`resolveInsightsLayout`)
  and the write path (`serializeInsightsLayout`), so a pre-rename layout
  surfaces English ids on GET without a forced re-PUT and a legacy PUT
  persists English ids;
- a layout carrying both a legacy and a canonical id for one tile
  dedupes to a single canonical entry.

The legacy ids are accepted-but-deprecated. Tests cover the read-side
normalisation and the write-side 200 (no 422) + canonical persistence.
2026-05-31 22:12:25 +02:00
Marc-André Bombeck c4ccd7e297 refactor(insights): migrate route slugs to english with redirects
Rename every routed Insights sub-page slug from German to English
(`/insights/blutdruck` -> `/insights/blood-pressure`, `gewicht` ->
`weight`, `medikamente` -> `medications`, and the full v1.7.0 metric
tail). UI copy stays localised through `t()` keys; only the internal
slugs change. The slug registry in `src/lib/insights/sub-page-metric.ts`
is the single source of truth, so the tab strip, target summary, and
daily-briefing routing targets follow it.

`next.config.ts` `redirects()` emits a permanent redirect from every
legacy German slug to its English target, including a `:path*` variant
so nested routes survive. Bookmarks and cached PWA navigation keep
resolving.
2026-05-31 22:12:25 +02:00
Marc-André Bombeck b416cabbf1 feat(insights): rewrite the overall assessment prompt to the assessment spec
Drop the dead-field guidance (avg90/allTime, historicalComparison,
ratePressureProduct, bodyCompositionDivergence, seasonalVariation) and
the chart-token instruction. Describe the per-type measurementSeries map
and the adherence/mood/target context, pull them into one coherent
picture against the person's own baseline, and close with the single
most important doable step.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 56cff68ec5 feat(insights): rewrite the medication-adherence assessment prompt to the assessment spec
Replace the historicalComparison and moodAdherenceRisk guidance with the
actual per-medication snapshot fields (compliance7/30, streak,
taken/skipped/missed, dailySeries). Read the recent direction as
compliance7 vs compliance30 against the person's own baseline, frame
positively, and close with one blame-free doable step.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 0f25226fdd feat(insights): rewrite the mood assessment prompt to the assessment spec
Describe the graded mood series, target band and tag list, lead on the
weekly pattern against the person's own baseline, name persistent low or
high phases calmly as an observation rather than a diagnosis, and close
with one kind doable step.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 4e04e375ad feat(insights): rewrite the BMI assessment prompt to the assessment spec
Describe the graded BMI series and target band, lead on the trend over
the single value, keep the WHO bands as placement anchors rather than a
label for the person, and name BMI's body-composition limits plainly.
Drop the chart-token instruction the status path strips out.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 052bbbfd7c feat(insights): rewrite the weight assessment prompt to the assessment spec
Replace the dead-field guidance (historicalComparison.weight,
allTimeMax, slope30, bodyCompositionDivergence, sleep.avg7) with the
graded weight series. Lead on the weekly/monthly trend rather than the
single value, define plateau and sustainable pace against the person's
own baseline, anchor milestones to their own maximum, and gate BMI
context on a known profile height.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 4f48160b3d feat(insights): rewrite the pulse assessment prompt to the assessment spec
Drop the stale snapshot vocabulary (avg7/30/90, historicalComparison,
slope30, rate-pressure product) and the chart-token instruction the
status path strips out. Describe the graded pulse series and target
band, compare the recent days to the person's own weekly/monthly
baseline at a ~5 bpm significance threshold, and frame a rising or
falling resting pulse as a possible explanation rather than a diagnosis.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck 0f9fc70440 feat(insights): rewrite the base + blood-pressure assessment prompts to the graded-snapshot spec
The status cards render only the model's summary field, yet the prompt
described a snapshot vocabulary (avg7/30/90, historicalComparison,
ratePressureProduct, seasonalVariation) that the graded snapshot no
longer carries, and demanded a full findings/correlations JSON schema
that this path never reads.

Rebuild the shared base prompt around the actual graded shape (summary +
recent/weekly/monthly/yearly with min/max/mean/slope), the own-baseline
comparison, a name -> place -> one-step structure, a warm
autonomy-supporting tone, a 2-4 sentence length, honest data-gating, and
a { summary } output. The blood-pressure section judges systolic and
diastolic together against the person's own baseline with ESH 2023 as
the placement anchor.
2026-05-31 22:06:17 +02:00
Marc-André Bombeck cd8849cd51 feat(insights): drop the per-metric assessment cache on fresh measurements
Hang `invalidateStatusInsightsForTypes` off every measurement ingest
path so a new reading of a type drops the cached assessment rows that
reading dirties — the next mount or nightly warm pass then regenerates
them against the new data instead of serving the pre-measurement text
for the rest of the day.

Wired into both `/api/measurements` modes (single + multi-entry batch),
`/api/measurements/batch`, and the three Withings sync paths
(measures + activity + sleep), reusing the `collapseToTypeDayKeys`
result each already computes for its rollup recompute. The call is
fire-and-forget after the user's write commits: idempotent, never a
blocker on the request path, and a failure only warns.
2026-05-31 22:05:31 +02:00
Marc-André Bombeck 177ce576d3 feat(insights): warm the per-metric assessment caches in the nightly pre-gen
The comprehensive generator evicts the seven `insights.<scope>-status`
caches as part of its write so a stale comprehensive insight can never
leave a stale per-metric card behind — but it does not re-fill them.
Before this, the morning after the nightly pre-gen cron ran the
per-metric status caches were empty, so the first `/insights` mount
still ran one live status generation per card.

After a successful comprehensive generation the cron now forces the
seven `*StatusForUser` generators so their caches are warm, not empty,
by the user's first visit. The warm pass only runs on a `generated`
outcome (a no-provider `skipped` has nothing to warm; a `failed` run
means the chain is unhealthy this tick — re-running it seven more times
would only multiply the failure). Each generator resolves the provider
chain internally, so a provider-less account stays cheap. The per-user
budget bucket that already bounds the comprehensive pass also gates the
warm pass — both run behind the same once-per-20h gate.

`runInsightPregenerate` now reports `assessmentsWarmed` and emits an
`insights.pregenerate.run` wide-event with the full per-run tally so the
nightly dashboard can track how many assessments each tick wrote.

Also adds `invalidateStatusInsightsForTypes` + `PER_STATUS_SCOPES` to
the comprehensive generator: a type → scope map (WEIGHT → weight + bmi +
general, BP → blood-pressure + general, PULSE/resting-HR → pulse +
general, everything else → general) so the ingest path can drop only the
scopes a fresh reading dirties.
2026-05-31 22:05:31 +02:00
Marc-André Bombeck 68a9f114a5 test(insights): cover graded compression and stub-skip
Pin the snapshot payload budget: a 2-year daily weigher (weight + daily
BP) and a six-type dense account both serialise under the 24 000-char
cap, proving the graded rewrite holds the line on the worst-case
accounts. The stub-skip and timeout-no-persist behaviour is covered by
the per-generator cache-read tests + the shared status-cache suite.
2026-05-31 21:51:18 +02:00
Marc-André Bombeck 11a06196f3 perf(insights): compress status snapshots via graded series (raw->week->month->year)
The seven per-card generators embedded the full ~360-day daily array
per metric plus correlation pair arrays, and never touched the
WEEK/MONTH/YEAR rollup tier. A dense daily weigher ran the weight
snapshot ~80-110 KB; a many-type account could push general-status past
100 K tokens.

Embed the shared graded series instead of the full daily array, cap the
embedded correlation/paired arrays to their most recent entries, skip
measurement types with no data in general-status, and apply a generic
24 000-char snapshot budget that sheds yearly -> weekly -> array-tails
-> recent until it fits. The applyPayloadBudget daily buckets stay
in-process to drive the latest-day focus, in-target gates, and
correlation pairing; only the compact shape reaches the prompt.

Measured on a 2-year daily account: weight-status ~15 KB, general-status
~12 KB across six dense types — both well under the cap.
2026-05-31 21:51:18 +02:00
Marc-André Bombeck 1b78df345d feat(insights): add a shared graded-series compressor for AI snapshots
Turn a metric's history into a small, bucketed, AI-ready shape: the
last ~21 days verbatim at daily granularity, the ~10 weeks before that
as ISO-week means, the ~12 months before that as calendar-month means,
and everything older as yearly buckets with a least-squares trend
slope. ~30-45 rows per metric regardless of history depth, never an
individual reading beyond the recent window.

A pure in-memory builder folds raw points; a rollup-backed builder
sources the monthly/yearly slices from the pre-aggregated MONTH/YEAR
tier (readBestGranularityRollups) and the recent/weekly slices from a
bounded ~90-day raw read, so the coarse rollup tier finally earns its
write amplification. The recent/weekly bucketing mirrors the coach's
timeline split, duplicated here so the coach contract stays put.
2026-05-31 21:51:18 +02:00
Marc-André Bombeck 5432063f5c fix(insights): stop caching the timeout fallback and align the status timeout with the coach
The per-card status path capped provider generation at 20 s and, on
timeout, persisted the generic no-key fallback as a day-keyed cache row.
The cache-read only checked the day key and text, so that stub looked
like a real assessment and stuck until midnight — hiding the real,
data-driven text for the rest of the day on any account that hit a
single transient stall.

Align the budget with the provider clients' 60 s ceiling, route the
status path through resolveProviderChain + runRawCompletionWithFallback
so a degraded provider cascades like the coach, and stop persisting the
fallback: a timeout or error is a transient miss that serves the
fallback for the current render and re-attempts on the next mount. A
shared cache-read rejects any lingering timeout-stub rows by their
markers, and withTimeout now annotates real errors instead of folding
them silently into the timeout path.
2026-05-31 21:51:18 +02:00
Marc-André Bombeck 16b4768fd1 feat(insights): surface target range and explainer on category pages
Each insights category page now carries two additions placed beside the
chart and assessment:

- a target-range card (MetricTargetSummary) showing the numeric goal
  band and the share of logged days within it, read from the shared
  /api/insights/targets payload so the bands match the /targets editor
  exactly. Blood pressure stitches the systolic and diastolic bands into
  one S/D string. A discreet link routes to /targets to adjust the band.
- a question-mark explainer next to each heading (MetricExplainer in
  SubPageShell) opening a static, layperson 'What is X?' read. Popover on
  desktop, bottom-sheet on phones; keyboard- and touch-reachable with a
  44px hit surface. Copy ships in all six locales.

The /targets page stays the canonical place to tune the bands.
2026-05-31 21:32:32 +02:00
709 changed files with 81333 additions and 10902 deletions

No files matched your search

+50 -8
View File
@@ -7,30 +7,41 @@
# compose `environment:` block at boot — `.env` should never ship.
.env
.env.*
!.env.example
!.env.production.example
.env.example
.env.production.example
# Version control + CI metadata.
.git
.github
.gitignore
.gitleaks.toml
# Build / install output that gets regenerated inside the builder stage.
node_modules
.next
out
dist
coverage
test-results
playwright-report
playwright/.cache
playwright.config.ts
vitest.config.mts
vitest.integration.config.mts
tests
tests/
e2e
e2e/
e2e-results
.eslintcache
eslint-plugins
eslint-plugins/
knip.json
# Persisted session state from e2e runs.
e2e/setup/storageState.json
# Planning scratch + per-release audit notes (operator-local).
.planning
docs/audit
# Generated local cache files
*.tsbuildinfo
next-env.d.ts
public/sw-version.js
# Captures from local debugging sessions.
*.har
@@ -43,3 +54,34 @@ docs/audit
.vscode
.idea
.DS_Store
*.swp
*.swo
# Logs / Debug
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# Docker compose / local ops files
docker-compose*.yml
compose*.yml
Dockerfile
.dockerignore
# Documentation not needed for runtime image
README.md
CHANGELOG.md
CLAUDE.md
CONTRIBUTING.md
CONTRIBUTING-AI.md
CODE_OF_CONDUCT.md
SECURITY.md
# LICENSE / LICENSE.md are deliberately NOT ignored: AGPL-3.0 conveys with
# the software, so the licence text ships inside the image.
AGENTS.md
.planning
docs
docs/*.md
docs/**/*.md
+26
View File
@@ -36,6 +36,21 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# WITHINGS_WEBHOOK_SECRET=""
# -----------------------------------------------------------------------------
# WHOOP -- optional integration
# -----------------------------------------------------------------------------
# The WHOOP app client id/secret are per-user BYO-keys: each user registers
# their own WHOOP developer app and pastes the client id/secret into Settings
# (stored encrypted in the DB). There is therefore no WHOOP_CLIENT_ID/SECRET.
#
# WHOOP_WEBHOOK_SECRET is the instance-level secret carried as the trailing
# path segment of the webhook URL AND used to verify the WHOOP HMAC body
# signature. WHOOP_REDIRECT_URI overrides the derived
# `${NEXT_PUBLIC_APP_URL}/api/whoop/callback` when the public URL differs.
# WHOOP_WEBHOOK_SECRET="<openssl rand -hex 32>"
# WHOOP_REDIRECT_URI=""
# -----------------------------------------------------------------------------
# APNs -- iOS push (optional, all-or-none)
# -----------------------------------------------------------------------------
@@ -62,6 +77,17 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# BACKUP_ENCRYPTION_KEY=""
# -----------------------------------------------------------------------------
# FHIR health-record export -- optional
# -----------------------------------------------------------------------------
# Per-export ceiling on the number of MedicationAdministration rows in the
# FHIR Bundle. The report window already scopes the set; this is a coarse
# safety ceiling on the serialised Bundle size. Bounded 1..50000; any unset
# or out-of-range value falls back to the default of 5000. Raise it only for
# an unusual multi-year, many-medication workload.
# FHIR_MAX_MEDICATION_ADMINISTRATIONS="5000"
# -----------------------------------------------------------------------------
# Dashboard snapshot -- BUILD-TIME toggle (default ON)
# -----------------------------------------------------------------------------
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
uses: pnpm/action-setup@v4
- name: Set up Node
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
+1 -1
View File
@@ -87,7 +87,7 @@ jobs:
fetch-depth: 0
- name: Gitleaks secret scan
uses: gitleaks/gitleaks-action@v2
uses: gitleaks/gitleaks-action@v3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+3
View File
@@ -22,6 +22,9 @@ regexes = [
'''idempotency-key''',
# Allow the placeholder prefix used in OpenAPI examples + docs.
'''hlk_example''',
# i18n caption keys for the briefing-driven trend charts are dotted message
# keys, not secrets — one trips the generic-api-key entropy heuristic.
'''insights\.trendsRow\.caption''',
]
# Specific commit fingerprints from prior false-positive findings (kept for reproducibility).
+108 -254
View File
@@ -1,270 +1,124 @@
# HealthLog v1.4.24 — roadmap
# HealthLog — roadmap
Milestone: **v1.4.24 — pre-iOS final polish** (not yet kicked off)
Latest tag at start: v1.4.23 (live in prod)
Current line: **v1.9.0** (shipping — Insights time-ranges, deeper mood, medication
drug-coding into FHIR, advanced-settings rebuild, connection-pool stability).
Trunk: `main`, always releasable. Release model in CLAUDE.md.
Carry-over candidates already captured in
`.planning/v1423-backlog.md`:
- Pearson incomplete-beta replacement — v1.4.23 W5 H6 raised
`MIN_PAIRED_N` from 14 → 20 as a conservative surfacing-gate
patch. Land the rigorous incomplete-beta or normal-approx
replacement before v1.5/v1.6 auto-correlation discovery ships.
- OpenAPI drift gate flip from warn-only to hard-fail — generator
covers ~880 lines vs the legacy hand-maintained spec's 5 468;
complete registry coverage in parallel so the lockstep happens
before the iOS DTO codegen is downloading the spec
automatically.
- Settings-cog vs per-message-controls UX consolidation — Design
pushback during W6 raised concern that the dual surface
duplicates intent. Wait on first-week thumbs data, decide
whether per-user prompt prefs drift from per-message ratings.
- `coach-prefs.test.ts` integration `NextRequest` URL mock
regression — pre-existing failure that predates v1.4.23.
Investigate the harness's `cookies()` mock interaction with
`NextRequest`'s URL parsing.
- Sec-MED-1 + LOW cluster — intra-batch dedup accounting
(Sec-LOW-1), idempotency 422 retry hint in the OpenAPI 422
description (Sec-LOW-2), APNs key-file path redaction in
wide-event meta (Sec-LOW-3), refresh-token failure audit
`userId` extension (Sec-LOW-4).
- S-05 simplify deferral (Session B) — touched too many call
sites for a single reconcile commit.
Reserved next strategic milestones:
- **v1.5** — iOS app + Apple Health integration + per-metric APNs
alerts. Refreshed strategic plan with concrete file paths at
`.planning/phase-W6-v1423-product-lead-review.md`. P1 is now a
~5-day iOS Swift sprint because every server-side contract
landed in v1.4.23. Per-user timezone foundation
(`.planning/feature-user-timezone.md`, issue #167) is now scoped
into v1.4.25 — Marc directive 2026-05-14, packs the iOS-launch
prep into the v1.4.25 polish window instead of slipping it.
- **v1.6+** — Auto-correlation discovery (FDR-controlled), Coach
full-page route at `/insights/coach`, conversation-driven goal
setting.
Next milestone: **v1.10.0 — derived / synthesized wellness metrics + provenance + docs**.
---
## Previous milestone — v1.4.23 (completed 2026-05-11)
## v1.10.0 — derived metrics, provenance, docs, discoverability
| Wave | Goal | State |
| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
| 1 | Research — Apple Health type mapping, APNs library decision (`@parse/node-apn`), OpenAPI tooling choice (`zod-openapi` + `yaml@^2`) | done |
| 2 | Apple Health foundation — F1 `MeasurementType` extension + sleep-stage enum + composite dedup index, F2 `APPLE_HEALTH` source + UI badge, F3 `POST /api/measurements/batch` + sleep-stage analytics aggregation | done |
| 3 | APNs scaffolding — F4 `@parse/node-apn` sender + dispatcher cascade rewire, `Device` columns + paired CHECK constraint, `POST /api/devices` apnsToken acceptance + cross-user-hijack guard | done |
| 4 | OpenAPI generator + Coach metric slot + native-auth hardening + Coolify runbook — F5 `zod-openapi` registry + warn-only CI gate, F6 nine HealthKit categories in strict schema + PROMPT_VERSION 4.23.0, F7 per-device refresh-token replay-detection + device-management endpoints, F8 Coolify runbook + `::notice::` line | done |
| 5 | Hygiene (H1-H7) — sentinel parser malformed-enum annotation, analytics chunked-paged aggregate, drawer controlled-prop refactor, per-user prompt prefs surface, `medication_schedules.days_of_week` deploy, Pearson n≥20 gate, Coach feedback observation view | done |
| 6 | Multi-agent QA + reconcile — six reviews (code, security, design, senior-dev, simplify, product-lead); 1 CRIT + 9 HIGH + 4 simplify + 3 MED applied; LOWs triaged into v1423-backlog | done |
| 7 | Release v1.4.23 — bump, CHANGELOG, release-merge, tag, GHCR, Coolify deploy, /api/version=1.4.23, smoke, GH release, docs + landing sync, brief | done |
The headline is derived wellness metrics that are honest on the data HealthLog
actually has — daily snapshots, not continuous streams. The governing constraint:
HRV is a single nightly SDNN value, there is no continuous HR, no EDA, no raw ECG/PPG,
and the nightly drain tombstones per-sample rows to a daily mean. So anything built on
intraday physiology is out of scope; day-scale deviation-from-personal-baseline
statistics are the sweet spot. Full synthesis in
`.planning/v1.10-derived-metrics-PROPOSAL.md`, implementation plan in
`.planning/v1.9.1-derived-metrics-IMPLEMENTATION-PLAN.md` (targeted at v1.10.0, not
1.9.1), research reports under `.planning/v1.10-research/`.
Milestone completed 2026-05-11 — v1.4.23 LIVE in prod.
Release brief: `docs/audit/v1423-summary.md`.
Backlog seeded to `.planning/v1423-backlog.md`. v1.5 strategic plan refresh
at `.planning/phase-W6-v1423-product-lead-review.md`.
### Ordering (data-availability first)
A derived metric appears only when its required inputs exist; composites degrade
gracefully and never present a headline number secretly computed from one of N signals.
Precedent: the Personal Health Score null-redistributes missing pillars.
(`.planning/v1.10-research/DESIGN-PRINCIPLE-data-availability.md`.)
1. **Per-metric Vitals dashboard** (flagship) — each available signal shows its own
personal-baseline card; absent signals don't render, so it scales 1→30 metrics with
no data assumptions. Pure rolling stats over inputs we 100% have, plus a multi-signal
early-strain flag. Build this first.
2. **Pre-computed easy wins** — age/sex-adjusted reference ranges (cross-cutting
enabler: `dateOfBirth` / `gender` are stored but unused for norms), Fitness Age /
cardio band from VO2max, Vascular Age framing from PWV. Render only when the device
value exists.
3. **Composites** — Sleep Score and a Readiness / Wellness index (extending the Personal
Health Score), each with a minimum-inputs threshold, reweighting around missing
inputs, a visible coverage / confidence indicator, and a "track BP/HRV to sharpen
this" nudge.
4. **Broader correlation discovery** — expand the fixed-hypothesis correlation engine
into an FDR-controlled behaviour↔outcome discovery engine, surfacing only pairs with
enough paired n (the existing n≥20 gate pattern).
Out of scope by construction (require sensing we deliberately don't retain): Body
Battery, all-day / real-time Stress, Strain / Training Load, a faithful Recovery score,
AFib / ECG derivation, breathing-disturbance / AHI, Oura Resilience, minute-by-minute
time-in-zone. State this plainly so we never over-promise; surface a device-computed
value as a passthrough where one exists, never re-derive it.
### Provenance / transparency (acceptance criterion, not an afterthought)
Every derived metric openly states what it's based on and links the basis:
- exact inputs + method / formula (plain-language + the math),
- why this method (rationale),
- a citation / link to the underlying authority (IEEE / RFC / WHO / LOINC /
peer-reviewed studies / Wikipedia — whichever is right),
- confidence / limitations stated honestly (SDNN≠RMSSD, snapshot-not-continuous,
consumer-sensor validity caveats),
- rendered through the existing collapsible provenance / explainer pattern — no
black-box number.
Needs a shared provenance / citation data model so each derived metric carries its
sources, surfaced via the explainer component everywhere it appears.
(`.planning/v1.10-research/REQUIREMENT-docs-and-provenance.md`.)
### Documentation audit + continuation
- Audit the docs site (`healthlog-docs`), in-repo `docs/`, README, and the OpenAPI
contract for accuracy vs the shipped state — much drifted across the v1.8.x → v1.9.0
arc.
- Continue / extend docs to cover the new derived metrics with the same provenance:
meaning, computation, linked standard, required data, graceful-degradation behaviour.
- This `ROADMAP.md` / `STATE.md` refresh folds into the audit.
### Discoverability / growth
A discoverability / growth workstream stands alongside the milestone (scope to be
shaped during planning).
---
## Previous milestone — v1.4.22 (completed 2026-05-10T22:43:50+02:00)
## Standing deferred items
| Wave | Goal | State |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----- |
| 1 | Research + probe — Playwright PROD probe (BD-Zielbereich 5th attempt, api-tokens 5th attempt, metric token leaks, Targets page brainstorm); health-coach prompt research | done |
| 2 | Insights surface polish — A1 BD framing, A2 BD-Kachel parity, A3 comparison-toggle global, A4 grid normalisation, A5 Muster rename + tabs above hero, A6 token-leak fix | done |
| 3 | Coach polish — B1 prompt rewrite (PROMPT_VERSION 4.20.2 → 4.22.0), B2 collapsible evidence, B3 Gravatar parity, B4 disclaimer move, B5 settings cog removal | done |
| 4 | Other surfaces + backlog cleanup — C1 Zielwerte sparkline + Δ-vs-last-month, C2 api-tokens 5th attempt, C3 Coolify auto-deploy runbook, C4 AuthShell flicker → proxy.ts, C5 node-26-alpine deferred, D backlog wave (12 items) | done |
| 5 | Multi-agent QA + Product-Lead — code, security, design, senior-dev, simplify, product-lead; 0 CRIT, 7 HIGH all applied inline, ~6 MED applied, rest deferred | done |
| 6 | Release v1.4.22 — bump, CHANGELOG, release-merge, tag, GHCR, host-side retag deploy (Coolify secrets still missing), /api/version=1.4.22, smoke, GH release, docs+landing sync, brief | done |
Carried forward; pick up as they become relevant or fold into a milestone.
Milestone completed 2026-05-10T22:43:50+02:00 — v1.4.22 LIVE in prod.
Release brief: `docs/audit/v1422-summary.md`.
Image digest:
`sha256:865154614303fdc362ee3941776f73ec0f60e1f16112ec272a75cbbe28e2cffb`.
Backlog seeded to `.planning/v1422-backlog.md`. v1.5 strategic plan at
`.planning/phase-W5-v1422-product-lead-review.md`.
- **BYOK AI fallback** — resilience gap: no provider fallback is configured, so a single
provider outage stalls assessment generation.
- **`MedicationAdministration` per-export cap tuning** — the per-dose administration
emission added in v1.9.0 needs a sensible cap for high-volume histories.
- **SNOMED route / site upgrade** — route-of-administration + injection-site could carry
SNOMED codes rather than the current local enum.
- **German bfarm ATC URI behind a locale toggle** — the export codes ATC against the WHO
system; a German deployment may prefer the bfarm URI.
---
## Previous patch — v1.4.21 (completed 2026-05-10T17:46+00:00)
## Shipped (coarse — CHANGELOG.md is the record)
| Phase | Goal | State |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ----- |
| F | Same-day patch on top of v1.4.20 — Daily Briefing regenerate fix, Coach day-level snapshot, duplicate streaming bubble, drawer header, scope picker UI | done |
| E | Release v1.4.21 — develop → main release-merge, bump, CHANGELOG, tag, GHCR, host-side retag fallback, /api/version=1.4.21, smoke, GH release, brief | done |
Patch completed 2026-05-10T17:46+00:00 — v1.4.21 LIVE in prod.
Release brief: `docs/audit/v1421-summary.md`.
Image digest:
`sha256:4e818d44702c3581a14d6480a953fd20d16cbbaf21c41e0c778c07340d3c4b1c`.
---
## Previous milestone — v1.4.20 (completed 2026-05-10T16:49:25Z)
| Phase | Goal | State |
| ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
| F0 | Bootstrap — commit dangling v1.4.19 reports, scaffold STATE+ROADMAP | done |
| F1 | Branch model — long-lived `develop` from `main` HEAD; GHCR builds on `main` + `v*` only | done |
| F2 | Document branch + release model — CONTRIBUTING.md + docs site mirror page | done |
| FX | User-facing artifact cleanup — PII (no real names, no health figures), internal jargon, German leaks; CHANGELOG + docs/audit + GH releases + docs + landing | done |
| F5 | Best-practice GitHub repo audit — CODE_OF_CONDUCT.md, issue + PR templates, dependabot expansion, package.json metadata | done |
| F6 | Multi-agent QA on new docs — 38 docs pages cross-checked vs deployed state, CRIT + HIGH inline | done |
| B1 | Hero strip + Daily Briefing + Suggested-prompts | done |
| B2 | AI Coach drawer + SSE streaming + encrypted persistence | done |
| B3 | Correlation discovery + Trends row with AI annotations | done |
| B4 | Weekly Report + Storyboard markers + Mobile passes | done |
| B5 | Personal Health Score (composite 0–100, 3 bands) | done |
| D | Multi-agent QA — code, security, design, senior-dev, simplify, product-lead; 13 HIGH + 6 MED + 5 simplify-yes inline; 22 MED + 16 LOW deferred | done |
| E | Release v1.4.20 — develop → main release-merge, bump, CHANGELOG, tag, GHCR, host-side retag deploy fallback, /api/version=1.4.20, smoke, docs+landing sync | done |
Milestone completed 2026-05-10T16:49:25Z — v1.4.20 LIVE in prod.
Release brief: `docs/audit/v1420-summary.md`. Backlog seeded to
`.planning/v1421-backlog.md`. v1.5 strategic plan at
`.planning/phase-D-v1420-product-lead-review.md`.
---
## Previous milestone — v1.4.19 (completed 2026-05-10T12:39:59Z)
| Phase | Goal | State |
| ----- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
| 0 | Bootstrap — STATE+ROADMAP for v1.4.19 | done |
| A1 | BD-Zielbereich constant 50% (4th attempt) — live-DB root-cause + integration test | done |
| A2 | Charts mobile audit — universal X-tick density helper, mobile-first stacked headers across HealthChart / MoodChart / MedicationComplianceChart | done |
| A3 | `/insights` polish — Comparison-toggle relocated, single page-level refresh, BP/Weight tile strip removed, raw-token leak guarded | done |
| A4 | AI prompt — GROUND RULE 7 forbids default-positivity opener, PROMPT_VERSION 4.16.1 → 4.19.0 | done |
| A5 | Settings/Integrations status-UI — `<IntegrationStatusPill>` consolidates Withings + Mood Log, divider parity, locale-aware relative-time | done |
| A6 | Settings mobile audit — input heights equalised at 36 px, action buttons standardised, Sprache select hoisted to its own row | done |
| A7 | Admin polish — feedback tab strip scrollbar, api-tokens 4th-attempt truncate+tooltip, Einklappen toggle removed, Zielwerte i18n | done |
| A8 | Quality-of-life audit — 78 findings prioritised CRITICAL / HIGH / MED / LOW | done |
| B | Apply A8 — 6/6 CRITICAL + 21/25 HIGH inline; 31 MED + 16 LOW carried to v1.4.20 backlog | done |
| D | Multi-agent QA (5 reviewers) + Product-Lead → v1.5 redesign plan filed | done |
| E1-E3 | Release v1.4.19 — tag, GHCR build green, host-side retag deploy via fallback (Coolify deploy hung, retried via SSH), GH release, docs+landing sync | done |
Milestone completed 2026-05-10T12:39:59Z — v1.4.19 LIVE in prod.
Release brief: `docs/audit/v1419-summary.md`. Backlog seeded to
`.planning/v1420-backlog.md` (carry-over) and v1.5 strategic items in
`.planning/v15-backlog.md` + `.planning/phase-D-v1419-product-lead-review.md`.
---
## Previous milestone — v1.4.18 (completed 2026-05-10T11:45+02:00)
| Phase | Goal | State |
| ----- | ------------------------------------------------------------------------------------------------------------ | ----- |
| 0 | Bootstrap — STATE+ROADMAP for v1.4.18 | done |
| A1 | BD-Zielbereich tile — 7T/30T sub-values render real numbers (currently "—" even with data) | done |
| A2 | `/admin/api-tokens` table scrollbar (3rd attempt) — Playwright live-verify against prod, fix actual offender | done |
| A3 | Chart visual revert + per-chart toggles — drop gradient/emoji/auto-mean, ship 3 opt-in overlay toggles | done |
| B1 | Achievements expansion — research + 15-25 new, hidden Easter-eggs, lock filter, hidden cards | done |
| D | Multi-agent QA + Product-Lead — code-reviewer, security, design, senior, simplify, product | done |
| E | Release v1.4.18 — bump, CHANGELOG, tag, GHCR, deploy, /api/version=1.4.18, smoke, docs+landing sync | done |
Marathon completed 2026-05-10T11:45+02:00 — v1.4.18 LIVE in prod.
Full report: `docs/audit/v1418-summary.md`. Backlog seeded to
`.planning/v1419-backlog.md` (tactical) and `.planning/v15-backlog.md`
- `.planning/phase-D-v1418-product-lead-review.md` (strategic).
---
## Previous milestone — v1.4.17 hotfix (live 2026-05-10T07:58+00:00)
| Phase | Goal | State |
| ------ | ---------------------------------------------------------------------------------------------------------- | ----- |
| Hotfix | `/insights` TypeError on legacy cached blob — `isLegacyInsightPayload()` flag + advisor card short-circuit | done |
| Audit | `git grep -nE '\.replace\(' src/` — 82 hits scanned, crash site is the only fragile case | done |
| E | Release v1.4.17 — bump, tag, GHCR, host-side retag deploy, GH release | done |
Hotfix completed 2026-05-10T07:58+00:00 — v1.4.17 LIVE in prod.
Detailed report: `.planning/phase-v1417-hotfix-report.md`.
---
## Previous milestone — v1.4.16 (completed 2026-05-10T04:05+02:00)
| Phase | Goal | State |
| ----- | ----------------------------------------------------------------------------------------------------- | ----- |
| 0 | Bootstrap — STATE+ROADMAP for v1.4.16 | done |
| A1 | Sidebar admin-expand bug — Admin nav from non-admin route + Gravatar dropdown side-effects | done |
| A2 | BD-Zielbereich real-fix (regression from v1.4.15 A4) — root-cause + E2E | done |
| A3 | `/admin/api-tokens` table responsive — card-list mobile fallback | done |
| A4 | "7-Tage-Schnitt" → "7-Tage-Trend" DE + indicator on ALL charts | done |
| A5 | Top-tile-selector real-fix — widget-id enum drift fixed | done |
| A6 | Medication-chart 7d-trend + target-range — match other charts | done |
| A7 | AI Generator rate-limit 10/h + cache-invalidate-on-new | done |
| A8 | Umlaute encoding bug + login-overview UTF-8 audit + long-window split-half delta | done |
| B1a | Charts visual leap — gradients, baseline, rich tooltip, mood emoji glyphs | done |
| B1b | Insights surface visual leap — page hero, recs grid, summary typography, dashboard preview | done |
| B2 | AI provider settings UX cleanup — single pulldown-driven form, fallback chain editor | done |
| B3 | Admin System-Status host-load chart — CPU/memory/disk-io graph last 2h | done |
| B4 | Admin logs visibility deepening — filterable audit log + structured wide-event tail | done |
| B5a | Medical-reference grounding — AHA / ESC / ESH / WHO bundle + UI citations | done |
| B5b | Multi-provider redundancy — try-each-on-hard-failure, configurable fallback order | done |
| B5c | Per-recommendation explainability — WHY / WINDOW / CITATIONS card with mini-chart | done |
| B5d | Confidence score per recommendation — deterministic 0-100 from sufficiency / recency / signal | done |
| B5e | User-feedback loop — thumbs persisted to RecommendationFeedback + daily aggregator | done |
| B6 | Settings naming-audit — stringency, consistency, no double naming | done |
| B7 | Settings → Export menu (Arztbrief consolidated) — new `/settings/export` route | done |
| B8 | Extended comparison views — Vormonat / Vorjahr overlay across charts + tiles + insights | done |
| C | Catch-up — 5 of 8 deferred HIGH + 3 of 5 mobile MED + docker-publish drop qemu-arm64 | done |
| D | Multi-agent QA + Product-Lead — code-review, security, design, senior, simplify, product-lead | done |
| E1-E3 | Release v1.4.16 — bump, tag, GHCR (both green), host-side retag deploy, GH release, docs+landing sync | done |
Marathon completed 2026-05-10T04:05+02:00 — v1.4.16 LIVE in prod.
Full report: `docs/audit/v1416-summary.md`. v1.5 backlog seeded at
`.planning/v15-backlog.md`.
---
## Previous milestone — v1.4.15 (completed 2026-05-09T22:50+02:00)
| Phase | Goal | State |
| -------- | ------------------------------------------------------------------------------------------------------------ | ----- |
| 0 | Bootstrap — STATE+ROADMAP for v1.4.15 | done |
| A1 | Nav conditionals + sidebar context-awareness | done |
| A2 | `/admin` overview redesign + `/admin/api-tokens` responsive | done |
| A3 | Quick-add labels + Stimmung-Card mobile + onboarding flicker | done |
| A4 | Dashboard analytics fixes (BD-Zielbereich, Medikamente graph, Stimmung agg, 7-Tage-Trend, top-tile selector) | done |
| A5 | Mobile UX audit + chart scroll-lockup fix | done |
| B-mobile | Mobile audit fix-application (5 commits, 2/2 CRITICAL, 6/8 HIGH) | done |
| B1 | Backup completeness — restore, download, upload, audit, docs | done |
| B2 | Withings + moodLog sync robustness — status UI, refresh rotation, telegram on fail | done |
| B3 | Notification reliability — auto-disable on 410, exp backoff, status visible | done |
| B4 | Achievements UI — `/achievements` page + dashboard card | done |
| B5 | Onboarding tour first-run — spotlight, Esc/arrows, restart from Settings | done |
| B6 | Doctor-report v2 — configurable date range, practice-name on cover | done |
| C1 | AI/Codex hardening — provider abstraction, JSON schema, citations, scope, slug-drift defense | done |
| C2 | Auto-deployment — Coolify webhook on GHCR push, failure-notify | done |
| C3 | CI/e2e reliability audit — root-cause flaky specs, docker-publish cache fix | done |
| C4 | i18n coverage audit — EN+DE parity, non-empty test guards | done |
| C5 | Empty-states audit — 13 surfaces upgraded | done |
| D | Multi-agent QA (5 reviewers + reconcile) | done |
| E1–E3 | Release v1.4.15 — bump, tag, GHCR, host-side retag deploy, docs+landing sync, Marc-Brief | done |
Marathon completed 2026-05-09T22:50+02:00 — v1.4.15 LIVE in prod.
Full report: `docs/audit/v1415-summary.md`.
---
## Previous milestone — v1.5 (relabelled v1.4.14, completed 2026-05-09)
| Phase | Goal | State |
| ----- | -------------------------------------------------------------------------------------------------------------------------------------- | ----- |
| 0 | Bootstrap — STATE+ROADMAP, git/CI/prod sanity, single chore commit | done |
| 1 | Verify Codex-OAuth end-to-end (device-start shape, prod logs, gpt-5.3-codex slug) | done |
| 2 | v1.4.6 deferred backlog — T2.1..T2.7 (wipe scope, DST math, 5xx → 422/503, status-card test, redact regex, Backups view, /admin/users) | done |
| 3 | End-to-end test coverage — authed dashboard, add-measurement, KI flow, doctor PDF, insights, mobile smoke, axe-core extended | done |
| 4 | Performance audit — Playwright capture, `docs/audit/v15-performance.md`, top-3 wins inline | done |
| 4b | Admin Panel refactor — `/admin/[section]` dynamic routes mirror Settings; sidebar Admin group; legacy hash redirects; bundle-size win | done |
| 5 | UX polish — design-review top-10 friction points, CRITICAL/HIGH triage | done |
| 6 | Multi-agent QA (parallel) — code-reviewer, security, visual/UX, simplify | done |
| 7 | Pre-release verification — typecheck / lint / format / test / integration / build / e2e | done |
| 8 | Release v1.4.14 — rebrand patch deploy (host-side retag, GHCR `:1.4.14`, image digest `0ced46004a54…`) | done |
| 9 | Docs + landing site sync to v1.4.14 | done |
| 10 | Backfill GitHub releases v1.4.7..v1.4.13 from CHANGELOG | done |
| 11 | Final summary `docs/audit/v1414-summary.md` with Marc-Brief | done |
Marathon completed 2026-05-09T18:35+02:00 — v1.4.14 LIVE in prod.
Full report: `docs/audit/v1414-summary.md`.
- **v1.9.0** (2026-06-02) — Insights time-ranges + period-over-period deltas, deeper
mood insights, medication ATC + RxNorm into the FHIR export (+ MedicationAdministration
per dose, Coverage-from-bare-KVNR, Composition narrative), advanced-settings rebuild,
inline targets (`/targets` retired), connection-pool sizing fix, decoupled insight
warm. Migration `0103`.
- **v1.8.7.1** (2026-06-02) — assessment on every HealthKit metric page, one-tap
pre-generation.
- **v1.8.x** (2026-05-31 → 06-02) — Insights big release (reliable assessments, graded
compression, embedded targets, explainers, English slugs), compliance + intake-slot
medical fixes, injection-site tracking, FHIR codesystem + Coverage, instant
assessments, GLP-1 blood-level chart.
- **v1.7.x** (2026-05-31) — health-record PDF + FHIR R4 export, PRN + cyclic schedules,
unified dashboard snapshot + nightly insight pre-gen, offline sync delta feed, full
HealthKit chart coverage, Coach data clustering.
- **v1.6.0** (2026-05-30) — medication editor overhaul + route of administration,
one-time injection, today-tile read-flip, profile-photo upload.
- **v1.5.x** (2026-05-24 → 29) — native iOS client public beta + Apple Health sync,
medication scheduling (RRULE / rolling / one-shot), step consolidation, `safeFetch`
egress hardening, avatar storage, `SESSION_COOKIE_SECURE` through compose.
- **v1.4.24 → v1.4.50** (2026-05-11 → 24) — rollup tiers + perf, APNs + `push_attempts`,
reminder suppression, self-healing stale-shell, localisation, MoodLog reverse-sync.
- **v1.4.23** (2026-05-11) — pre-iOS backend foundation + hygiene (Apple Health enum +
batch ingest + APNs scaffolding + OpenAPI generator). Earlier history archived.
</content>
+95 -223
View File
@@ -1,245 +1,117 @@
# v1.4.23 marathon — state log
# State log — where we are now
Status: SHIPPED — v1.4.23 LIVE in prod
Last update: 2026-05-11 (release wave)
Status: **v1.9.0 shipping** — on branch `release/v1.9.0`, Draft PR #240 → `main`,
about to tag + docker-publish + deploy.
Last update: 2026-06-02
> Previous milestone: v1.4.22 live (image digest
> `sha256:865154614303…`, `/api/version=1.4.22`).
> v1.4.23 = pre-iOS prep + hygiene. Backend foundation so the iOS
> Health app can ship in v1.5 without contract churn, plus 7
> hygiene items from `.planning/v1422-backlog.md`.
> Single trunk: `main` is always releasable. `develop` is retired (archived as the
> tag `archive/develop-pre-v1.5`; never recreate it). Releases cut on a short-lived
> `release/vX.Y.Z` branch → PR → merge → tag → `docker-publish.yml` → manual deploy →
> verify `/api/version` on every target. See CLAUDE.md for the full model.
## Wave 1 — Research (single agent, three streams)
---
- [ ] Apple Health `HKQuantityTypeIdentifier` → `MeasurementType`
mapping, with units + canonical aggregation rules
- [ ] APNs Node library decision (`apn` vs `@parse/node-apn` vs
raw HTTP/2) with maintenance / type-safety / footprint pros/cons
- [ ] OpenAPI 3.1 generator tooling for Next.js routes
(`@asteasolutions/zod-to-openapi`, `ts-rest`, `next-rest`,
hand-rolled)
- Detailed report: `.planning/phase-W1-v1423-research.md`
## v1.9.0 — what it carries
## Wave 2 — Apple Health foundation (F1+F2+F3)
Insights time-ranges + period-over-period deltas, deeper mood insights, medication
drug-coding into the FHIR export, an advanced-settings rebuild, an inline-targets
move, and a stability fix to the connection pool.
### F1 — `MeasurementType` enum extension
### Added
- [x] Added `HEART_RATE_VARIABILITY`, `RESTING_HEART_RATE`,
`ACTIVE_ENERGY_BURNED`, `FLIGHTS_CLIMBED`,
`WALKING_RUNNING_DISTANCE`, `VO2_MAX`, `BODY_TEMPERATURE`
(W1 recommended reusing `ACTIVITY_STEPS` + `SLEEP_DURATION`
verbatim; the iOS DTO already shipped `BODY_TEMPERATURE` so
that joined the additive set — net new = 7)
- [x] Prisma migration `0036_apple_health_measurement_types`
- [x] Sleep unit shifted from hours to minutes; new `SleepStage`
enum + nullable `Measurement.sleepStage` column (CHECK
constraint scopes it to SLEEP_DURATION rows)
- [x] Composite unique index `(user_id, type, source, external_id)`
— Apple Health batch dedup key
- [x] Unit conversions in
`src/lib/measurements/apple-health-mapping.ts` (16 unit tests)
- **Selectable time ranges on the Insights pages** — week / month / quarter / year
range pills per metric, with a period-over-period delta (the change in the average,
stated plainly with its direction).
- **Deeper mood insights** — time-of-day pattern (highest / lowest), a stability read,
and correlation cards against weight and blood pressure. Every correlation is
paired-n gated (only shown when there are enough paired days to mean anything).
- **Standard drug codes on a medication** — an optional ATC and RxNorm code (entered,
never guessed; migration `0103` adds the nullable `atc_code` / `rxnorm_code`).
These flow into the health-record export: the `MedicationStatement` codes the drug
with the WHO ATC system + RxNorm alongside the plain name, and the export adds a
`MedicationAdministration` for every dose actually taken or skipped.
- **`scripts/assert-deploy.ts`** — a deploy-verification script that checks a target
reports the expected version after a release.
### F2 — `MeasurementSource` enum expansion
### Changed
- [x] `APPLE_HEALTH` appended to the enum
- [x] UI badge in measurement-list (Dracula-pink chip) + bilingual
`measurements.sourceAppleHealth` keys + admin restore-route
enum guard sync
- **Medication advanced-settings page rebuilt** — import / intake-import / export in
their own group; the external-API endpoints listed one by one with collapsible
request examples; tidier layout.
- **Targets edited inline** — the standalone `/targets` page is retired; a metric's
target range is set from the metric itself.
- **Health-record export emits insurer Coverage from a bare KVNR** (not only with a
full insurer organisation present) and carries a top-level Composition narrative
summary.
### F3 — `POST /api/measurements/batch`
### Fixed
- [x] New route at `src/app/api/measurements/batch/route.ts`,
idempotent via `Idempotency-Key`
- [x] Validates batch ≤ 500 entries (returns 422
`coach.batch.too_large`)
- [x] Dedupes via `(userId, type, source, externalId)` composite
- [x] Returns per-entry status (`inserted` / `duplicate` /
`skipped`) + idempotency-replay-safe
- [x] Integration test (`tests/integration/measurements-batch.test.ts`,
6 cases including idempotency replay)
- [x] Sleep-stage aggregation in `/api/analytics`:
per-Berlin-day summary + `sleepStages` block
(`tests/integration/analytics-sleep-stages.test.ts`)
- Detailed report: `.planning/phase-W2-v1423-report.md`
- **App stays responsive under load** — `DB_CONNECTION_LIMIT` is now sized for real
concurrency (the 9 default could starve while a background insight warm and a
foreground request competed, surfacing as the self-recovering "server not
responding"); tunable for larger self-hosts.
- **Background insight warm decoupled + sync-burst invalidation debounced** — a warm
no longer blocks a page, and a burst of Apple Health / Withings sync no longer
triggers a storm of regenerations.
- **Medication card rows hold an equal height** ("last dose" / "next dose" alignment).
- **Glucose entered in mmol/L converts correctly** in the editor.
- **Scrollbar-gutter reserved** — admin + global layout no longer shifts when a
scrollbar appears.
- **Six legacy `*-status` routes documented** in the OpenAPI contract.
## Wave 3 — APNs scaffolding (F4)
---
- [x] Library install + lock-file (`@parse/node-apn@8.1.0`,
W1 stream-2 decision)
- [x] `src/lib/notifications/senders/apns.ts` — `sendApnsPush()`
one-shot helper plus `sendViaApns(userId, payload)` dispatcher
entry mirroring the web-push contract
- [x] Env-var contract: `APNS_KEY_ID`, `APNS_TEAM_ID`,
`APNS_BUNDLE_ID`, one of `APNS_KEY` / `APNS_KEY_FILE`,
optional `APNS_PRODUCTION` — documented in `.env.example`,
all-or-none guard with one-shot warning when partially set
- [x] `Device` Prisma model extension via migration
`0037_apns_device_columns`: nullable `apnsToken` +
`apnsEnvironment`, paired CHECK constraint, single-column
index on `apns_token` for the dispatcher fan-out lookup
- [x] Dispatcher wiring: `APNS` joins the cascade as channel-type
4; cascade order is now deterministic
(APNs → Telegram → ntfy → Web Push)
- [x] Mock provider at `src/lib/notifications/senders/__mocks__/apns.ts`
with queued per-token responses + recorded calls
- [x] Integration test
`tests/integration/apns-dispatch.test.ts` — round-trip,
hard-reject + cleanup, cascade fall-through (3 tests)
- [x] `POST /api/devices` accepts paired `apnsToken` +
`apnsEnvironment`, enforces hex format, applies the
cross-user-hijack guard at the APNs-token layer
(409 `apns_token_owned_by_other_user`)
- Detailed report: `.planning/phase-W3-v1423-report.md`
## What is live (the release arc since v1.4.23)
## Wave 4 — OpenAPI + Coach schema + native auth + Coolify
Coarse summary; CHANGELOG.md is the accurate per-release record.
### F5 — OpenAPI 3.1 generator + CI gate
- **v1.4.24 → v1.4.50** — perf + rollup tiers (measurement / mood / compliance /
cumulative-sum rollups, read-swap with live fallback, auto-converging boot
backfill), APNs delivery + per-channel test endpoint + `push_attempts` ledger,
server-side reminder suppression (`clientManaged`), self-healing stale-shell after
deploy, full localisation push, MoodLog reverse-sync.
- **v1.5.x** — native iOS client public beta + Apple Health sync (`POST /api/measurements/batch`,
per-day cumulative `stats:` overwrite), medication scheduling (RRULE / rolling /
one-shot lifecycle, creation wizard → modal-dialog compose-mode), per-day-cumulative
step consolidation, `safeFetch` egress hardening, self-hosted avatar storage,
`SESSION_COOKIE_SECURE` plumbed through compose.
- **v1.6.0** — medication editor overhaul + route of administration (`deliveryForm`,
migration `0088` ORAL backfill), one-time injection, today-tile read-flip onto the
canonical recurrence engine, profile-photo upload.
- **v1.7.x** — health-record export (enriched PDF + HL7 FHIR R4 bundle), PRN + cyclic
schedules, unified dashboard snapshot + nightly insight pre-generation, offline sync
delta feed (tombstones), full HealthKit chart coverage + display-unit preference,
Coach data clustering, multi-time compliance fixes.
- **v1.8.x** — Insights big release (reliable data-driven assessments, graded
compression, embedded targets, explainers, English slugs + tile-id aliases),
multi-time compliance, one-intake-row-per-dose-slot medical fix, injection-site
tracking, FHIR codesystem for HealthKit-only metrics, FHIR `Coverage`, instant
assessments (stale-while-revalidate), GLP-1 blood-level chart.
- **v1.8.7.1** — a plain-language assessment on every HealthKit metric page (~30
metrics), one-tap pre-generation of every assessment.
- [x] Tool wired (W1 decision — `zod-openapi` (samchungy) + `yaml@^2`)
- [x] `pnpm openapi:generate` script emits
`docs/api/openapi.yaml` from Zod schemas
- [x] CI step compares generated vs committed; PR warns on drift
(`continue-on-error: true` — flips to hard-fail in v1.4.24+)
- [x] Legacy hand-maintained spec preserved at
`docs/api/openapi-v1422-legacy.yaml` during the incremental
migration
apps01 + demo are LIVE on the latest tag; v1.9.0 deploy is pending the tag.
### F6 — Coach + Daily Briefing schema slot for new metrics
---
- [x] `aiInsightResponseSchema.dailyBriefing.keyFindings[].sourceMetric`
enum extends to include the 9 Apple Health categories
(hrv, sleep, resting_hr, steps, active_energy, flights,
distance, vo2_max, body_temp)
- [x] `trendAnnotations` schema mirrors the same additive enum
- [x] `coach/snapshot.ts` queries the new measurement types when
scope toggles them on; web-only accounts pay zero extra SQL
- [x] `CoachProvenance.metrics` + `counts` extended symmetrically
- [x] PROMPT_VERSION 4.22.0 → 4.23.0 with new GROUND RULE 12
("treat Apple Health categories as silent when absent")
- [x] EN + DE prompt bodies, OUTPUT FORMAT block, and i18n strings
all updated
## Deferred set (carry-forward from v1.9.0)
### F7 — Native API hardening (refresh-token per-device)
| Item | Where it goes | Note |
|---|---|---|
| Derived / synthesized wellness metrics | **v1.10.0** | per-metric Vitals dashboard first, then composites with coverage/confidence gating. Plans in `.planning/v1.10-derived-metrics-PROPOSAL.md` + `.planning/v1.9.1-derived-metrics-IMPLEMENTATION-PLAN.md` (targeted at v1.10.0) + `.planning/v1.10-research/*`. |
| Docs / provenance audit | **v1.10.0** | docs site + in-repo `docs/` + README + OpenAPI drifted across the v1.8.x → v1.9.0 arc; audit + continue, and surface every derived metric's sources via the explainer pattern. Requirement: `.planning/v1.10-research/REQUIREMENT-docs-and-provenance.md`. |
| Discoverability / growth workstream | **v1.10.0** | standing alongside the derived-metrics milestone. |
| BYOK AI fallback | open | resilience gap — no provider fallback is configured, so a single provider outage stalls assessment generation. |
| `MedicationAdministration` per-export cap tuning | open | the per-dose administration emission needs a sensible cap for high-volume histories. |
| SNOMED route / site upgrade | open | route-of-administration + injection-site could carry SNOMED codes rather than the current local enum. |
| German bfarm ATC URI behind a locale toggle | open | the export codes ATC against the WHO system; a German deployment may prefer the bfarm URI — gate behind a locale toggle. |
- [x] Refresh-token reuse-detection switches from "revoke all" to
per-device-token revocation (legacy null-deviceId tokens fall
back to user-wide revoke — safety hatch)
- [x] New route `GET /api/auth/me/devices` lists active devices
with last-seen, label, channels, isCurrent marker
- [x] New route `DELETE /api/auth/me/devices/[id]` revokes one device
(refresh + access tokens + Device row)
- [x] Alternate `DELETE /api/devices/[id]` for the iOS token-rotation
cleanup path (mirror of the auth/me variant)
- [x] Ownership-boundary 404 on cross-user attempts
---
### F8 — Coolify auto-deploy fix for real
## Next milestone — v1.10.0
- [x] `COOLIFY_WEBHOOK` + `COOLIFY_TOKEN` GitHub repo secrets
documented (maintainer action; see
`.planning/coolify-auto-deploy-howto.md` for the verbatim
recipe)
- [x] Coolify "Watch image registry for new digests" UI toggle
documented as the load-bearing piece (maintainer action — can't
be flipped from CI)
- [x] Workflow step gains a `::notice::` line so future runs surface
the deploy timestamp + sha without opening the verbose log
- [x] Verification recipe (`curl /api/version | jq .data.version`) + host-side fallback documented inline
## Wave 5 — Hygiene (H1-H7)
- [x] H1 sentinel parser malformed-enum hardening
(`SentinelParseResult.malformedEntries[]` + per-line typed
reasons; chat route splits `coach.keyvalues.parse_partial` from
the full-block `coach.keyvalues.parse_failed`)
- [x] H2 analytics-route unbounded `findMany` pagination
(cursor-paged 5 000-row chunks via `fetchBpSeriesChunked`,
`analytics.bp_in_target.row_count` wide-event meta for slow-
query attribution; integration test seeds 6 000 rows across a
chunk boundary)
- [x] H3 `<CoachDrawer key={prefill}>` controlled-prop refactor
(`useResettableValue` hook + pure `nextResettableValue` helper;
`key={prefill}` removed from the parent mount)
- [x] H4 per-user prompt-tuning surface (Coach settings cog return)
(`User.coachPrefsJson` migration `0038_coach_prefs`; new
`GET/PUT /api/auth/me/coach-prefs`; settings cog opens a
right-edge `<Sheet>`; system-prompt prepends a per-user
OVERRIDE; snapshot reads prefs BEFORE measurement queries so
`excludeMetrics` filters before the snapshot lands)
- [x] H5 schema drift on `medication_schedules.days_of_week`
(decision: deploy — column is referenced by 9 source files
across 4 user-visible surfaces; migration
`0039_medication_schedule_days_of_week`, NULL = daily)
- [x] H6 Pearson p-value normal-approx replacement
(raised `MIN_PAIRED_N` from 14 → 20 — conservative patch;
rigorous incomplete-beta queued as a v1.4.24 candidate)
- [x] H7 Coach helpful/unhelpful first-week observation view
(polymorphic `RecommendationFeedback.target_type` migration
`0040_recommendation_feedback_target_type`; new POST
`/api/insights/chat/messages/:id/feedback`; aggregator slice
`buildCoachFeedbackBuckets` by (promptVersion, tone, verbosity);
admin section `/admin/coach-feedback` with the H7 i18n bundle
both EN + DE)
W5 commits (8): 58ae9bc, fa07748, 9413d29, 3f60c81, 0eda1de, 1faee95,
05c7f14, plus this STATE tick.
Test deltas: 2191 → 2223 unit (+32). Integration suite added 3
files: `coach-prefs`, `coach-feedback`, plus the 6000-row chunk
boundary regression in the existing `bp-in-target` test.
OpenAPI registry coverage: +3 routes (GET / PUT
`/api/auth/me/coach-prefs`, POST
`/api/insights/chat/messages/{id}/feedback`).
## Wave 6 — Multi-agent QA + Product-Lead review
- [x] code-reviewer
- [x] security review
- [x] design / UX review
- [x] senior-dev review
- [x] simplify
- [x] Product Lead — v1.5 P1 (iOS first launch) plan refresh with
concrete file paths now that backend contracts exist
- [x] Reconcile — 1 CRITICAL + all 9 HIGH + 4 of 5 simplify + 3 MED
applied; remainder triaged into `.planning/v1423-backlog.md`
W6 reconcile commits (11): 5486507, 13977bc, d5202e5, a2dfc5e (Session A
— CRIT + HIGH 1-3); 3ee6dab, dfffe6b, d25e50e (Session B — HIGH 4 +
S-02-S-04 simplify + HIGH 6); deadc73 (Session D — HIGH 5); 650f150
(Session E — HIGH 7); 1a46bfe (Session F — MED cluster); plus this
STATE tick.
Detailed reconcile report: `.planning/phase-W6-v1423-reconcile-report.md`.
Deferred items: `.planning/v1423-backlog.md` (settings-cog vs
per-message-controls debate, rigorous Pearson incomplete-beta, surplus
MEDs, all LOWs, S-05 simplify, pre-existing `coach-prefs.test.ts` mock
issue, sandbox `git commit` no-op).
Test deltas: W5 ended at 2223 unit. Session A added the `revoke.test.ts`
- `apns-dispatch` device tests landing at 2227. Session E ended at 2235.
Session F added the forged-X-Device-Id regression — final at 2236 unit
(+45 across the W5+W6 reconcile arc).
## Wave 7 — Release v1.4.23
- [x] Pre-release verify (typecheck / lint / openapi:check / 2236
unit / 110 of 112 integration — 2 failures are the pre-existing
`coach-prefs.test.ts` `NextRequest` URL mock carryover from
v1.4.22, documented in `v1423-backlog.md`, non-blocking)
- [x] Format sweep commit (`f1e6630` prettier sweep on `develop`) +
W1 research + W5/W6 review packs commit (`766a9ae`) +
OpenAPI regen (`4183552`)
- [x] Bump `package.json` 1.4.22 → 1.4.23 + CHANGELOG (`d2331d9`
`chore(release): v1.4.23`)
- [x] Release-merge develop → main (`0dc0e16 Release v1.4.23`)
- [x] Tag + push v1.4.23
- [x] GHCR build green
- [x] Coolify deploy + `/api/version=1.4.23` confirmed
- [x] Production smoke (gated routes 307; `/api/version=1.4.23`)
- [x] GH release published
- [x] Docs site + landing site sync (image pins 1.4.22 → 1.4.23 +
ai-insights v1.4.23 callout; softwareVersion JSON-LD bump)
- [x] `docs/audit/v1423-summary.md` release brief
- [x] v1.5 P1 plan refresh recorded
(`.planning/phase-W6-v1423-product-lead-review.md` section C)
Derived / synthesized wellness metrics, honest on the daily-snapshot data HealthLog
actually stores; full provenance + standards-linking; full docs audit;
discoverability / growth. See `ROADMAP.md`.
</content>
</invoke>
@@ -0,0 +1,80 @@
# v1.8.0 — server → iOS: Insights tile-id rename (non-breaking)
Date: 2026-05-31
From: server
To: iOS
Status: informational — no action required to keep working; action recommended before a future major
## Summary
v1.8.0 renames the Insights tile ids (and the matching web route slugs) from
German to English to make the identifier space consistent. **This is
non-breaking for the iOS layout sync.** The `GET/PUT /api/insights/layout`
endpoint keeps accepting the old German ids. You do not need to ship anything to
stay working. When convenient, migrate to the canonical English ids.
## What changed
The canonical tile ids in `GET/PUT /api/insights/layout` are now English:
| Legacy (≤ v1.7.x) | Canonical (v1.8.0+) |
|---|---|
| `blutdruck` | `blood-pressure` |
| `puls` | `pulse` |
| `sauerstoff` | `oxygen` |
| `koerpertemperatur` | `body-temperature` |
| `gewicht` | `weight` |
| `aktive-energie` | `active-energy` |
| `schlaf` | `sleep` |
| `ruhepuls` | `resting-pulse` |
| `stimmung` | `mood` |
| `medikamente` | `medications` |
`overview`, `bmi`, `hrv`, and `workouts` were already language-neutral and are
unchanged.
## Why it does not break you
- **PUT still accepts the legacy German ids.** The server's validation enum is
the union of the canonical English ids and the legacy German aliases, so a
`PUT` carrying `blutdruck` / `puls` / … validates (no 422).
- **The server normalises legacy → canonical on write.** A `PUT` with German ids
persists the English equivalents. So after any save, the stored layout is
canonical English regardless of what you sent.
- **GET always returns canonical English ids.** A layout you persisted before
v1.8.0 (German ids) is normalised on read — `GET` surfaces the English ids
without forcing a re-`PUT`.
- **Dedupe.** If a payload carries both a legacy and a canonical id for one tile,
the server keeps a single canonical entry.
So the worst case for an un-migrated iOS build is: it keeps sending German ids,
the server keeps accepting and normalising them, and on the next `GET` the app
sees English ids it does not recognise in its local enum. If your client filters
unknown tile ids defensively, that filter must learn the English ids — see
below.
## What iOS should do (recommended, before a future major)
1. **Add the English ids to your tile-id enum / model** (keep the German ones as
decode-only aliases if your decoder is strict, or just map both).
2. **Send English ids on `PUT`.** Once your build is out, you stop relying on the
server's alias acceptance.
3. **Decode `GET` responses expecting English ids.** Because the server
normalises on read, a current `GET` already returns English; an app that hard-
filters to the old German enum would drop every tile. Decode the English ids
before you rely on this endpoint in a v1.8.0+ environment.
## Deprecation timeline
The legacy German ids are accepted-but-deprecated. They will be **removed from
the accepted input set in a future major version** once we confirm clients have
migrated. No date is fixed yet; we will give notice through this channel before
the removal. Until then, both id sets validate.
## References
- Contract: `docs/api/openapi.yaml` → `InsightsLayoutBody` (lists canonical +
legacy ids, with the deprecation noted in the schema description).
- Rationale: `docs/adr/0001-insights-naming-convention.md`.
- Web route slugs got the same English rename with 301 redirects from the legacy
German URLs; that is web-only and does not affect the iOS contract.
@@ -0,0 +1,82 @@
# v1.8.5 — server → iOS: injection-site capture on intake
**Direction:** server → iOS
**Status:** additive, non-breaking. iOS adoption is optional.
## What changed
Injection-site tracking is now real on the server. The `injectionSite`
column on the intake event existed but was never written; v1.8.5 makes
the capture + rotation path end-to-end.
### 1. New optional request field: `injectionSite`
`POST /api/medications/{id}/intake`, `POST /api/medications/intake`
(status toggle), and `POST /api/medications/intake/bulk` now accept an
optional `injectionSite` on a **taken** write. Enum values:
```
ABDOMEN_LEFT, ABDOMEN_RIGHT, ABDOMEN_UPPER_LEFT, ABDOMEN_UPPER_RIGHT,
THIGH_LEFT, THIGH_RIGHT, UPPER_ARM_LEFT, UPPER_ARM_RIGHT
```
The field is **optional everywhere** — omit it and the dose records
exactly as before. There is no behaviour change for any existing client
that never sends it. (It is the same enum the response already echoes via
the GLP-1 detail endpoint, so the type is already known to the client.)
### 2. Server-side gating + validation (important for iOS UX)
The server only persists `injectionSite` when ALL hold:
- the dose is being recorded **taken** (never on a skip),
- the medication is `deliveryForm === "INJECTION"`,
- the medication has `trackInjectionSites === true`,
- the submitted site is in the medication's **effective allowed set**.
The effective allowed set = the per-medication `allowedInjectionSites`
(empty = all eight) **minus** the user-level
`globalExcludedInjectionSites` deny-list. **Deny always wins**: a site the
user globally excluded is never valid even if a medication lists it as
preferred.
A submitted site outside the effective set:
- per-medication + status-toggle routes → **422**
`errorCode: "medications.intake.injection_site.disallowed"`.
- bulk route → that entry is reported `status: "skipped"`,
`reason: "injection_site_not_allowed"` (the batch still succeeds).
A site sent for a non-injection / tracking-off medication, or on a skip,
is silently dropped (the dose still records, no error).
iOS should only offer the picker when the medication is an injection with
tracking enabled, and restrict the choices to the effective allowed set,
so the 422 path stays an edge case (stale UI / race).
### 3. New medication fields (read + write)
`GET /api/medications` and `GET /api/medications/{id}` now echo:
- `trackInjectionSites: boolean` (default `false`)
- `allowedInjectionSites: InjectionSite[]` (default `[]` = no restriction)
`POST /api/medications` + `PUT /api/medications/{id}` accept both as
optional fields (field-by-field; `false` / `[]` are valid explicit
values — `false` deactivates tracking, `[]` clears the per-med list).
### 4. New user-level endpoint
`GET` / `PATCH /api/auth/me/injection-site-prefs`
```
{ "globalExcludedInjectionSites": InjectionSite[] }
```
The PATCH hard-sets the deny-list (empty array clears it). 60/min rate
limit, same envelope as `unit-preference`.
## Contract source
All of the above is in `docs/api/openapi.yaml` (regenerated this
release). No field was removed or renamed; every addition is optional /
defaulted. Existing iOS builds keep working untouched.
@@ -0,0 +1,67 @@
# v1.8.5 — server folds high-frequency mean metrics nightly (informational, no iOS change)
Direction: server → iOS. Status: informational + optional. No breaking
change. iOS needs zero changes for correctness.
## What changed on the server
The server now consolidates the high-frequency HealthKit "spot" metrics
into one canonical daily row per metric per day, server-side, on a nightly
cron — the same treatment cumulative metrics (steps, energy, distance)
already get. The daily reduction is the **MEAN** of the day's samples,
written at local-noon under the existing
`stats:<HKQuantityTypeIdentifier>:<YYYY-MM-DD>` externalId shape, and the
per-sample rows are soft-deleted (tombstoned, pruned later).
v1.8.5 extends the consolidated set to cover the gait/mobility metrics that
previously piled up at sampling granularity:
- `WalkingAsymmetryPercentage` (WALKING_ASYMMETRY)
- `WalkingDoubleSupportPercentage` (WALKING_DOUBLE_SUPPORT)
- `AppleWalkingSteadiness` (WALKING_STEADINESS)
- `WalkingHeartRateAverage` (WALKING_HEART_RATE_AVERAGE)
joining the metrics already folded since v1.7.0: `RespiratoryRate`,
`EnvironmentalAudioExposure`, `HeadphoneAudioExposure`, `WalkingSpeed`,
`WalkingStepLength`.
The fold now runs on the nightly maintenance tick (alongside the cumulative
drain), not just at worker boot. A 36-hour grace window keeps the current
day's in-flight watch syncs raw so the live "today" view stays current.
## What this means for iOS
**Nothing is required.** Keep sending these metrics as per-sample rows with
opaque UUID externalIds exactly as today. The server folds them nightly;
the daily read path averages over the single consolidated row, so the
metric pages and detail history read consistently with no client change.
Existing accumulated per-sample rows are back-consolidated automatically on
the first deploy by the boot-time discovery pass — no migration, no manual
backfill.
## Pulse is unchanged — still raw
Regular heart-rate / `PULSE` is deliberately NOT consolidated. It is a
discrete clinical reading and feeds correlation + scatter analytics, which
read raw PULSE rows. Keep posting PULSE per-sample as today. Its display
already daily-averages via the read-path AVG; storage stays raw.
## Optional future optimisation (not required, not yet scheduled)
If iOS later wants to cut upload volume for these mean metrics, it MAY send
them pre-aggregated as a daily value under the same `stats:` shape it
already uses for cumulative metrics — e.g.
`stats:HKQuantityTypeIdentifierWalkingSpeed:2026-06-01`. The server's batch
route already routes any `stats:*` externalId to the idempotent overwrite
path, so no server change is needed to accept it.
One caveat if iOS adopts this: for a mean metric the daily `stats:` value
must carry the **average**, not the sum. Compute it on-device with
`HKStatisticsCollectionQuery` using the `discreteAverage` option (NOT
`cumulativeSum`, which is correct only for the cumulative metrics). The
server-side nightly fold remains the safety net for any client not on that
contract, so this stays a pure bandwidth optimisation rather than a
correctness dependency.
No `docs/api/openapi.yaml` change — the batch contract is unchanged.
+32
View File
@@ -0,0 +1,32 @@
# v1.11.1 W10 QA LEDGER
## Reviewers (6): qa-code-review, qa-security, qa-senior-dev, qa-product-lead, qa-simplifier, qa-i18n-deadcode
Verdicts so far: security PASS (0C/0H/0M), code-review SHIP (0C/0H/1M), product-lead SHIP (0C/0H/2M), senior-dev ship-able (0C/0H/1M). simplifier + i18n pending.
## RECONCILED (fixed this session)
- [FIXED commit pending] M (code-review M-1 / security Info-1 / product-lead M2 / senior-dev L2): conversation-summary.ts fold-loop decrypt not fault-isolated → wrapped in try/catch (flatMap skip). 4 reviewers flagged same spot.
- [FIXED] M (senior-dev): live/rollup tiebreak divergence for ranked types with only off-ladder sources → unified JS collapse + rollup all-time SQL on `source` ASC (matches canonicalMeasurementsFrom + route CTE). Unit test updated.
- [FIXED] L (security L-1): stale `/^[A-Z_]+$/` doc comment in source-rank-sql.ts → `/^[A-Z0-9_]+$/`.
## MUST DO IN RELEASE COMMIT (product-lead M1)
- bump package.json 1.11.0→1.11.1 + `pnpm openapi:generate` (else openapi:check reds — v1.6.0/v1.8.5 trap).
## DEFERRED (Low — backlog, documented)
- code-review L-2 / fast-path redundant loadUserSourcePriority lookups (perf nit; thread userPriorityJson param) — defer.
- code-review L-3 / facts soft-cap drifts >50 (injection bounded top-8) — defer.
- code-review L-4 / route rollup read dropped take:cap (window-bounded) — defer.
- senior-dev L1 / 60s snapshot cache vs fact-delete (≤60s staleness) — CHANGELOG note.
- senior-dev L3 / groupBy=day list view sums all sources while chart is source-aware — defer + note (raw-data view vs canonical chart).
- senior-dev L4 / pre-existing delete-then-insert P2002 race widened by per-source range delete (queue retry mitigates) — defer.
- security Low-2/Info — central redaction covers worker err.message; background-only.
- CHANGELOG known-limitations: latest-tile canonical-source shift (intended R1) + 60s fact-deletion staleness.
## PENDING: read qa-simplifier.md + qa-i18n-deadcode.md when they land; reconcile any new Medium+.
## LAST 2 REVIEWERS (simplifier + i18n/knip) — reconciled
- [FIXED] HIGH (i18n/knip + simplifier S1): 3 net-new unused exports failing the enforcing knip Dead-code CI gate — SUMMARY_PROMPT_VERSION + SUMMARY_TARGET_CHARS (conversation-summary.ts) + FACTS_PROMPT_VERSION (facts.ts). Fix: deleted the 2 pure version constants (no consumer), and CONSUMED SUMMARY_TARGET_CHARS as a real safety cap on the stored summary length. Post-fix knip: 3 gone, exit clean. typecheck clean, 47 compute tests green.
- [DEFERRED — Low/perf, rationale] simplifier S2 / code-review L-2: the userPriorityJson load-once param is threaded by zero callers → fast-paths make 2-4 redundant loadUserSourcePriority lookups/request. Split rating (code-review Low, simplifier Medium); impact = sub-ms indexed PK reads, NOT correctness/security/safety; the param already exists for when it matters. Deferred to backlog to avoid ship-time scope creep across 3 loop sites.
- [DEFERRED — Low] simplifier: ExtractOpts.now dead field (facts.ts) — harmless forward-compat; stale measurement-read.ts docstring ("max count" vs source-name tiebreak) — cosmetic; residual hand-inlined canonicalMeasurementsFrom copy in summaries-slice — equivalent SQL. All Low, backlogged.
- i18n: CLEAN (zero new t() calls, no UI files, prompts server-composed). openapi:check IN SYNC.
## FINAL QA TALLY: 0 Critical / 0 High open / 0 Medium open. All Medium+ reconciled (decrypt isolation, tiebreak parity, knip unused exports). Lows deferred with rationale. SHIP-CLEARED.
+326
View File
@@ -1,5 +1,331 @@
# Changelog
## [1.11.2] — 2026-06-04 — Coach-memory controls, privacy hardening, more pinnable metrics
### Added
- **Review and clear what the Coach remembers.** A new "What the Coach remembers" settings section lists the durable facts the assistant has learned about you, grouped by category, and lets you forget a single one or clear all of them. Encrypted at rest; available wherever the Coach is enabled.
- **More dashboard metrics you can pin.** Cardio recovery, six-minute walk distance, stair ascent/descent speed, breathing disturbances, wrist temperature, fall count, and walking steadiness can now be pinned to your Home layout.
### Security
- **Outbound request hardening.** The AI provider clients (when pointed at a custom base URL) and the optional IP-geo lookup now reject any address that resolves to a private or internal host, closing a server-side request-forgery / DNS-rebinding gap.
### Fixed
- A rare write race when two updates recompute the same day's rollup at once is now handled cleanly instead of surfacing a transient error.
- Analytics fast paths resolve your source-priority preference once per request instead of repeatedly.
## [1.11.1] — 2026-06-04 — source-aware vitals + Coach long-term memory
Closes the three follow-ups left open by v1.11.0: cross-source vital de-duplication, the Coach's conversation memory, and durable personal facts.
### Added
- **Coach long-term memory.** The assistant now keeps a private, encrypted rolling summary of long conversations and remembers durable facts you have told it — standing preferences, goals, constraints, and conditions you have stated about yourself. Both are descriptive recall, never a diagnosis, and ride the same Coach setting; turning the Coach off stops all of it.
- **A facts surface to review and clear what the Coach has learned.** List your active facts, forget a single one, or forget everything (`GET` / `DELETE /api/insights/coach/facts`, `DELETE /api/insights/coach/facts/{id}`). Facts are stored encrypted at rest.
### Changed
- **Measurement rollups are now source-aware.** When two sources report the same standard vital on the same day (for example a resting heart rate from two devices), charts, summaries, and insights now show the higher-priority source's reading instead of a blend of the two. Cumulative metrics such as steps and energy continue to total per source. Your source-priority settings decide which reading wins.
### Notes
- The "latest" value shown for a vital with two competing sources now follows your source priority for the most recent day, so it matches the chart line. For some metrics this may surface a different device's reading than before.
- After clearing a Coach fact it can take up to a minute to disappear from the assistant's working context, in line with the existing snapshot refresh window.
- On first start after upgrading, each account's rollup cache is rebuilt once in the background; charts fall back to a live read until it converges.
## [1.11.0] — 2026-06-04 — WHOOP, a longitudinal coach, and a clinician-grade record
A multi-feature milestone across three fronts: a second connected provider, deeper Insights, and a shareable clinical record.
### Added
- **WHOOP integration.** Connect a WHOOP account with your own developer keys to bring its recovery, day- and workout-strain, sleep-performance, HRV (RMSSD), and energy readings into HealthLog alongside Apple Health and Withings — synced on a schedule and via signed webhooks, each value kept distinct by its source so it never overwrites a reading from another device.
- **A longitudinal Insights coach.** A weekly/monthly narrative summarises what changed over the period and the likely contributing factors (descriptive, never causal); the Coach now carries a rolling profile of your recent baselines and trends; and a short-horizon trajectory projection shows where a metric is heading with an honest, widening confidence band — shown only when there is enough history to mean something.
- **A clinician-grade health record.** A read-only FHIR REST API (`GET /api/fhir/*`) serves your data as standard FHIR R4 resources, and you can mint a scoped, time-limited, revocable share link that opens a clean read-only clinician view — no account needed. Wellness figures stay fenced off from the clinical ones with a plain "not a clinical assessment" note.
- **More resilient AI generation.** A durable provider-health record skips a known-bad credential instead of failing every run and surfaces an expired credential proactively, with a local model as a guaranteed fallback.
### Known limitations (planned follow-ups)
- When two sources supply the same standard vital (e.g. WHOOP and an Apple Watch both report resting heart rate), both readings may currently appear for a day until a source-aware aggregation update resolves them to your preferred source. WHOOP's own scores are unaffected; a note explains this on the WHOOP card.
- The coach reflects your rolling health profile and trajectory; full conversation-summary memory and saved personal facts are a later refinement.
## [1.10.4] — 2026-06-03 — Strain honesty + six-minute-walk caveat
### Changed
- **The Strain reading now says which scale it used.** When the score is anchored to your own recent training load it reads "relative to your typical effort"; while there is too little history and it falls back to a general reference, it says so — so the framing always matches the number actually shown.
- **The six-minute-walk band notes its reference range.** The reference equation was established for ages 40–80; outside that range the percent-of-predicted is now flagged as an extrapolation.
## [1.10.3] — 2026-06-03 — Personalised strain, a daily signal card, deeper derived metrics
### Added
- **A "Today's signal" card.** The coincident-deviation read — which notices when several of your vitals sit off their personal baseline at once — now leads the Insights overview as a calm daily card instead of a flag buried in the grid. It shows an all-clear on a normal day, names the vitals to keep an eye on when a few drift, and always frames them as possible factors, never a cause or a diagnosis.
- **Derived bands for more of what your watch measures.** Overnight wrist temperature and stair-climbing and stair-descent pace each get a personal typical-range band, and your device's estimated six-minute-walk distance is placed against a published reference for your age, height, weight and sex. Each is shown with its method and its cited standard, and only once there is enough history. They appear under a new "Mobility & body" group.
- **Trailing trend sparklines** on the derived tiles, drawn from the readings the tile already uses.
### Changed
- **The Strain score is now anchored to your own training load.** It reads how hard a day was relative to your own recent training-day effort rather than a fixed population figure, so a genuinely hard day reads high even while you are building back up; with too little history it falls back to a general reference and says so.
- Age-banded reference norms now interpolate across bracket boundaries instead of stepping, and the sleep midpoint is computed in your own timezone.
## [1.10.2] — 2026-06-03 — Honest AI connection test, consistent insights, retention re-enabled
### Fixed
- **The AI connection test now tells you what actually went wrong.** A failed test used to surface a cryptic parse error ("unexpected token") because the server answered with a gateway-level error page the settings screen could not read; worse, the test probed a different provider than the one your nightly insights are generated with, so it could report a problem with a fallback you do not even use. The test now always returns a readable, translated reason — rejected credentials, rate-limited, a provider server error, or unreachable — and it checks the same provider your insights run on, so the result is the truth about your setup.
- **Every insight metric page carries the same time-range controls.** The core-metric pages (weight, blood pressure, pulse, BMI, sleep) were missing the period selector that the other metric pages already had; they now match. Drill-down back-links are consistent and a "show all values" link returns you to the metric you came from.
- **The derived-metrics dashboard no longer collapses or jumps while loading.** It shows a placeholder row at the right height, keeps its heading hidden until there is something to show, and offers an inline retry if the data fails to load instead of silently vanishing.
- **More status colours meet contrast on the light theme** across the medication and admin surfaces.
### Changed
- **The intra-day retention drain is back on.** The storage optimisation behind the stress reading was switched off in 1.10.0.2 after a daily-summary collision kept the app cycling post-deploy. The fold now adopts the existing daily row deterministically and recovers cleanly if a concurrent write reaches the same slot first — verified against real data — and the start-up defer that protects the connection pool stays in place.
- **The batch-ingest and health-record export endpoints cap request-body size**, rejecting an oversized payload before parsing it.
### Added
- **A capability endpoint for API clients.** `GET /api/meta/capabilities` returns the server's live metric, tile, ingest and FHIR vocabularies alongside a contract version, so a client renders what it recognises and ignores what it does not — no more transcribing each release's new identifiers by hand.
## [1.10.1] — 2026-06-03 — Consistent medication cards
### Fixed
- **Every medication card looks the same now, whatever the type.** Oral, injection, GLP-1, as-needed, cyclic and one-time medications previously drew their "next / last intake" line, dose accent, spacing and compliance bars slightly differently, so cards in the same row could sit at different heights with the action buttons misaligned. The cards now share one layout: the same intake line, a reserved-height compliance area, and the take/skip buttons pinned to the bottom — so a row of mixed medications lines up cleanly. The dose accent also meets contrast on the light theme.
## [1.10.0.2] — 2026-06-03 — Disable the intra-day retention drain
### Fixed
- **Stops the post-deploy restart loop for good.** The intra-day retention drain (a storage optimisation behind the new stress reading) folded older samples into a daily summary, but on real data that summary collided with an existing daily row and the drain failed on every run, which kept the app cycling after a deploy. The drain is now switched off until it is reworked and tested against real data; the nightly pass is skipped, nothing is queued at start-up, and any work already queued completes harmlessly. No user-facing feature is lost — the stress reading simply falls back to its sparse-data behaviour.
## [1.10.0.1] — 2026-06-03 — Defer the intra-day retention drain past startup
### Fixed
- **The app no longer turns unresponsive shortly after a deploy or restart.** The new intra-day retention drain ran its catch-up pass the moment the background worker started, at the same time as the database migration, the other start-up backfills, and the first health checks — all sharing one connection pool. On an instance with a lot of history this exhausted the pool, so the app stopped answering until it restarted, then repeated. The catch-up now waits until start-up has settled before it runs; it is unchanged otherwise and the nightly pass is unaffected.
## [1.10.0] — 2026-06-03 — Derived wellness metrics, device-event awareness, deeper ingestion
### Added
- **Derived wellness metrics, each shown with how it is worked out.** From data you already sync, the Insights surface now derives a personal typical range for a vital, a cardio-fitness band, a vascular-age delta, an HRV (SDNN) balance read, body-mass index, a sleep score, a readiness index, and a coincident-deviation flag that notices when several vitals sit off their personal range at once. Every metric states its inputs, its method in plain language, and the published standard it is grounded in, with an honest read of how much data backs it — never a bare number. A metric appears only when there is enough history to mean something.
- **Recovery, Stress, and Strain scores, computed each night.** Recovery blends your resting-heart-rate, HRV, sleep and respiratory trends against your own baseline; Strain reads the heart-rate load of your workouts; Stress is an HRV-derived proxy and is labelled as exactly that — not a sensor-measured stress reading. Each is stored as a first-class value you can chart, and each opens to a breakdown of its contributors and its cited basis.
- **More of what your watch already measures.** Cardio recovery, overnight wrist temperature, fall count, six-minute-walk distance, stair ascent and descent speed, and the sleep breathing-disturbance index are now ingested and surfaced.
- **An awareness timeline for device-flagged events.** Irregular-rhythm, high- and low-heart-rate, walking-steadiness, and breathing-disturbance notifications your device produced are shown as a timeline — strictly as awareness of your own device's certified result, never re-assessed and never a HealthLog diagnosis, with a permanent disclaimer to that effect. The section stays hidden until there is something to show.
- **A per-workout heart-rate series**, so an indoor workout with no GPS still yields a training-load signal.
- **A wellness summary in the doctor report.** The derived scores and metrics appear in their own section, kept out of the clinical vitals table, labelled descriptive rather than clinical, and exported to FHIR as `survey`-category observations with the same note — so a clinician's system never mistakes them for a vital sign or a diagnosis.
### Changed
- **The health-record export carries richer medication codings.** A `MedicationAdministration` now adds a SNOMED route and injection-site coding alongside the existing plain text, a German-locale export can append the German BfArM ATC coding next to the unchanged WHO ATC entry, and the number of administrations an export can carry is raised and made configurable by the operator.
- **The Insights overview reads its metrics through a single request** instead of one per tile, so opening the page no longer fans out into a burst of concurrent reads.
- **Score-band colours meet contrast on the light theme**, and the device-notification copy — including its medical disclaimer — is translated across every supported language.
## [1.9.3] — 2026-06-02 — Medication card layout polish
### Fixed
- **The medication cards look right again.** A recent alignment change pushed each card's action buttons to the very bottom of the cell, which left an empty gap between a shorter card's content and its buttons when it sat next to a taller card in the grid. The buttons now sit directly under the card's content again; the cards still share a height and the dose rows still line up, without the gap.
## [1.9.2] — 2026-06-02 — Document the medication compliance endpoint
### Changed
- **The medication compliance endpoint is now in the public API contract.** `GET /api/medications/{id}/compliance` was missing from the OpenAPI document, so a client generating its types from the contract could mistake the separate cadence endpoint (a different shape) for it. The route is now documented with its exact response — the 7- and 30-day adherence summaries, the per-day compliance grid, and the two-row display block — with the field a client should read for the headline 30-day rate and how to draw the per-day history. No behaviour change; the handler was already correct.
## [1.9.1] — 2026-06-02 — No assessment warm on a page visit
### Fixed
- **Opening the Insights overview no longer regenerates every assessment.** A returning visit fired a one-per-session background warm that asked the provider to regenerate the comprehensive briefing and every category and metric assessment at once — a burst that could run for minutes and make the whole app feel unresponsive while it ran, recovering on its own once it finished. Assessments are kept fresh by the nightly pass, and each metric's text refreshes gently on its own when you open it; the "prepare assessments" button still regenerates everything on demand. A page visit now only reads the cached text.
## [1.9.0] — 2026-06-02 — Insights time-ranges, deeper mood, medication coding, stability
### Added
- **A time range you can choose on the Insights pages.** Each metric now carries range pills (week, month, quarter, year) and shows how the period compares with the one before it — the change in your average, stated plainly with its direction — so a trend reads at a glance instead of by eye.
- **Deeper mood insights.** The mood page now surfaces your time-of-day pattern (when your mood tends to sit highest and lowest), a stability read, and correlation cards that line mood up against weight and blood pressure — each shown only when there are enough paired days to mean something.
- **Standard drug codes on a medication.** A medication can carry an ATC and an RxNorm code (entered, never guessed). These flow into the health-record export: the exported `MedicationStatement` now codes the drug with the WHO ATC system and RxNorm alongside the plain name, and the export adds a `MedicationAdministration` for every dose you actually took or skipped, so a clinician's system can read the record without relying on free text.
- **A deploy-verification script** (`scripts/assert-deploy.ts`) that checks a target reports the expected version after a release.
### Changed
- **The medication advanced-settings page is rebuilt.** Import, intake-import and export sit in their own group, the external-API endpoints are listed one by one with collapsible request examples, and the layout is tidied so the technical settings read clearly instead of crowding together.
- **Targets are edited inline where they belong.** The separate `/targets` page is retired — you set a metric's target range from the metric itself, with no detour to a standalone editor.
- **The health-record export emits insurer coverage from a bare insurance number**, not only when a full insurer organisation is present, and carries a top-level narrative summary.
- **Notification settings wording** is tightened for clarity.
### Fixed
- **The app stays responsive under load.** The database connection pool was sized far too small by default and could starve while a background insight warm and a foreground request competed, which showed up as the occasional "server not responding" that recovered on its own; the pool is now sized for real concurrency and tunable for larger self-hosts.
- **A background insight warm no longer blocks a page**, and a burst of Apple Health / Withings sync no longer triggers a storm of regenerations — the warm is decoupled and the invalidation is debounced.
- **The medication card rows stay aligned.** "Last dose" and "next dose" could break onto different heights and look misaligned; the rows now hold an equal height.
- **Glucose entered in mmol/L converts correctly** in the editor instead of being stored against the wrong unit.
- **The admin and global layout no longer shifts** when a scrollbar appears, by reserving the gutter.
- **The legacy status endpoints are documented** — six older `*-status` routes were missing from the API contract and are now included.
## [1.8.7.1] — 2026-06-02 — Assessments for every HealthKit metric, one-tap pre-generation
### Added
- **A plain-language assessment on every HealthKit metric page.** The HealthKit metric pages (resting heart rate, heart-rate variability, blood oxygen, glucose, body composition, gait, audio exposure, sleep, and the rest) showed charts but no written assessment, because the core metrics' bespoke per-metric prompts don't scale to thirty more. Each page now carries an assessment, generated from the metric's own normal range and the direction a healthy value moves, anchored on your individual baseline — the same treatment the core metrics already had. A metric with no data keeps its existing insufficient-data note.
- **One-tap pre-generation of every assessment.** A button on the Insights overview generates all assessments in the background so they are ready immediately the next time you open them. The overview also warms a cold cache on its own, and the nightly pass keeps everything fresh — so a page opens to its assessment instead of a wait.
### Changed
- **"Auswertungen" is now "KI-Auswertungen" / "AI Insights"** in the settings heading and the menu, so it's clear the section is AI-generated.
- **Targets and Sources are two separate settings pages** instead of one combined page, each with its own heading.
- **The back link sits above the heading** on a metric's detail page.
- **Dropdown fields have symmetric padding**, so the chevron no longer crowds the right edge.
- **The Insights layout accepts the full metric set**, so a saved layout (order and visibility) can include every metric page, not just the core ones.
### Fixed
- **Assessments generate again.** The assessment provider's accepted model identifiers had rotated, so generation failed and an assessment could sit on "preparing" indefinitely; the model ladder is updated and falls through to the current identifiers.
- **The Active Energy assessment loads.** Its page requested an assessment under a mismatched identifier and silently fell back to "no analysis yet"; the identifier is corrected and now type-checked, so the same class of mismatch is caught at build time.
- **The source-priority editor is fully translated** for Spanish, French, Italian and Polish — it was English-only after the settings split.
## [1.8.7] — 2026-06-02 — Instant insight assessments, GLP-1 blood-level chart, tile + caption polish
### Fixed
- **Insight assessments are instant again.** A category's assessment was being re-prepared on almost every visit: the constant Apple Health / Withings sync kept evicting the cached text, and a miss only ever deleted-and-waited. Assessments now serve the last good text immediately (stale-while-revalidate) and refresh in the background — "preparing" shows only when an assessment has genuinely never been generated. The background refresh is also debounced per metric, so a sync burst no longer triggers a storm of regenerations, and it warms only the active language (halving the work).
- **The dashboard tiles never truncate the value.** In a dense tile strip the number could clip or wrap mid-value (e.g. "130 mmHg" showing as "13"); the value now always renders in full and the unit yields the space instead.
- **GLP-1 medications show the drug-level-in-blood estimate by default.** The estimated concentration curve was hidden behind the Research-Mode opt-in and below the dose-strength curve; for GLP-1 medications it now shows by default, above the dose-strength curve, with the "educational estimate, not a measurement" disclaimer kept clearly attached.
- **The Trends captions read consistently.** Metrics without an advisor note previously rendered their caption in a different, plainer style that broke the row; every Trends caption now uses the same treatment.
### Changed
- **The mood assessment sits directly under the first chart** on the mood insights page.
## [1.8.6] — 2026-06-01 — Compliance two-row return, insights polish, targets deprecation
### Added
- **Mood narrative takeaways above the charts** — a ranked feed of plain-language findings (the weekday your mood dips, the overall trend, the tags that lift or lower it, your in-target share, your logging streak, the weekend effect), now drawing on the structured tags as well as free-text ones.
- **A GLP-1 dose-strength curve** that plots the titration history (2.5 → 5 → 7.5 mg …) in place of the previous empty therapy-course block.
- **A FHIR `Coverage` resource in the health-record export**, with an optional insurer institution number (IKNR) captured on the profile — making the insurer machine-resolvable for German systems.
- **An optional `source` on the measurements batch endpoint**, so a client backfilling manually-entered history can tag it correctly instead of defaulting to Apple Health.
### Changed
- **Medication compliance returns to two rows for every medication.** The cadence-aware timeline is gone; the two windows now scale to how often a medication is due — a daily medication keeps 7-day and 30-day, a rarely-taken one steps up to longer windows (up to twelve months) so both rows stay meaningful and the layout stays steady.
- **The medication advanced settings are a single, calmer column** with a symmetric danger zone (matched delete-history / delete-medication actions), replacing the cramped two-column layout.
- **The medication wizard uses a jumpable dot stepper** with a "next step" hint; in edit mode every step is reachable in one tap.
- **Insights category headers are quieter.** The question-mark circle is gone (the metric definition stays inline beneath the heading), the measurement-diversity hint moved to a heading lightbulb with the explanation on hover, the assessment border is de-emphasised, and "Coach fragen" moved to the header as an icon.
- **Target ranges are now edited inline from Insights.** The Targets page is deprecated — it carries a notice, is removed from the menu, and will be retired in a future release; editing happens where you read the trend.
### Fixed
- **Every briefing-driven Trend card now shows its caption** — additive metrics no longer render a chart with empty space below it.
- **A long mood note no longer stretches the entries table** — it truncates with the full text on hover.
- **The mood in-target share is shown once**, not duplicated between the headline tile and the takeaway feed.
- **Medication compliance no longer counts days before a medication existed**, so a newly-added medication's expected-dose figures reflect its real age.
## [1.8.5] — 2026-06-01 — Insights reference panels, mood depth, injection tracking
### Added
- **A target reference panel on every Insights category page.** Each metric now shows the target band, where the latest reading sits inside it, a plain-language status, the guideline source behind the range, the 30-day average and a seven-day consistency strip — the same reference the Targets page carries, now on the page where you read the trend. Blood glucose surfaces one panel per context (fasting, post-meal, random, bedtime).
- **A statistics strip per metric** — minimum, maximum, median and mean — plus a dedicated page that lists every underlying reading with edit and delete, reachable from each Insights category.
- **Injection-site tracking and rotation.** Opt-in per medication (injections only): record the site after a dose, see the history on a body map, and get a rotation suggestion. Sites can be restricted per medication, and an account-level exclusion always wins.
- **Structured mood tags and a per-entry note**, with a notes timeline so the context behind a mood is kept alongside the score.
- **A richer mood page** — calendar heatmap, score distribution, weekday pattern, and correlations with sleep and activity.
- **A measurement-diversity nudge** that suggests logging at other times or days when readings cluster, for a fuller picture.
### Changed
- **The medication compliance display adapts to how often a dose is due** — a percentage for frequent schedules, a dose-by-dose adherence timeline for sparse ones, so an every-few-weeks medication reads sensibly.
- **The Trends section now follows the daily briefing**, charting the metrics the briefing actually flags rather than a fixed set.
- **Tightened the Insights category pages and rebalanced the overview** for a denser, calmer layout.
- **Gait and mobility metrics from Apple Health are consolidated to a daily mean overnight**, while discrete clinical readings (weight, blood pressure, glucose, mood, pulse) stay raw.
- **The health-record FHIR export codes HealthKit-only metrics under a dedicated code system** instead of the LOINC namespace, for FHIR R4 conformance and alignment with the native client.
### Fixed
- **A rolling-interval medication now surfaces its first dose at the start date** — including when that date is already in the past — so the dashboard and reminders no longer skip the opening dose.
- **The medication wizard no longer shows each time-of-day suggestion twice.**
- **Deleting a medication no longer hangs on a spinner.**
- **Mood entries with tags save atomically** — the entry and its tags commit together, and create and update return the saved tags immediately rather than after a refresh.
- **Accessibility:** the injection-site picker has a visible focus state and screen-reader labels; mood tag chips and the status pill meet the contrast and minimum tap-target guidelines.
## [1.8.4] — 2026-06-01 — Medication card accuracy + Insights polish
### Fixed
- **The medication card shows the correct next intake for every schedule.** Flexible "interval after the last dose" and one-time medications previously showed a next-intake derived from a simplified day-of-week rule that ignored the interval and the last logged dose — so a medication taken every few weeks proposed tomorrow and never moved after a dose was logged. Both the standard and the injection card now read the schedule engine's computed next-due, so the next intake is right on creation and advances the moment a dose is recorded.
- **Insights status polling is bounded.** When a model is configured but generation stalls, the per-category assessment card no longer polls indefinitely on an open page — it stops after a fixed ceiling and shows its static state.
- **Clean deploys no longer hit a missing settings column.** Four `app_settings` columns existed in the schema but had only ever been applied ad-hoc, so a migrations-only deploy could fail on first read; an idempotent migration now adds them (a no-op on instances that already have them).
### Changed
- **Logging a dose confirms itself.** Marking a medication taken or skipped now shows a brief confirmation, and the card's next-intake updates immediately.
- **Each Insights category explains itself inline.** The short metric definition now also appears as a caption under the category heading, alongside the existing question-mark tooltip.
- **Medication history shows where each dose was logged** — web, the iOS app, a reminder, or an import — as a small origin label on each entry.
## [1.8.3] — 2026-06-01 — Insights no longer block the interface
Opening an Insights category and switching between them could freeze the whole interface for several seconds while the per-category assessment was generated. The interface now stays responsive throughout.
### Fixed
- **Switching Insights categories no longer freezes the interface.** Each category's short assessment is now served from cache as an immediate, read-only response; when it is not yet ready the page shows a brief preparing state and the assessment is generated in the background, so navigation and taps stay responsive. The client request is capped, so a slow or unreachable model can never block the interface — the worst case is a preparing state, never a frozen screen.
- **The overnight pre-generation warms the assessment actually shown.** The nightly warm pass keyed its cache differently from what the page requests, so a returning visit often fell back to an on-demand generation; it now warms the languages the interface uses and runs even when the daily summary was already cached, so a returning visit lands on a ready assessment.
- **A stalled model no longer re-blocks every visit.** A generation timeout is briefly remembered so the next visits return immediately instead of retrying the slow path each time.
- **Streamed loading states.** Insights and the dashboard now render a skeleton while their first segment loads, rather than waiting on a blank transition.
## [1.8.2] — 2026-06-01 — One intake row per dose slot
A multi-time medication could end up with two entries for the same dose — one still open, one marked taken — for a dose the user had not taken. This release guarantees a single entry per scheduled dose.
### Fixed
- **A dose slot can no longer hold a duplicate entry.** Logging a dose now updates the slot's existing entry in place instead of inserting a second row, regardless of where the log came from, and the logged time is aligned to the scheduled dose rather than the exact moment of the tap. A twice-daily medication no longer shows the same time twice (once open, once taken), the daily count is no longer inflated, and the "due now" prompt is no longer suppressed for a dose that has not actually been taken.
- **A recorded dose is never silently un-recorded.** A background re-sync that replays an open dose onto a slot already marked taken is now ignored rather than clearing the taken mark, so an offline sync can never flip a taken dose back to missed.
- **Concurrent logs converge.** Two logs landing on the same dose at once resolve to one entry instead of failing or duplicating.
- **Existing duplicates are cleaned up on startup.** A one-time pass collapses any duplicate dose entries already stored, keeping the recorded dose and correcting the affected compliance figures.
## [1.8.1] — 2026-06-01 — Multi-time medication compliance
A follow-up to the multi-time compliance work in 1.7.3, closing the two surfaces it did not reach.
### Fixed
- **Every scheduled time of a multi-time medication is now loggable** — a medication taken more than once a day on a single schedule with several times (e.g. 07:00 and 19:00) surfaced only its first dose in the today tile and the logging sheet, so the second dose could never be recorded and the day's compliance was counted against a single expected dose. The today-window projection now creates one pending dose per scheduled time, matching how reminders are issued.
- **The compliance heatmap classifies each dose against its own time** — a twice-daily dose logged in the evening was measured against the morning time and read as very late, painting the day amber even when both doses were taken on time. Each logged dose is now matched to its nearest scheduled time, so a day with every dose taken on time reads as on time. Single-time schedules are unaffected.
## [1.8.0] — 2026-05-31 — Insights: reliable data-driven assessments, embedded targets, explainers
The per-metric Insights pages become the coherent heart of the app. The data-driven assessment — a short, honest reading of your own trend — now reliably reaches the page: it previously timed out and cached a generic placeholder for the rest of the day, so most users only ever saw the platitude. The generation budget is aligned with the provider, the placeholder is never cached, and the AI payload is compressed into a graded shape (recent days raw, then weekly, monthly, and yearly aggregates drawn from the rollup tier) so a heavy logger no longer ships thousands of raw points. Each metric's prompt is rewritten to a consistent house style — name the finding, place it against your own baseline, offer one concrete step; honest on poor values, never alarmist, never diagnostic. Target ranges move onto each category page beside the chart, every category gains a plain-language "what is this?" tooltip, and the assessment is warmed overnight so the page is a cache read instead of a live call. Route slugs and tile ids move to English (German tile ids stay accepted as aliases, so existing clients keep working).
### Added
- **Per-category target ranges** — each Insights category page shows its numeric target range and the share of recent days within target, beside the chart and the assessment, with a link to adjust the range. The dedicated targets page remains the editing surface.
- **Per-category explainer tooltips** — a question-mark affordance next to every category heading opens a short, plain-language definition of the metric, available offline in all six languages and reachable by keyboard and touch.
- **Nightly assessment pre-generation** — a budget-gated overnight job warms the per-metric assessment caches (and invalidates them when fresh measurements arrive), so opening a category page is a cache read rather than a synchronous model call.
- **Graded measurement compression for assessments** — a shared compressor folds a metric's history into recent (daily), weekly, monthly, and yearly buckets, drawing the monthly/yearly tiers from the rollup store, so the model receives a compact picture instead of the full daily series.
- **Naming decision record** — `docs/adr/0001-insights-naming-convention.md` documents the convention: localised UI, English internal keys and route slugs.
### Changed
- **Data-driven assessments reach the page reliably** — the per-metric assessment generation budget is aligned with the provider (was capped well below the provider floor), runs through the provider chain with fallback, and a transient timeout or error is treated as a passing miss rather than cached as a placeholder for the rest of the day.
- **Assessment wording** — every metric prompt follows one house style (name → place against own baseline → one actionable step; 2–4 sentences; honest, autonomy-supporting, non-diagnostic; says so plainly when the data is too thin). Blood pressure reads systolic and diastolic together; weight tracks the trend while BMI speaks to threshold bands; the mood assessment carries a calm support cue on a sustained low.
- **Insights route slugs are English** — `/insights/<german>` moves to `/insights/<english>` with permanent redirects from the old paths. The dashboard-layout tile ids are English canonically; the previous German ids stay accepted as aliases and are normalised on read and write, so a client that stored the old ids keeps working.
- **Per-metric assessment caches drop on measurement changes** — a fresh, edited, or deleted measurement invalidates the affected category's cached assessment so it regenerates rather than serving a stale reading.
## [1.7.3] — 2026-05-31 — Health-record PDF fixes, multi-time compliance
Two fixes to live behaviour.
### Fixed
- **Health-record export renders in the account language** — the PDF came out in English regardless of the in-app language because the export only consulted the browser's `Accept-Language`. The client now sends the active language and the server falls back to the language cookie before the browser header.
- **Health-record export layout** — charts now label their time axis (start and end date of the plotted window), modules are kept together instead of breaking across a page, a consistent bottom margin is held on every page, and a glyph-encoding issue that stretched a few lines (trend arrows and the `m²` unit) is resolved by sanitising to the font's supported characters.
- **Compliance counts every scheduled time on multi-time plans** — a medication taken twice a day on a weekday plan with two times but no recurrence rule reported 50% even when both doses were logged: the expected-dose count and the taken count expanded the schedule through two different code paths. Both now run through the one canonical recurrence engine, so the rate is correct for every schedule shape.
## [1.7.2] — 2026-05-31 — Coach source parity, first-paint snapshot, medication card cleanup
A focused follow-up to v1.7.0. The unified dashboard snapshot that shipped in v1.7.0 is now the default, so a cold dashboard paints its above-the-fold tiles together instead of letting the mood tile arrive ahead of the rest. The Coach's in-chat data-source rail now reads and writes the same persisted data clusters as the settings sheet — one source of truth that survives a reload, so what the panel shows always matches what reaches the model. The medication overview cards collapse their action row into a single overflow menu, and the detail page is pared back to the intake history under a read-only plan summary. The advanced-settings sheet widens into a two-column layout and offers a medications export beside the existing import.
+7 -5
View File
@@ -18,11 +18,13 @@ If a draft commit message or release note would violate one of the three, rewrit
## Branch and release model
- `main` is release-only. Every commit on `main` is either a release commit (`chore(release): vX.Y.Z`), the matching tag push, or a maintenance commit (docs, gitignore, audit findings) that the maintainer chose to apply directly.
- Feature work targets the `develop` branch via topic branches (`fix/X`, `feat/X`), merged into `develop` through PRs with green CI.
- Releases merge `develop` → `main` (squash or merge-commit, document each), then a tag push (`v1.X.Y`) triggers the `docker-publish.yml` workflow.
- Hotfixes branch from `main`, merge back into both `main` and `develop`.
- Never force-push `main`. Never skip hooks (`--no-verify`). Never `--no-gpg-sign` unless explicitly asked.
`main` is the single trunk and is always releasable. There is no long-lived `develop` branch — the former one was retired and archived as the tag `archive/develop-pre-v1.5` (it carried no work absent from `main`; a long-lived integration branch has no role in a single-maintainer shop and only accrued back-merge debt). This is trunk-based development with release tags: short-lived branches off `main`, work always converges back onto `main`, and the immutable `vX.Y.Z` image built from a tag on `main` is the one source of truth — including for the OpenAPI contract the iOS client consumes.
- **Trunk.** `main` always builds, passes CI, and is deployable. Every commit on it is a release commit (`chore(release): vX.Y.Z`), a release-branch merge, or a maintenance commit (docs, gitignore, audit findings) applied directly.
- **A release** is built on a short-lived `release/vX.Y.Z` branch cut off `main` — built wave-by-wave, then opened as a PR `release/vX.Y.Z` → `main` with green CI, merged (merge-commit), and tagged `vX.Y.Z`. The tag push triggers `docker-publish.yml` (GHCR multi-arch + `:latest`). Deploy is manual (see `docs/ops/deploy.md`); after a deploy, verify `/api/version` (it returns `version` + `buildSha` + `builtAt`) on every target, since the `:latest` pull is the source of truth, not the queued deploy status. Delete the release branch after merge.
- **Small standalone changes** (a single fix, a docs touch) can go through a short-lived `fix/X` / `feat/X` branch + PR, or directly onto `main` when the maintainer chooses — `main` is the target either way.
- **Hotfixes** branch from `main` and merge straight back to `main`. There is no second long-lived line to forward-port to, so the old back-merge debt cannot recur by construction.
- Never force-push `main` or any release branch. Never skip hooks (`--no-verify`). Never `--no-gpg-sign` unless explicitly asked.
## Semver
+49 -7
View File
@@ -21,7 +21,7 @@
<p align="center">
Self-hosted health tracker. Weight, blood pressure, glucose, mood, medications.<br/>
Withings and Apple Health sync, multi-provider AI Insights you own, doctor-report PDF.
Withings, WHOOP, and Apple Health sync, multi-provider AI Insights you own, doctor-report PDF.
</p>
<p align="center">
@@ -36,9 +36,9 @@
## What it is
HealthLog is a self-hosted personal health tracker that runs from a single `docker compose up`. It covers the metrics most people actually log -- weight, blood pressure, pulse, body composition, blood glucose, sleep, mood, and medication compliance -- and brings them together in one dashboard with reference ranges from ESH 2023, ADA 2024, and NICE NG115. Withings devices sync automatically; an `export.zip` import folds your full Apple Health history into the same timeline; a native SwiftUI iOS client (public-beta via [TestFlight](https://testflight.apple.com/join/bucuTBpa)) streams HealthKit live; multi-provider AI Insights (BYOK or local) explain what the numbers mean; a doctor-report PDF generates client-side. EN/DE end-to-end. AGPL-3.0.
HealthLog is a self-hosted personal health tracker that runs from a single `docker compose up`. It covers the metrics most people actually log -- weight, blood pressure, pulse, body composition, blood glucose, sleep, mood, and medication compliance -- and brings them together in one dashboard with reference ranges from ESH 2023, ADA 2024, and NICE NG115. Withings and WHOOP devices sync automatically over OAuth2; an `export.zip` import folds your full Apple Health history into the same timeline; a native SwiftUI iOS client (public-beta via [TestFlight](https://testflight.apple.com/join/bucuTBpa)) streams HealthKit live; multi-provider AI Insights (BYOK or local) explain what the numbers mean; a doctor-report PDF generates client-side. EN/DE end-to-end. AGPL-3.0.
> **Status**: active. New releases roughly weekly -- see [CHANGELOG](CHANGELOG.md). Current line: v1.7 — health-record export (PDF + FHIR R4), flexible medication schedules, full HealthKit metric coverage, and a first-paint dashboard snapshot. The native iOS client is public-beta via [TestFlight](https://testflight.apple.com/join/bucuTBpa).
> **Status**: active. New releases roughly weekly -- see [CHANGELOG](CHANGELOG.md). Current line: v1.10 — a derived-metrics tier (fitness-age, vascular-age delta, HRV balance, sleep score, readiness and recovery scores, an early-strain flag), each computed from your own measurements and citing its inputs, on top of the v1.7 health-record export (PDF + FHIR R4), flexible medication schedules, and full HealthKit metric coverage. The native iOS client is public-beta via [TestFlight](https://testflight.apple.com/join/bucuTBpa).
> **Heavily developed.** HealthLog ships multiple releases per week. Behaviour, API shapes, and database schema can change between minor versions; migrations are forward-only and not all are rehearsed against every legacy fixture. If you self-host, pin a tag, take a backup before every upgrade, and read the [CHANGELOG](CHANGELOG.md) before pulling `latest`. Issue reports and PRs welcome — this is the rough edge where the project gets sharper.
@@ -60,12 +60,26 @@ Most health apps lock your data behind proprietary clouds, push subscriptions, a
| Open source | AGPL-3.0 | No | No | No | n/a |
| Withings device sync | Yes (OAuth2) | Yes (native) | Via shortcut | No | No |
| Apple Health import | Yes (`export.zip`) | No | Native | No | Manual |
| Blood pressure + glucose | First-class | BP only | Manual | No | Manual |
| Medication compliance | Cadence-aware | No | No | No | Manual |
| Derived wellness metrics | Yes (transparent) | Limited | Limited | Yes (closed)| No |
| Custom clinician targets | Yes (audit-logged) | Limited | No | No | n/a |
| Doctor-report PDF | Yes (client-side) | No | No | No | n/a |
| Doctor-report PDF + FHIR | Yes (client-side) | No | No | No | n/a |
| AI Insights | Multi-provider BYOK | No | Limited | Subscription| n/a |
| Subscription required | No | For some metrics| No | Yes | No |
| Your data leaves device | Never | Withings cloud | Apple cloud | Oura cloud | Depends |
### Versus WHOOP / Oura / Fitbit ecosystems
The wrist-band ecosystems are good at what their hardware measures, and HealthLog does not try to be a ring or a strap. It does not ship a sensor, and it does not claim to match one. What it does is take the readings those devices already collect — plus the ones they don't hold, like cuff blood pressure, finger-stick or CGM glucose, and medication intake — and keep them on a server you run.
- **You own the data and the host.** No vendor account, no cloud round-trip, no subscription tier gating a metric you already recorded. AGPL-3.0, single `docker compose up`, encrypted at rest, on your NAS / homelab / VPS.
- **It aggregates across providers instead of locking you to one.** Withings devices sync over OAuth2, an Apple Health `export.zip` folds your full history in, and the native iOS client streams HealthKit live — so a Withings scale, an Apple Watch, and a glucometer land on one timeline instead of three apps.
- **It carries context the wrist bands don't.** Blood pressure, blood glucose, body composition, and cadence-aware medication compliance sit next to the wearable signals, so a trend reads against the whole picture rather than activity and sleep alone.
- **The derived metrics are transparent, not a black box.** HealthLog computes a fitness-age and vascular-age delta, an HRV-balance and sleep-score band, a daily readiness and recovery score, and a coincident-deviation early-strain flag — each from your own measurements, each citing the inputs and the published method behind it, each degrading honestly to "not enough data" rather than fabricating a number. These are descriptive wellness framings, not clinical or training-grade assessments, and a score is only stored once its minimum inputs are present.
HealthLog is the right fit when you want your wearable and clinical numbers in one place that you control, with explainable analytics on top — not when you want a closed device that scores you and keeps the data.
---
## Key Features
@@ -84,12 +98,16 @@ Most health apps lock your data behind proprietary clouds, push subscriptions, a
**Apple Health import** -- Drop your iOS `export.zip` on the import page. A streaming parser handles multi-gigabyte archives (Zip64), folds every `<Record>`, `<Workout>`, `<Correlation>`, and `<ClinicalRecord>` into the same timeline as your other metrics, and stays idempotent on re-upload. Per-type ingestion stats plus a live status endpoint so you can watch the progress on a long historical drain.
**AI Coach + Insights** -- A conversational Coach grounded in your own data, a daily briefing, a weekly report, and a Health Score tile on the dashboard. Pick OpenAI, Anthropic Claude, ChatGPT via Codex device-OAuth (no API key needed), or any OpenAI-compatible local endpoint (Ollama, LM Studio, vLLM). BYOK or admin-shared. Feed the Coach a chosen set of data clusters (cardiovascular, body composition, activity, workouts, sleep, mood, glucose, medication, mobility, environment) with a soft budget cap that degrades the lowest-signal clusters first. Every claim links back to the measurements that produced it. Local endpoints keep all data on your network.
**AI Coach + Insights** -- A conversational Coach grounded in your own data, a daily briefing, a weekly report, and a Health Score tile on the dashboard. Pick OpenAI, Anthropic Claude, ChatGPT via Codex device-OAuth (no API key needed), or any OpenAI-compatible local endpoint (Ollama, LM Studio, vLLM). BYOK or admin-shared. Feed the Coach a chosen set of data clusters (cardiovascular, body composition, activity, workouts, sleep, mood, glucose, medication, mobility, environment) with a soft budget cap that degrades the lowest-signal clusters first. Every claim links back to the measurements that produced it. The Coach now reads your history longitudinally — a narrative of how a metric has moved and a per-metric trajectory framing — so an answer reflects the direction of travel rather than only the latest reading. Local endpoints keep all data on your network.
**Derived wellness metrics** -- A transparent metrics tier computed from your own measurements: a fitness-age band from VO₂max, a vascular-age delta, an HRV-balance band, a sleep score, a daily readiness and a stored recovery score, plus a coincident-deviation early-strain flag. Each one re-frames or blends signals you already recorded against age/sex norms or your personal baseline, cites the inputs and the published method behind it, and returns "not enough data" rather than a fabricated value when its minimum inputs are missing. The recovery score persists as a daily 0–100 series the dashboard, charts, and native client read without recomputing. These are descriptive wellness framings — not clinical or training-grade assessments.
**Doctor Report PDF Export** -- Generate professional medical reports client-side. Locale-aware (English/German), with vital sign summaries, BP/BMI/glucose classification, compliance rates, custom-threshold badges, and optional AI analysis.
**Health-record export (PDF + FHIR R4)** -- `POST /api/export/health-record` produces a selectable export: an enriched clinical PDF, a machine-readable HL7 FHIR R4 document bundle (LOINC-coded observations, a BP panel, medication statements, a diagnostic report), or both packaged as one zip. The selection chooses date range and per-domain sections; both formats read the same aggregator so they describe identical numbers, and the optional AI summary is an explicit opt-in section marked as not clinically validated. Optional patient identity (name, insurer, insurance number) on Account feeds the report cover and the FHIR `Patient`.
**Clinician-grade FHIR API + shareable record** -- A read-only HL7 FHIR R4 REST API (`GET /api/fhir/{metadata,Patient,Observation,MedicationStatement,MedicationAdministration,$everything}`) lets a clinician system pull your record in a standard shape, gated behind a dedicated `fhir:read` token scope. Alongside it, a shareable clinician record: create a scoped, time-limited share link, hand a clinician the read-only `/c/<token>` view, and revoke it when the visit is over. The two are not yet wired together — a share link does not expose the FHIR API (`capabilities.share.fhirApi=false`) — but each stands on its own.
**Built-in Feedback** -- Send bug reports and feature requests from inside the app. Stored in your HealthLog database — no GitHub config required. Optional GitHub escalation for admins.
**PWA with Offline Support** -- Installable on iOS and Android. Service worker with intelligent caching strategies for reliable offline access. A paginated, opaque-cursor sync delta feed (`GET /api/sync/changes`) with measurement tombstones lets native and offline clients reconcile against the server incrementally.
@@ -197,6 +215,8 @@ HealthLog is designed for people who take data ownership seriously.
| `WITHINGS_CLIENT_SECRET` | Withings OAuth2 client secret |
| `WITHINGS_REDIRECT_URI` | OAuth callback URL |
| `WITHINGS_WEBHOOK_SECRET` | Webhook URL hardening secret |
| `WHOOP_REDIRECT_URI` | WHOOP OAuth callback URL (client id/secret set in Settings) |
| `WHOOP_WEBHOOK_SECRET` | HMAC secret for WHOOP webhook signature verification |
| `TELEGRAM_WEBHOOK_SECRET` | Telegram bot webhook secret |
Telegram bot token, ntfy settings, Web Push VAPID keys, Umami, and GlitchTip URLs are configured in the **Admin Panel** and stored encrypted in the database.
@@ -421,6 +441,24 @@ All mutations require authentication via session cookie. External ingest uses Be
</details>
<details>
<summary><strong>FHIR + clinician sharing (v1.11)</strong></summary>
Read-only HL7 FHIR R4 REST API, gated behind the `fhir:read` token scope:
| Method | Endpoint | Description |
| ------ | -------------------------------------- | ---------------------------------------------------- |
| `GET` | `/api/fhir/metadata` | FHIR CapabilityStatement |
| `GET` | `/api/fhir/Patient` | Patient resource for the token's user |
| `GET` | `/api/fhir/Observation` | Vitals + labs as LOINC-coded observations |
| `GET` | `/api/fhir/MedicationStatement` | Medication regimen |
| `GET` | `/api/fhir/MedicationAdministration` | Logged intake events |
| `GET` | `/api/fhir/$everything` | Bundle of every resource above |
Clinician share-link lifecycle — create a scoped, time-limited link, hand a clinician the read-only `/c/<token>` view, and revoke it after the visit. Share links do not expose the FHIR API (`capabilities.share.fhirApi=false`).
</details>
---
## Integrations
@@ -428,6 +466,7 @@ All mutations require authentication via session cookie. External ingest uses Be
| Integration | Setup | Purpose |
| --------------- | ------------- | ---------------------------------------- |
| **Withings** | Env vars | Auto-sync weight, BP, and activity |
| **WHOOP** | User Settings | OAuth2 sync of recovery, strain, and sleep (BYO-keys) |
| **Telegram** | Admin Panel | Medication reminders with inline buttons |
| **ntfy** | User Settings | Self-hosted push notifications |
| **Web Push** | Admin Panel | Browser-native VAPID notifications |
@@ -488,9 +527,12 @@ For a single-process default the same container hosts both the web and worker (`
| ------------ | ----- |
| **v1.4.x** | Web maturity — Apple Health import, AI Coach, persistent rollup tier, multi-provider AI, doctor PDF, encryption-key rotation, Coolify autodeploy. Roughly weekly cadence. |
| **v1.5** | Native iOS client (SwiftUI) in public beta via [TestFlight](https://testflight.apple.com/join/bucuTBpa). Backend contract locked in [`docs/api/openapi.yaml`](docs/api/openapi.yaml); the iOS app lives in a separate repository and ingests via the same `/api/measurements/batch` and `/api/auth/refresh` surfaces the web uses. |
| **v1.6 – v1.7** (current) | Medication editor overhaul + route of administration (v1.6), then health-record export (PDF + HL7 FHIR R4), flexible schedules (RRULE / rolling / interval-weeks / one-time / PRN / cyclic) with cadence-canonical compliance, full HealthKit metric coverage, a metric/imperial display preference, a first-paint dashboard snapshot, and a sync delta feed for offline clients (v1.7). |
| **v1.6 – v1.7** | Medication editor overhaul + route of administration (v1.6), then health-record export (PDF + HL7 FHIR R4), flexible schedules (RRULE / rolling / interval-weeks / one-time / PRN / cyclic) with cadence-canonical compliance, full HealthKit metric coverage, a metric/imperial display preference, a first-paint dashboard snapshot, and a sync delta feed for offline clients (v1.7). |
| **v1.8 – v1.10** (current) | Insights redesign with selectable time ranges (v1.8 – v1.9), then a derived-metrics tier (v1.10): fitness-age, vascular-age delta, HRV balance, sleep score, readiness and recovery scores, and a coincident-deviation early-strain flag — each computed from your own measurements, each citing its inputs and degrading to "not enough data" rather than fabricating a value. |
| **v2.x** (planned) | Multi-tenant hardening, expanded device passthrough (Garmin / Polar), opt-in cross-user aggregate research mode (off by default; never enabled without explicit consent). |
Two known limitations carry forward from v1.11: dedup across two sources of the same standard vital is deferred (both rows persist, source priority decides display), and the coach's durable conversation-summary / remembered-facts layer is deferred — each answer reasons from your data afresh rather than from a running memory.
The detailed changelog lives in [`CHANGELOG.md`](CHANGELOG.md).
---
@@ -513,7 +555,7 @@ A SwiftUI iOS companion that lives on the same `/api` surfaces as the web client
### What the phone unlocks
- **HealthKit two-way sync.** Today's step count, weight, blood pressure, HRV, sleep, glucose, etc. read live from Apple Health and round-trip to your server through `HKObserverQuery` + `HKAnchoredObjectQuery` + a `BGProcessingTask` for guaranteed delivery. `HKMetadataKeyExternalUUID` on every iOS-side write keeps the server and Apple Health from echoing each other.
- **Medication reminders that actually fire.** Local notifications with action buttons (Genommen / Snooze 15 min / Übersprungen) that hit the server's mark-intake endpoint directly — without opening the app.
- **Medication reminders that actually fire.** Local notifications with action buttons (Taken / Snooze 15 min / Skipped) that hit the server's mark-intake endpoint directly — without opening the app.
- **On-device AI Coach.** A conversational surface powered by Apple's Foundation Models framework on iOS 26+ Apple-Intelligence-eligible iPhones. The prompt and the response never leave the device — your numbers, your health questions, your phone.
- **Passkey-first auth.** Sign in with Face ID or Touch ID via WebAuthn; email + magic-link is the fallback. SPKI public-key pinning on every authenticated request, Keychain with `afterFirstUnlockThisDeviceOnly`, and a log sanitizer that filters tokens and hostnames out of every line.
- **Doctor-report export.** Generate a FHIR-flavoured PDF bundle from the iPhone based on the LOINC mappings reviewed on the server's clinician surface.
+23 -1
View File
@@ -18,7 +18,14 @@ services:
ports:
- "3000:3000"
environment:
DATABASE_URL: "postgresql://healthlog:${POSTGRES_PASSWORD}@db:5432/healthlog?schema=public"
# connection_limit is set explicitly: Prisma's own default is
# cpu_count*2+1, which starves the combined web+worker process
# (HEALTHLOG_PROCESS_TYPE=all) under background AI/rollup load. Default
# 20 suits a small host; raise DB_CONNECTION_LIMIT on a busy one (keep it
# below the database's max_connections, leaving headroom for pg-boss,
# migrations, and backups). pool_timeout is the seconds a query waits for
# a free connection before erroring.
DATABASE_URL: "postgresql://healthlog:${POSTGRES_PASSWORD}@db:5432/healthlog?schema=public&connection_limit=${DB_CONNECTION_LIMIT:-20}&pool_timeout=${DB_POOL_TIMEOUT:-20}"
NODE_ENV: production
ENCRYPTION_KEY: "${ENCRYPTION_KEY}"
ENCRYPTION_KEYS: "${ENCRYPTION_KEYS:-}"
@@ -43,6 +50,21 @@ services:
BACKUP_S3_SECRET_KEY: "${BACKUP_S3_SECRET_KEY:-}"
BACKUP_S3_REGION: "${BACKUP_S3_REGION:-auto}"
BACKUP_RETENTION_DAYS: "${BACKUP_RETENTION_DAYS:-30}"
# Per-export ceiling on MedicationAdministration rows in the FHIR
# health-record Bundle. Bounded 1..50000, default 5000. Listed here so
# an operator override in .env actually reaches the container (the
# `environment:` block is a whitelist).
FHIR_MAX_MEDICATION_ADMINISTRATIONS: "${FHIR_MAX_MEDICATION_ADMINISTRATIONS:-}"
# WHOOP integration (optional). The app client id/secret are per-user
# BYO-keys stored encrypted in the DB, so there is no
# WHOOP_CLIENT_ID/SECRET env. WHOOP_WEBHOOK_SECRET is the instance-level
# path-segment + HMAC-verification secret for the webhook;
# WHOOP_REDIRECT_URI overrides the derived
# `${NEXT_PUBLIC_APP_URL}/api/whoop/callback` when the public URL
# differs. Listed here so an operator override in .env reaches the
# container (the `environment:` block is a whitelist).
WHOOP_WEBHOOK_SECRET: "${WHOOP_WEBHOOK_SECRET:-}"
WHOOP_REDIRECT_URI: "${WHOOP_REDIRECT_URI:-}"
depends_on:
db:
condition: service_healthy
@@ -0,0 +1,82 @@
# 0001 — Insights naming convention: localised UI, English identifiers
- Status: accepted
- Date: 2026-05-31
## Context
The Insights surface grew bilingually. The mother page (`/insights`) and its
routed metric sub-pages were keyed by German slugs (`/insights/blutdruck`,
`/insights/gewicht`, …) because German was the primary author voice when the
routed strip first shipped. Over time the surface accumulated a mix: route
folders, the tile-layout enum, and several internal maps were German, while
later additions (`hrv`, `oxygenSaturation`, `restingHr`, `activeEnergy`,
`workouts`) landed in English. The result was an inconsistent identifier space
where a contributor could not predict whether a given key was German or English.
Identifiers leak. A German route slug shows up in URLs, in browser history, in
the OpenAPI contract the iOS client reads, and in every internal map that pivots
on the slug. Mixed-language identifiers make the codebase harder to navigate and
make the public API contract read inconsistently.
Two surfaces also speak these identifiers across a boundary we do not control:
1. **URLs** — bookmarked and cached by the PWA.
2. **The tile-layout contract** — `GET/PUT /api/insights/layout`, which the
native iOS client persists against. The tile ids in that payload are a
client-visible contract.
## Decision
Separate the two naming axes cleanly:
- **UI copy is always localised.** Every visible string resolves through an
i18n `t()` key and is translated across all six locales (`de / en / es / fr /
it / pl`). The user never sees a raw identifier.
- **Internal identifiers are English.** Route slugs (`/insights/<slug>`), the
tile-layout enum (`INSIGHTS_TILE_IDS`), query keys, and the internal
slug→metric / slug→target maps all use established English terms. English is
the lingua franca of the codebase and of the public API contract.
Concretely, v1.8.0 migrates the routed Insights slugs and the tile-layout enum
from German to English (e.g. `blutdruck` → `blood-pressure`, `gewicht` →
`weight`, `medikamente` → `medications`). The full rename table lives in
`src/lib/insights/sub-page-metric.ts` (slugs) and `src/lib/insights-layout.ts`
(tile ids).
## Non-breaking strategy
The migration must not break either client-visible boundary:
- **URLs.** `next.config.ts` `redirects()` emits a `permanent: true` (301)
redirect from every legacy German slug to its English target, including a
`:path*` variant so any nested route survives. Bookmarks and cached PWA
navigation keep resolving.
- **Tile-layout contract.** The layout endpoint keeps **accepting** the legacy
German tile ids on input. The Zod enum is built from
`ACCEPTED_INSIGHTS_TILE_IDS` (canonical English ids *plus* the legacy German
aliases), so a `PUT` carrying old ids validates rather than tripping a 422.
`normalizeInsightsTileId` collapses each legacy id onto its canonical English
replacement; this normalisation runs on **both** the read path
(`resolveInsightsLayout`) and the write path (`serializeInsightsLayout`), so:
- a layout persisted by a `≤ v1.7.x` client surfaces canonical English ids on
`GET` without forcing a re-`PUT`;
- a `PUT` sending legacy ids persists canonical English ids;
- a layout that carries both a legacy and a canonical id for one tile dedupes
to a single canonical entry.
The legacy ids are accepted-but-deprecated. They will be removed from the
accepted set in a future major version once telemetry shows clients have
migrated. The OpenAPI `InsightsLayoutBody` schema documents the canonical ids,
the accepted legacy ids, and the deprecation.
## Consequences
- The Insights identifier space is uniformly English and predictable.
- No client breaks on upgrade: old URLs redirect, old tile ids normalise.
- The legacy-alias map and the redirect table are deliberate, finite debt to be
retired in a future major. Until then they are covered by tests
(`src/app/api/insights/layout/__tests__/route.test.ts`) that assert the
non-breaking round-trip.
- New Insights surfaces follow the convention from the start: English slug,
English tile id, localised `t()` copy.
+3346 -22
View File
File diff suppressed because it is too large. Load diff
+19
View File
@@ -44,6 +44,25 @@ PDF in a new tab without preserving the filename or fails the blob save).
`500` if rendering fails.
- Audit action: `doctor-report.pdf.generate`.
## Wellness summary (derived scores)
Since v1.10.0 the report carries a **Wellness summary** section below the
clinical content, holding the server-derived wellness scores (Recovery,
Stress, Strain) and the other derived metrics where present. It is kept
deliberately separate from the clinical vitals table:
- Each entry is labelled **descriptive, not a clinical assessment**, and the
scores never enter the vitals table or the clinical aggregations.
- The Stress score is shown as an HRV-derived proxy, not a sensor-measured
stress value.
- In the FHIR export the same scores are emitted as `survey`-category
`Observation`s (text-only `code`, no fabricated LOINC) with a per-Observation
non-clinical note — so a downstream system never mistakes them for a vital
sign or a diagnosis.
Each derived metric states its inputs, method, and the cited standard it is
grounded in (the same provenance the in-app explainer shows).
## Implementation notes
- `src/lib/doctor-report-pdf-core.ts` contains the isomorphic renderer.
+71
View File
@@ -0,0 +1,71 @@
# WHOOP integration
HealthLog connects to WHOOP via OAuth2 plus HMAC-signed webhooks for
near-real-time sync of recovery, strain, sleep, and the underlying
heart-rate / HRV signals. Unlike Withings, WHOOP credentials are
brought per user: each user (or the operator on their behalf)
registers their own WHOOP developer app and pastes the client
id/secret into Settings.
## Why bring your own keys
WHOOP caps the number of users a single developer app may authorise.
Per-user BYO-keys sidestep that per-app cap: every user authorises
against their own WHOOP app, so a shared HealthLog instance never
runs into one app's user ceiling. It also keeps each user's WHOOP
grant scoped to credentials they control.
## 1. Register a WHOOP developer app
1. Sign in at <https://developer.whoop.com/> and create a new app.
2. **Redirect URI:** `https://your-instance.example.com/api/whoop/callback`
(matches `WHOOP_REDIRECT_URI`, below). Add one entry per
environment you connect from.
3. Request the scopes for recovery, cycle/strain, sleep, and the
workout/heart-rate reads the sync uses.
4. Save the app. WHOOP issues a **Client ID** and **Client Secret** —
keep the secret out of any chat log; it grants read access to the
linked account's full WHOOP history.
## 2. Wire the credentials in Settings → Integrations
WHOOP credentials are stored per user, not in `.env`. Sign in as the
target user, open **Settings → Integrations → WHOOP**, and paste the
client ID and secret. They are encrypted AES-256-GCM at rest.
## 3. Connect
Click **Connect WHOOP**. The flow:
1. The Connect button redirects to WHOOP's OAuth authorize endpoint.
2. The user signs in on WHOOP and grants the requested scopes.
3. WHOOP redirects back to `/api/whoop/callback` with an auth code.
4. HealthLog exchanges the code for an access + refresh token, stores
them encrypted, registers the webhook, and triggers an initial
sync of recent history.
5. Subsequent syncs run on every webhook delivery plus a safety-net
cron pull.
## Optional instance env vars
Two server-level env vars tune the OAuth callback and webhook
verification. They are optional — the per-user client id/secret in
Settings drive the connection itself.
```env
WHOOP_REDIRECT_URI="https://your-instance.example.com/api/whoop/callback"
WHOOP_WEBHOOK_SECRET="$(openssl rand -hex 32)"
```
- `WHOOP_REDIRECT_URI` — the OAuth callback URL handed to WHOOP. Must
match a redirect URI registered in the WHOOP developer app.
- `WHOOP_WEBHOOK_SECRET` — the secret HealthLog verifies the WHOOP
webhook HMAC signature against. WHOOP signs each webhook body; the
handler validates the signature before processing. Generate a fresh
random value and restart the `app` container after setting it.
## Disconnect
The Settings page **Disconnect** button revokes the stored tokens and
removes the connection. Existing measurements synced from WHOOP stay
in the database — disconnect does not delete data.
+31
View File
@@ -30,6 +30,20 @@ step 2 is redundant in normal Coolify flow. It's listed explicitly for
the manual case so an operator can verify the migration result before
flipping traffic.
### v1.11.0 notes
Migrations `0110`–`0114` are additive (new tables / columns for the
WHOOP provider hub, the longitudinal coach, and the clinician FHIR
record). They require no special steps — `prisma migrate deploy` runs
them in order on boot like any other.
WHOOP introduces two optional instance env vars, `WHOOP_REDIRECT_URI`
and `WHOOP_WEBHOOK_SECRET` (HMAC secret for WHOOP webhook signature
verification). Per-user WHOOP client id/secret live in Settings, not
in the environment. See `docs/integrations/whoop.md`. Add the two vars
to the compose `environment:` whitelist if you set them — vars not on
the whitelist never reach the container.
### What goes wrong if you reverse it
If the new app container starts before migrations run, the legacy
@@ -59,3 +73,20 @@ roll back:
dev --create-only --name vX_Y_Z_rollback_<col>`), edit the SQL,
commit, and re-deploy. Never `migrate resolve --rolled-back` against
production unless you've taken a fresh `pg_dump` first.
## Verify the served version
The queued-deploy status is **not** the source of truth — the version
`/api/version` actually answers is. A BuildKit layer-cache hit can
re-ship the prior image even when Coolify reports a clean deploy, so
always confirm the served build after a deploy:
```sh
# Asserts prod + demo serve 1.9.0, prints each target's buildSha,
# exits non-zero on a mismatch or timeout after a bounded retry loop.
pnpm dlx tsx scripts/assert-deploy.ts 1.9.0
```
Pass `--only=prod` / `--only=demo` to check a single target, or
`--attempts=N --interval=ms` to widen the retry window while a slow
pull settles.
+1
View File
@@ -151,6 +151,7 @@ NEXT_PUBLIC_DASHBOARD_SNAPSHOT=false pnpm build
| Off-host encrypted backups to S3/R2/B2 | `docs/ops/backup-restore.md` |
| Encryption-key rotation procedure | `docs/ops/encryption-key-rotation.md` |
| Withings device sync | `docs/integrations/withings.md` |
| WHOOP device sync (per-user BYO-keys) | `docs/integrations/whoop.md` |
| Apple Health `export.zip` import | `docs/integrations/apple-health.md` |
| AI provider setup (OpenAI / Anthropic / local / ChatGPT OAuth) | `docs/integrations/ai-providers.md` |
+21 -5
View File
@@ -217,10 +217,16 @@ export async function expectStep(
displayIndex: number,
totalSteps?: number,
): Promise<void> {
const pattern = totalSteps
? new RegExp(`Schritt ${displayIndex} von ${totalSteps}`, "i")
: new RegExp(`Schritt ${displayIndex} von \\d+`, "i");
await expect(page.getByText(pattern)).toBeVisible({ timeout: 5_000 });
// The "Schritt X von Y" caption is mobile-only (`sm:hidden`) since the dot
// stepper landed, so it is hidden on the desktop e2e viewport. Assert the
// viewport-independent root data-attributes the dialog always carries.
const root = page.locator('[data-slot="medication-wizard-dialog"]');
await expect(root).toHaveAttribute("data-display-step", String(displayIndex), {
timeout: 5_000,
});
if (totalSteps != null) {
await expect(root).toHaveAttribute("data-total-steps", String(totalSteps));
}
}
/**
@@ -245,10 +251,20 @@ export async function expectMedicationOnList(
page: Page,
{ name, withNextDueChip }: { name: string; withNextDueChip: boolean },
): Promise<void> {
// Pin the clock to a fixed afternoon before rendering the list. The
// recurring stub schedules an 08:00–09:00 window; the card derives its
// header from the real clock, so when CI happens to run inside that
// window the card shows the "take now" (in_window) pill and the
// "Nächste Einnahme:" next-due line is correctly suppressed — making the
// chip assertion below depend on the wall-clock. A fixed afternoon puts
// the morning window in the past so the next-due line always renders.
await page.clock.setFixedTime(new Date("2026-06-04T13:00:00Z"));
await page.goto("/medications", { waitUntil: "domcontentloaded" });
const main = page.locator("main");
await expect(main.getByText(name).first()).toBeVisible({ timeout: 10_000 });
if (withNextDueChip) {
await expect(main.getByText(/Nächste Einnahme:/i).first()).toBeVisible();
await expect(main.getByText(/Nächste Einnahme:/i).first()).toBeVisible({
timeout: 10_000,
});
}
}
+10 -5
View File
@@ -127,12 +127,17 @@ test.describe("/settings/integrations Pixel-5 layout", () => {
// Wait for the pills to mount (queries resolve after first paint).
const pills = page.locator('[data-testid="integration-status-pill"]');
await expect(pills).toHaveCount(2, { timeout: 10_000 });
// Three integration cards now (Withings, moodLog, WHOOP) → three pills.
await expect(pills).toHaveCount(3, { timeout: 10_000 });
// Each pill carries the data-state marker so we know the
// pill rendered the connected branch with relative time.
await expect(pills.nth(0)).toHaveAttribute("data-state", "connected");
await expect(pills.nth(1)).toHaveAttribute("data-state", "connected");
// Withings + moodLog are connected in this fixture; WHOOP is a BYO-keys
// card that stays dormant until an operator adds credentials, so assert
// the two connected pills order-independently.
await expect(
page.locator(
'[data-testid="integration-status-pill"][data-state="connected"]',
),
).toHaveCount(2);
// The redundant v1.4.18 banner must be gone.
await expect(
+1
View File
@@ -37,6 +37,7 @@ function summary(partial: Partial<DataSummary>): DataSummary {
min: null,
max: null,
mean: null,
median: null,
avg7: null,
avg30: null,
slope7: null,
+17 -24
View File
@@ -8,13 +8,13 @@ import { STORAGE_STATE_PATH } from "./setup/global-setup";
*
* Two contracts under test:
*
* 1. Every routed Insights sub-page mounts a `<CoachLaunchButton>`.
* The component renders BOTH a sticky-bottom FAB
* (`data-slot="coach-launch-fab"`, visible on `<lg`) and an
* inline action (`data-slot="coach-launch-inline"`, visible on
* `lg+`). The DOM carries both nodes; CSS picks the visible one.
* The spec asserts the FAB renders on Pixel-5 and the inline
* action renders on Desktop Chrome.
* 1. Every routed Insights sub-page mounts a Coach launch surface.
* The layout renders a sticky-bottom FAB
* (`data-slot="coach-launch-fab"`, visible on `<lg`); v1.8.6 moved
* the per-page action into the sub-page header as an icon-only
* button (`data-slot="coach-launch-icon"`, mounted by the shell at
* heading height across breakpoints). The spec asserts the FAB
* renders on Pixel-5 and the header icon renders on Desktop Chrome.
*
* 2. Opening the Coach drawer on `<sm` mounts it as a bottom-sheet
* (`data-variant="bottom-sheet"`). On `>=sm` it mounts as a
@@ -121,28 +121,23 @@ test.describe("v1.4.27 — Coach reachability on insights sub-pages", () => {
.locator('[data-slot="coach-launch-fab"]')
.first();
await expect(fab).toBeVisible({ timeout: 10_000 });
// The inline branch is in the DOM but hidden via `hidden lg:inline-flex`.
const inline = page.locator('[data-slot="coach-launch-inline"]').first();
await expect(inline).toBeHidden();
});
test(`/insights/${slug} mounts the Coach launch button on Desktop Chrome (inline branch)`, async ({
test(`/insights/${slug} mounts the header Coach icon on Desktop Chrome`, async ({
page,
}, testInfo) => {
// Desktop Chrome viewport is 1280 — `lg` (1024) is matched so the
// inline branch wins; the FAB is hidden by `lg:hidden`.
// layout FAB is hidden by `lg:hidden`; the header icon the shell
// mounts is the Coach entry on the page itself.
test.skip(
testInfo.project.name !== "chromium-desktop",
"desktop inline branch",
"desktop header-icon branch",
);
await page.goto(`/insights/${slug}`, { waitUntil: "domcontentloaded" });
const inline = page
.locator('[data-slot="coach-launch-inline"]')
.first();
await expect(inline).toBeVisible({ timeout: 10_000 });
const icon = page.locator('[data-slot="coach-launch-icon"]').first();
await expect(icon).toBeVisible({ timeout: 10_000 });
const fab = page.locator('[data-slot="coach-launch-fab"]').first();
await expect(fab).toBeHidden();
@@ -168,7 +163,7 @@ test.describe("v1.4.27 — Coach reachability on insights sub-pages", () => {
await expect(drawer).toHaveAttribute("data-variant", "bottom-sheet");
});
test("clicking the inline action opens the Coach drawer as a side-sheet on Desktop Chrome", async ({
test("clicking the header Coach icon opens the Coach drawer as a side-sheet on Desktop Chrome", async ({
page,
}, testInfo) => {
test.skip(
@@ -178,11 +173,9 @@ test.describe("v1.4.27 — Coach reachability on insights sub-pages", () => {
await page.goto("/insights/blutdruck", { waitUntil: "domcontentloaded" });
const inline = page
.locator('[data-slot="coach-launch-inline"]')
.first();
await expect(inline).toBeVisible({ timeout: 10_000 });
await inline.click();
const icon = page.locator('[data-slot="coach-launch-icon"]').first();
await expect(icon).toBeVisible({ timeout: 10_000 });
await icon.click();
const drawer = page.locator('[data-slot="coach-drawer"]');
await expect(drawer).toBeVisible({ timeout: 10_000 });
+791 -88
View File
File diff suppressed because it is too large. Load diff
+791 -88
View File
File diff suppressed because it is too large. Load diff
+818 -115
View File
File diff suppressed because it is too large. Load diff
+817 -114
View File
File diff suppressed because it is too large. Load diff
+818 -115
View File
File diff suppressed because it is too large. Load diff
+818 -115
View File
File diff suppressed because it is too large. Load diff
+59
View File
@@ -53,6 +53,65 @@ const nextConfig: NextConfig = {
// from memory instead of paying a full reload. See
// `src/lib/http/cache-headers.ts` for the typed constant reused by
// route handlers that opt into the same posture.
// v1.8.0 — the routed Insights sub-pages migrated from German to
// English slugs (`/insights/blutdruck` → `/insights/blood-pressure`,
// …). Every legacy German URL 301-redirects to its English target so
// bookmarks, the PWA's cached navigation, and any external link keep
// resolving. The redirect set is exhaustive and matches the rename
// table in `docs/adr/0001-insights-naming-convention.md`; the slug
// registry itself lives in `src/lib/insights/sub-page-metric.ts`.
// `bmi`, `hrv`, and `workouts` were already English and need no entry.
async redirects() {
const insightsSlugRenames: Array<[string, string]> = [
["blutdruck", "blood-pressure"],
["puls", "pulse"],
["sauerstoff", "oxygen"],
["koerpertemperatur", "body-temperature"],
["atemfrequenz", "respiratory-rate"],
["gewicht", "weight"],
["koerperwasser", "body-water"],
["knochenmasse", "bone-mass"],
["fettfreie-masse", "fat-free-mass"],
["fettmasse", "fat-mass"],
["muskelmasse", "muscle-mass"],
["viszeralfett", "visceral-fat"],
["magermasse", "lean-body-mass"],
["aktive-energie", "active-energy"],
["stockwerke", "flights-climbed"],
["gehstrecke", "walking-distance"],
["gangstabilitaet", "walking-steadiness"],
["gehpuls", "walking-heart-rate"],
["gangasymmetrie", "walking-asymmetry"],
["doppelstandphase", "double-support-time"],
["schrittlaenge", "step-length"],
["gehgeschwindigkeit", "walking-speed"],
["schlaf", "sleep"],
["ruhepuls", "resting-pulse"],
["pulswellengeschwindigkeit", "pulse-wave-velocity"],
["gefaessalter", "vascular-age"],
["laermbelastung", "environmental-audio"],
["kopfhoererpegel", "headphone-audio"],
["laermereignisse", "audio-events"],
["tageslicht", "daylight"],
["blutzucker", "blood-glucose"],
["hauttemperatur", "skin-temperature"],
["stimmung", "mood"],
["medikamente", "medications"],
];
return insightsSlugRenames.flatMap(([from, to]) => [
{
source: `/insights/${from}`,
destination: `/insights/${to}`,
permanent: true,
},
// Preserve any nested path (e.g. a future `/insights/sleep/2026-05-31`).
{
source: `/insights/${from}/:path*`,
destination: `/insights/${to}/:path*`,
permanent: true,
},
]);
},
async headers() {
return [
{
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "healthlog",
"version": "1.7.2",
"version": "1.11.2",
"description": "Self-hosted personal-health-tracking PWA with Withings integration, AI insights, and doctor-report PDF export.",
"license": "AGPL-3.0-only",
"homepage": "https://healthlog.dev",
@@ -0,0 +1,20 @@
-- 0098_app_settings_global_toggles_drift_fix
-- Four `app_settings` columns have been on `prisma/schema.prisma` since the
-- per-channel global notification toggles + admin default-locale work but
-- never landed in the migration history (applied via `prisma db push` to
-- existing environments but not committed as a migration). The drift is
-- invisible on a database kept in sync via `db push`, but a database built
-- from migrations alone is missing the columns — and the admin settings
-- read path (`/api/admin/settings`) selects `default_locale`, so a fresh
-- deploy reports `column "default_locale" does not exist` on first read.
--
-- Same class of drift as 0025_user_locale_drift_fix. Each add uses
-- `IF NOT EXISTS` with the schema default, so the migration is a safe no-op
-- against any environment already carrying the columns and a clean add
-- against one built strictly from this migrations directory (CI test
-- containers, fresh deploys, demo seeds).
ALTER TABLE "app_settings"
ADD COLUMN IF NOT EXISTS "default_locale" TEXT NOT NULL DEFAULT 'de',
ADD COLUMN IF NOT EXISTS "telegram_global" BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN IF NOT EXISTS "ntfy_global" BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN IF NOT EXISTS "web_push_global" BOOLEAN NOT NULL DEFAULT true;
@@ -0,0 +1,34 @@
-- v1.8.5 — per-medication injection-site tracking.
--
-- Makes injection-site tracking + rotation real. Prior to this release
-- the `injection_site` column on `medication_intake_events` was read in
-- several surfaces but never written; tracking was effectively dead.
--
-- Two additive, defaulted columns on `medications`:
--
-- - `track_injection_sites` — per-medication opt-in. Only meaningful
-- (and only offered in the UI) when `delivery_form = 'INJECTION'`.
-- Default false: the post-dose site prompt fires only when this is
-- true, and the prompt is always skippable. Deactivatable any time.
--
-- - `allowed_injection_sites` — per-medication allowed / preferred
-- sites. Empty = no per-medication restriction (every site offered).
-- The effective pickable set is this list MINUS the user-level
-- `users.global_excluded_injection_sites` deny-list (deny wins). The
-- intake write path validates a submitted site against the effective
-- set and rejects (422) a disallowed value.
--
-- Both columns are additive + defaulted; no backfill is required. The
-- `injection_site` enum type already exists (migration 0046).
--
-- Idempotent guards (`IF NOT EXISTS`) make reruns safe.
--
-- Reversibility:
-- ALTER TABLE "medications" DROP COLUMN IF EXISTS "track_injection_sites";
-- ALTER TABLE "medications" DROP COLUMN IF EXISTS "allowed_injection_sites";
-- A roll-back loses the opt-in flag + the per-medication site list; the
-- application reads tolerate a missing column / default-empty value.
ALTER TABLE "medications"
ADD COLUMN IF NOT EXISTS "track_injection_sites" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS "allowed_injection_sites" "injection_site"[] NOT NULL DEFAULT ARRAY[]::"injection_site"[];
@@ -0,0 +1,30 @@
-- v1.8.5 — user-level global injection-site exclusion.
--
-- A per-user deny-list of injection sites. Sites listed here are never
-- offered for ANY medication's injection-site picker, and the intake
-- write path rejects (422) a submitted site that lands on this list —
-- even when the per-medication `medications.allowed_injection_sites`
-- lists it as preferred. Deny always wins.
--
-- Typical use: a user develops lipohypertrophy at one site and wants it
-- excluded across every injectable they track, without editing each
-- medication's allowed list individually.
--
-- Single additive, defaulted enum-array column on `users`. Default
-- `'{}'` = no global exclusion (the pre-v1.8.5 behaviour). No backfill.
-- The `injection_site` enum type already exists (migration 0046).
--
-- Idempotent guard (`IF NOT EXISTS`) makes reruns safe.
--
-- Reversibility:
-- ALTER TABLE "users" DROP COLUMN IF EXISTS "global_excluded_injection_sites";
-- A roll-back loses the global deny-list (every site becomes pickable
-- again, subject to each medication's own allowed list); the
-- application reads tolerate a missing column / default-empty value.
--
-- No index — reads are per-user at request time (`WHERE id = $1`),
-- matching `insights_exclude_metrics` and the other display-pref
-- columns on the same table.
ALTER TABLE "users"
ADD COLUMN IF NOT EXISTS "global_excluded_injection_sites" "injection_site"[] NOT NULL DEFAULT ARRAY[]::"injection_site"[];
@@ -0,0 +1,252 @@
-- v1.8.5 — structured mood-tag taxonomy.
--
-- Adds a global Category -> Tag catalog plus a per-entry join, modelled
-- on the standalone mood diary's structured taxonomy. Purely additive:
-- the legacy flat `mood_entries.tags` JSON column is untouched and keeps
-- working for every existing row, the GLP-1 quick-tag chips, and the
-- Telegram / MoodLog sync. The structured taxonomy is a second, richer
-- capture surface; the tag-frequency / lift breakdown folds the two
-- axes together.
--
-- `label_key` columns carry an i18n message key (resolved client-side
-- against all six locales) rather than a hard-coded label, so the seeded
-- catalog renders localised everywhere. The seed at the bottom uses
-- deterministic ids + ON CONFLICT upsert so re-running is idempotent.
--
-- Reversibility (down):
-- DROP TABLE IF EXISTS "mood_entry_tag_links";
-- DROP TABLE IF EXISTS "mood_tags";
-- DROP TABLE IF EXISTS "mood_tag_categories";
-- CreateTable
CREATE TABLE "mood_tag_categories" (
"id" TEXT NOT NULL,
"key" TEXT NOT NULL,
"label_key" TEXT NOT NULL,
"icon" TEXT,
"sort_order" INTEGER NOT NULL DEFAULT 0,
"is_active" BOOLEAN NOT NULL DEFAULT true,
CONSTRAINT "mood_tag_categories_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "mood_tags" (
"id" TEXT NOT NULL,
"category_id" TEXT NOT NULL,
"key" TEXT NOT NULL,
"label_key" TEXT NOT NULL,
"icon" TEXT,
"sort_order" INTEGER NOT NULL DEFAULT 0,
"is_active" BOOLEAN NOT NULL DEFAULT true,
CONSTRAINT "mood_tags_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "mood_entry_tag_links" (
"mood_entry_id" TEXT NOT NULL,
"mood_tag_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "mood_entry_tag_links_pkey" PRIMARY KEY ("mood_entry_id","mood_tag_id")
);
-- CreateIndex
CREATE UNIQUE INDEX "mood_tag_categories_key_key" ON "mood_tag_categories"("key");
-- CreateIndex
CREATE UNIQUE INDEX "mood_tags_key_key" ON "mood_tags"("key");
-- CreateIndex
CREATE INDEX "mood_tags_category_id_sort_order_idx" ON "mood_tags"("category_id", "sort_order");
-- CreateIndex
CREATE INDEX "mood_entry_tag_links_mood_tag_id_idx" ON "mood_entry_tag_links"("mood_tag_id");
-- AddForeignKey
ALTER TABLE "mood_tags" ADD CONSTRAINT "mood_tags_category_id_fkey" FOREIGN KEY ("category_id") REFERENCES "mood_tag_categories"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "mood_entry_tag_links" ADD CONSTRAINT "mood_entry_tag_links_mood_entry_id_fkey" FOREIGN KEY ("mood_entry_id") REFERENCES "mood_entries"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "mood_entry_tag_links" ADD CONSTRAINT "mood_entry_tag_links_mood_tag_id_fkey" FOREIGN KEY ("mood_tag_id") REFERENCES "mood_tags"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- Seed the default taxonomy (idempotent upsert by `key`). Mirrors
-- `src/lib/mood/tag-taxonomy.ts` — keep the two in sync if either
-- changes.
INSERT INTO "mood_tag_categories" ("id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mtc_feelings', 'feelings', 'mood.tagCategory.feelings', 'Heart', 0, true)
ON CONFLICT ("key") DO UPDATE SET
"label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_happy', 'mtc_feelings', 'happy', 'mood.tag.happy', 'Smile', 0, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_excited', 'mtc_feelings', 'excited', 'mood.tag.excited', 'Zap', 1, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_grateful', 'mtc_feelings', 'grateful', 'mood.tag.grateful', 'HandHeart', 2, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_relaxed', 'mtc_feelings', 'relaxed', 'mood.tag.relaxed', 'CloudSun', 3, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_content', 'mtc_feelings', 'content', 'mood.tag.content', 'ThumbsUp', 4, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_tired', 'mtc_feelings', 'tired', 'mood.tag.tired', 'Moon', 5, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_unsure', 'mtc_feelings', 'unsure', 'mood.tag.unsure', 'HelpCircle', 6, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_bored', 'mtc_feelings', 'bored', 'mood.tag.bored', 'Meh', 7, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_tense', 'mtc_feelings', 'tense', 'mood.tag.tense', 'AlertTriangle', 8, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_angry', 'mtc_feelings', 'angry', 'mood.tag.angry', 'Flame', 9, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_stressed', 'mtc_feelings', 'stressed', 'mood.tag.stressed', 'Brain', 10, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_sad', 'mtc_feelings', 'sad', 'mood.tag.sad', 'Frown', 11, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tag_categories" ("id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mtc_sleep', 'sleep', 'mood.tagCategory.sleep', 'BedDouble', 1, true)
ON CONFLICT ("key") DO UPDATE SET
"label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_slept_well', 'mtc_sleep', 'slept_well', 'mood.tag.sleptWell', 'Moon', 0, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_slept_ok', 'mtc_sleep', 'slept_ok', 'mood.tag.sleptOk', 'CloudMoon', 1, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_slept_poorly', 'mtc_sleep', 'slept_poorly', 'mood.tag.sleptPoorly', 'MoonStar', 2, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_early_night', 'mtc_sleep', 'early_night', 'mood.tag.earlyNight', 'Clock', 3, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tag_categories" ("id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mtc_health', 'health', 'mood.tagCategory.health', 'HeartPulse', 2, true)
ON CONFLICT ("key") DO UPDATE SET
"label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_worked_out', 'mtc_health', 'worked_out', 'mood.tag.workedOut', 'Dumbbell', 0, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_ate_well', 'mtc_health', 'ate_well', 'mood.tag.ateWell', 'Apple', 1, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_hydrated', 'mtc_health', 'hydrated', 'mood.tag.hydrated', 'GlassWater', 2, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_walked', 'mtc_health', 'walked', 'mood.tag.walked', 'Footprints', 3, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_alcohol', 'mtc_health', 'alcohol', 'mood.tag.alcohol', 'Wine', 4, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tag_categories" ("id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mtc_social', 'social', 'mood.tagCategory.social', 'Users', 3, true)
ON CONFLICT ("key") DO UPDATE SET
"label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_family', 'mtc_social', 'family', 'mood.tag.family', 'Home', 0, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_friends', 'mtc_social', 'friends', 'mood.tag.friends', 'Users', 1, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_party', 'mtc_social', 'party', 'mood.tag.party', 'PartyPopper', 2, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_alone', 'mtc_social', 'alone', 'mood.tag.alone', 'User', 3, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tag_categories" ("id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mtc_work', 'work', 'mood.tagCategory.work', 'Briefcase', 4, true)
ON CONFLICT ("key") DO UPDATE SET
"label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_productive', 'mtc_work', 'productive', 'mood.tag.productive', 'CheckCircle', 0, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_overtime', 'mtc_work', 'overtime', 'mood.tag.overtime', 'Clock', 1, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_day_off', 'mtc_work', 'day_off', 'mood.tag.dayOff', 'LogOut', 2, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_travel', 'mtc_work', 'travel', 'mood.tag.travel', 'Plane', 3, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
INSERT INTO "mood_tags" ("id", "category_id", "key", "label_key", "icon", "sort_order", "is_active")
VALUES ('mt_sick_day', 'mtc_work', 'sick_day', 'mood.tag.sickDay', 'Thermometer', 4, true)
ON CONFLICT ("key") DO UPDATE SET
"category_id" = EXCLUDED."category_id", "label_key" = EXCLUDED."label_key", "icon" = EXCLUDED."icon", "sort_order" = EXCLUDED."sort_order";
@@ -0,0 +1,32 @@
-- v1.8.6 — optional German insurer institution number (IKNR) on the user
-- profile.
--
-- The IKNR ("Institutionskennzeichen", 9 digits) identifies the statutory
-- or private health insurer. It sits next to the existing plaintext
-- `insurer_name` and the encrypted `insurance_number_encrypted` (KVNR).
-- Unlike the KVNR — a per-person quasi-identifier kept AES-256-GCM
-- encrypted at rest — the IKNR is a public registry number for the
-- institution, so it is stored plaintext, matching `insurer_name`.
--
-- Surfaced on the health-record FHIR export as the contained payor
-- `Organization` identifier (system `http://fhir.de/sid/arge-ik/iknr`)
-- inside the new `Coverage` resource.
--
-- Single additive, nullable, NULL-defaulted column on `users`. No
-- backfill — pre-v1.8.6 rows read NULL (no IKNR captured yet), which the
-- exporter treats identically to an absent value.
--
-- Idempotent guard (`IF NOT EXISTS`) makes reruns safe. Forward-only.
--
-- Reversibility:
-- ALTER TABLE "users" DROP COLUMN IF EXISTS "insurer_ik_number";
-- A roll-back loses the captured IKNR; the FHIR export simply emits the
-- payor `Organization` with a name only (no identifier), and the
-- application reads tolerate a missing column / NULL value.
--
-- No index — reads are per-user at request time (`WHERE id = $1`),
-- matching `insurer_name` and the other display-identity columns on the
-- same table.
ALTER TABLE "users"
ADD COLUMN IF NOT EXISTS "insurer_ik_number" TEXT;
@@ -0,0 +1,38 @@
-- v1.9.0 — optional drug-classification codes on the medication row.
--
-- Two additive, nullable, NULL-defaulted columns on `medications`:
--
-- * `atc_code` — the WHO ATC active-substance class (e.g. "A10BX10").
-- Emitted on the FHIR `MedicationStatement` /
-- `MedicationAdministration` `medicationCodeableConcept`
-- under the system URI `http://www.whocc.no/atc`.
-- * `rxnorm_code` — the RxNorm RxCUI (US identifier). Secondary coding
-- under `http://www.nlm.nih.gov/research/umls/rxnorm`.
--
-- Both are user/clinician-asserted, never machine-guessed: a wrong code
-- is a clinical-safety problem, an absent code is merely a (conformant)
-- text-only concept. The application validates the format on write
-- (ATC `^[A-Z]\d{2}[A-Z]{2}\d{2}$`, RxCUI `^\d+$`) and 422s on a
-- malformed value; the DB column is a plain nullable TEXT field.
--
-- No backfill — pre-v1.9.0 rows read NULL, which the exporter treats
-- identically to an absent value (the medicationCodeableConcept stays
-- text-only, the pre-v1.9.0 shape).
--
-- Idempotent guards (`IF NOT EXISTS`) make reruns safe. Forward-only.
--
-- Reversibility:
-- ALTER TABLE "medications" DROP COLUMN IF EXISTS "atc_code";
-- ALTER TABLE "medications" DROP COLUMN IF EXISTS "rxnorm_code";
-- A roll-back loses the captured codes; the FHIR export falls back to the
-- text-only medicationCodeableConcept and the application reads tolerate a
-- missing column / NULL value.
--
-- No index — reads are per-user at request time (`WHERE user_id = $1`),
-- matching the other display-identity columns on the same table.
ALTER TABLE "medications"
ADD COLUMN IF NOT EXISTS "atc_code" TEXT;
ALTER TABLE "medications"
ADD COLUMN IF NOT EXISTS "rxnorm_code" TEXT;
@@ -0,0 +1,36 @@
-- v1.10.0 — extend `measurement_type` with seven additive HealthKit
-- signals that previously sat in the deferred set.
--
-- Background: each identifier below was emitted by the iOS client but
-- mapped to no `MeasurementType`, so the batch route ack-200'd a
-- per-entry `skipped:"unmappable_identifier"` and the sample was lost.
-- They are now wired end-to-end (mapping + plausibility range + the
-- generic metric-status assessment surface).
--
-- CARDIO_RECOVERY ← HKQuantityTypeIdentifierHeartRateRecoveryOneMinute
-- WRIST_TEMPERATURE ← HKQuantityTypeIdentifierAppleSleepingWristTemperature
-- FALL_COUNT ← HKQuantityTypeIdentifierNumberOfTimesFallen
-- SIX_MINUTE_WALK_DISTANCE ← HKQuantityTypeIdentifierSixMinuteWalkTestDistance
-- STAIR_ASCENT_SPEED ← HKQuantityTypeIdentifierStairAscentSpeed
-- STAIR_DESCENT_SPEED ← HKQuantityTypeIdentifierStairDescentSpeed
-- BREATHING_DISTURBANCES ← HKQuantityTypeIdentifierAppleSleepingBreathingDisturbances
--
-- Unit convention: every one of these ships raw on the wire and passes
-- through `convertToDbUnit` as identity — none is a 0..1 fraction, so the
-- ×100 percent-scaling path the gait-percent metrics use does NOT apply.
-- The convention block at the top of
-- `src/lib/measurements/apple-health-mapping.ts` spells the split out.
--
-- Pure additive — no existing row carries any of these values. The
-- `IF NOT EXISTS` guard keeps the migration idempotent so the runner can
-- replay it on a partially-applied environment without failing on the
-- duplicate-enum-value error code. Forward-only; enum values cannot be
-- dropped in PostgreSQL, so there is no automatic down path.
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'CARDIO_RECOVERY';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'WRIST_TEMPERATURE';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'FALL_COUNT';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'SIX_MINUTE_WALK_DISTANCE';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'STAIR_ASCENT_SPEED';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'STAIR_DESCENT_SPEED';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'BREATHING_DISTURBANCES';
@@ -0,0 +1,95 @@
-- v1.10.0 — categorical EVENT row class + device rhythm classification.
--
-- Adds a discrete EVENT row class to the existing `Measurement` model,
-- following the `sleep_stage` / `glucose_context` nullable-context
-- precedent (migration 0021 + 0036) — an additive nullable column on the
-- existing table, NOT a new storage paradigm. An EVENT row stores ONE
-- on-device notification the user's wearable already produced (Apple Watch
-- irregular-rhythm / high-HR / low-HR / walking-steadiness, ScanWatch AFib
-- screening, sleep breathing-disturbance). `value` is always 1; the
-- device's own verdict / severity rides in the new `rhythm_classification`
-- column.
--
-- ── Regulatory framing (load-bearing) ──────────────────────────────────
-- HealthLog stores ONLY the classification RESULT the device's
-- FDA-cleared / CE-marked on-device algorithm emitted. It never ingests a
-- raw ECG waveform, never re-classifies, and never produces a HealthLog
-- diagnosis. The surface is awareness/screening of the DEVICE's decision.
--
-- Two schema objects:
--
-- 1. Five new `measurement_type` enum values (the EVENT classes).
-- 2. A new `rhythm_classification` enum + a nullable column carrying the
-- device verdict / severity, NULL for every continuous measurement.
--
-- Idempotent guards (`IF NOT EXISTS`) make reruns safe. Forward-only.
--
-- Reversibility:
-- ALTER TABLE "measurements" DROP CONSTRAINT IF EXISTS "measurements_rhythm_classification_requires_event_type";
-- ALTER TABLE "measurements" DROP COLUMN IF EXISTS "rhythm_classification";
-- DROP TYPE IF EXISTS "rhythm_classification";
-- Postgres does not support removing an enum value, so the five new
-- `measurement_type` members stay; with no rows carrying them after a
-- column drop they are inert.
-- ── 1. measurement_type — append the five EVENT classes ────────────────
-- Pure additive; no existing row carries any of these values. The
-- `IF NOT EXISTS` guard keeps the migration idempotent across a
-- partially-applied environment.
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'IRREGULAR_RHYTHM_NOTIFICATION';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'HIGH_HEART_RATE_EVENT';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'LOW_HEART_RATE_EVENT';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'WALKING_STEADINESS_EVENT';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'BREATHING_DISTURBANCE_EVENT';
-- ── 2. rhythm_classification — the device verdict / severity enum ──────
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'rhythm_classification') THEN
CREATE TYPE "rhythm_classification" AS ENUM (
'IRREGULAR',
'NOT_DETECTED',
'INCONCLUSIVE',
'LOW',
'VERY_LOW',
'FIRED'
);
END IF;
END
$$;
-- Nullable column. NULL for every continuous measurement; non-NULL only
-- for the EVENT classes. Mirrors the `sleep_stage` additive-column shape.
ALTER TABLE "measurements"
ADD COLUMN IF NOT EXISTS "rhythm_classification" "rhythm_classification";
-- Enforce: rhythm_classification is only set for the EVENT-class rows.
-- Mirrors the `measurements_sleep_stage_requires_type` CHECK (migration
-- 0036) and the glucose_context CHECK (migration 0021).
--
-- The comparison casts `type` to text so the predicate references the
-- newly-added enum members as string literals. Postgres forbids using an
-- enum value in the same transaction that adds it (the ALTER TYPE ... ADD
-- VALUE statements above run in this same migration transaction); the
-- `::text` cast sidesteps that restriction without weakening the check.
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'measurements_rhythm_classification_requires_event_type'
) THEN
ALTER TABLE "measurements"
ADD CONSTRAINT "measurements_rhythm_classification_requires_event_type"
CHECK (
"rhythm_classification" IS NULL
OR "type"::text IN (
'IRREGULAR_RHYTHM_NOTIFICATION',
'HIGH_HEART_RATE_EVENT',
'LOW_HEART_RATE_EVENT',
'WALKING_STEADINESS_EVENT',
'BREATHING_DISTURBANCE_EVENT'
)
);
END IF;
END
$$;
@@ -0,0 +1,37 @@
-- v1.10.0 — computed scores (WX-C): COMPUTED source + the three `*_SCORE`
-- measurement types.
--
-- Two purely-additive enum extensions, no new columns and no backfill:
--
-- 1. A new `measurement_source` value `COMPUTED` for server-derived rows.
-- A `COMPUTED` Measurement is minted by a nightly engine from the user's
-- already-stored signals (the Recovery score is the first); it is NEVER
-- ingested from a client. The client-facing batch + single-POST write
-- surfaces reject it exactly like `WITHINGS` / `IMPORT`. It is part of
-- the enum so the read/response shapes (and the iOS decoder) can decode
-- the rows it surfaces.
--
-- 2. Three new `measurement_type` values — the server-derived wellness
-- scores `RECOVERY_SCORE`, `STRESS_SCORE`, `STRAIN_SCORE` (0–100, unit
-- `score`), each minted nightly by its own engine. These are NOT
-- clinical vitals: they stay out of the clinical vitals table and
-- surface only in a clearly-labelled, descriptive-not-clinical wellness
-- summary (and as FHIR `survey`-category observations).
--
-- Idempotent guards (`IF NOT EXISTS`) make reruns safe. Forward-only.
--
-- Reversibility:
-- Postgres does not support removing an enum value, so the four new
-- members stay; with no rows carrying them (a `COMPUTED` source / a
-- `*_SCORE` type) after the nightly job is disabled they are inert.
-- ── 1. measurement_source — append the COMPUTED server-owned source ────
-- Pure additive; no existing row carries this value. The `IF NOT EXISTS`
-- guard keeps the migration idempotent across a partially-applied environment.
ALTER TYPE "measurement_source" ADD VALUE IF NOT EXISTS 'COMPUTED';
-- ── 2. measurement_type — append the three computed-score classes ──────
-- Pure additive; no existing row carries any of these values.
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'RECOVERY_SCORE';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'STRESS_SCORE';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'STRAIN_SCORE';
@@ -0,0 +1,44 @@
-- v1.10.0 — per-workout heart-rate series (route-independent).
--
-- A companion to `workout_routes` that holds the per-sample HR series
-- WITHOUT requiring GPS geometry. The route table only exists when a
-- workout has a GeoJSON LineString, so an INDOOR session (treadmill,
-- trainer, strength) had nowhere to store its heart-rate samples even
-- though HealthKit ships them. That series feeds the training-strain
-- engine (TRIMP / time-in-HR-zone), so decoupling it from the route is
-- what unblocks indoor strain.
--
-- Shape rationale:
-- * `samples` JSONB — `[{ t: ISO string, hr?: int, speedMs?, power?,
-- cadence? }]`, one entry per recorded sample. Same JSONB decision
-- as `workout_routes.geometry` / `sample_timestamps`: no PostGIS
-- extension dependency on a self-hosted Postgres install, and the
-- blob mirrors HealthKit's per-sample shape directly.
-- * `sample_count` — denormalised `samples.length` so the strain
-- reader + observability can size the series without deserialising
-- the JSONB blob. The application caps the array length on write
-- (MAX_WORKOUT_HR_SAMPLES in src/lib/validations/workout.ts) so the
-- per-workout payload — and the largest new workout-side write
-- stream — stays bounded.
--
-- 1:1 with the workout: `workout_id` is UNIQUE with an ON DELETE CASCADE
-- FK, exactly like `workout_routes`. A re-submitted batch that wins the
-- workout-row race but loses the sample-row race is an idempotent no-op
-- (the ingest path uses `skipDuplicates`), not a hard error.
--
-- Idempotent guards (`IF NOT EXISTS`) make reruns safe. Forward-only.
--
-- Reversibility:
-- DROP TABLE IF EXISTS "workout_samples";
-- A roll-back loses the captured per-workout HR series; the workout row,
-- its aggregates (avg/max/min HR), and the route survive untouched.
CREATE TABLE IF NOT EXISTS "workout_samples" (
"id" TEXT PRIMARY KEY,
"workout_id" TEXT NOT NULL UNIQUE REFERENCES "workouts"("id") ON DELETE CASCADE,
-- JSONB array: [{ t: ISO string, hr?: int, speedMs?, power?, cadence? }]
"samples" JSONB NOT NULL,
-- Denormalised samples.length — sized without parsing the blob.
"sample_count" INTEGER NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1,54 @@
-- v1.10.0 — dense intra-day retention tier for daytime HRV / heart-rate.
--
-- The Stress engine reads the intra-day SDNN (and daytime heart-rate)
-- SHAPE across the day, not a single daily mean. Apple Health ships those
-- as discrete per-sample rows, so the engine needs the raw samples to
-- survive long enough to read. Two facts make that safe:
--
-- 1. `HEART_RATE_VARIABILITY` and `PULSE` are NOT in the destructive
-- daily-mean drain's allowlist (`HIGH_FREQUENCY_MEAN_TYPES` in
-- src/lib/measurements/apple-health-mapping.ts), so the nightly
-- mean-consolidation never collapses them — the intra-day shape is
-- preserved by construction. (PULSE was already excluded for the
-- correlation/scatter readers; HRV is exempted for the same reason
-- the Stress proxy needs it.)
--
-- 2. A BOUNDED retention window contains the volume: per-sample HRV / HR
-- rows older than the window are folded to one daily-mean `stats:` row
-- (the same idempotent fold + soft-delete the mean-consolidation uses)
-- and the raw rows are tombstoned. Within the window the raw samples
-- stay, so the Stress engine always has its intra-day inputs for the
-- days it scores.
--
-- This migration adds ONLY the partial index that keeps the dense-tier
-- drain's discovery + per-user scan cheap. No new column, no backfill, no
-- table rewrite. The retention bound itself lives in application code
-- (DENSE_INTRADAY_RETENTION_DAYS in
-- src/lib/measurements/dense-intraday-retention.ts) so tuning it never
-- needs a migration.
--
-- The index is keyed on `(user_id, measured_at)` and partial over the two
-- dense-tier types on live rows only, so it shrinks toward the in-window
-- working set as out-of-window samples are folded away — it carries no
-- steady-state cost once a tenant's history is past the retention window.
--
-- Idempotent guard (`IF NOT EXISTS`) makes reruns safe. Forward-only.
--
-- Lock note (conscious trade-off): a plain, non-`CONCURRENTLY` build, so
-- it runs inside Prisma's migration transaction and holds an ACCESS
-- EXCLUSIVE lock on `measurements` for the build. The partial predicate
-- (two types, `deleted_at IS NULL`) keeps the index small on a typical
-- self-host, so the build is fast and the lock is not felt; the largest
-- multi-year HealthKit tenants should deploy at a low-traffic window. A
-- `CONCURRENTLY` build cannot run inside the migration transaction and is
-- not warranted given the partial-index size on the vast majority of
-- deployments.
--
-- Reversibility:
-- DROP INDEX IF EXISTS "measurements_dense_intraday_retention_idx";
-- A roll-back loses only the scan acceleration; no data is touched.
CREATE INDEX IF NOT EXISTS "measurements_dense_intraday_retention_idx"
ON "measurements" ("user_id", "measured_at")
WHERE "type" IN ('HEART_RATE_VARIABILITY', 'PULSE')
AND "deleted_at" IS NULL;
@@ -0,0 +1,48 @@
-- v1.10.3 — Strain personal-anchor cache.
--
-- A server-internal per-(user, day) cache that lets the nightly Strain engine
-- anchor the 0–100 map to the user's OWN recent training-day load (an
-- EWMA-smoothed P75 of day-total TRIMP over a 42-day chronic window) instead
-- of the fixed population reference. Persisting the day-total TRIMP + the
-- running EWMA reference means the chronic window reads cheap cached values
-- rather than re-integrating 42 days of HR series every night.
--
-- Purely additive: one new table, no enum changes, no backfill. The nightly
-- idempotent recompute populates the cache forward; until a user accrues
-- enough personal training history the engine falls back to the population
-- anchor, so behaviour matches today until the cache fills in — a clean,
-- self-healing rollout.
--
-- NOT a Measurement: never read through the derived registry, never on a
-- user-facing surface, never in the doctor PDF or FHIR bundle, never ingested
-- from a client. A dedicated table keeps it server-internal and out of every
-- MeasurementType completeness wall.
--
-- Reversibility: forward-only; dropping the table loses only the cache, and
-- the nightly job rebuilds it (falling back to the population anchor in the
-- interim).
CREATE TABLE IF NOT EXISTS "strain_trimp_cache" (
"id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"day" TEXT NOT NULL,
"day_trimp" DOUBLE PRECISION NOT NULL,
"ref_personal" DOUBLE PRECISION NOT NULL,
"anchor" TEXT NOT NULL,
"training_days" INTEGER NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "strain_trimp_cache_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX IF NOT EXISTS "strain_trimp_cache_user_id_day_key"
ON "strain_trimp_cache" ("user_id", "day");
CREATE INDEX IF NOT EXISTS "strain_trimp_cache_user_id_day_idx"
ON "strain_trimp_cache" ("user_id", "day" DESC);
ALTER TABLE "strain_trimp_cache"
ADD CONSTRAINT "strain_trimp_cache_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users" ("id")
ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,50 @@
-- v1.11.0 — clinician share links.
--
-- A user mints a link (`hls_<48 hex>`) they hand a clinician, who opens it in
-- any browser with no account and sees a scoped, time-limited, revocable
-- read-only view of the health record. The raw token is stored ONLY as an
-- HMAC-SHA256 hash (`token_hash`, same scheme as `api_tokens.token_hash`);
-- the plaintext is returned to the owner exactly once at creation.
--
-- The scope is FROZEN at creation: `range_start`, `sections_json` and
-- `resource_types` are write-once — a share can NEVER widen later. Only
-- `revoked_at`, `last_access_at` and `access_count` mutate after mint, which
-- mirrors the append-only spirit of `consent_receipts`. `expires_at` is
-- mandatory (capped at SHARE_LINK_MAX_DAYS, default 90) — no never-expiring
-- share. Deleting the user cascades every share away (clean GDPR-erasure).
--
-- Purely additive: one new table, no enum changes, no backfill. Forward-only;
-- dropping the table loses only the share links (read access is revoked).
CREATE TABLE IF NOT EXISTS "clinician_share_links" (
"id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"token_hash" TEXT NOT NULL,
"label" TEXT NOT NULL,
"range_start" TIMESTAMP(3) NOT NULL,
"range_end" TIMESTAMP(3),
"sections_json" JSONB NOT NULL,
"resource_types" TEXT[],
"allow_fhir_api" BOOLEAN NOT NULL DEFAULT false,
"expires_at" TIMESTAMP(3) NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"revoked_at" TIMESTAMP(3),
"last_access_at" TIMESTAMP(3),
"access_count" INTEGER NOT NULL DEFAULT 0,
CONSTRAINT "clinician_share_links_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX IF NOT EXISTS "clinician_share_links_token_hash_key"
ON "clinician_share_links" ("token_hash");
CREATE INDEX IF NOT EXISTS "clinician_share_links_user_id_created_at_idx"
ON "clinician_share_links" ("user_id", "created_at" DESC);
CREATE INDEX IF NOT EXISTS "clinician_share_links_expires_at_idx"
ON "clinician_share_links" ("expires_at");
ALTER TABLE "clinician_share_links"
ADD CONSTRAINT "clinician_share_links_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users" ("id")
ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,98 @@
-- v1.11.0 — WHOOP integration (schema + data layer).
--
-- Purely-additive: two enum-extension batches, two new tables, and two new
-- nullable columns on `users`. No backfill, no existing row touched.
--
-- 1. `measurement_type` += seven WHOOP-native score classes. WHOOP day-strain
-- lands in the NEW `DAY_STRAIN` (NOT the existing COMPUTED `STRAIN_SCORE`,
-- the v1.10.3 TRIMP engine) so the native value and the derived proxy
-- never share a bucket. The RMSSD HRV gets its own `HRV_RMSSD` for the
-- same reason (distinct estimator from the SDNN `HEART_RATE_VARIABILITY`).
-- WHOOP-native Recovery reuses the existing `RECOVERY_SCORE`, distinguished
-- only by `source = WHOOP` vs `COMPUTED`.
-- 2. `measurement_source` += `WHOOP` for the server-side native ingest.
-- 3. `whoop_connections` — per-user encrypted token row (1:1 with users),
-- mirroring `withings_connections` plus `whoop_user_id`,
-- `backfill_completed_at`, and `max_heart_rate`.
-- 4. `whoop_oauth_states` — short-lived `(nonce → userId)` CSRF ledger,
-- identical in shape to `withings_oauth_states`.
-- 5. `users` += `whoop_client_id_encrypted` / `whoop_client_secret_encrypted`
-- — per-user BYO-keys (the per-app authorized-user cap makes a single
-- shared WHOOP app unworkable for a multi-operator product).
--
-- Idempotent guards (`IF NOT EXISTS`) make reruns safe. Forward-only.
--
-- Reversibility: Postgres cannot remove an enum value, so the eight new
-- members stay; with no rows carrying them they are inert. The two tables drop
-- with `DROP TABLE IF EXISTS`, the two columns with `DROP COLUMN IF EXISTS`.
-- ── 1. measurement_type — append the seven WHOOP-native score classes ──
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'HRV_RMSSD';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'DAY_STRAIN';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'WORKOUT_STRAIN';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'SLEEP_PERFORMANCE';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'SLEEP_EFFICIENCY';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'SLEEP_CONSISTENCY';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'SLEEP_NEED';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'ENERGY_EXPENDITURE_KJ';
-- ── 2. measurement_source — append the WHOOP server-owned source ───────
ALTER TYPE "measurement_source" ADD VALUE IF NOT EXISTS 'WHOOP';
-- ── 3. whoop_connections ──────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS "whoop_connections" (
"id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"whoop_user_id" TEXT NOT NULL,
"access_token" TEXT NOT NULL,
"refresh_token" TEXT NOT NULL,
"token_expires_at" TIMESTAMP(3) NOT NULL,
"scope" TEXT,
"last_synced_at" TIMESTAMP(3),
"backfill_completed_at" TIMESTAMP(3),
"max_heart_rate" INTEGER,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "whoop_connections_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX IF NOT EXISTS "whoop_connections_user_id_key"
ON "whoop_connections" ("user_id");
DO $$ BEGIN
ALTER TABLE "whoop_connections"
ADD CONSTRAINT "whoop_connections_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION
WHEN duplicate_object THEN NULL;
END $$;
-- ── 4. whoop_oauth_states ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS "whoop_oauth_states" (
"nonce" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expires_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "whoop_oauth_states_pkey" PRIMARY KEY ("nonce")
);
CREATE INDEX IF NOT EXISTS "whoop_oauth_states_expires_at_idx"
ON "whoop_oauth_states" ("expires_at");
DO $$ BEGIN
ALTER TABLE "whoop_oauth_states"
ADD CONSTRAINT "whoop_oauth_states_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION
WHEN duplicate_object THEN NULL;
END $$;
-- ── 5. users — per-user WHOOP BYO-key columns (encrypted at app level) ─
ALTER TABLE "users"
ADD COLUMN IF NOT EXISTS "whoop_client_id_encrypted" TEXT;
ALTER TABLE "users"
ADD COLUMN IF NOT EXISTS "whoop_client_secret_encrypted" TEXT;
@@ -0,0 +1,43 @@
-- v1.11.0 W1 — durable, multi-instance provider-health ledger.
--
-- Promotes the volatile per-worker last-working cache in
-- `provider-runner.ts` to Postgres, modelled on the atomic-upsert
-- rate-limiter table so every worker shares one health signal. One row
-- per (user, provider chain entry):
-- - the runner records each generation outcome (ok / hard_failed /
-- auth_failed) and reads the row to deprioritise or skip a provider
-- inside its backoff window instead of re-burning a dead round-trip;
-- - an auth-class failure (401/403) sets `last_result = 'auth_failed'`
-- plus a `next_retry_at` cooldown — a durable negative cache that
-- also drives the proactive `credential_expired` surfacing.
--
-- Purely additive: one new table, no enum changes, no backfill. Until a
-- provider fails the table is empty and behaviour matches today.
-- Reversibility: forward-only; dropping the table loses only the cache,
-- and the runner repopulates it on the next outcome.
CREATE TABLE IF NOT EXISTS "provider_health" (
"id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"provider_type" TEXT NOT NULL,
"last_result" TEXT NOT NULL,
"last_status" INTEGER,
"consecutive_failures" INTEGER NOT NULL DEFAULT 0,
"last_ok_at" TIMESTAMP(3),
"last_failure_at" TIMESTAMP(3),
"next_retry_at" TIMESTAMP(3),
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "provider_health_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX IF NOT EXISTS "provider_health_user_id_provider_type_key"
ON "provider_health" ("user_id", "provider_type");
CREATE INDEX IF NOT EXISTS "provider_health_user_id_last_result_idx"
ON "provider_health" ("user_id", "last_result");
ALTER TABLE "provider_health"
ADD CONSTRAINT "provider_health_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,43 @@
-- v1.11.0 — period-narrative cache (Pillar P1).
--
-- One durable, typed row per (user, period, locale) holding the latest
-- generated period summary ("how your week/month went"). Delete +
-- regenerate clean: the unique index on (user_id, period, locale) enforces
-- a single row per slot, so a regeneration upserts in place and there is
-- never a stale duplicate to disambiguate.
--
-- The generated prose is held AES-256-GCM at rest in `encrypted_content`
-- (BYTEA), following the `coach_messages.encrypted_content` precedent. The
-- `provenance_json` envelope is labels-only (metric names, the read window,
-- the FDR footer) and carries no PII, so it stays plaintext for a stable,
-- queryable shape — matching `coach_messages.metric_source_json`.
--
-- Purely additive: one new table, no enum changes, no backfill. Deleting the
-- user cascades every narrative away (clean GDPR-erasure).
CREATE TABLE IF NOT EXISTS "insight_narratives" (
"id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"period" TEXT NOT NULL,
"locale" TEXT NOT NULL,
"date_key" TEXT NOT NULL,
"encrypted_content" BYTEA NOT NULL,
"provenance_json" TEXT,
"provider_type" TEXT,
"prompt_version" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "insight_narratives_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX IF NOT EXISTS "insight_narratives_user_id_period_locale_key"
ON "insight_narratives" ("user_id", "period", "locale");
CREATE INDEX IF NOT EXISTS "insight_narratives_user_id_updated_at_idx"
ON "insight_narratives" ("user_id", "updated_at" DESC);
ALTER TABLE "insight_narratives"
ADD CONSTRAINT "insight_narratives_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users" ("id")
ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,5 @@
-- v1.11.0 — rolling encrypted conversation summary for the Coach.
-- Additive only; safe on a populated table (nullable + defaulted).
ALTER TABLE "coach_conversations" ADD COLUMN IF NOT EXISTS "summary_encrypted" BYTEA;
ALTER TABLE "coach_conversations" ADD COLUMN IF NOT EXISTS "summary_updated_at" TIMESTAMP(3);
ALTER TABLE "coach_conversations" ADD COLUMN IF NOT EXISTS "summary_turn_count" INTEGER NOT NULL DEFAULT 0;
@@ -0,0 +1,32 @@
-- v1.11.1 — source-aware measurement rollups.
--
-- `measurement_rollups` is a derived cache; the authoritative readings live in
-- `measurements`. Existing rollup rows are SOURCE-BLIND aggregates: they group
-- by (type, day) only, so two sources reporting the same standard vital for one
-- day (e.g. WHOOP + Apple Watch resting heart rate) were AVG-blended into one
-- row. Re-grain the table to (type, day, source) so the read path can collapse
-- overlapping sources to the ladder-canonical reading while cumulative metrics
-- (steps, energy) still sum per source.
--
-- The existing rows cannot be re-grained in place (their source is unknown —
-- they already blend N sources), so purge them. This is non-destructive of user
-- data: the boot-time rollup backfill (`rollup-full-backfill`) and the
-- read-time self-heal (`ensureUserRollupsFresh` + the /api/measurements
-- coverage fallback) re-mint per-source rows on next worker boot / first read.
-- Bounded, idempotent, multi-tenant-safe; no operator action required.
DELETE FROM "measurement_rollups";
-- Additive column. DEFAULT only to satisfy NOT NULL during the (now empty)
-- table rewrite, then dropped so every writer must supply an explicit source.
ALTER TABLE "measurement_rollups"
ADD COLUMN "source" "measurement_source" NOT NULL DEFAULT 'MANUAL';
ALTER TABLE "measurement_rollups" ALTER COLUMN "source" DROP DEFAULT;
-- Re-grain the primary key to include source. The hot descending index
-- (user_id, type, granularity, bucket_start DESC) is unchanged: readers fetch
-- every source for a (user, type) range and collapse in application code, so
-- they never filter by source in SQL.
ALTER TABLE "measurement_rollups" DROP CONSTRAINT "measurement_rollups_pkey";
ALTER TABLE "measurement_rollups"
ADD CONSTRAINT "measurement_rollups_pkey"
PRIMARY KEY ("user_id", "type", "granularity", "bucket_start", "source");
@@ -0,0 +1,27 @@
-- v1.11.1 — durable Coach personal facts (Epic B, B-W7).
--
-- Additive, multi-tenant-safe: one new table + index + FK, no column on an
-- existing hot table, no backfill. The fact text is encrypted at rest
-- (AES-256-GCM, same codec as coach_messages.encrypted_content); category /
-- confidence / source stay plain so the injection picker can rank without a
-- per-row decrypt. Soft-delete via deleted_at keeps "forget this" auditable.
CREATE TABLE "coach_facts" (
"id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"fact_encrypted" BYTEA NOT NULL,
"category" TEXT NOT NULL,
"confidence" INTEGER NOT NULL DEFAULT 50,
"source_conversation_id" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"deleted_at" TIMESTAMP(3),
CONSTRAINT "coach_facts_pkey" PRIMARY KEY ("id")
);
CREATE INDEX "coach_facts_user_id_deleted_at_confidence_idx"
ON "coach_facts" ("user_id", "deleted_at", "confidence");
ALTER TABLE "coach_facts"
ADD CONSTRAINT "coach_facts_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE;
+597 -12
View File
@@ -43,6 +43,13 @@ model User {
// behaviour for every existing row.
insightsExcludeMetrics String[] @default([]) @map("insights_exclude_metrics")
// v1.8.5 — user-level injection-site deny-list. Sites listed here are
// never offered for ANY medication's injection-site picker and the
// intake write path 422s a submitted site that lands on this list,
// even when the per-medication `allowedInjectionSites` lists it as
// preferred (deny always wins). Default `[]` = no global exclusion.
globalExcludedInjectionSites InjectionSite[] @default([]) @map("global_excluded_injection_sites")
// Telegram notifications (per-user)
telegramBotToken String? @map("telegram_bot_token") // AES-256-GCM encrypted
telegramChatId String? @map("telegram_chat_id")
@@ -52,6 +59,13 @@ model User {
withingsClientIdEncrypted String? @map("withings_client_id_encrypted")
withingsClientSecretEncrypted String? @map("withings_client_secret_encrypted")
// v1.11.0 — WHOOP OAuth credentials (per-user BYO-keys, encrypted at app
// level). The per-app authorized-user cap makes a single shared WHOOP app
// unworkable for a multi-operator product, so each self-hoster registers
// their own WHOOP dev app and pastes the client id/secret into Settings.
whoopClientIdEncrypted String? @map("whoop_client_id_encrypted")
whoopClientSecretEncrypted String? @map("whoop_client_secret_encrypted")
// moodLog integration (per-user, encrypted)
moodLogUrlEncrypted String? @map("mood_log_url_encrypted")
moodLogApiKeyEncrypted String? @map("mood_log_api_key_encrypted")
@@ -322,6 +336,10 @@ model User {
// where the legacy `${user.id}:${nonce}` shape leaked the user id
// into request logs / network captures.
withingsOAuthStates WithingsOAuthState[]
// v1.11.0 — WHOOP integration. Mirrors the Withings connection (1:1) +
// OAuth-state ledger (1:N) relations.
whoopConnection WhoopConnection?
whoopOAuthStates WhoopOAuthState[]
moodEntries MoodEntry[]
notificationChannels NotificationChannel[]
pushSubscriptions PushSubscription[]
@@ -333,6 +351,7 @@ model User {
devices Device[]
integrationStatuses IntegrationStatus[]
coachConversations CoachConversation[]
coachFacts CoachFact[]
coachUsage CoachUsage[]
// v1.4.25 W8d — workout passthrough (Apple HKWorkout / Withings
// getworkouts / future Strava). Schema lands now so the v1.5 iOS
@@ -397,6 +416,22 @@ model User {
// retires rows older than 90 days (see `handlePushAttemptCleanup` in
// `reminder-worker.ts`).
pushAttempts PushAttempt[]
// v1.10.3 — per-(user, day) Strain personal-anchor cache (day-total
// TRIMP + running EWMA reference) so the nightly Strain engine anchors
// the 0–100 map to the user's own training load without re-integrating
// the 42-day chronic window of HR series each night.
strainTrimpCache StrainTrimpCache[]
// v1.11.0 — owner-minted clinician share links. Each row grants a
// scoped, time-limited, revocable read view of the health record to a
// clinician holding the raw `hls_` token (stored only as an HMAC hash).
clinicianShareLinks ClinicianShareLink[]
// v1.11.0 W1 — durable per-provider AI-health ledger (one row per
// provider chain entry) so a known-bad credential is negatively cached
// across workers instead of re-burning a 401 every generation.
providerHealth ProviderHealth[]
// v1.11.0 W3 — one durable period-narrative row per (period, locale).
// Delete/regenerate-clean; the generated prose is AES-256-GCM at rest.
insightNarratives InsightNarrative[]
// v1.7.0 profile — optional patient-identity fields surfaced on the
// health-record export cover (PDF) and the FHIR `Patient` resource.
@@ -411,6 +446,16 @@ model User {
insurerName String? @map("insurer_name")
insuranceNumberEncrypted String? @map("insurance_number_encrypted")
// v1.8.6 profile — optional German insurer institution number (IKNR,
// 9 digits). Surfaced on the FHIR `Coverage` resource's contained
// payor `Organization` (system `http://fhir.de/sid/arge-ik/iknr`).
// Stored plaintext, matching `insurerName` — the IKNR is a public
// registry identifier, not a quasi-identifier like the KVNR, so it
// does not warrant the encrypted column treatment. Optional; an unset
// field collapses the Coverage payor identifier exactly like an
// unset `insurerName` collapses its name.
insurerIkNumber String? @map("insurer_ik_number")
@@map("users")
}
@@ -515,10 +560,90 @@ enum MeasurementType {
// and pass through `convertToDbUnit` as identity.
WALKING_STEP_LENGTH // metres — HealthKit `walkingStepLength`. Mobility section gait metric; adult walking typically 0.5–0.8 m.
WALKING_SPEED // metres per second — HealthKit `walkingSpeed`. Mobility section gait metric; healthy adult casual gait ≈ 1.2–1.4 m/s.
// v1.10.0 — additive HealthKit signals (WX-A)
// Seven previously-deferred quantity identifiers, wired end-to-end with
// the generic metric-status assessment treatment. Each rides the same
// server-side `convertToDbUnit` + plausibility-range path as the rest of
// the HealthKit surface; see `src/lib/measurements/apple-health-mapping.ts`.
CARDIO_RECOVERY // bpm — HealthKit `heartRateRecoveryOneMinute` (iOS 16+). The drop in heart rate one minute after peak exercise; a larger drop signals fitter autonomic recovery (higher-better).
WRIST_TEMPERATURE // celsius — HealthKit `appleSleepingWristTemperature` (iOS 16+). Overnight wrist temperature; Apple surfaces it as a baseline deviation, we store the absolute reading. DISTINCT from BODY_TEMPERATURE (core) and SKIN_TEMPERATURE (Withings dermal spot).
FALL_COUNT // count — HealthKit `numberOfTimesFallen`. Hard-fall detections; cumulative daily count, lower-better.
SIX_MINUTE_WALK_DISTANCE // metres — HealthKit `sixMinuteWalkTestDistance`. Apple's estimated 6-minute-walk-test distance; mobility + cardiopulmonary endurance signal, higher-better.
STAIR_ASCENT_SPEED // metres per second — HealthKit `stairAscentSpeed`. Mobility section gait metric measured while climbing stairs, higher-better.
STAIR_DESCENT_SPEED // metres per second — HealthKit `stairDescentSpeed`. Mobility section gait metric measured while descending stairs, higher-better.
BREATHING_DISTURBANCES // count — HealthKit `appleSleepingBreathingDisturbances` (iOS 18+). Per-night sleep-breathing-disturbance index Apple classifies as NotElevated / Elevated; lower-better.
// v1.10.0 — categorical events (WX-B)
// Device-flagged EVENT rows. These are NOT continuous measurements —
// each row records a discrete on-device notification the user's wearable
// produced (Apple Watch / Withings ScanWatch). `value` is always 1 (one
// fired event); the device's verdict / severity lands in the
// `rhythmClassification` column (see the `RhythmClassification` enum and
// the CHECK constraint in migration 0105). HealthLog never re-derives or
// re-classifies the underlying signal — it only stores and surfaces the
// result the device's own certified algorithm already emitted.
IRREGULAR_RHYTHM_NOTIFICATION // HealthKit `HKCategoryTypeIdentifierIrregularHeartRhythmEvent` + ScanWatch AFib screening. The certified on-device algorithm flagged a possible irregular rhythm. AWARENESS ONLY — never a HealthLog diagnosis.
HIGH_HEART_RATE_EVENT // HealthKit `HKCategoryTypeIdentifierHighHeartRateEvent`. The watch detected a sustained high heart rate above the user's configured threshold while apparently inactive.
LOW_HEART_RATE_EVENT // HealthKit `HKCategoryTypeIdentifierLowHeartRateEvent`. The watch detected a sustained low heart rate below the user's configured threshold.
WALKING_STEADINESS_EVENT // HealthKit `HKCategoryTypeIdentifierAppleWalkingSteadinessEvent`. The device flagged low / very-low walking steadiness (a falls-risk mobility signal); the severity rides in `rhythmClassification`.
BREATHING_DISTURBANCE_EVENT // HealthKit `HKCategoryTypeIdentifierSleepApneaEvent` + `AppleSleepingBreathingDisturbances`. The device flagged an elevated breathing-disturbance / possible sleep-apnea signal during sleep. SCREENING SIGNAL ONLY — never a HealthLog diagnosis.
// v1.10.0 — computed scores (WX-C)
// Server-derived wellness scores (0–100, unit `score`). Each is minted by a
// nightly engine from the user's already-stored signals and persisted as a
// `COMPUTED`-source Measurement row — never ingested from a client. Only
// RECOVERY_SCORE is computed in v1.10.0; STRESS_SCORE + STRAIN_SCORE are
// defined now so the later engines that compute them need no schema change.
// These are NOT clinical vitals — they never appear in the doctor-report PDF.
RECOVERY_SCORE // Daily recovery / readiness proxy. Higher = more recovered. Blends RHR + HRV (SDNN) + sleep + respiratory-rate deviation from the personal baseline (Plews 2013 / Buchheit 2014 lineage). Descriptive, not a clinical or training-recovery assessment. v1.11.0: WHOOP ships a device-native Recovery into this SAME type, distinguished by `source = WHOOP` vs `COMPUTED` — the two unique keys keep both rows; the cross-source picker decides display.
STRESS_SCORE // Reserved for the later strain/stress engine. Higher = more physiological stress. No engine computes it in v1.10.0.
STRAIN_SCORE // Reserved for the later strain/stress engine. Higher = more cardiovascular strain (workout-load lineage). No engine computes it in v1.10.0. WHOOP day-strain does NOT reuse this — it lands in DAY_STRAIN so the WHOOP-native value and HealthLog's TRIMP proxy never share a bucket.
// ── v1.11.0 — WHOOP integration (additive) ──
// Native WHOOP scores ingest as first-class `source = WHOOP` Measurement
// rows. Where the concept already exists as a COMPUTED type (RECOVERY_SCORE)
// the WHOOP row reuses that type and is distinguished by source; where it
// would collide with a HealthLog engine (STRAIN_SCORE) or a different
// physiological measure (SDNN HEART_RATE_VARIABILITY) it gets a NEW type so
// the native value and the derived proxy never share a bucket. See
// `.planning/v1.11-build/epic-A-whoop-buildspec.md` §3.2 / §5.
HRV_RMSSD // ms — WHOOP `recovery.score.hrv_rmssd_milli`. The RMSSD HRV metric WHOOP reports; kept structurally distinct from the SDNN HEART_RATE_VARIABILITY (different estimator, not interchangeable).
DAY_STRAIN // score (0–21) — WHOOP `cycle.score.strain`. The day's cardiovascular load on WHOOP's 0–21 scale. Distinct from the COMPUTED STRAIN_SCORE (0–100 TRIMP proxy) so the two never share a bucket.
WORKOUT_STRAIN // score (0–21) — WHOOP `workout.score.strain`. Per-workout strain; preferentially stored in `Workout.metadata` (tied to the workout row) rather than as a free-floating Measurement, but the type exists for the rare detached case.
SLEEP_PERFORMANCE // % (0–100) — WHOOP `sleep.score.sleep_performance_percentage`. Sleep achieved vs sleep needed.
SLEEP_EFFICIENCY // % (0–100) — WHOOP `sleep.score.sleep_efficiency_percentage`. Time asleep vs time in bed.
SLEEP_CONSISTENCY // % (0–100) — WHOOP `sleep.score.sleep_consistency_percentage`. Night-to-night bed/wake timing regularity.
SLEEP_NEED // minutes — WHOOP `sleep.score.sleep_needed.baseline_milli` (+ debt / strain / nap components; ms→min). The model's recommended sleep duration for the night.
ENERGY_EXPENDITURE_KJ // kJ — WHOOP `cycle.score.kilojoule`. Day energy expenditure in kilojoules (WHOOP reports kJ natively; kept in kJ rather than converted to kcal so the device-native value round-trips).
@@map("measurement_type")
}
/// v1.10.0 — categorical events (WX-B)
/// The device's own classification RESULT / severity for an EVENT row.
/// Non-NULL only for the categorical EVENT `MeasurementType`s
/// (IRREGULAR_RHYTHM_NOTIFICATION, HIGH/LOW_HEART_RATE_EVENT,
/// WALKING_STEADINESS_EVENT, BREATHING_DISTURBANCE_EVENT), NULL for every
/// continuous measurement — mirroring the `GlucoseContext` / `SleepStage`
/// nullable-context precedent.
///
/// HealthLog stores ONLY the verdict the device's FDA-cleared / CE-marked
/// on-device algorithm already produced. It never re-classifies a raw
/// signal and never emits a diagnosis of its own. `IRREGULAR` means the
/// device flagged a possible irregular rhythm; `NOT_DETECTED` /
/// `INCONCLUSIVE` carry the device's own non-positive verdicts so the
/// awareness timeline can be honest rather than only ever showing alarms.
/// `LOW` / `VERY_LOW` carry the walking-steadiness severity; `FIRED` is the
/// neutral "this event occurred" verdict for the high/low-HR + breathing
/// events that have no finer device-side grading.
enum RhythmClassification {
IRREGULAR // device flagged a possible irregular rhythm (AFib screening)
NOT_DETECTED // device's algorithm ran and did not flag an irregular rhythm
INCONCLUSIVE // device could not classify (poor signal / out-of-range HR)
LOW // walking-steadiness: low
VERY_LOW // walking-steadiness: very low
FIRED // neutral "event occurred" verdict (high/low-HR, breathing disturbance)
@@map("rhythm_classification")
}
/// Context for glucose measurements — affects which target range applies.
/// NULL for non-glucose measurements.
enum GlucoseContext {
@@ -535,6 +660,18 @@ enum MeasurementSource {
WITHINGS
IMPORT
APPLE_HEALTH // v1.4.23 — HealthKit batch ingest. iOS DTO mirrors this exact spelling (not "HEALTHKIT").
// v1.10.0 — computed scores (WX-C)
// Server-derived rows. A `COMPUTED` measurement is minted by a nightly
// engine from the user's already-stored signals (the Recovery score is the
// first); it is NEVER ingested from a client. Server-owned / read-only:
// the client-facing batch + single-POST write surfaces reject it exactly
// like WITHINGS / IMPORT, but it is part of the read enum so iOS can decode
// the rows it queries / charts.
COMPUTED
// v1.11.0 — WHOOP integration. Native WHOOP scores ingest server-side
// (no client write path) as `source = WHOOP` rows. iOS DTO mirrors this
// exact spelling so the `/api/sync/changes` delta feed decodes the rows.
WHOOP
@@map("measurement_source")
}
@@ -579,6 +716,15 @@ model Measurement {
// only for `type = SLEEP_DURATION`. Mirrors the glucoseContext
// pattern. A single night produces ~5 rows (one per stage).
sleepStage SleepStage? @map("sleep_stage")
// v1.10.0 — categorical events (WX-B). The device's own classification
// verdict / severity for an EVENT row. NULL for every continuous
// measurement; non-NULL only for the categorical EVENT `MeasurementType`s.
// Mirrors the `sleepStage` / `glucoseContext` nullable-context columns. A
// CHECK constraint (migration 0105) enforces the type pairing so a
// continuous row can never carry a classification. NOT part of any unique
// index — dedup stays on `(userId, type, source, externalId)` keyed by the
// device's `HKSample.uuid`, so a re-posted event collapses to a duplicate.
rhythmClassification RhythmClassification? @map("rhythm_classification")
// v1.4.25 W8c — device-type tag for the cross-source canonical
// picker. Stored as a free-text string (kept simple — Prisma enum
// would require coordinated client + server bumps every time we
@@ -638,6 +784,11 @@ model Measurement {
// migration 0087. It accelerates the v1.5.6 legacy step-consolidation
// discovery scan. Prisma can't express a partial-predicate index, so
// it lives in raw migration SQL and is intentionally omitted here.
// `measurements_dense_intraday_retention_idx` is a partial index over
// `type IN ('HEART_RATE_VARIABILITY','PULSE') AND deleted_at IS NULL`
// — see migration 0108. It accelerates the v1.10.0 dense intra-day
// retention drain's discovery + per-user scan. Same Prisma-can't-
// express-a-partial-predicate reason it is omitted here.
@@map("measurements")
}
@@ -671,6 +822,13 @@ model MeasurementRollup {
type MeasurementType
granularity RollupGranularity
bucketStart DateTime @map("bucket_start") @db.Timestamptz(3)
/// v1.11.1 — source-aware grain. Rollup rows are minted per source so the
/// read path can collapse overlapping sources (e.g. WHOOP + Apple Watch
/// resting heart rate) to the ladder-canonical reading, while cumulative
/// metrics (steps, energy) sum per source. Always non-null; migration 0115
/// purged the legacy source-blind aggregates and the boot backfill re-mints
/// per-source rows.
source MeasurementSource
count Int
mean Float
minValue Float @map("min_value")
@@ -689,7 +847,7 @@ model MeasurementRollup {
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@id([userId, type, granularity, bucketStart])
@@id([userId, type, granularity, bucketStart, source])
@@index([userId, type, granularity, bucketStart(sort: Desc)])
@@map("measurement_rollups")
}
@@ -741,21 +899,28 @@ model Workout {
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
route WorkoutRoute?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
route WorkoutRoute?
samples WorkoutSamples?
/// Ingest dedup. NULL externalId is distinct so two manual
/// entries on the same day never collide here.
///
/// TODO(v1.5 iOS): cross-source workout dedup. The current key is
/// (userId, source, externalId) — so the SAME workout ingested from
/// MANUAL plus the iOS HealthKit passthrough lands two rows because
/// `source` differs. Measurements already solved this via
/// `pickCanonicalSourceRows()` (the read-time canonical-source
/// picker in src/lib/analytics/source-priority.ts); workouts need
/// the symmetric helper before the dashboard "recent workouts" tile
/// can show one row per workout instead of one per source. Tracked
/// for v1.5 P1 alongside the iOS app.
/// Cross-source dedup (the SAME logical workout arriving from two
/// paired sensors — e.g. Apple Watch + Withings ScanWatch — under
/// different `source`/`externalId` pairs) is handled in two layers,
/// mirroring the measurement-side `pickCanonicalSourceRows()`:
/// * WRITE-time — `dedupeWorkoutBatch()` in
/// src/lib/workouts/canonical-rows.ts groups an inbound batch by
/// (userId, activityType, startedAt ± 90 s) and keeps one
/// canonical row per logical workout BEFORE the insert, so the
/// duplicate never reaches storage.
/// * READ-time — `pickCanonicalWorkoutRows()` in
/// src/lib/measurements/pick-canonical-workout-rows.ts collapses
/// any cross-batch twins (e.g. one source's row from Monday's
/// batch + the other's from Tuesday's backfill) so the dashboard
/// "recent workouts" tile shows one row per logical workout.
/// Both pickers resolve the user's `sourcePriorityJson` ladder.
@@unique([userId, source, externalId])
/// Dashboard "recent workouts" query path.
@@index([userId, startedAt])
@@ -784,6 +949,89 @@ model WorkoutRoute {
@@map("workout_routes")
}
// ─── Per-workout heart-rate (+ optional speed/power/cadence) series ──
//
// v1.10.0 — a route-independent companion to `WorkoutRoute`.
//
// The route table only exists when a workout has GPS geometry, so an
// INDOOR session (treadmill, bike trainer, strength) had no home for
// its per-sample heart-rate series even though HealthKit ships one.
// That series is the input the training-strain engine (TRIMP /
// time-in-HR-zone) needs, so decoupling it from the route is what
// unblocks indoor strain.
//
// `samples` is a JSONB array `[{ t, hr?, speedMs?, power?, cadence? }]`
// — `t` is an ISO timestamp, `hr` beats/min. Same JSONB-over-PostGIS
// decision as `WorkoutRoute` (no extension dependency on a self-hosted
// Postgres). 1:1 with the workout (FK `workout_id` UNIQUE) so a
// re-ingested batch that wins the workout-row race but loses the
// sample-row race is an idempotent no-op, exactly like the route table.
//
// `sample_count` is denormalised so the strain reader + observability
// can size the series without deserialising the JSONB blob. The ingest
// path caps the count (see MAX_WORKOUT_HR_SAMPLES in
// src/lib/validations/workout.ts) to keep the per-workout payload — and
// the largest new workout-side write stream — bounded.
model WorkoutSamples {
id String @id @default(cuid())
workoutId String @unique @map("workout_id")
/// JSONB array of `{ t: ISO string, hr?: int, speedMs?, power?,
/// cadence? }`. One entry per recorded sample; ordered by `t`
/// ascending at ingest. Capped at MAX_WORKOUT_HR_SAMPLES.
samples Json
/// Denormalised `samples.length` — sized without parsing the blob.
sampleCount Int @map("sample_count")
createdAt DateTime @default(now()) @map("created_at")
workout Workout @relation(fields: [workoutId], references: [id], onDelete: Cascade)
@@map("workout_samples")
}
// ─── Strain personal anchor cache (v1.10.3) ─────────────────
//
// Server-internal per-(user, day) cache that lets the nightly Strain
// engine anchor the 0–100 map to the USER'S OWN recent training-day load
// instead of a fixed population reference. Each row records the scored
// day's day-total Banister TRIMP plus the running EWMA-smoothed personal
// reference and which anchor produced that night's score (personal once
// the cold-start floor is met, population before). Persisting day-total
// TRIMP means the 42-day chronic window reads cheap cached values instead
// of re-integrating 42 days of HR series every night.
//
// NOT a Measurement: it is never read through the derived registry, never
// surfaced on any user-facing surface, never in the doctor PDF or FHIR
// bundle, and never ingested from a client. Reusing the Measurement enum
// would have pulled an internal cache type through every MeasurementType
// completeness wall (chart tokens, categories, PR direction); a dedicated
// table keeps it cleanly server-internal. Idempotent on `(userId, day)` so
// a re-fired nightly tick overwrites the day's cache row in place.
model StrainTrimpCache {
id String @id @default(cuid())
userId String @map("user_id")
/// The scored UTC calendar day (`YYYY-MM-DD`), matching the score row's day key.
day String
/// Day-total Banister TRIMP for the day (0 when no usable HR series).
dayTrimp Float @map("day_trimp")
/// EWMA-smoothed personal reference TRIMP in effect for this day's score.
refPersonal Float @map("ref_personal")
/// Which anchor produced this day's score: `personal` once enough personal
/// training history accrued, `population` during cold start.
anchor String
/// Distinct training days (TRIMP > 0) seen in the chronic window — drives
/// the cold-start gate + the confidence label.
trainingDays Int @map("training_days")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([userId, day])
@@index([userId, day(sort: Desc)])
@@map("strain_trimp_cache")
}
// ─── Personal records (v1.4.25 W8d — schema only) ──────────
//
// MAX vs MIN direction is stored on the row so the future detection
@@ -917,6 +1165,19 @@ model Medication {
/// A one-time injection is `oneShot = true` + `deliveryForm =
/// INJECTION`. The migration backfills ORAL for every existing row.
deliveryForm MedicationDeliveryForm @default(ORAL) @map("delivery_form")
/// v1.8.5 — per-medication injection-site tracking opt-in. Only
/// meaningful (and only offered in the UI) when `deliveryForm ===
/// INJECTION`. Default false: after marking a dose taken the client
/// prompts for the site only when this is true, and the prompt is
/// always skippable (never blocking). Deactivatable at any time.
trackInjectionSites Boolean @default(false) @map("track_injection_sites")
/// v1.8.5 — per-medication allowed / preferred injection sites. Empty
/// = no per-medication restriction (every site is offered). The
/// effective pickable set is this list MINUS the user-level
/// `globalExcludedInjectionSites` deny-list (deny always wins). The
/// intake write path validates a submitted site against the effective
/// set and 422s on a disallowed value.
allowedInjectionSites InjectionSite[] @default([]) @map("allowed_injection_sites")
/// v1.7.0 — iOS Live Activity opt-in for this medication's reminders.
/// Default false; existing rows backfill false. The server stores +
/// echoes the flag; the iOS client owns the ActivityKit lifecycle. No
@@ -927,6 +1188,18 @@ model Medication {
/// stores the preference only — it does not itself authorise anything
/// server-side.
criticalAlarmEnabled Boolean @default(false) @map("critical_alarm_enabled")
/// v1.9.0 — optional ATC classification code (active-substance class,
/// e.g. `A10BX10`). User/clinician-asserted; never machine-guessed on
/// the export path. NULL = no code (the FHIR exporter emits a text-only
/// `medicationCodeableConcept`, the pre-v1.9.0 behaviour). The WHO URI
/// `http://www.whocc.no/atc` is the emitted system. Validated on write
/// against `^[A-Z]\d{2}[A-Z]{2}\d{2}$`.
atcCode String? @map("atc_code")
/// v1.9.0 — optional RxNorm RxCUI (US; secondary coding). Same NULL
/// semantics as `atcCode`. Validated on write against `^\d+$`. Emitted
/// under `http://www.nlm.nih.gov/research/umls/rxnorm` alongside any
/// ATC code, never instead of the free-text `.text` anchor.
rxNormCode String? @map("rxnorm_code")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@ -1495,6 +1768,65 @@ model WithingsOAuthState {
@@map("withings_oauth_states")
}
// ─── WHOOP ─────────────────────────────────────────────────
//
// v1.11.0 — structural copy of the Withings connection/oauth-state pair.
// WHOOP ships solo on copy-of-Withings rails (no provider-adapter
// abstraction yet). Tokens are encrypted at app level via `encrypt()` /
// `decrypt()` — the column names mirror the Withings `access_token` /
// `refresh_token` convention (not `*Encrypted`) so the rotation CLI's
// column registry extends the same way.
model WhoopConnection {
id String @id @default(cuid())
userId String @unique @map("user_id")
whoopUserId String @map("whoop_user_id")
accessToken String @map("access_token") // encrypted at app level
refreshToken String @map("refresh_token") // encrypted at app level
tokenExpiresAt DateTime @map("token_expires_at")
/// Space-separated OAuth scope string granted by the WHOOP authorisation
/// flow (`offline read:recovery read:sleep read:workout read:cycles
/// read:profile read:body_measurement`). `offline` is required to receive
/// a refresh token. Null = legacy connection that predates scope tracking.
scope String? @map("scope")
lastSyncedAt DateTime? @map("last_synced_at")
/// Set once the self-converging history backfill walks every collection to
/// completion. Null = backfill still in flight (or never started).
backfillCompletedAt DateTime? @map("backfill_completed_at")
/// Max heart rate from the WHOOP body-measurement profile — a profile
/// constant, not a time series, so it lives here rather than as a
/// Measurement row.
maxHeartRate Int? @map("max_heart_rate")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("whoop_connections")
}
/// v1.11.0 — short-lived `(nonce → userId)` ledger backing the WHOOP OAuth
/// state check, identical in shape + lifecycle to `WithingsOAuthState`.
///
/// Lifecycle:
/// * `connect` mints a row with `expiresAt = now() + 10 min` and sets the
/// state cookie to JUST the random base64url nonce (no user id).
/// * `callback` looks up the row, asserts `expiresAt > now()`, then DELETEs
/// it in the same transaction — replay of the same nonce fails because
/// the row is gone.
/// * A daily cleanup cron sweeps abandoned rows whose `expiresAt` passed.
model WhoopOAuthState {
nonce String @id
userId String @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
expiresAt DateTime @map("expires_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([expiresAt])
@@map("whoop_oauth_states")
}
// ─── Mood Entries (moodLog) ───────────────────────────────────
model MoodEntry {
@@ -1540,6 +1872,13 @@ model MoodEntry {
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
// v1.8.5 — structured-tag links. Additive alongside the legacy flat
// `tags` JSON string: an entry can carry both (a free-text tag the user
// typed AND a structured tag they picked from the taxonomy). The
// aggregates read whichever is present; existing rows keep their flat
// `tags` untouched.
tagLinks MoodEntryTagLink[]
@@unique([userId, date, moodLoggedAt])
@@index([userId, date])
// v1.7.0 sync — keyset support for the `/api/sync/changes` mood feed
@@ -1548,6 +1887,79 @@ model MoodEntry {
@@map("mood_entries")
}
// ─── Mood Tag Taxonomy (v1.8.5 W6-tax) ────────────────────────
//
// Structured, icon-bearing tag catalog modelled on the standalone mood
// diary's Category → TagItem shape. Global reference data (one shared
// catalog for the deployment, not per-user): a self-hoster's account
// inherits the seeded categories the same way the metric-type enum is
// shared. `MoodEntryTagLink` is the per-entry join.
//
// Backward-compat: this is purely ADDITIVE. The legacy flat
// `MoodEntry.tags` (a JSON string array of free-text keys) keeps working
// unchanged — the GLP-1 quick-tag chips, the Telegram/MoodLog sync, and
// every existing row stay on the flat axis. The structured taxonomy is a
// second, richer capture surface that the tag-frequency / lift breakdown
// folds in next to the flat tags (`mood-aggregates.ts`).
//
// `labelKey` carries an i18n key (resolved client-side against all six
// locales) rather than a hard-coded German label, so the seeded catalog
// renders localised everywhere. `icon` is a Lucide icon name rendered by
// the capture UI + breakdown.
model MoodTagCategory {
id String @id @default(cuid())
/// Stable machine key (e.g. `feelings`). Unique across the catalog so
/// the seed migration can upsert idempotently.
key String @unique
/// i18n message key for the category label (`mood.tagCategory.<key>`).
labelKey String @map("label_key")
/// Lucide icon name for the category header.
icon String?
sortOrder Int @default(0) @map("sort_order")
/// Soft-hide a category without deleting its historical links.
isActive Boolean @default(true) @map("is_active")
tags MoodTag[]
@@map("mood_tag_categories")
}
model MoodTag {
id String @id @default(cuid())
categoryId String @map("category_id")
/// Stable machine key (e.g. `happy`). Unique across the catalog.
key String @unique
/// i18n message key for the tag label (`mood.tag.<key>`).
labelKey String @map("label_key")
/// Lucide icon name for the tag chip.
icon String?
sortOrder Int @default(0) @map("sort_order")
isActive Boolean @default(true) @map("is_active")
category MoodTagCategory @relation(fields: [categoryId], references: [id], onDelete: Cascade)
links MoodEntryTagLink[]
@@index([categoryId, sortOrder])
@@map("mood_tags")
}
// Join: which structured tags a mood entry carries. Composite PK keeps
// the pairing unique; cascade on both sides so deleting an entry (or a
// catalog tag) cleans up its links. Distinct from the flat `tags` JSON
// column on `MoodEntry`.
model MoodEntryTagLink {
moodEntryId String @map("mood_entry_id")
moodTagId String @map("mood_tag_id")
createdAt DateTime @default(now()) @map("created_at")
moodEntry MoodEntry @relation(fields: [moodEntryId], references: [id], onDelete: Cascade)
moodTag MoodTag @relation(fields: [moodTagId], references: [id], onDelete: Cascade)
@@id([moodEntryId, moodTagId])
@@index([moodTagId])
@@map("mood_entry_tag_links")
}
// ─── Mood Reminder Dispatch Ledger (v0.5.4 ios-coord) ─────
//
// Idempotency guard for the daily 22:00 MOOD_REMINDER push. The
@@ -1990,6 +2402,41 @@ model RateLimit {
@@map("rate_limits")
}
/// v1.11.0 W1 — durable, multi-instance provider-health ledger.
///
/// Promotes the volatile per-worker `lastWorkingCache`
/// (`provider-runner.ts`) to Postgres, modelled on the atomic-upsert
/// rate-limiter pattern so every worker shares one signal. One row per
/// (user, providerType): the runner records each outcome and reads the
/// row to (a) deprioritise / skip a provider inside its backoff window
/// instead of re-burning a dead round-trip every call, and (b) hold a
/// durable negative-cache for an auth-class failure (401/403 =
/// credential dead) far longer than the old 1h in-memory TTL, surfacing
/// it rather than silently retrying.
///
/// `nextRetryAt` is the backoff gate: while `lastResult = "auth_failed"`
/// and NOW() < `nextRetryAt`, the provider is skipped (negative cache).
/// On a success the row clears to `ok` with a null `nextRetryAt`.
/// Server-internal: never a Measurement, never ingested from a client.
model ProviderHealth {
id String @id @default(cuid())
userId String @map("user_id")
providerType String @map("provider_type") // ProviderChainType tag
lastResult String @map("last_result") // "ok" | "hard_failed" | "auth_failed"
lastStatus Int? @map("last_status") // HTTP status of the last failure; null on ok/network
consecutiveFailures Int @default(0) @map("consecutive_failures")
lastOkAt DateTime? @map("last_ok_at")
lastFailureAt DateTime? @map("last_failure_at")
nextRetryAt DateTime? @map("next_retry_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([userId, providerType])
@@index([userId, lastResult])
@@map("provider_health")
}
// ─── Idempotency Keys (mobile-client replay protection) ──
/// Caches the response of a POST/PUT/PATCH/DELETE request keyed by
@@ -2190,6 +2637,13 @@ model CoachConversation {
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
// v1.11.0 — rolling encrypted summary of the elided older turns, so a long
// conversation keeps memory of what came before without re-sending every
// turn to the provider. AES-256-GCM (same codec as CoachMessage.encrypted).
summaryEncrypted Bytes? @map("summary_encrypted")
summaryUpdatedAt DateTime? @map("summary_updated_at")
summaryTurnCount Int @default(0) @map("summary_turn_count")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
messages CoachMessage[]
@@ -2234,6 +2688,37 @@ model CoachMessage {
@@map("coach_messages")
}
// v1.11.1 (Epic B, B-W7) — durable, user-scoped personal facts the Coach
// extracts from conversations: stable preferences, conditions the user states
// about themselves, goals, constraints, durable life context. The fact TEXT is
// encrypted at rest (AES-256-GCM, the same codec as CoachMessage). `category`,
// `confidence`, and `sourceConversationId` stay plain so the injection picker
// can rank without paying a per-row decrypt. Descriptive, never diagnostic.
// Soft-delete via `deletedAt` so a user "forget this" action is reversible /
// auditable and re-extraction can avoid resurrecting it.
model CoachFact {
id String @id @default(cuid())
userId String @map("user_id")
factEncrypted Bytes @map("fact_encrypted")
// App-side closed enum (not a DB enum, to keep the migration purely additive
// and avoid an enum-migration per new category): preference | condition |
// goal | constraint | context.
category String
// 0..100 server-assigned extraction confidence.
confidence Int @default(50)
// Provenance — nullable so a future manual-entry surface can leave it null.
sourceConversationId String? @map("source_conversation_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
// Soft-delete: hides the fact from injection but keeps the row for audit.
deletedAt DateTime? @map("deleted_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId, deletedAt, confidence])
@@map("coach_facts")
}
// Per-user, per-day token-spend ledger for the AI Coach. The dispatcher
// reads `totalTokens` against `MAX_TOKENS_PER_USER_PER_DAY` before
// hitting any provider, so a runaway client cannot drain the operator's
@@ -2340,3 +2825,103 @@ model PushAttempt {
@@index([userId, createdAt(sort: Desc)])
@@map("push_attempts")
}
// ─── Clinician share links (scoped, time-limited, revocable read view) ───
//
// v1.11.0 — a user mints a link they hand a clinician (email, paper, QR).
// The clinician opens it in any browser with no account and sees a
// read-only view of the health record. The raw `hls_` token is stored
// ONLY as an HMAC-SHA256 hash (`tokenHash`, same scheme as
// `ApiToken.tokenHash`, keyed by `API_TOKEN_HMAC_KEY`); the plaintext is
// returned to the owner exactly once at creation and never persisted.
//
// The scope is FROZEN at creation: `rangeStart`, `sectionsJson` and
// `resourceTypes` are write-once and a share can NEVER widen later — only
// `revokedAt`, `lastAccessAt` and `accessCount` mutate after mint. This
// mirrors the append-only spirit of `ConsentReceipt`. `expiresAt` is
// mandatory (capped at `SHARE_LINK_MAX_DAYS`, default 90) — there is no
// never-expiring share. Deleting the user cascades every share away so
// the GDPR-erasure path stays clean.
model ClinicianShareLink {
id String @id @default(cuid())
userId String @map("user_id")
/// HMAC-SHA256 of the raw `hls_` token (same scheme as `ApiToken.tokenHash`).
tokenHash String @unique @map("token_hash")
/// Human label the owner sets (e.g. a clinic/specialty note). Plaintext, bounded.
label String
// ── Frozen scope (write-once at creation; never widened) ──
/// Reporting-window start (absolute, not "last N days"). Frozen so a
/// rolling share can never reach data older than the owner chose.
rangeStart DateTime @map("range_start")
/// Window end. Null = rolling ("up to now"); set = frozen snapshot window.
rangeEnd DateTime? @map("range_end")
/// Section toggles (the `DoctorReportPrefs` shape the export uses). JSON.
sectionsJson Json @map("sections_json")
/// FHIR resource types this link may serve (a subset of the catalogue),
/// e.g. `["Observation","MedicationStatement"]`.
resourceTypes String[] @map("resource_types")
/// Whether the FHIR API is reachable via this link at all (vs the view only).
allowFhirApi Boolean @default(false) @map("allow_fhir_api")
/// REQUIRED — no never-expiring share (capped at `SHARE_LINK_MAX_DAYS`).
expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
// ── Mutable lifecycle/access counters (the only columns that change) ──
revokedAt DateTime? @map("revoked_at")
lastAccessAt DateTime? @map("last_access_at")
accessCount Int @default(0) @map("access_count")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId, createdAt(sort: Desc)])
@@index([expiresAt])
@@map("clinician_share_links")
}
// v1.11.0 W3 — period-narrative cache (Pillar P1).
//
// One durable, typed row per (user, period, locale) carrying the latest
// generated period summary ("how your week/month went"). Delete +
// regenerate clean: the unique constraint enforces a single row per slot,
// so a regeneration upserts in place and there is never a stale duplicate
// to disambiguate. The generated prose is held AES-256-GCM at rest in
// `encryptedContent` (Bytes), following the `CoachMessage.encryptedContent`
// precedent — the body is descriptive health narrative and is treated as
// sensitive even though it carries labels-plus-numbers, not raw rows.
//
// `provenanceJson` is the labels-only provenance envelope the surface
// renders as ⓘ chips (metric names + the read window + the FDR footer);
// it carries no PII so it stays plaintext for a stable, queryable shape,
// matching `CoachMessage.metricSourceJson`. `providerType` + `promptVersion`
// mirror the attribution columns so the cross-feature aggregator can slice
// quality per (provider × prompt). `period` is `week` | `month`; `dateKey`
// is the UTC `YYYY-MM-DD` boundary the row was generated for, so the
// stale-while-revalidate read can tell "today's" narrative from an older
// one without decrypting.
model InsightNarrative {
id String @id @default(cuid())
userId String @map("user_id")
/// "week" | "month".
period String
/// Resolved UI locale of the prose ("de" | "en").
locale String
/// UTC YYYY-MM-DD boundary the narrative was generated for.
dateKey String @map("date_key")
/// AES-256-GCM ciphertext of the generated narrative prose.
encryptedContent Bytes @map("encrypted_content")
/// Labels-only provenance envelope (metric names, window, FDR footer).
provenanceJson String? @map("provenance_json")
providerType String? @map("provider_type")
promptVersion String? @map("prompt_version")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
// One row per (user, period, locale) — regeneration upserts in place.
@@unique([userId, period, locale])
@@index([userId, updatedAt(sort: Desc)])
@@map("insight_narratives")
}
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env tsx
/**
* Post-deploy version assertion.
*
* Polls `/api/version` on production + demo and asserts the running
* build's `data.version` matches an expected value, printing each
* target's `buildSha`. Exits non-zero on a mismatch or after the retry
* window elapses — so a CI step or a manual deploy can fail loudly when
* the `:latest` pull served the prior image (the recurring BuildKit
* layer-cache pitfall where Coolify reports "deployed" while
* `/api/version` still answers the old number).
*
* Run it after every deploy — the queued-deploy status is not the source
* of truth, the served version is:
*
* pnpm dlx tsx scripts/assert-deploy.ts <expected-version>
*
* Examples:
*
* # assert both prod + demo serve 1.9.0
* pnpm dlx tsx scripts/assert-deploy.ts 1.9.0
*
* # assert prod only
* pnpm dlx tsx scripts/assert-deploy.ts 1.9.0 --only=prod
*
* # widen the retry window (default 24 attempts × 5s = 2 min)
* pnpm dlx tsx scripts/assert-deploy.ts 1.9.0 --attempts=60 --interval=5000
*
* Pure script — strips the leading `v` from the expected version so both
* `v1.9.0` and `1.9.0` work. No app-library import, no runtime wiring;
* the standalone image never ships this file.
*/
interface Target {
name: string;
url: string;
}
const TARGETS: Record<string, Target> = {
prod: { name: "prod", url: "https://healthlog.bombeck.io/api/version" },
demo: { name: "demo", url: "https://demo.healthlog.dev/api/version" },
};
interface VersionPayload {
version?: string;
buildSha?: string | null;
builtAt?: string | null;
}
function parseArgs(argv: string[]): {
expected: string;
attempts: number;
intervalMs: number;
only: string | null;
} {
const positional: string[] = [];
let attempts = 24;
let intervalMs = 5_000;
let only: string | null = null;
for (const arg of argv) {
if (arg.startsWith("--attempts=")) {
attempts = Number.parseInt(arg.slice("--attempts=".length), 10);
} else if (arg.startsWith("--interval=")) {
intervalMs = Number.parseInt(arg.slice("--interval=".length), 10);
} else if (arg.startsWith("--only=")) {
only = arg.slice("--only=".length);
} else {
positional.push(arg);
}
}
const expected = (positional[0] ?? "").trim().replace(/^v/, "");
if (!expected) {
console.error(
"usage: pnpm dlx tsx scripts/assert-deploy.ts <expected-version> [--only=prod|demo] [--attempts=N] [--interval=ms]",
);
process.exit(2);
}
if (!Number.isFinite(attempts) || attempts < 1) attempts = 24;
if (!Number.isFinite(intervalMs) || intervalMs < 0) intervalMs = 5_000;
return { expected, attempts, intervalMs, only };
}
const sleep = (ms: number): Promise<void> =>
new Promise((res) => setTimeout(res, ms));
/** One probe. Returns the parsed payload or null on any transport / shape error. */
async function probe(url: string): Promise<VersionPayload | null> {
try {
const res = await fetch(url, {
redirect: "manual",
signal: AbortSignal.timeout(10_000),
headers: { accept: "application/json" },
});
if (!res.ok) return null;
const body = (await res.json()) as { data?: VersionPayload } | null;
return body?.data ?? null;
} catch {
return null;
}
}
/**
* Poll one target until its served version matches `expected` or the
* retry window elapses. Resolves true on a match, false otherwise.
*/
async function assertTarget(
target: Target,
expected: string,
attempts: number,
intervalMs: number,
): Promise<boolean> {
for (let attempt = 1; attempt <= attempts; attempt += 1) {
const payload = await probe(target.url);
const version = payload?.version?.trim() ?? null;
if (version === expected) {
console.log(
`[${target.name}] OK version=${version} buildSha=${payload?.buildSha ?? "—"}`,
);
return true;
}
const seen = version ?? "unreachable";
console.log(
`[${target.name}] attempt ${attempt}/${attempts}: expected ${expected}, got ${seen}`,
);
if (attempt < attempts) await sleep(intervalMs);
}
console.error(
`[${target.name}] FAIL: ${target.url} did not report ${expected} within ${attempts} attempts`,
);
return false;
}
async function main(): Promise<void> {
const { expected, attempts, intervalMs, only } = parseArgs(
process.argv.slice(2),
);
let selected: Target[];
if (only) {
const picked = TARGETS[only];
if (!picked) {
console.error(`unknown --only target: ${only} (use prod or demo)`);
process.exit(2);
}
selected = [picked];
} else {
selected = Object.values(TARGETS);
}
console.log(
`Asserting version ${expected} on: ${selected.map((t) => t.name).join(", ")}`,
);
// Probe targets in parallel; each runs its own bounded retry loop.
const results = await Promise.all(
selected.map((t) => assertTarget(t, expected, attempts, intervalMs)),
);
if (results.every((ok) => ok)) {
console.log("All targets serve the expected version.");
process.exit(0);
}
process.exit(1);
}
void main();
+100
View File
@@ -100,6 +100,8 @@ async function main() {
moodLogApiKeyEncrypted: true,
withingsClientIdEncrypted: true,
withingsClientSecretEncrypted: true,
whoopClientIdEncrypted: true,
whoopClientSecretEncrypted: true,
},
});
@@ -115,6 +117,8 @@ async function main() {
"moodLogApiKeyEncrypted",
"withingsClientIdEncrypted",
"withingsClientSecretEncrypted",
"whoopClientIdEncrypted",
"whoopClientSecretEncrypted",
];
for (const field of userFields) {
const r = await rotateField(
@@ -152,6 +156,26 @@ async function main() {
results.push(r);
}
// ───── WhoopConnection table (accessToken / refreshToken) ─────
const whoop = await prisma.whoopConnection.findMany({
select: { id: true, accessToken: true, refreshToken: true },
});
for (const field of ["accessToken", "refreshToken"] as const) {
const r = await rotateField(
"WhoopConnection",
field,
whoop,
(w) => w[field],
async (id, ciphertext) => {
await prisma.whoopConnection.update({
where: { id },
data: { [field]: ciphertext } as Record<string, string>,
});
},
);
results.push(r);
}
// ───── AppSettings table (singleton typically) ─────
const settings = await prisma.appSettings.findMany({
select: {
@@ -288,6 +312,82 @@ async function main() {
}
results.push(coachResult);
// ───── CoachConversation.summaryEncrypted ─────
// v1.11.1 — `Bytes` column carrying the UTF-8 ciphertext of the rolling
// conversation summary. Same Buffer round-trip as CoachMessage; nullable, so
// skip empty/absent rows.
const coachConversations = await prisma.coachConversation.findMany({
where: { summaryEncrypted: { not: null } },
select: { id: true, summaryEncrypted: true },
});
const summaryResult: RotationResult = {
table: "CoachConversation",
field: "summaryEncrypted",
scanned: coachConversations.length,
rotated: 0,
errors: 0,
};
for (const row of coachConversations) {
const buf = row.summaryEncrypted;
if (!buf || buf.byteLength === 0) continue;
const asString = Buffer.from(buf).toString("utf8");
if (!shouldRotate(asString)) continue;
try {
const rotated = encrypt(decrypt(asString));
const encoded = Buffer.from(rotated, "utf8");
const next = new Uint8Array(new ArrayBuffer(encoded.byteLength));
next.set(encoded);
await prisma.coachConversation.update({
where: { id: row.id },
data: { summaryEncrypted: next },
});
summaryResult.rotated++;
} catch (err) {
summaryResult.errors++;
console.error(
`[CoachConversation.summaryEncrypted] row ${row.id}: ${(err as Error).message}`,
);
}
}
results.push(summaryResult);
// ───── CoachFact.factEncrypted ─────
// v1.11.1 — `Bytes` column carrying the UTF-8 ciphertext of each durable
// personal fact. Same Buffer round-trip as CoachMessage.
const coachFacts = await prisma.coachFact.findMany({
select: { id: true, factEncrypted: true },
});
const factResult: RotationResult = {
table: "CoachFact",
field: "factEncrypted",
scanned: coachFacts.length,
rotated: 0,
errors: 0,
};
for (const row of coachFacts) {
const buf = row.factEncrypted;
if (!buf || buf.byteLength === 0) continue;
const asString = Buffer.from(buf).toString("utf8");
if (!shouldRotate(asString)) continue;
try {
const rotated = encrypt(decrypt(asString));
const encoded = Buffer.from(rotated, "utf8");
const next = new Uint8Array(new ArrayBuffer(encoded.byteLength));
next.set(encoded);
await prisma.coachFact.update({
where: { id: row.id },
data: { factEncrypted: next },
});
factResult.rotated++;
} catch (err) {
factResult.errors++;
console.error(
`[CoachFact.factEncrypted] row ${row.id}: ${(err as Error).message}`,
);
}
}
results.push(factResult);
console.log("\n=== Rotation summary ===");
let totalRotated = 0;
let totalErrors = 0;
+12 -12
View File
@@ -247,14 +247,14 @@ async function seed() {
const takenTime = new Date(date);
takenTime.setHours(8, Math.floor(Math.random() * 45), 0);
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5, $5)`,
[cuid(), userId, med1Id, date, takenTime],
);
} else {
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4, $4)`,
[cuid(), userId, med1Id, date],
);
}
@@ -265,14 +265,14 @@ async function seed() {
const takenTime = new Date(date);
takenTime.setHours(8, Math.floor(5 + Math.random() * 50), 0);
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5, $5)`,
[cuid(), userId, med2Id, date, takenTime],
);
} else {
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4, $4)`,
[cuid(), userId, med2Id, date],
);
}
@@ -284,14 +284,14 @@ async function seed() {
const takenTime = new Date(date);
takenTime.setHours(20, Math.floor(Math.random() * 60), 0);
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, false, 'WEB', $5, $5)`,
[cuid(), userId, med3Id, date, takenTime],
);
} else {
await client.query(
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4)`,
`INSERT INTO medication_intake_events (id, user_id, medication_id, scheduled_for, taken_at, skipped, source, created_at, updated_at)
VALUES ($1, $2, $3, $4, NULL, true, 'WEB', $4, $4)`,
[cuid(), userId, med3Id, date],
);
}
@@ -101,3 +101,35 @@ describe("proxy.ts Withings CSP gating (F-5, 2026-05-16)", () => {
expect(csp).not.toMatch(/wbsapi\.withings\.net/);
});
});
describe("proxy.ts WHOOP CSP gating (v1.11.0)", () => {
it("does NOT allow api.prod.whoop.com on a non-WHOOP page", () => {
const res = proxy(makeRequest("/", { healthlog_session: "sess-1" }));
const csp = res.headers.get("content-security-policy") ?? "";
expect(csp).not.toMatch(/api\.prod\.whoop\.com/);
});
it("allows api.prod.whoop.com under /settings/integrations/whoop/*", () => {
const res = proxy(
makeRequest("/settings/integrations/whoop", {
healthlog_session: "sess-1",
}),
);
const csp = res.headers.get("content-security-policy") ?? "";
expect(csp).toMatch(/connect-src[^;]*https:\/\/api\.prod\.whoop\.com/);
});
it("allows api.prod.whoop.com under /api/whoop/*", () => {
const res = proxy(
makeRequest("/api/whoop/callback", { healthlog_session: "sess-1" }),
);
const csp = res.headers.get("content-security-policy") ?? "";
expect(csp).toMatch(/connect-src[^;]*https:\/\/api\.prod\.whoop\.com/);
});
it("never ships the WHOOP host on the auth surface", () => {
const res = proxy(makeRequest("/auth/login"));
const csp = res.headers.get("content-security-policy") ?? "";
expect(csp).not.toMatch(/api\.prod\.whoop\.com/);
});
});
@@ -1,175 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
/**
* v1.4.25 W3e — Coach drawer mount + per-card CTA gate.
*
* Three scenarios:
* 1. AI provider configured → per-card "Ask Coach" CTAs render
* alongside each card; the drawer is mounted at the page level.
* 2. AI provider NOT configured → CTAs are completely absent (no
* broken-button state).
* 3. v1.4.37 W5 — operator's global Coach flag off → both the CTAs
* and the page-level drawer mount vanish. The flag default is
* all-on for fresh installs and on any fetch error, so the path
* stays open by default (mocked via `useFeatureFlags` below).
*/
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/targets",
}));
let coachFlag = true;
vi.mock("@/hooks/use-feature-flags", async () => {
const actual = await vi.importActual<
typeof import("@/hooks/use-feature-flags")
>("@/hooks/use-feature-flags");
return {
...actual,
useFeatureFlags: () => ({
...actual.DEFAULT_ASSISTANT_FLAGS,
coach: coachFlag,
}),
};
});
const sampleData = {
targets: [
{
type: "WEIGHT",
label: "Weight",
current: 78,
average30: 78,
trend: "stable",
unit: "kg",
range: { min: 60, max: 80 },
classification: { category: "Normal", color: "#50fa7b" },
source: "WHO BMI",
daysInRange7d: 5,
daysLogged7d: 7,
lastMetGoalAt: null,
streakDays: 0,
insufficientData: false,
consistency7d: ["in", "in", "in", "in", "in", "in", "in"],
},
],
pageSummary: {
targetsMetThisWeek: 1,
totalTargets: 1,
streakHighlight: null,
},
bpDiastolic: { current: null, average30: null, range: null },
profile: { heightCm: 180, age: 35, gender: "MALE", glucoseUnit: null },
};
let providerChainResponse: { activeProvider: string | null } | null = null;
vi.mock("@tanstack/react-query", () => {
const noopClient = {
invalidateQueries: vi.fn(),
setQueryData: vi.fn(),
getQueryData: vi.fn(),
refetchQueries: vi.fn(),
};
return {
useQuery: ({ queryKey }: { queryKey: unknown[] }) => {
if (Array.isArray(queryKey) && queryKey[1] === "provider-chain") {
return {
data: providerChainResponse,
isLoading: false,
isError: false,
refetch: vi.fn(),
};
}
return {
data: sampleData,
isLoading: false,
isError: false,
refetch: vi.fn(),
};
},
useQueryClient: () => noopClient,
useMutation: () => ({
mutate: vi.fn(),
mutateAsync: vi.fn(),
isPending: false,
reset: vi.fn(),
}),
};
});
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
role: "USER",
},
isAuthenticated: true,
isLoading: false,
refetch: vi.fn(),
}),
}));
import { I18nProvider } from "@/lib/i18n/context";
import TargetsPage from "../targets/page";
function render() {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<TargetsPage />
</I18nProvider>,
);
}
describe("/targets page — Coach drawer mount + CTA gate", () => {
beforeEach(() => {
coachFlag = true;
});
it("renders the per-card Coach CTA when an AI provider is configured", () => {
providerChainResponse = { activeProvider: "openai" };
const html = render();
expect(html).toContain('data-slot="target-coach-cta"');
expect(html).toContain("Ask Coach");
});
it("hides every per-card Coach CTA when no AI provider is configured", () => {
providerChainResponse = { activeProvider: null };
const html = render();
expect(html).not.toContain('data-slot="target-coach-cta"');
});
it("renders nothing different when chainStatus query is still loading", () => {
providerChainResponse = null;
const html = render();
// Same as the "no provider" branch — until we know the provider is
// configured we don't render a CTA whose click would 404.
expect(html).not.toContain('data-slot="target-coach-cta"');
});
// v1.4.37 W5 — Marc directive: when the operator turns off the
// global Coach flag, every Coach affordance on /targets must vanish.
// That is BOTH the per-card CTAs (currently gated through `aiEnabled`)
// AND the page-level <CoachDrawer> mount — so the SSE machinery,
// Sheet portal and source-chip thread never load.
it("hides every per-card Coach CTA when the global Coach flag is off", () => {
coachFlag = false;
providerChainResponse = { activeProvider: "openai" };
const html = render();
expect(html).not.toContain('data-slot="target-coach-cta"');
});
it("does not mount the CoachDrawer when the global Coach flag is off", () => {
coachFlag = false;
providerChainResponse = { activeProvider: "openai" };
const html = render();
// The drawer renders a Sheet that the body markup exposes via a
// role + the i18n key it carries. We grep on the localised
// composer label that the drawer always paints.
expect(html).not.toContain('data-slot="coach-drawer"');
expect(html).not.toContain('data-slot="coach-drawer-composer"');
});
});
-204
View File
@@ -1,204 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
/**
* v1.4.19 phase A7 — the maintainer reported the `/targets` (Zielwerte) page
* still surfaces English status labels even when the rest of the UI
* renders in German: "Low / On Target / Stable / Moderate" stayed in
* the source language. The card titles ("Weight", "Blood pressure",
* "Body fat" …) had the same issue — server returns English
* strings, the page renders them verbatim.
*
* Translate every classification category and card label on the
* client. The server keeps emitting stable English keys (so external
* consumers / logs don't churn); the page resolves them to i18n
* strings via `useTranslations()`.
*/
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/targets",
}));
const sampleData = {
targets: [
{
type: "WEIGHT",
label: "Weight",
current: 88.2,
average30: 88.6,
trend: "stable",
unit: "kg",
range: { min: 60, max: 80 },
classification: { category: "Normal", color: "#50fa7b" },
source: "WHO BMI",
},
{
type: "BLOOD_PRESSURE_IN_TARGET",
label: "Blood pressure on target",
current: 65,
average30: 65,
trend: null,
unit: "%",
range: { min: 70, max: 100 },
classification: { category: "Moderate", color: "#f1fa8c" },
source: "ESH 2023",
},
{
type: "PULSE",
label: "Resting pulse",
current: 72,
average30: 72,
trend: "stable",
unit: "bpm",
range: { min: 60, max: 100 },
classification: { category: "On target", color: "#50fa7b" },
source: "AHA",
},
{
type: "MOOD_STABILITY",
label: "Mood stability",
current: 0.6,
average30: 0.6,
trend: null,
unit: "σ",
range: { min: 0, max: 0.5 },
classification: { category: "Stable", color: "#f1fa8c" },
source: "moodLog",
},
{
type: "MEDICATION_COMPLIANCE",
label: "Medication compliance",
current: 60,
average30: 60,
trend: null,
unit: "%",
range: { min: 90, max: 100 },
classification: { category: "Low", color: "#ff5555" },
source: "7-day",
},
],
bpDiastolic: { current: null, average30: null, range: null },
profile: { heightCm: 180, age: 35, gender: "MALE", glucoseUnit: null },
};
vi.mock("@tanstack/react-query", () => {
const noopClient = {
invalidateQueries: vi.fn(),
setQueryData: vi.fn(),
getQueryData: vi.fn(),
refetchQueries: vi.fn(),
};
return {
useQuery: ({ queryKey }: { queryKey: unknown[] }) => {
// v1.4.25 W3e — the targets page now also queries
// ["insights", "provider-chain"] to gate the per-card Coach
// CTA. Return null for that query (no AI provider configured)
// so the CTA hides and the existing test cases keep asserting
// the unchanged visual surface.
if (Array.isArray(queryKey) && queryKey[1] === "provider-chain") {
return {
data: null,
isLoading: false,
isError: false,
refetch: vi.fn(),
};
}
return {
data: sampleData,
isLoading: false,
isError: false,
refetch: vi.fn(),
};
},
useQueryClient: () => noopClient,
useMutation: () => ({
mutate: vi.fn(),
mutateAsync: vi.fn(),
isPending: false,
reset: vi.fn(),
}),
};
});
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
role: "USER",
},
isAuthenticated: true,
isLoading: false,
refetch: vi.fn(),
}),
}));
// v1.4.37 W5 — `/targets/page.tsx` now reads `useFeatureFlags` to gate
// the Coach drawer + per-card CTAs. The hook resolves QueryClientContext
// from `@tanstack/react-query`, and this test mocks the library
// without exposing that context. Mock the hook directly with the
// all-on default so the i18n assertions below run against the visible
// Coach surfaces.
vi.mock("@/hooks/use-feature-flags", async () => {
const actual = await vi.importActual<
typeof import("@/hooks/use-feature-flags")
>("@/hooks/use-feature-flags");
return {
...actual,
useFeatureFlags: () => actual.DEFAULT_ASSISTANT_FLAGS,
};
});
import { I18nProvider } from "@/lib/i18n/context";
import TargetsPage from "../targets/page";
function render(locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<TargetsPage />
</I18nProvider>,
);
}
describe("/targets page — i18n status labels and titles", () => {
it("translates card titles to German when the locale is `de`", () => {
const html = render("de");
expect(html).toContain("Gewicht"); // Weight
expect(html).toContain("Ruhepuls"); // Resting pulse
expect(html).toContain("Stimmungsstabilität"); // Mood stability
expect(html).toContain("Einnahmetreue"); // Medication compliance
// Server-emitted English labels must not leak.
expect(html).not.toContain("Resting pulse");
expect(html).not.toContain("Mood stability");
expect(html).not.toContain("Medication compliance");
});
it("translates every status badge category to German", () => {
const html = render("de");
// the maintainer explicitly named these in his bug report.
expect(html).not.toMatch(/>Low</);
expect(html).not.toMatch(/>On target</);
expect(html).not.toMatch(/>Stable</);
expect(html).not.toMatch(/>Moderate</);
// Their German renderings must show up instead.
expect(html).toContain("Niedrig"); // Low
expect(html).toContain("Im Zielbereich"); // On target
expect(html).toContain("Stabil"); // Stable
expect(html).toContain("Moderat"); // Moderate
// "Normal" is identical in EN and DE — the badge should still
// render the localised key (`targets.status.normal` → "Normal"),
// not the raw server string.
expect(html).toContain("Normal");
});
it("English locale still surfaces the original English status labels (no breakage)", () => {
const html = render("en");
expect(html).toContain("Normal");
expect(html).toContain("Moderate");
expect(html).toContain("On target");
expect(html).toContain("Stable");
expect(html).toContain("Low");
});
});
@@ -1,148 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
/**
* v1.4.25 W3e — mobile-first responsive layout audit.
*
* Marc directive: "mobile layout must be designed alongside desktop,
* not as an afterthought". This test pins the Tailwind responsive
* utilities so a future refactor cannot quietly collapse the grid
* back to the v1.4.22 `sm:grid-cols-2` and remove the lg three-col
* row.
*
* The three breakpoints we care about:
* • default (<640px): one column, full-width cards
* • sm (640-1023px): two columns
* • lg (1024px+): three columns, slightly wider gutters
*/
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/targets",
}));
const sampleData = {
targets: [
{
type: "WEIGHT",
label: "Weight",
current: 78,
average30: 78,
trend: "stable",
unit: "kg",
range: { min: 60, max: 80 },
classification: { category: "Normal", color: "#50fa7b" },
source: "WHO BMI",
daysInRange7d: 5,
daysLogged7d: 7,
lastMetGoalAt: null,
streakDays: 0,
insufficientData: false,
consistency7d: ["in", "in", "in", "in", "in", "in", "in"],
},
],
pageSummary: {
targetsMetThisWeek: 1,
totalTargets: 1,
streakHighlight: null,
},
bpDiastolic: { current: null, average30: null, range: null },
profile: { heightCm: 180, age: 35, gender: "MALE", glucoseUnit: null },
};
vi.mock("@tanstack/react-query", () => {
const noopClient = {
invalidateQueries: vi.fn(),
setQueryData: vi.fn(),
getQueryData: vi.fn(),
refetchQueries: vi.fn(),
};
return {
useQuery: ({ queryKey }: { queryKey: unknown[] }) => {
if (Array.isArray(queryKey) && queryKey[1] === "provider-chain") {
return {
data: { activeProvider: "openai" },
isLoading: false,
isError: false,
refetch: vi.fn(),
};
}
return {
data: sampleData,
isLoading: false,
isError: false,
refetch: vi.fn(),
};
},
useQueryClient: () => noopClient,
useMutation: () => ({
mutate: vi.fn(),
mutateAsync: vi.fn(),
isPending: false,
reset: vi.fn(),
}),
};
});
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
role: "USER",
},
isAuthenticated: true,
isLoading: false,
refetch: vi.fn(),
}),
}));
// v1.4.37 W5 — `/targets/page.tsx` now reads `useFeatureFlags` to gate
// the Coach drawer + per-card CTAs. The hook resolves QueryClientContext
// from `@tanstack/react-query`, and this test mocks the library
// without exposing that context. Mock the hook directly so the page
// runs with the all-on default (CTAs + drawer mount visible) the
// responsive assertions below pin.
vi.mock("@/hooks/use-feature-flags", async () => {
const actual = await vi.importActual<
typeof import("@/hooks/use-feature-flags")
>("@/hooks/use-feature-flags");
return {
...actual,
useFeatureFlags: () => actual.DEFAULT_ASSISTANT_FLAGS,
};
});
import { I18nProvider } from "@/lib/i18n/context";
import TargetsPage from "../targets/page";
function render(locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<TargetsPage />
</I18nProvider>,
);
}
describe("/targets page — mobile-first responsive grid", () => {
it("uses one column by default, two at sm, three at lg", () => {
const html = render();
expect(html).toMatch(/grid-cols-1/);
expect(html).toMatch(/sm:grid-cols-2/);
expect(html).toMatch(/lg:grid-cols-3/);
});
it("uses gap-4 at mobile/sm, gap-6 at lg", () => {
const html = render();
expect(html).toMatch(/\bgap-4\b/);
expect(html).toMatch(/lg:gap-6/);
});
it("renders the Coach CTA as an icon-only affordance on every target card", () => {
const html = render();
expect(html).toContain('data-slot="target-coach-cta"');
expect(html).toContain('aria-label="Ask Coach"');
expect(html).toContain("size-10");
});
});
-111
View File
@@ -1,111 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
/**
* v1.4.19 phase A7 — `/targets` (Zielwerte) had `space-y-8` between
* the page header (h1 + intro) and the first card grid. At Pixel-5
* the maintainer reported "relativ viel Platz" wasted between the overview
* and the first values. Tighten the rhythm to `space-y-6` (24px)
* which matches the rest of the admin / settings pages.
*/
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/targets",
}));
vi.mock("@tanstack/react-query", () => {
const noopClient = {
invalidateQueries: vi.fn(),
setQueryData: vi.fn(),
getQueryData: vi.fn(),
refetchQueries: vi.fn(),
};
return {
useQuery: ({ queryKey }: { queryKey: unknown[] }) => {
if (Array.isArray(queryKey) && queryKey[1] === "provider-chain") {
return {
data: null,
isLoading: false,
isError: false,
refetch: vi.fn(),
};
}
return {
data: {
targets: [],
bpDiastolic: { current: null, average30: null, range: null },
profile: {
heightCm: null,
age: null,
gender: null,
glucoseUnit: null,
},
},
isLoading: false,
isError: false,
refetch: vi.fn(),
};
},
useQueryClient: () => noopClient,
useMutation: () => ({
mutate: vi.fn(),
mutateAsync: vi.fn(),
isPending: false,
reset: vi.fn(),
}),
};
});
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: {
id: "u1",
username: "marc",
email: "marc@example.com",
role: "USER",
},
isAuthenticated: true,
isLoading: false,
refetch: vi.fn(),
}),
}));
// v1.4.37 W5 — `/targets/page.tsx` now reads `useFeatureFlags` to gate
// the Coach drawer + per-card CTAs. The hook resolves QueryClientContext
// from `@tanstack/react-query`, and this test mocks the library
// without exposing that context. Mock the hook directly with the
// all-on default so the spacing assertions below run against the
// fully-painted page shape.
vi.mock("@/hooks/use-feature-flags", async () => {
const actual = await vi.importActual<
typeof import("@/hooks/use-feature-flags")
>("@/hooks/use-feature-flags");
return {
...actual,
useFeatureFlags: () => actual.DEFAULT_ASSISTANT_FLAGS,
};
});
import { I18nProvider } from "@/lib/i18n/context";
import TargetsPage from "../targets/page";
function render(locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<TargetsPage />
</I18nProvider>,
);
}
describe("/targets page — vertical spacing", () => {
it("uses space-y-6 (not space-y-8) between header and card grid", () => {
const html = render();
// Outer wrapper rhythm. `space-y-8` would leave ~32px of
// unnecessary breathing room between the intro paragraph and the
// first card; `space-y-6` (24px) brings it in line with the
// admin / settings pages.
expect(html).toMatch(/<div[^>]*\bspace-y-6\b/);
expect(html).not.toMatch(/<div[^>]*\bspace-y-8\b/);
});
});
+64 -30
View File
@@ -65,11 +65,27 @@ function jsonRequest(body: unknown): Request {
});
}
interface TestFailureEnvelope {
data: {
ok: false;
providerType: string;
reasonCode: "credentials" | "rate_limited" | "server_error" | "unreachable";
reason: string;
};
error: null;
}
// V3 audit: /api/ai/test was returning provider err.message + bodyExcerpt
// directly to the client, leaking provider URLs / partial keys / internal
// headers. Server now logs full details via annotate() and responds with
// a categorised, generic message.
describe("POST /api/ai/test — provider error leak guard", () => {
// a categorised, secret-free reason.
//
// This route MUST NEVER return a 5xx: a 5xx origin response is rewritten
// by Cloudflare to its own HTML error page, so the browser's res.json()
// crashes with `Unexpected token '<', "<!DOCTYPE "`. Every provider-call
// failure returns HTTP 200 with `{ ok:false, reason }` the client shows
// verbatim.
describe("POST /api/ai/test — provider error leak guard + non-5xx contract", () => {
function makeProviderThatThrows(
err: Error & { httpStatus?: number; bodyExcerpt?: string },
) {
@@ -81,7 +97,7 @@ describe("POST /api/ai/test — provider error leak guard", () => {
} as never);
}
it("does not echo provider err.message back to the client (HIGH coverage gap)", async () => {
it("never returns a 5xx and does not echo provider err.message back to the client", async () => {
const err = Object.assign(
new Error("OpenAI 401 from https://api.openai.com/v1 sk-leaked-key"),
{
@@ -92,49 +108,67 @@ describe("POST /api/ai/test — provider error leak guard", () => {
makeProviderThatThrows(err);
const response = await POST(emptyRequest() as never);
const body = (await response.json()) as ApiErrorEnvelope;
// v1.4.5: credential failures map to 422 (not 502) so Cloudflare
// doesn't replace our JSON body with its HTML error page — that
// rewrite was the root cause of the "Unexpected token '<'…" client
// crash the maintainer hit when typing a bad OpenAI key.
expect(response.status).toBe(422);
expect(body.error ?? "").not.toMatch(/sk-/);
expect(body.error ?? "").not.toMatch(/api\.openai\.com/);
expect(body.error ?? "").not.toMatch(/invalid api key/i);
expect(body.error).toBe("Provider rejected the credentials");
// Always JSON-parseable, never a 5xx (the Cloudflare HTML-rewrite
// root cause of "Unexpected token '<'…").
expect(response.status).toBe(200);
const body = (await response.json()) as TestFailureEnvelope;
expect(body.data.ok).toBe(false);
expect(body.data.reasonCode).toBe("credentials");
// The stable machine code must itself be secret-free.
expect(body.data.reasonCode).not.toMatch(/sk-/);
expect(body.data.reason).not.toMatch(/sk-/);
expect(body.data.reason).not.toMatch(/api\.openai\.com/);
expect(body.data.reason).not.toMatch(/invalid api key/i);
expect(body.data.reason).toMatch(/re-authenticate/i);
});
it("returns the 429-categorised message when the provider rate-limits", async () => {
it("reclassifies a 5xx whose body signals an invalidated session as a credential failure", async () => {
// The shape an operator hit: re-auth, gateway answers 500 with
// "authentication token has been invalidated" instead of a 401.
makeProviderThatThrows(
Object.assign(new Error("upstream 500"), {
httpStatus: 500 as const,
bodyExcerpt:
'{"error":{"message":"Your authentication token has been invalidated. Please try signing in again."}}',
}),
);
const response = await POST(emptyRequest() as never);
expect(response.status).toBe(200);
const body = (await response.json()) as TestFailureEnvelope;
expect(body.data.ok).toBe(false);
expect(body.data.reasonCode).toBe("credentials");
expect(body.data.reason).toMatch(/re-authenticate/i);
});
it("categorises a 429 rate-limit", async () => {
makeProviderThatThrows(
Object.assign(new Error("429 from openai"), { httpStatus: 429 as const }),
);
const response = await POST(emptyRequest() as never);
// v1.4.5: rate-limit passes through as 429 (was 502 in v1.4.4) so
// the React Query mutation can read the JSON body instead of
// tripping over Cloudflare's HTML 502.
expect(response.status).toBe(429);
expect(((await response.json()) as ApiErrorEnvelope).error).toBe(
"Provider rate-limited the request",
);
expect(response.status).toBe(200);
const body = (await response.json()) as TestFailureEnvelope;
expect(body.data.reasonCode).toBe("rate_limited");
expect(body.data.reason).toMatch(/rate-limited/i);
});
it("returns the 5xx-categorised message when the provider has a server error", async () => {
it("categorises a plain 5xx provider server error (no auth signal)", async () => {
makeProviderThatThrows(
Object.assign(new Error("503 upstream"), { httpStatus: 503 as const }),
);
const response = await POST(emptyRequest() as never);
expect(((await response.json()) as ApiErrorEnvelope).error).toBe(
"Provider returned a server error",
);
expect(response.status).toBe(200);
const body = (await response.json()) as TestFailureEnvelope;
expect(body.data.reasonCode).toBe("server_error");
expect(body.data.reason).toMatch(/server error/i);
});
it("returns the unknown-error fallback otherwise", async () => {
it("categorises a network/timeout failure", async () => {
makeProviderThatThrows(new Error("ECONNRESET"));
const response = await POST(emptyRequest() as never);
expect(((await response.json()) as ApiErrorEnvelope).error).toBe(
"Provider connection failed",
);
expect(response.status).toBe(200);
const body = (await response.json()) as TestFailureEnvelope;
expect(body.data.reasonCode).toBe("unreachable");
expect(body.data.reason).toMatch(/could not reach/i);
});
});
+68 -24
View File
@@ -81,7 +81,7 @@ export const POST = apiHandler(async (request: NextRequest) => {
// V3 audit: do not return provider error message + bodyExcerpt to the
// client (leaks provider URL / partial keys / internal headers).
// Log full details server-side for the operator and respond with a
// categorised, generic message.
// categorised, generic reason.
const err = e as Error & { httpStatus?: number; bodyExcerpt?: string };
annotate({
meta: {
@@ -91,28 +91,72 @@ export const POST = apiHandler(async (request: NextRequest) => {
ai_test_provider: provider.type,
},
});
// Map upstream status to a *client-side* status code that won't be
// rewritten by Cloudflare. 5xx from origin causes Cloudflare to swap
// the body for its own HTML error page — `await res.json()` in the
// browser then crashes with `Unexpected token '<', "<!DOCTYPE "`,
// which is exactly how the maintainer encountered this when typing a bad
// OpenAI key. 4xx codes pass through untouched.
const status = err.httpStatus ?? 0;
let outboundStatus: number;
let safeMessage: string;
if (status === 401 || status === 403) {
outboundStatus = 422;
safeMessage = "Provider rejected the credentials";
} else if (status === 429) {
outboundStatus = 429;
safeMessage = "Provider rate-limited the request";
} else if (status >= 500) {
outboundStatus = 502;
safeMessage = "Provider returned a server error";
} else {
outboundStatus = 422;
safeMessage = "Provider connection failed";
}
return apiError(safeMessage, outboundStatus);
// This route MUST NEVER return a 5xx. A 5xx origin response is
// rewritten by Cloudflare / the reverse proxy to its own HTML error
// page, so the browser's `res.json()` crashes with
// `Unexpected token '<', "<!DOCTYPE "` (Safari: "The string did not
// match the expected pattern"). That is exactly the failure an
// operator hit re-authenticating a provider whose token came back as
// an invalidated-session 500. We always reply 200 with a categorised,
// secret-free `{ ok:false, reason }` the client can show verbatim.
const { reasonCode, reason } = classifyTestFailure(err);
return apiSuccess({
ok: false,
providerType: provider.type,
reasonCode,
reason,
});
}
});
/**
* Stable, machine-readable failure categories. The client maps each to a
* localised string; the English `reason` stays as a fallback for any
* legacy / unmapped code. Secret-free by construction.
*/
type TestFailureCode =
| "credentials"
| "rate_limited"
| "server_error"
| "unreachable";
/**
* Map an upstream provider failure to a human-readable, secret-free
* reason string. Distinguishes credential/auth, rate-limit, provider
* server-error and network/timeout classes. A 5xx whose body carries an
* auth signal (invalidated session token, expired key, "sign in again")
* is reclassified as a credential failure — that is the shape the
* operator's re-auth produced, where the gateway answered 500 instead of
* the expected 401.
*/
function classifyTestFailure(
err: Error & { httpStatus?: number; bodyExcerpt?: string },
): { reasonCode: TestFailureCode; reason: string } {
const status = err.httpStatus ?? 0;
const haystack = `${err.message} ${err.bodyExcerpt ?? ""}`;
const looksLikeAuth =
/authentication|invalidated|expired|sign in again|api key/i.test(haystack);
if (status === 401 || status === 403 || (status >= 500 && looksLikeAuth)) {
return {
reasonCode: "credentials",
reason: "Provider rejected the credentials — re-authenticate in AI settings.",
};
}
if (status === 429) {
return {
reasonCode: "rate_limited",
reason: "Provider rate-limited the request — try again shortly.",
};
}
if (status >= 500) {
return {
reasonCode: "server_error",
reason: "The AI provider returned a server error.",
};
}
return {
reasonCode: "unreachable",
reason: "Could not reach the AI provider.",
};
}
+13 -2
View File
@@ -44,7 +44,12 @@ vi.mock("@/lib/db", () => ({
findFirst: vi.fn().mockResolvedValue(null),
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
upsert: vi.fn().mockResolvedValue({}),
// v1.11.1 — the writer now delete-then-inserts via createMany.
createMany: vi.fn().mockResolvedValue({ count: 0 }),
},
// v1.11.1 — the source-aware rollup readers load the user's
// source-priority blob; null → default ladders.
user: { findUnique: vi.fn().mockResolvedValue(null) },
$transaction: vi.fn().mockImplementation(async (queries: unknown[]) => {
if (Array.isArray(queries)) return Promise.all(queries);
return undefined;
@@ -256,8 +261,14 @@ describe("GET /api/analytics", () => {
// two parallel ones (all-time + windowed), so the cold fixture
// now mocks 4 `$queryRaw` calls: coverage + allTime + windowed +
// latest.
vi.mocked(prisma.$queryRaw)
.mockResolvedValueOnce([{ n: BigInt(0) }] as never)
// The coverage probe rides `$queryRaw` (n:0 → cold path). v1.11.1 — the
// cold path's data aggregates (allTime + windowed + latest) now run via
// `$queryRawUnsafe` (the source-aware collapse splices a whitelisted CASE).
vi.mocked(prisma.$queryRaw).mockResolvedValueOnce([
{ n: BigInt(0) },
] as never);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.$queryRawUnsafe as any)
.mockResolvedValueOnce([
{
type: "WEIGHT",
+72
View File
@@ -0,0 +1,72 @@
/**
* v1.9.0 — single-metric period-over-period range read.
*
* `GET /api/analytics/range?type=<MeasurementType>&range=7d|30d|90d|1y`
* returns the current-window aggregate, the previous comparable window, and
* the composed delta. Single metric type by construction — the Insights
* metric page is single-metric — so the read is one
* `readBestGranularityRollups` covering the trailing `2N` days, sliced into
* the two halves. No per-type fan-out, no Prisma-pool burst (the opposite of
* the deleted 15-way live walk).
*
* The cached `/api/analytics?slice=summaries` slice is deliberately left
* untouched: adding a range dimension to its single shared cache key would
* fragment the hottest cache on the dashboard. This dedicated route carries
* its own per-(type, range) cache slot on the client (`queryKeys.analyticsRange`).
*
* iOS-safe: additive new route, no change to the `/api/analytics` envelope.
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiSuccess, returnAllZodIssues } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { measurementTypeEnum } from "@/lib/validations/measurement";
import {
ANALYTICS_RANGES,
computeRangeDelta,
type AnalyticsRange,
} from "@/lib/analytics/range-delta";
import type { MeasurementType } from "@/generated/prisma/client";
export const dynamic = "force-dynamic";
const rangeQuerySchema = z.object({
type: measurementTypeEnum,
range: z.enum(ANALYTICS_RANGES),
});
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const parsed = rangeQuerySchema.safeParse({
type: request.nextUrl.searchParams.get("type"),
range: request.nextUrl.searchParams.get("range"),
});
if (!parsed.success) {
annotate({
action: { name: "analytics.range.invalid-params" },
meta: { issue_count: parsed.error.issues.length },
});
return returnAllZodIssues(parsed.error, 422);
}
const type = parsed.data.type as MeasurementType;
const range = parsed.data.range as AnalyticsRange;
const result = await computeRangeDelta(user.id, type, range);
annotate({
action: { name: "analytics.range.read" },
meta: {
type,
range,
granularity: result.granularity,
current_count: result.current.count,
previous_count: result.previous.count,
},
});
return apiSuccess(result);
});
@@ -0,0 +1,129 @@
/**
* v1.8.5 — user-level injection-site preferences endpoint.
*
* GET /api/auth/me/injection-site-prefs
* → `{ globalExcludedInjectionSites: InjectionSite[] }`
*
* PATCH /api/auth/me/injection-site-prefs
* Body: `{ globalExcludedInjectionSites: InjectionSite[] }`
* → the resolved next state (idempotent hard-set).
*
* The global exclusion is a per-user deny-list. Sites listed here are
* never offered for ANY medication's injection-site picker, and the
* intake write path rejects (422) a submitted site that lands on this
* list — even when a medication's `allowedInjectionSites` lists it as
* preferred (deny always wins).
*
* Mirrors the `unit-preference` per-user-scalar pattern: 60/min rate
* limit, Zod safeParse → 422 via `returnAllZodIssues`, audit-log row,
* field-by-field write (no mass assignment).
*/
import { z } from "zod/v4";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import {
injectionSiteEnum,
INJECTION_SITE_VALUES,
type InjectionSiteValue,
} from "@/lib/validations/medication";
import { NextRequest } from "next/server";
export const dynamic = "force-dynamic";
const PATCH_RATE_LIMIT = 60;
const PATCH_WINDOW_MS = 60_000;
const patchBodySchema = z.object({
// Dedup at write time; cap at the full enum size. An empty array
// clears the exclusion.
globalExcludedInjectionSites: z
.array(injectionSiteEnum)
.max(INJECTION_SITE_VALUES.length)
.meta({
description:
"User-level injection-site deny-list. Sites here are never offered for any medication and rejected at intake (deny wins). Empty array clears the exclusion.",
}),
});
interface InjectionSitePrefsResponse {
globalExcludedInjectionSites: InjectionSiteValue[];
}
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
annotate({ action: { name: "auth.me.injection-site-prefs.get" } });
const row = await prisma.user.findUnique({
where: { id: user.id },
select: { globalExcludedInjectionSites: true },
});
const payload: InjectionSitePrefsResponse = {
globalExcludedInjectionSites: (row?.globalExcludedInjectionSites ??
[]) as InjectionSiteValue[],
};
return apiSuccess(payload);
});
export const PATCH = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const rl = await checkRateLimit(
`injection-site-prefs:patch:${user.id}`,
PATCH_RATE_LIMIT,
PATCH_WINDOW_MS,
);
if (!rl.allowed) {
const response = apiError("Too many requests", 429);
for (const [k, v] of Object.entries(rateLimitHeaders(rl))) {
response.headers.set(k, v);
}
return response;
}
const { data: body, error: jsonError } = await safeJson(request);
if (jsonError) return jsonError;
const parsed = patchBodySchema.safeParse(body);
if (!parsed.success) {
annotate({
action: { name: "auth.me.injection-site-prefs.patch.invalid_shape" },
});
return returnAllZodIssues(parsed.error, 422);
}
// Dedup while preserving canonical order from the enum tuple.
const submitted = new Set(parsed.data.globalExcludedInjectionSites);
const next = INJECTION_SITE_VALUES.filter((s) => submitted.has(s));
await prisma.user.update({
where: { id: user.id },
data: { globalExcludedInjectionSites: next },
});
await auditLog("user.injection-site-prefs.update", {
userId: user.id,
ipAddress: getClientIp(request),
details: { count: next.length },
});
annotate({
action: { name: "auth.me.injection-site-prefs.patch" },
meta: { excluded_count: next.length },
});
const payload: InjectionSitePrefsResponse = {
globalExcludedInjectionSites: next,
};
return apiSuccess(payload);
});
+1
View File
@@ -66,6 +66,7 @@ export const GET = apiHandler(async () => {
// v1.7.0 — health-record export identity fields. All optional.
fullName: user.fullName ?? null,
insurerName: user.insurerName ?? null,
insurerIkNumber: user.insurerIkNumber ?? null,
insuranceNumber,
});
});
+1
View File
@@ -33,6 +33,7 @@ export const PUT = apiHandler(async (request: NextRequest) => {
timezone: result.user.timezone,
fullName: result.user.fullName,
insurerName: result.user.insurerName,
insurerIkNumber: result.user.insurerIkNumber,
hasInsuranceNumber: result.user.hasInsuranceNumber,
});
});
@@ -623,6 +623,68 @@ describe("GET /api/dashboard/summary", () => {
]);
});
it("projects one row per timesOfDay for a twice-daily schedule", async () => {
// A single MedicationSchedule row carrying two first-class
// `timesOfDay` is two distinct dose slots per day. Pre-fix the
// projector minted only the `windowStart` slot, so the second daily
// dose never appeared in the today-tile and the event-count
// compliance rollup read half the expected doses (a 2×/day med
// showed 50%). Assert the backfill mints both slots.
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-05-21T03:00:00.000Z"));
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.medication.findMany).mockResolvedValue([
{
id: "med-twice-daily",
startsOn: null,
endsOn: null,
oneShot: false,
createdAt: new Date("2026-01-01T00:00:00Z"),
schedules: [
{
id: "sched-bid",
medicationId: "med-twice-daily",
windowStart: "07:00",
windowEnd: "07:30",
daysOfWeek: null,
timesOfDay: ["07:00", "19:00"],
reminderGraceMinutes: null,
rrule: null,
rollingIntervalDays: null,
},
],
},
] as never);
vi.mocked(prisma.medicationIntakeEvent.findMany).mockImplementation(((
args: unknown,
) => {
const a = args as { where: { OR?: unknown }; select?: { id?: boolean } };
if (a.where.OR) return Promise.resolve([]) as never;
if (!a.select?.id) return Promise.resolve([]) as never;
return Promise.resolve([]) as never;
}) as never);
vi.mocked(prisma.medicationIntakeEvent.createMany).mockResolvedValue({
count: 2,
} as never);
const res = await callGet(makeReq());
expect(res.status).toBe(200);
expect(prisma.medicationIntakeEvent.createMany).toHaveBeenCalledTimes(1);
const args = vi.mocked(prisma.medicationIntakeEvent.createMany).mock
.calls[0][0] as {
data: Array<{ medicationId: string; scheduledFor: Date }>;
};
expect(args.data).toHaveLength(2);
const hours = args.data
.map((r) => new Date(r.scheduledFor).getUTCHours())
.sort((a, b) => a - b);
// 07:00 and 19:00 in the default zone (Europe/Berlin, UTC+2 in May)
// materialise to 05:00 and 17:00 UTC. The assertion that matters is
// two distinct slots, not one.
expect(hours).toEqual([5, 17]);
vi.useRealTimers();
});
it("is idempotent on a second pass (v1.4.39 W-SERVER-FIX-2)", async () => {
// When the existence probe already sees a row for the projected
// slot (e.g. the intake route or the reminder worker minted it
+5 -4
View File
@@ -70,10 +70,11 @@ const layoutSchema = z.object({
}),
)
.min(1)
// v1.7.0 W1 — raised from 20 to 30 so the full 27-id catalogue PUT
// (web 16 + iOS-only 11) fits with headroom; the enum still bounds
// each id to one of the 27.
.max(30),
// v1.11.2 B5 — raised to 40 so the full catalogue PUT (24 writable +
// 11 iOS-only = 35) fits with headroom after the v1.10 additive
// HealthKit signals became pinnable; the enum still bounds each id to
// one of the catalogue ids.
.max(40),
// v1.4.16 phase B8 — comparison baseline (Vormonat / Vorjahr) rides
// on the layout blob per research §7 Q3 (no Prisma migration). Optional
// so v1.4.15 clients that don't know the field can still PUT.
@@ -9,6 +9,7 @@
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
import { PDFParse } from "pdf-parse";
vi.mock("@/lib/db", () => ({
prisma: {
@@ -38,14 +39,27 @@ const SESSION_OK = {
user: { id: "user-1", email: "test@example.com", role: "USER" },
} as const;
function mkReq(body: unknown): NextRequest {
function mkReq(
body: unknown,
headers: Record<string, string> = {},
): NextRequest {
return new NextRequest("http://localhost/api/export/health-record", {
method: "POST",
headers: { "content-type": "application/json" },
headers: { "content-type": "application/json", ...headers },
body: JSON.stringify(body),
});
}
async function pdfText(res: Response): Promise<string> {
const bytes = new Uint8Array(await res.arrayBuffer());
const parser = new PDFParse({ data: bytes });
try {
return (await parser.getText()).text;
} finally {
await parser.destroy();
}
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
@@ -137,6 +151,46 @@ describe("POST /api/export/health-record — outputs", () => {
expect(buf.subarray(0, 2).toString("latin1")).toBe("PK");
});
it("renders the PDF in the explicit selection locale", async () => {
const { POST } = await import("../route");
const res = await POST(
mkReq({ format: "pdf", locale: "de", practiceName: "Sample Practice" }),
);
const text = await pdfText(res);
// German cover label.
expect(text).toContain("Praxis:");
});
it("falls back to the healthlog-locale cookie when no locale is sent", async () => {
const { POST } = await import("../route");
const res = await POST(
mkReq(
{ format: "pdf", practiceName: "Sample Practice" },
{
// Browser default English, but the in-app cookie says German — the
// cookie must win over Accept-Language.
"accept-language": "en-US,en;q=0.9",
cookie: "healthlog-locale=de",
},
),
);
const text = await pdfText(res);
expect(text).toContain("Praxis:");
expect(text).not.toContain("Practice:");
});
it("uses Accept-Language only when neither selection nor cookie is present", async () => {
const { POST } = await import("../route");
const res = await POST(
mkReq(
{ format: "pdf", practiceName: "Sample Practice" },
{ "accept-language": "en-US,en;q=0.9" },
),
);
const text = await pdfText(res);
expect(text).toContain("Practice:");
});
it("scopes the aggregator measurement read to the session user", async () => {
const { POST } = await import("../route");
await POST(mkReq({ format: "fhir", userId: "user-2" } as never));
+43 -5
View File
@@ -39,14 +39,17 @@ import {
sanitisePracticeName,
} from "@/lib/doctor-report-data";
import { renderDoctorReportPdfBytes } from "@/lib/doctor-report-pdf-core";
import { buildFhirDocumentBundle } from "@/lib/fhir/build-bundle";
import {
buildFhirDocumentBundle,
GERMAN_ATC_DEFAULT_LOCALES,
} from "@/lib/fhir/build-bundle";
import {
exportSelectionSchema,
toDoctorReportPrefs,
} from "@/lib/validations/health-record-export";
import { getServerTranslator } from "@/lib/i18n/server-translator";
import { parseLocaleFromAcceptLanguage } from "@/lib/format-locale";
import { type Locale } from "@/lib/i18n/config";
import { locales, type Locale } from "@/lib/i18n/config";
import { resolveUserTimezone } from "@/lib/tz/resolver";
export const POST = apiHandler(async (request: NextRequest) => {
@@ -58,7 +61,14 @@ export const POST = apiHandler(async (request: NextRequest) => {
return apiError("Maximum 10 exports per hour", 429);
}
const { data: body, error: jsonError } = await safeJson(request);
// The selection payload is small and bounded — format, range,
// section toggles, a few flags, an optional practice-name string.
// 64 KB is far above any legitimate selection while still rejecting
// a multi-megabyte body before it reaches `JSON.parse`. A DoS
// ceiling, not a tight bound.
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 64 * 1024,
});
if (jsonError) return jsonError;
const parsed = exportSelectionSchema.safeParse(body);
@@ -72,12 +82,30 @@ export const POST = apiHandler(async (request: NextRequest) => {
const sections = toDoctorReportPrefs(selection.sections);
const includeCharts = selection.includeCharts ?? true;
// Locale resolution, most-specific first: the explicit selection wins, then
// the in-app `healthlog-locale` cookie (what the user actually chose in the
// UI), and only then the browser's Accept-Language header. The header is the
// weakest signal — a German user on an English-default browser would
// otherwise get an English report.
const cookieValue = request.cookies.get("healthlog-locale")?.value;
const cookieLocale = (locales as readonly string[]).includes(
cookieValue ?? "",
)
? (cookieValue as Locale)
: null;
const locale: Locale =
selection.locale ??
cookieLocale ??
parseLocaleFromAcceptLanguage(
request.headers.get("accept-language") ?? "",
);
// BfArM ATC: an explicit selection flag wins; otherwise derive it from a
// German-region locale. The WHO ATC coding is unaffected either way.
const germanAtc =
selection.germanAtc ??
(GERMAN_ATC_DEFAULT_LOCALES as readonly string[]).includes(locale);
const [data, userTz, userRow] = await Promise.all([
collectDoctorReportData(user.id, range, { practiceName, sections }),
resolveUserTimezone(user.id),
@@ -124,7 +152,12 @@ export const POST = apiHandler(async (request: NextRequest) => {
});
if (selection.format === "fhir") {
const bundle = buildFhirDocumentBundle(data, { insuranceNumber });
const bundle = buildFhirDocumentBundle(
data,
{ insuranceNumber },
undefined,
{ germanAtc },
);
const json = JSON.stringify(bundle);
annotate({
meta: { format: "fhir", bytes: json.length, days: range.days },
@@ -166,7 +199,12 @@ export const POST = apiHandler(async (request: NextRequest) => {
}
// format === "package": one zip holding the PDF + FHIR Bundle + a README.
const bundle = buildFhirDocumentBundle(data, { insuranceNumber });
const bundle = buildFhirDocumentBundle(
data,
{ insuranceNumber },
undefined,
{ germanAtc },
);
const readme = t("doctorReport.packageReadme");
const zipped = zipSync(
{
+53
View File
@@ -0,0 +1,53 @@
/**
* GET /api/fhir/$everything — FHIR R4 `$everything` operation.
*
* Returns every resource in the caller's own record — Patient, Coverage,
* Observations, MedicationStatements, MedicationAdministrations — in one
* `searchset` Bundle, in the canonical document order. Read-only; `userId`
* narrowed from `requireAuth`. Offset paging applies across the flattened
* resource list via `_count` (clamped ≤200) / `_offset`.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import {
coverageResource,
medicationAdministrationsFromReportData,
medicationStatementsFromReportData,
observationsFromReportData,
patientResource,
} from "@/lib/fhir/resources";
import type { FhirResource } from "@/lib/fhir/types";
import {
FHIR_READ_SCOPE,
loadFhirContext,
operationOutcome,
parsePaging,
searchsetResponse,
} from "@/lib/fhir/rest";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth(FHIR_READ_SCOPE);
annotate({ action: { name: "fhir.everything.read" } });
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
if (!rl.allowed) {
return operationOutcome(429, "throttled", "Rate limit exceeded");
}
const { count, offset } = parsePaging(request.nextUrl.searchParams);
const { data, identity, germanAtc } = await loadFhirContext(user.id);
const all: FhirResource[] = [patientResource(data, identity)];
const coverage = coverageResource(data, identity);
if (coverage) all.push(coverage);
all.push(...observationsFromReportData(data, identity, { germanAtc }));
all.push(...medicationStatementsFromReportData(data, { germanAtc }));
all.push(...medicationAdministrationsFromReportData(data, { germanAtc }));
const page = all.slice(offset, offset + count);
annotate({ meta: { total: all.length, count, offset } });
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
});
@@ -0,0 +1,39 @@
/**
* GET /api/fhir/MedicationAdministration — FHIR R4 `searchset` of the caller's
* own acted intakes (`completed` taken / `not-done` skip), with the same
* ATC/RxNorm + dose/route/site coding the document export carries.
*
* Read-only. `userId` narrowed from `requireAuth`; shared emitter is the
* single source of the coding. Offset paging via `_count` (≤200) / `_offset`.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import { medicationAdministrationsFromReportData } from "@/lib/fhir/resources";
import {
FHIR_READ_SCOPE,
loadFhirContext,
operationOutcome,
parsePaging,
searchsetResponse,
} from "@/lib/fhir/rest";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth(FHIR_READ_SCOPE);
annotate({ action: { name: "fhir.medicationadministration.search" } });
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
if (!rl.allowed) {
return operationOutcome(429, "throttled", "Rate limit exceeded");
}
const { count, offset } = parsePaging(request.nextUrl.searchParams);
const { data, germanAtc } = await loadFhirContext(user.id);
const all = medicationAdministrationsFromReportData(data, { germanAtc });
const page = all.slice(offset, offset + count);
annotate({ meta: { total: all.length, count, offset } });
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
});
@@ -0,0 +1,40 @@
/**
* GET /api/fhir/MedicationStatement — FHIR R4 `searchset` of the caller's own
* active-medication statements (one per active medication, with additive
* ATC/RxNorm codings).
*
* Read-only. `userId` narrowed from `requireAuth`; shared emitter is the
* single source of the drug coding. Offset paging via `_count` (≤200) /
* `_offset`.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import { medicationStatementsFromReportData } from "@/lib/fhir/resources";
import {
FHIR_READ_SCOPE,
loadFhirContext,
operationOutcome,
parsePaging,
searchsetResponse,
} from "@/lib/fhir/rest";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth(FHIR_READ_SCOPE);
annotate({ action: { name: "fhir.medicationstatement.search" } });
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
if (!rl.allowed) {
return operationOutcome(429, "throttled", "Rate limit exceeded");
}
const { count, offset } = parsePaging(request.nextUrl.searchParams);
const { data, germanAtc } = await loadFhirContext(user.id);
const all = medicationStatementsFromReportData(data, { germanAtc });
const page = all.slice(offset, offset + count);
annotate({ meta: { total: all.length, count, offset } });
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
});
+40
View File
@@ -0,0 +1,40 @@
/**
* GET /api/fhir/Observation — FHIR R4 `searchset` of the caller's own
* Observations (vitals / activity / lab / survey), one latest reading per
* type plus the BP panel, BMI, glucose, adherence, mood and wellness scores.
*
* Read-only. `userId` is narrowed from `requireAuth`; the shared emitter is
* the single source of the LOINC/UCUM coding. Offset paging via `_count`
* (clamped ≤200) / `_offset`.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import { observationsFromReportData } from "@/lib/fhir/resources";
import {
FHIR_READ_SCOPE,
loadFhirContext,
operationOutcome,
parsePaging,
searchsetResponse,
} from "@/lib/fhir/rest";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth(FHIR_READ_SCOPE);
annotate({ action: { name: "fhir.observation.search" } });
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
if (!rl.allowed) {
return operationOutcome(429, "throttled", "Rate limit exceeded");
}
const { count, offset } = parsePaging(request.nextUrl.searchParams);
const { data, identity, germanAtc } = await loadFhirContext(user.id);
const all = observationsFromReportData(data, identity, { germanAtc });
const page = all.slice(offset, offset + count);
annotate({ meta: { total: all.length, count, offset } });
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
});
+39
View File
@@ -0,0 +1,39 @@
/**
* GET /api/fhir/Patient — FHIR R4 `searchset` of the caller's own Patient.
*
* Read-only. A FHIR `Patient` search always yields exactly the authenticated
* user's single Patient resource (the `userId` is narrowed from `requireAuth`;
* there is no cross-user search). Returned as a one-entry `searchset` Bundle
* so a generic FHIR client can page it like any other resource type.
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import { patientResource } from "@/lib/fhir/resources";
import {
FHIR_READ_SCOPE,
loadFhirContext,
operationOutcome,
parsePaging,
searchsetResponse,
} from "@/lib/fhir/rest";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth(FHIR_READ_SCOPE);
annotate({ action: { name: "fhir.patient.search" } });
const rl = await checkRateLimit(`fhir:${user.id}`, 120, 60 * 60 * 1000);
if (!rl.allowed) {
return operationOutcome(429, "throttled", "Rate limit exceeded");
}
const { count, offset } = parsePaging(request.nextUrl.searchParams);
const { data, identity } = await loadFhirContext(user.id);
const all = [patientResource(data, identity)];
const page = all.slice(offset, offset + count);
annotate({ meta: { total: all.length, count, offset } });
return searchsetResponse(request.nextUrl, page, all.length, count, offset);
});
+167
View File
@@ -0,0 +1,167 @@
/**
* v1.11.0 (Epic C, C2) — read-only FHIR R4 REST face.
*
* Asserts the searchset Bundle shape (total + self/next links + `match`
* mode + `application/fhir+json`), `_count` clamping (≤200), paging, the
* `fhir:read` scope wiring, and the `OperationOutcome` rate-limit envelope.
* The shared data loader is stubbed so the test pins the REST contract, not
* the aggregator (which has its own coverage).
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn() }));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/fhir/rest", async (importOriginal) => {
const actual =
await importOriginal<typeof import("@/lib/fhir/rest")>();
return { ...actual, loadFhirContext: vi.fn() };
});
vi.mock("@/lib/fhir/resources", () => ({
observationsFromReportData: vi.fn(),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET as observationGet } from "../Observation/route";
import { getSession } from "@/lib/auth/session";
import { checkRateLimit } from "@/lib/rate-limit";
import { loadFhirContext, MAX_COUNT } from "@/lib/fhir/rest";
import { observationsFromReportData } from "@/lib/fhir/resources";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "tester", role: "USER" as const },
};
function obs(id: number) {
return {
resourceType: "Observation" as const,
id: `obs-${id}`,
status: "final" as const,
code: { text: `m-${id}` },
subject: { reference: "Patient/patient-1" },
};
}
function req(query = ""): NextRequest {
return new NextRequest(`http://localhost/api/fhir/Observation${query}`);
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(checkRateLimit).mockResolvedValue({
allowed: true,
count: 1,
resetAt: Date.now(),
} as never);
vi.mocked(loadFhirContext).mockResolvedValue({
data: {} as never,
identity: { insuranceNumber: null },
germanAtc: false,
});
});
describe("GET /api/fhir/Observation — searchset", () => {
it("returns a searchset Bundle with total, self link, and match mode", async () => {
vi.mocked(observationsFromReportData).mockReturnValue([
obs(1),
obs(2),
] as never);
const res = await observationGet(req());
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toContain("application/fhir+json");
const bundle = (await res.json()) as {
resourceType: string;
type: string;
total: number;
link: Array<{ relation: string; url: string }>;
entry: Array<{ search: { mode: string }; fullUrl: string }>;
};
expect(bundle.resourceType).toBe("Bundle");
expect(bundle.type).toBe("searchset");
expect(bundle.total).toBe(2);
expect(bundle.entry).toHaveLength(2);
expect(bundle.entry[0].search.mode).toBe("match");
expect(bundle.entry[0].fullUrl).toContain("/api/fhir/Observation/obs-1");
expect(bundle.link.find((l) => l.relation === "self")).toBeTruthy();
// Single page → no next link.
expect(bundle.link.find((l) => l.relation === "next")).toBeUndefined();
});
it("clamps _count above the ceiling and emits a next link when more remain", async () => {
vi.mocked(observationsFromReportData).mockReturnValue(
Array.from({ length: 250 }, (_, i) => obs(i)) as never,
);
const res = await observationGet(req("?_count=9999&_offset=0"));
const bundle = (await res.json()) as {
total: number;
link: Array<{ relation: string; url: string }>;
entry: unknown[];
};
// 250 total, clamped page of MAX_COUNT.
expect(bundle.total).toBe(250);
expect(bundle.entry).toHaveLength(MAX_COUNT);
const next = bundle.link.find((l) => l.relation === "next");
expect(next).toBeTruthy();
expect(next!.url).toContain(`_count=${MAX_COUNT}`);
expect(next!.url).toContain(`_offset=${MAX_COUNT}`);
});
it("pages with _offset", async () => {
vi.mocked(observationsFromReportData).mockReturnValue([
obs(1),
obs(2),
obs(3),
] as never);
const res = await observationGet(req("?_count=2&_offset=2"));
const bundle = (await res.json()) as {
total: number;
entry: Array<{ resource: { id: string } }>;
};
expect(bundle.total).toBe(3);
expect(bundle.entry).toHaveLength(1);
expect(bundle.entry[0].resource.id).toBe("obs-3");
});
it("enforces the fhir:read scope (Bearer narrow token without it 403s)", async () => {
// No session → Bearer path. requireAuth(FHIR_READ_SCOPE) must reject a
// token lacking the scope; here no auth at all yields 401, proving the
// route does gate auth before doing any work.
vi.mocked(getSession).mockResolvedValue(null as never);
const res = await observationGet(req());
expect(res.status).toBe(401);
expect(loadFhirContext).not.toHaveBeenCalled();
});
it("returns an OperationOutcome on rate-limit", async () => {
vi.mocked(checkRateLimit).mockResolvedValue({
allowed: false,
count: 999,
resetAt: Date.now(),
} as never);
const res = await observationGet(req());
expect(res.status).toBe(429);
expect(res.headers.get("content-type")).toContain("application/fhir+json");
const body = (await res.json()) as {
resourceType: string;
issue: Array<{ severity: string; code: string }>;
};
expect(body.resourceType).toBe("OperationOutcome");
expect(body.issue[0].code).toBe("throttled");
});
});
+60
View File
@@ -0,0 +1,60 @@
/**
* GET /api/fhir/metadata — FHIR R4 `CapabilityStatement`.
*
* Declares the read-only REST face: the resource types served, the search
* parameters honoured (`_count`, `_offset`), the `$everything` operation, and
* the `application/fhir+json` format. Static — no per-user data — but still
* gated behind the `fhir:read` scope so the whole `/api/fhir` tree answers
* uniformly. Read-only: no write interactions are advertised.
*/
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import {
FHIR_READ_SCOPE,
FHIR_REST_RESOURCE_TYPES,
FHIR_SEARCH_PARAMS,
fhirJsonResponse,
} from "@/lib/fhir/rest";
export const GET = apiHandler(async () => {
await requireAuth(FHIR_READ_SCOPE);
annotate({ action: { name: "fhir.metadata.read" } });
const capability = {
resourceType: "CapabilityStatement",
status: "active",
date: new Date().toISOString(),
kind: "instance",
fhirVersion: "4.0.1",
format: ["application/fhir+json"],
rest: [
{
mode: "server",
documentation:
"Read-only access to the authenticated user's own health record.",
resource: [
...FHIR_REST_RESOURCE_TYPES.map((type) => ({
type,
interaction: [{ code: "read" }, { code: "search-type" }],
searchParam: FHIR_SEARCH_PARAMS.map((name) => ({
name,
type: "number",
})),
})),
{
type: "Patient",
operation: [
{
name: "everything",
definition:
"http://hl7.org/fhir/OperationDefinition/Patient-everything",
},
],
},
],
},
],
};
return fhirJsonResponse(capability);
});
@@ -39,9 +39,31 @@ const NON_COACH_GATED_ROUTES: ReadonlyArray<string> = [
"src/app/api/insights/bmi-status/route.ts",
"src/app/api/insights/cards/route.ts",
"src/app/api/insights/correlations/route.ts",
// v1.10.0 — generic derived-wellness-metric route. Pure compute over
// the rollup tier; gates on the same `insightStatus` sub-flag as the
// assessment routes (no Coach prose).
"src/app/api/insights/derived/route.ts",
// v1.10.0 — batched derived-metric route (the dashboard fan-out fix).
// Same pure compute + `insightStatus` sub-flag as the single route.
"src/app/api/insights/derived/batch/route.ts",
"src/app/api/insights/medication-compliance-status/route.ts",
// v1.8.7.1 — generic per-HealthKit-metric assessment. Gated on the
// same `insightStatus` sub-flag as the seven specialised status routes.
"src/app/api/insights/metric-status/route.ts",
"src/app/api/insights/mood-status/route.ts",
// v1.11.0 — period-narrative read route. Gates on the same `insightStatus`
// sub-flag as the assessment routes (no Coach prose).
"src/app/api/insights/narrative/route.ts",
// v1.9.0 — on-demand full assessment warm. Warms the same assessment
// cards the status routes serve, so it gates on `insightStatus`, not
// `coach`: a user with assessments enabled but Coach disabled can warm.
"src/app/api/insights/pregenerate/route.ts",
"src/app/api/insights/pulse-status/route.ts",
// v1.10.0 — device-flagged event awareness timeline (categorical
// events, WX-B). Pure DB read of the device's own verdicts; gates on
// the same `insightStatus` sub-flag as the assessment routes (no Coach
// prose).
"src/app/api/insights/rhythm-events/route.ts",
"src/app/api/insights/weight-status/route.ts",
];
@@ -23,9 +23,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = resolveBloodPressureStatusLocale(resolved);
// v1.8.3 — read-only: serve the cache, enqueue generation out of band on
// a miss. The GET never awaits the provider, so opening /insights/<metric>
// can no longer pin the main thread behind a cold LLM round-trip.
const result = await generateBloodPressureStatusForUser(user.id, {
locale,
force: false,
readOnly: true,
});
annotate({ action: { name: "insights.blood-pressure-status" } });
+4
View File
@@ -23,9 +23,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = resolveBmiStatusLocale(resolved);
// v1.8.3 — read-only: serve the cache, enqueue generation out of band on
// a miss. The GET never awaits the provider, so opening /insights/<metric>
// can no longer pin the main thread behind a cold LLM round-trip.
const result = await generateBmiStatusForUser(user.id, {
locale,
force: false,
readOnly: true,
});
annotate({ action: { name: "insights.bmi-status" } });
+49 -15
View File
@@ -55,6 +55,7 @@ import {
fetchConversationWithMessages,
listConversations,
} from "@/lib/ai/coach/persistence";
import { enqueueCoachMemoryRefresh } from "@/lib/ai/coach/coach-memory-shared";
import {
buildDateKey,
enforceBudget,
@@ -109,23 +110,26 @@ interface CoachTurn {
* `{ role, content }` chat shape the provider clients expect.
*
* Also enforces the 20-turn cap: when the conversation history exceeds
* `TURN_CAP`, the older half is folded into a single synthetic
* "[summary]" user message so the prompt budget stays bounded. This is
* best-effort — we don't pay for a separate provider call to summarise;
* we just keep the last `RECENT_HISTORY` turns verbatim and prepend a
* placeholder line that names the elided count.
* `TURN_CAP`, the older half is folded out of the verbatim window. v1.11.1 —
* if a rolling summary of those elided turns is on file
* (`CoachConversation.summaryEncrypted`, refreshed off-budget by the
* coach-memory-refresh worker) it is prepended so the Coach keeps memory of
* the older conversation; otherwise we fall back to a placeholder that just
* names the elided count (the pre-v1.11.1 behaviour). The summary is read
* stale-while-revalidate — the current turn uses whatever is on disk, the
* enqueued refresh makes the next long turn fresh.
*/
function buildHistoryWindow(turns: CoachTurn[]): CoachTurn[] {
function buildHistoryWindow(
turns: CoachTurn[],
summary: string | null,
): CoachTurn[] {
if (turns.length <= TURN_CAP) return turns;
const elided = turns.length - RECENT_HISTORY;
const recent = turns.slice(turns.length - RECENT_HISTORY);
return [
{
role: "user",
content: `[summary placeholder — ${elided} earlier turns elided to stay within the conversation budget]`,
},
...recent,
];
const memo = summary
? `[earlier conversation summary] ${summary}`
: `[summary placeholder — ${elided} earlier turns elided to stay within the conversation budget]`;
return [{ role: "user", content: memo }, ...recent];
}
async function handleChatRequest(request: NextRequest): Promise<Response> {
@@ -197,6 +201,9 @@ async function handleChatRequest(request: NextRequest): Promise<Response> {
// ── Conversation resolution ──────────────────────────────────
let workingConversationId: string;
let priorTurns: CoachTurn[] = [];
// v1.11.1 — rolling summary of the elided older turns, read stale-while-
// revalidate; null for a fresh conversation or when none is on file.
let priorSummary: string | null = null;
if (conversationId) {
const existing = await fetchConversationWithMessages(
@@ -208,6 +215,7 @@ async function handleChatRequest(request: NextRequest): Promise<Response> {
throw new HttpError(404, "coach.conversation.notFound");
}
workingConversationId = existing.id;
priorSummary = existing.summary ?? null;
priorTurns = existing.messages.map((m) => ({
role: m.role,
content: m.content,
@@ -286,10 +294,24 @@ async function handleChatRequest(request: NextRequest): Promise<Response> {
: scope;
const snapshot = await buildCoachSnapshot(userId, effectiveScope);
const systemPrompt = getCoachSystemPrompt(locale, coachPrefs);
const window = buildHistoryWindow([
const allTurns: CoachTurn[] = [
...priorTurns,
{ role: "user", content: message },
]);
];
const window = buildHistoryWindow(allTurns, priorSummary);
// v1.11.1 — once a conversation grows past the history cap, refresh the
// rolling summary + extract durable facts off the request path. Fire-and-
// forget: this turn uses whatever summary is already on disk; the refresh
// makes the next long turn fresh. No-ops without an embedded worker.
if (allTurns.length > TURN_CAP) {
void enqueueCoachMemoryRefresh({
conversationId: workingConversationId,
userId,
// Coach memory prose is composed in de/en only (the snapshot's
// coachLocale); collapse the wider UI locale union here.
locale: locale === "en" ? "en" : "de",
});
}
const transcript = window
.map((t) => `${t.role.toUpperCase()}: ${t.content}`)
.join("\n\n");
@@ -336,8 +358,20 @@ Reply now as the assistant, in ${locale === "de" ? "German" : "English"}.`;
meta: {
attempts: err.attempts.length,
firstStatus: err.attempts[0]?.httpStatus ?? null,
credentialExpired: err.primaryCredentialExpired,
},
});
// v1.11.0 W1 — when the user's PRIMARY provider failed with an
// auth-class status (401/403), the credential is dead, not the
// service. Surface a distinct `credential_expired` frame so the
// drawer can deep-link the user to reconnect rather than telling
// them to "try again later" — the gap that let an expired codex
// token silently kill all generation.
if (err.primaryCredentialExpired) {
return streamProviderError({
code: "coach.provider.credential_expired",
});
}
// v1.4.25 W5 — distinguish provider rate-limit (every attempt
// landed on 429) from generic unavailability. The drawer's
// error-decoder surfaces the rate-limit copy with a warning
@@ -0,0 +1,57 @@
/**
* DELETE /api/insights/coach/facts/[id] — soft-delete one Coach fact.
*
* v1.11.1 — the per-fact "forget this one thing" delete for the durable
* Coach facts surface.
*
* Ownership + existence privacy: the soft-delete uses `updateMany` scoped
* `where: { id, userId, deletedAt: null }` rather than `update`. A
* cross-user id, an unknown id, or an already-deleted fact all resolve to
* a `count: 0` no-op — the route returns `200 { deleted: false }` and
* never reveals whether the id exists under another account. The matching
* convention is the idempotent-delete one used elsewhere in the tree
* (a not-found delete is a successful no-op, not a 404).
*
* Coach-gated: same `requireAssistantSurface("coach")` kill-switch as the
* collection route.
*/
import type { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { prisma } from "@/lib/db";
import { requireAssistantSurface } from "@/lib/feature-flags";
interface RouteCtx {
params: Promise<{ id: string }>;
}
export const DELETE = apiHandler(
async (_request: NextRequest, ctx: RouteCtx) => {
const { user } = await requireAuth();
await requireAssistantSurface("coach");
const { id } = await ctx.params;
// `updateMany` (not `update`) so an unknown / cross-user / already-soft-
// deleted id is a 0-count no-op rather than a P2025 throw — the
// existence channel never leaks across accounts.
const { count } = await prisma.coachFact.updateMany({
where: { id, userId: user.id, deletedAt: null },
data: { deletedAt: new Date() },
});
const deleted = count > 0;
annotate({
action: { name: "coach.facts.deleted" },
meta: { deleted },
});
return apiSuccess({ deleted });
},
);
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -0,0 +1,332 @@
/**
* v1.11.1 — `/api/insights/coach/facts` (+ `/[id]`) routes.
*
* The GDPR / "forget what you know about me" management surface for the
* durable Coach facts. Covers:
* - GET lists only ACTIVE facts (deletedAt: null), decrypted, scoped to
* the caller, highest-confidence-then-newest ordered.
* - GET skips an undecryptable row rather than 500ing the whole list.
* - bulk DELETE soft-deletes all active facts (sets deletedAt) and
* returns the count.
* - [id] DELETE soft-deletes the caller's own fact, and a cross-user /
* unknown id is a 0-count no-op that returns `{ deleted: false }`.
* - the `requireAssistantSurface("coach")` gate is present on every verb.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
coachFact: {
findMany: vi.fn(),
updateMany: vi.fn(),
},
},
}));
vi.mock("@/lib/auth/session", () => ({
getSession: vi.fn(),
}));
// v1.4.31 — `requireAssistantSurface()` gates near the top of each
// handler. Mock the module boundary so flag reads are deterministic; the
// gate-presence assertions below verify the call is actually made.
vi.mock("@/lib/feature-flags", () => ({
requireAssistantSurface: vi.fn(async () => undefined),
AssistantDisabledError: class extends Error {},
}));
// Mock the codec so the test never needs an encryption key. The "row"
// carries a tagged Uint8Array and the mock maps it back to a string;
// a sentinel buffer triggers a throw to exercise the fail-closed skip.
vi.mock("@/lib/ai/coach/bytes-codec", () => ({
decryptFromBytes: vi.fn((buf: Uint8Array) => {
const tag = Buffer.from(buf).toString("utf8");
if (tag === "__undecryptable__") {
throw new Error("unknown key id");
}
return `decrypted:${tag}`;
}),
}));
vi.mock("@/lib/logging/transports", () => ({
emitIfSampled: vi.fn(),
}));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/context", async (importOriginal) => {
const actual =
await importOriginal<typeof import("@/lib/logging/context")>();
return {
...actual,
annotate: vi.fn(),
};
});
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET, DELETE } from "../route";
import { DELETE as DELETE_ONE } from "../[id]/route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { annotate } from "@/lib/logging/context";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-1",
username: "tester",
role: "USER" as const,
displayName: null,
},
};
const callGet = GET as unknown as () => Promise<Response>;
const callDeleteAll = DELETE as unknown as () => Promise<Response>;
const callDeleteOne = DELETE_ONE as unknown as (
req: NextRequest,
ctx: { params: Promise<{ id: string }> },
) => Promise<Response>;
function bytes(tag: string): Uint8Array {
return new Uint8Array(Buffer.from(tag, "utf8"));
}
function deleteReq(): NextRequest {
return new NextRequest("http://localhost/api/insights/coach/facts/x", {
method: "DELETE",
});
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(requireAssistantSurface).mockResolvedValue(undefined as never);
});
describe("GET /api/insights/coach/facts", () => {
it("lists the caller's active facts, decrypted, scoped to the user", async () => {
vi.mocked(prisma.coachFact.findMany).mockResolvedValue([
{
id: "f1",
category: "goal",
factEncrypted: bytes("lose 5kg"),
confidence: 90,
createdAt: new Date("2026-06-01T00:00:00Z"),
},
{
id: "f2",
category: "preference",
factEncrypted: bytes("morning workouts"),
confidence: 70,
createdAt: new Date("2026-06-02T00:00:00Z"),
},
] as never);
const res = await callGet();
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: {
facts: Array<{
id: string;
category: string;
text: string;
confidence: number;
}>;
};
};
expect(body.data.facts).toHaveLength(2);
expect(body.data.facts[0]).toMatchObject({
id: "f1",
category: "goal",
text: "decrypted:lose 5kg",
confidence: 90,
});
expect(body.data.facts[1]?.text).toBe("decrypted:morning workouts");
// Ownership-scoped + active-only query.
const where = vi.mocked(prisma.coachFact.findMany).mock.calls[0]?.[0]
?.where as { userId: string; deletedAt: null };
expect(where.userId).toBe("user-1");
expect(where.deletedAt).toBeNull();
});
it("orders highest-confidence then newest", async () => {
vi.mocked(prisma.coachFact.findMany).mockResolvedValue([] as never);
await callGet();
const orderBy = vi.mocked(prisma.coachFact.findMany).mock.calls[0]?.[0]
?.orderBy;
expect(orderBy).toEqual([
{ confidence: "desc" },
{ createdAt: "desc" },
]);
});
it("skips an undecryptable row rather than 500ing the whole list", async () => {
vi.mocked(prisma.coachFact.findMany).mockResolvedValue([
{
id: "f1",
category: "goal",
factEncrypted: bytes("__undecryptable__"),
confidence: 90,
createdAt: new Date("2026-06-01T00:00:00Z"),
},
{
id: "f2",
category: "context",
factEncrypted: bytes("works night shifts"),
confidence: 60,
createdAt: new Date("2026-06-02T00:00:00Z"),
},
] as never);
const res = await callGet();
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { facts: Array<{ id: string; text: string }> };
};
// The undecryptable row is dropped; the good one survives.
expect(body.data.facts).toHaveLength(1);
expect(body.data.facts[0]?.id).toBe("f2");
expect(body.data.facts[0]?.text).toBe("decrypted:works night shifts");
});
it("annotates coach.facts.listed with the count only", async () => {
vi.mocked(prisma.coachFact.findMany).mockResolvedValue([
{
id: "f1",
category: "goal",
factEncrypted: bytes("a"),
confidence: 50,
createdAt: new Date(),
},
] as never);
await callGet();
const call = vi
.mocked(annotate)
.mock.calls.find(
(c) =>
(c[0] as { action?: { name?: string } })?.action?.name ===
"coach.facts.listed",
);
expect(call).toBeTruthy();
expect((call![0] as { meta?: { count?: number } }).meta).toEqual({
count: 1,
});
});
it("invokes the coach assistant-surface gate", async () => {
vi.mocked(prisma.coachFact.findMany).mockResolvedValue([] as never);
await callGet();
expect(requireAssistantSurface).toHaveBeenCalledWith("coach");
});
});
describe("DELETE /api/insights/coach/facts — forget all", () => {
it("soft-deletes all active facts and returns the count", async () => {
vi.mocked(prisma.coachFact.updateMany).mockResolvedValue({
count: 3,
} as never);
const res = await callDeleteAll();
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { cleared: number } };
expect(body.data.cleared).toBe(3);
const arg = vi.mocked(prisma.coachFact.updateMany).mock.calls[0]?.[0] as {
where: { userId: string; deletedAt: null };
data: { deletedAt: Date };
};
expect(arg.where.userId).toBe("user-1");
expect(arg.where.deletedAt).toBeNull();
// Soft-delete sets a deletedAt timestamp; the row is not removed.
expect(arg.data.deletedAt).toBeInstanceOf(Date);
});
it("is idempotent — a second clear returns 0", async () => {
vi.mocked(prisma.coachFact.updateMany).mockResolvedValue({
count: 0,
} as never);
const res = await callDeleteAll();
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { cleared: number } };
expect(body.data.cleared).toBe(0);
});
it("invokes the coach assistant-surface gate", async () => {
vi.mocked(prisma.coachFact.updateMany).mockResolvedValue({
count: 0,
} as never);
await callDeleteAll();
expect(requireAssistantSurface).toHaveBeenCalledWith("coach");
});
});
describe("DELETE /api/insights/coach/facts/[id] — forget one", () => {
it("soft-deletes the caller's own fact and returns deleted:true", async () => {
vi.mocked(prisma.coachFact.updateMany).mockResolvedValue({
count: 1,
} as never);
const res = await callDeleteOne(deleteReq(), {
params: Promise.resolve({ id: "f1" }),
});
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { deleted: boolean } };
expect(body.data.deleted).toBe(true);
const arg = vi.mocked(prisma.coachFact.updateMany).mock.calls[0]?.[0] as {
where: { id: string; userId: string; deletedAt: null };
data: { deletedAt: Date };
};
// Scoped by BOTH id and userId, active-only.
expect(arg.where.id).toBe("f1");
expect(arg.where.userId).toBe("user-1");
expect(arg.where.deletedAt).toBeNull();
expect(arg.data.deletedAt).toBeInstanceOf(Date);
});
it("returns deleted:false for an unknown / cross-user id (0-count no-op)", async () => {
// updateMany scoped to { id, userId } matches no row owned by the
// caller → count 0 → no other user's row is ever touched.
vi.mocked(prisma.coachFact.updateMany).mockResolvedValue({
count: 0,
} as never);
const res = await callDeleteOne(deleteReq(), {
params: Promise.resolve({ id: "someone-elses-fact" }),
});
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { deleted: boolean } };
expect(body.data.deleted).toBe(false);
// The where clause pins userId so the query can never reach a
// foreign row regardless of the id supplied.
const arg = vi.mocked(prisma.coachFact.updateMany).mock.calls[0]?.[0] as {
where: { userId: string };
};
expect(arg.where.userId).toBe("user-1");
});
it("invokes the coach assistant-surface gate", async () => {
vi.mocked(prisma.coachFact.updateMany).mockResolvedValue({
count: 0,
} as never);
await callDeleteOne(deleteReq(), {
params: Promise.resolve({ id: "f1" }),
});
expect(requireAssistantSurface).toHaveBeenCalledWith("coach");
});
});
+102
View File
@@ -0,0 +1,102 @@
/**
* GET /api/insights/coach/facts — list the caller's ACTIVE Coach facts.
* DELETE /api/insights/coach/facts — "forget all": soft-delete every active
* fact for the caller.
*
* v1.11.1 — the GDPR / "forget what you know about me" surface for the
* durable Coach facts the assistant extracts during conversations. Facts
* are server-extracted, not user-authored, so this surface is read +
* delete only (no POST / PATCH).
*
* Ownership: every query is scoped `where: { userId, ... }`, so a caller
* can only ever see or clear their own facts. The fact text is decrypted
* on the fly; an undecryptable row (e.g. a key rotated out of the map) is
* skipped rather than 500ing the whole list — the surface stays available
* for the rows that DO decrypt.
*
* Coach-gated: a fact only exists because the Coach extracted it, so the
* management surface sits behind the same `requireAssistantSurface("coach")`
* kill-switch as the rest of the Coach stack.
*/
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { prisma } from "@/lib/db";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { decryptFromBytes } from "@/lib/ai/coach/bytes-codec";
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
await requireAssistantSurface("coach");
const rows = await prisma.coachFact.findMany({
where: { userId: user.id, deletedAt: null },
// Highest-confidence first, then newest — mirrors the injection
// ordering so the management list reads in the same priority the
// assistant actually weights the facts.
orderBy: [{ confidence: "desc" }, { createdAt: "desc" }],
select: {
id: true,
category: true,
factEncrypted: true,
confidence: true,
createdAt: true,
},
});
const facts: Array<{
id: string;
category: string;
text: string;
confidence: number;
createdAt: Date;
}> = [];
for (const row of rows) {
let text: string;
try {
text = decryptFromBytes(row.factEncrypted);
} catch {
// Fail closed per row — never surface ciphertext, never 500 the
// whole list because one row's key id is no longer in the map.
continue;
}
facts.push({
id: row.id,
category: row.category,
text,
confidence: row.confidence,
createdAt: row.createdAt,
});
}
annotate({
action: { name: "coach.facts.listed" },
meta: { count: facts.length },
});
return apiSuccess({ facts });
});
export const DELETE = apiHandler(async () => {
const { user } = await requireAuth();
await requireAssistantSurface("coach");
// Soft-delete every active fact — keeps the rows for audit while
// hiding them from injection. `updateMany` scoped to the caller can
// never touch another user's rows.
const { count } = await prisma.coachFact.updateMany({
where: { userId: user.id, deletedAt: null },
data: { deletedAt: new Date() },
});
annotate({
action: { name: "coach.facts.cleared" },
meta: { cleared: count },
});
return apiSuccess({ cleared: count });
});
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -5,6 +5,9 @@ vi.mock("@/lib/db", () => ({
prisma: {
auditLog: { create: vi.fn() },
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
user: { findUnique: vi.fn().mockResolvedValue({ timezone: "Europe/Berlin" }) },
measurement: { findMany: vi.fn().mockResolvedValue([]) },
moodEntry: { findMany: vi.fn().mockResolvedValue([]) },
},
}));
@@ -31,7 +34,6 @@ vi.mock("next/headers", () => ({
import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
const SESSION_OK = {
@@ -47,6 +49,16 @@ beforeEach(() => {
(prisma.appSettings.findUnique as ReturnType<typeof vi.fn>).mockResolvedValue(
null,
);
// v1.10.0 — the discovery engine reads the profile timezone + the
// measurement / mood series. Default to an empty corpus so the engine
// returns no discovered pairs (the n ≥ 20 gate trivially fails).
(prisma.user.findUnique as ReturnType<typeof vi.fn>).mockResolvedValue({
timezone: "Europe/Berlin",
});
(prisma.measurement.findMany as ReturnType<typeof vi.fn>).mockResolvedValue(
[],
);
(prisma.moodEntry.findMany as ReturnType<typeof vi.fn>).mockResolvedValue([]);
});
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
@@ -61,21 +73,16 @@ describe("GET /api/insights/correlations", () => {
expect(res.status).toBe(401);
});
it("returns an empty array as the placeholder", async () => {
it("returns the discovery result shape (no pairs on an empty corpus)", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq());
expect(res.status).toBe(200);
const body = (await res.json()) as { data: unknown[] };
expect(body.data).toEqual([]);
});
it("writes the empty-state audit log", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
await callGet(makeReq());
expect(auditLog).toHaveBeenCalledWith(
"insights.correlations.empty",
expect.objectContaining({ userId: "user-1" }),
);
const body = (await res.json()) as {
data: { discovered: unknown[]; pairsTested: number; fdrQ: number };
};
expect(body.data.discovered).toEqual([]);
expect(body.data.pairsTested).toBe(0);
expect(body.data.fdrQ).toBeGreaterThan(0);
});
it("returns 403 + errorCode when the correlations flag is off", async () => {
+125 -12
View File
@@ -1,29 +1,142 @@
/**
* GET /api/insights/correlations — placeholder iOS endpoint.
* GET /api/insights/correlations — FDR-controlled correlation discovery.
*
* The full correlations engine is part of `/api/insights/comprehensive`
* and is intentionally not re-exposed yet — iOS only needs a stable
* shape to render the empty state. We return `[]` and emit an audit log
* so the gap is visible until Phase 7 fills it in.
* v1.10.0 — promotes the former placeholder to the real discovery engine.
* Scans a curated behaviour × outcome matrix (daylight / mood / glucose /
* BP / steps × sleep / HRV / resting HR / weight), lag-joins each behaviour
* day to the NEXT day's outcome, runs Pearson with the exact Student-t
* p-value, and applies Benjamini-Hochberg FDR control across every tested
* pair so only statistically-defensible patterns surface. Every surfaced
* pair carries n, r, p, and the BH-adjusted q, framed descriptive — never
* causal.
*
* Reads daily series bounded to a trailing window, day-keyed in the user's
* display timezone (late-night readings mis-bucket under UTC). Pure compute
* lives in `src/lib/insights/correlation-discovery.ts`; this route only
* fetches + day-keys + responds. No LLM, no narrative, no cache table.
*/
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { prisma } from "@/lib/db";
import { getLocalDateParts } from "@/lib/timezone";
import type { MeasurementType } from "@/generated/prisma/client";
import {
discoverCorrelations,
DISCOVERY_BEHAVIOURS,
DISCOVERY_OUTCOMES,
type DailySeriesPoint,
type NamedSeries,
} from "@/lib/insights/correlation-discovery";
export const dynamic = "force-dynamic";
const MS_PER_DAY = 24 * 60 * 60 * 1000;
/** Trailing window for the discovery scan (days). */
const WINDOW_DAYS = 180;
/** Day key (YYYY-MM-DD) for an instant in the user's display timezone. */
function tzDayKey(at: Date, tz: string): string {
const { year, month, day } = getLocalDateParts(at, tz);
const mm = String(month).padStart(2, "0");
const dd = String(day).padStart(2, "0");
return `${year}-${mm}-${dd}`;
}
/** Collapse rows to per-day means keyed in the user's tz. */
function toDailyMeans(
rows: Array<{ value: number; at: Date }>,
tz: string,
): DailySeriesPoint[] {
const byDay = new Map<string, { sum: number; count: number }>();
for (const r of rows) {
if (!Number.isFinite(r.value)) continue;
const day = tzDayKey(r.at, tz);
const acc = byDay.get(day) ?? { sum: 0, count: 0 };
acc.sum += r.value;
acc.count += 1;
byDay.set(day, acc);
}
return [...byDay.entries()]
.map(([day, acc]) => ({ day, value: acc.sum / acc.count }))
.sort((a, b) => (a.day < b.day ? -1 : 1));
}
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
// v1.4.31 — operator can hide the correlation narration tile.
// Operator can hide the correlation surface entirely.
await requireAssistantSurface("correlations");
annotate({ action: { name: "insights.correlations" } });
await auditLog("insights.correlations.empty", {
userId: user.id,
details: { reason: "phase7_pending" },
const profile = await prisma.user.findUnique({
where: { id: user.id },
select: { timezone: true },
});
const tz = profile?.timezone ?? "Europe/Berlin";
const since = new Date(Date.now() - WINDOW_DAYS * MS_PER_DAY);
// Behaviour channels are measurement-backed except MOOD (mood entries).
const behaviourTypes = DISCOVERY_BEHAVIOURS.filter(
(k) => k !== "MOOD",
) as MeasurementType[];
const outcomeTypes = [...DISCOVERY_OUTCOMES] as MeasurementType[];
const [measurements, moodEntries] = await Promise.all([
prisma.measurement.findMany({
where: {
userId: user.id,
deletedAt: null,
measuredAt: { gte: since },
type: { in: [...behaviourTypes, ...outcomeTypes] },
},
orderBy: { measuredAt: "asc" },
take: 20000,
select: { type: true, value: true, measuredAt: true },
}),
prisma.moodEntry.findMany({
where: { userId: user.id, deletedAt: null, moodLoggedAt: { gte: since } },
orderBy: { moodLoggedAt: "asc" },
take: 5000,
select: { score: true, moodLoggedAt: true },
}),
]);
const measurementsByType = new Map<string, Array<{ value: number; at: Date }>>();
for (const m of measurements) {
const list = measurementsByType.get(m.type) ?? [];
list.push({ value: m.value, at: m.measuredAt });
measurementsByType.set(m.type, list);
}
const series: NamedSeries[] = [];
for (const key of DISCOVERY_BEHAVIOURS) {
const points =
key === "MOOD"
? toDailyMeans(
moodEntries.map((e) => ({ value: e.score, at: e.moodLoggedAt })),
tz,
)
: toDailyMeans(measurementsByType.get(key) ?? [], tz);
series.push({ key, role: "behaviour", points });
}
for (const key of DISCOVERY_OUTCOMES) {
series.push({
key,
role: "outcome",
points: toDailyMeans(measurementsByType.get(key) ?? [], tz),
});
}
const result = discoverCorrelations(series);
annotate({
action: { name: "insights.correlations.discover" },
meta: {
pairs_tested: result.pairsTested,
discovered: result.discovered.length,
fdr_q: result.fdrQ,
},
});
return apiSuccess([]);
return apiSuccess(result);
});
@@ -0,0 +1,148 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
user: {
findUnique: vi.fn().mockResolvedValue({
dateOfBirth: new Date("1986-01-01"),
gender: "MALE",
}),
},
},
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
// Stub the compute layer so the route test stays isolated.
vi.mock("@/lib/insights/derived", async (importOriginal) => {
const actual =
await importOriginal<typeof import("@/lib/insights/derived")>();
return {
...actual,
computeDerivedMetric: vi.fn(async () => ({
status: "ok",
value: { type: "RESTING_HEART_RATE", center: 55, low: 48, high: 62, spread: 7, sampleDays: 30, k: 3 },
coverage: { requiredInputs: 1, presentInputs: 1, historyDays: 30, missing: [] },
confidence: { score: 100, band: "high" },
provenance: { inputs: ["RESTING_HEART_RATE"], source: "DAY", windowDays: 30, computedAt: "2026-06-02T07:00:00+02:00" },
})),
};
});
import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/db";
import { computeDerivedMetric } from "@/lib/insights/derived";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, locale: "en" },
};
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
function makeReq(metric?: string, type?: string): NextRequest {
const url = new URL("http://localhost/api/insights/derived");
if (metric !== undefined) url.searchParams.set("metric", metric);
if (type !== undefined) url.searchParams.set("type", type);
return new NextRequest(url);
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue(null as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
dateOfBirth: new Date("1986-01-01"),
gender: "MALE",
} as never);
});
describe("GET /api/insights/derived", () => {
it("returns 200 + a flat Derived envelope for a valid metric", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq("VITALS_BASELINE", "RESTING_HEART_RATE"));
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: {
metric: string;
status: string;
value: { center: number } | null;
coverage: { historyDays: number };
confidence: { band: string } | null;
provenance: { source: string };
reason: string | null;
} | null;
error: string | null;
};
expect(body.error).toBeNull();
expect(body.data?.metric).toBe("VITALS_BASELINE");
expect(body.data?.status).toBe("ok");
expect(body.data?.value?.center).toBe(55);
expect(body.data?.confidence?.band).toBe("high");
expect(body.data?.provenance.source).toBe("DAY");
expect(body.data?.reason).toBeNull();
});
it("narrows userId from the session into the compute call (never a query field)", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
await callGet(makeReq("VITALS_BASELINE"));
expect(computeDerivedMetric).toHaveBeenCalledWith(
expect.objectContaining({ userId: "user-1", metric: "VITALS_BASELINE" }),
);
});
it("422s on an unknown metric without calling compute", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq("NOT_A_METRIC"));
expect(res.status).toBe(422);
expect(computeDerivedMetric).not.toHaveBeenCalled();
});
it("422s on a missing metric param", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq());
expect(res.status).toBe(422);
expect(computeDerivedMetric).not.toHaveBeenCalled();
});
it("401s when unauthenticated", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const res = await callGet(makeReq("VITALS_BASELINE"));
expect(res.status).toBe(401);
});
it("flattens an insufficient result with a null value + reason", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(computeDerivedMetric).mockResolvedValueOnce({
status: "insufficient",
coverage: { requiredInputs: 1, presentInputs: 0, historyDays: 0, missing: ["RESTING_HEART_RATE"] },
provenance: { inputs: ["RESTING_HEART_RATE"], source: "none", windowDays: 30, computedAt: "2026-06-02T07:00:00+02:00" },
reason: "no_readings_in_window",
} as never);
const res = await callGet(makeReq("VITALS_BASELINE"));
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { status: string; value: unknown; confidence: unknown; reason: string } | null;
};
expect(body.data?.status).toBe("insufficient");
expect(body.data?.value).toBeNull();
expect(body.data?.confidence).toBeNull();
expect(body.data?.reason).toBe("no_readings_in_window");
});
});
@@ -0,0 +1,146 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
user: {
findUnique: vi.fn().mockResolvedValue({
dateOfBirth: new Date("1986-01-01"),
gender: "MALE",
heightCm: 180,
}),
},
},
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
// Stub the compute layer; keep the real registry + loadBaselineProfile.
vi.mock("@/lib/insights/derived", async (importOriginal) => {
const actual =
await importOriginal<typeof import("@/lib/insights/derived")>();
return {
...actual,
computeDerivedMetric: vi.fn(async (args: { metric: string }) => ({
status: "ok",
value: { metric: args.metric, n: 1 },
coverage: { requiredInputs: 1, presentInputs: 1, historyDays: 30, missing: [] },
confidence: { score: 100, band: "high" },
provenance: { inputs: [], source: "DAY", windowDays: 30, computedAt: "2026-06-02T07:00:00+02:00" },
})),
};
});
import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/db";
import { computeDerivedMetric } from "@/lib/insights/derived";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, locale: "en" },
};
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
function makeReq(metrics?: string): NextRequest {
const url = new URL("http://localhost/api/insights/derived/batch");
if (metrics !== undefined) url.searchParams.set("metrics", metrics);
return new NextRequest(url);
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue(null as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
dateOfBirth: new Date("1986-01-01"),
gender: "MALE",
heightCm: 180,
} as never);
});
describe("GET /api/insights/derived/batch", () => {
it("resolves several metrics into one keyed map", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(
makeReq("READINESS,BMI,VITALS_BASELINE:WEIGHT"),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { metrics: Record<string, { metric: string; status: string }> };
error: string | null;
};
expect(body.error).toBeNull();
expect(Object.keys(body.data.metrics).sort()).toEqual([
"BMI",
"READINESS",
"VITALS_BASELINE:WEIGHT",
]);
expect(body.data.metrics["VITALS_BASELINE:WEIGHT"].status).toBe("ok");
expect(body.data.metrics.READINESS.metric).toBe("READINESS");
});
it("loads the profile once regardless of metric count", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
await callGet(makeReq("READINESS,BMI,FITNESS_AGE,HRV_BALANCE"));
// One User read for the whole batch — the pool-contention mitigation.
expect(prisma.user.findUnique).toHaveBeenCalledTimes(1);
expect(computeDerivedMetric).toHaveBeenCalledTimes(4);
});
it("narrows userId from the session into every compute call", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
await callGet(makeReq("READINESS"));
expect(computeDerivedMetric).toHaveBeenCalledWith(
expect.objectContaining({ userId: "user-1", metric: "READINESS" }),
);
});
it("collapses a duplicate token so it cannot inflate the fan-out", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
await callGet(makeReq("BMI,BMI,BMI"));
expect(computeDerivedMetric).toHaveBeenCalledTimes(1);
});
it("422s when any token is an unknown metric id", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq("READINESS,NOT_A_METRIC"));
expect(res.status).toBe(422);
expect(computeDerivedMetric).not.toHaveBeenCalled();
});
it("422s on a missing metrics param", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq());
expect(res.status).toBe(422);
expect(computeDerivedMetric).not.toHaveBeenCalled();
});
it("422s on an empty metrics list", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq(" , , "));
expect(res.status).toBe(422);
expect(computeDerivedMetric).not.toHaveBeenCalled();
});
it("401s when unauthenticated", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const res = await callGet(makeReq("READINESS"));
expect(res.status).toBe(401);
});
});
+190
View File
@@ -0,0 +1,190 @@
/**
* v1.10.0 — batched derived-wellness-metric route.
*
* `GET /api/insights/derived/batch?metrics=<id,id,…>[&types=<type,…>]`
* resolves several derived metrics in ONE request and returns a map keyed
* by the per-request key (`<metric>` or `<metric>:<type>` for a
* VITALS_BASELINE sub-target). It exists to collapse the Insights cold
* mount's 14+ independent `GET /api/insights/derived` requests — each
* sharing one Prisma pool — into a single request that fans out
* server-side under a bounded `p-limit`, the exact pool-starvation class
* that bit v1.4.49.1 / v1.4.40 (the "app hangs then recovers" symptom).
*
* Honors the same contract as the single route: closed registry enum
* (unknown id → 422), cookie OR Bearer auth, `userId` narrowed from the
* session (never a query field), pure compute over the rollup tier (no
* provider call, no cache table). The profile is loaded ONCE via the
* shared `loadBaselineProfile` and threaded into every compute, so the
* batch never re-reads the `User` row per metric.
*
* The single-metric route stays for the anatomy detail pages (one metric
* per page); this route backs the dashboard's one-shot grid read.
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
import pLimit from "p-limit";
import { apiSuccess, apiError, returnAllZodIssues } from "@/lib/api-response";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { prisma } from "@/lib/db";
import {
computeDerivedMetric,
loadBaselineProfile,
isDerivedMetricId,
type DerivedMetricId,
} from "@/lib/insights/derived";
export const dynamic = "force-dynamic";
// Bounded internal fan-out — matches the W-POOL `p-limit(4)` discipline
// v1.4.40 applied to the per-type analytics walk so a batch of 14 metrics
// never floods the shared Prisma pool.
const BATCH_CONCURRENCY = 4;
// Defensive ceiling — the dashboard requests ~11 metrics + ~6 baseline
// sub-targets; cap the list so a crafted query can't fan out unbounded.
const MAX_METRICS = 24;
/**
* A single batch request item: a registered metric id with an optional
* VITALS_BASELINE sub-target. The wire form is `metric` or `metric:type`
* inside the `metrics` CSV; an entry's `type` is parsed off the colon.
*/
interface BatchItem {
metric: DerivedMetricId;
type: string | null;
/** The map key the response is keyed by (mirrors the request token). */
key: string;
}
const batchQuerySchema = z.object({
metrics: z
.string()
.min(1)
.max(1024)
.describe("CSV of derived-metric tokens (`metric` or `metric:type`)."),
});
/**
* Parse the `metrics` CSV into validated items. An entry `metric:type`
* sub-targets a VITALS_BASELINE vital; a bare `metric` carries no type.
* Unknown ids are returned as `invalid` so the route 422s the whole
* request rather than silently dropping a metric (the closed-enum rule).
* Duplicate keys collapse to one item (last write wins) so a repeated
* token can't inflate the fan-out.
*/
function parseBatchItems(csv: string): {
items: BatchItem[];
invalid: string[];
} {
const seen = new Map<string, BatchItem>();
const invalid: string[] = [];
for (const raw of csv.split(",")) {
const token = raw.trim();
if (token === "") continue;
const colon = token.indexOf(":");
const metric = colon === -1 ? token : token.slice(0, colon);
const type = colon === -1 ? null : token.slice(colon + 1) || null;
if (!isDerivedMetricId(metric)) {
invalid.push(metric);
continue;
}
const key = type ? `${metric}:${type}` : metric;
seen.set(key, { metric, type, key });
}
return { items: [...seen.values()], invalid };
}
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
await requireAssistantSurface("insightStatus");
const parsed = batchQuerySchema.safeParse({
metrics: request.nextUrl.searchParams.get("metrics"),
});
if (!parsed.success) {
annotate({
action: { name: "insights.derived.batch.invalid-query" },
meta: { issue_count: parsed.error.issues.length },
});
return returnAllZodIssues(parsed.error, 422);
}
const { items, invalid } = parseBatchItems(parsed.data.metrics);
if (invalid.length > 0) {
// Mirror the single route's closed-enum rule — an unknown id is a
// contract violation, not a silent drop. The id name is the caller's
// own input, never user health data, so it is safe to echo.
annotate({
action: { name: "insights.derived.batch.invalid-metric" },
meta: { invalid_count: invalid.length },
});
return apiError(
`Unknown derived metric id(s): ${invalid.join(", ")}`,
422,
);
}
if (items.length === 0 || items.length > MAX_METRICS) {
annotate({
action: { name: "insights.derived.batch.invalid-count" },
meta: { requested: items.length, max: MAX_METRICS },
});
return apiError(
items.length === 0
? "metrics must name at least one registered derived metric"
: `metrics must name at most ${MAX_METRICS} entries`,
422,
);
}
// Profile read ONCE — the pool-contention mitigation; the same shared
// loader the nightly score jobs use, so the batch never re-reads the
// User row per metric.
const profile = await loadBaselineProfile(prisma, user.id);
// Fan out under a bounded limiter so a 17-item dashboard read resolves
// four computes at a time against the shared pool, not seventeen.
const limit = pLimit(BATCH_CONCURRENCY);
const now = new Date();
const results = await Promise.all(
items.map((item) =>
limit(async () => {
const derived = await computeDerivedMetric({
metric: item.metric,
userId: user.id,
profile,
type: item.type,
now,
});
return {
key: item.key,
payload: {
metric: item.metric,
status: derived.status,
value: derived.status === "ok" ? derived.value : null,
coverage: derived.coverage,
confidence: derived.status === "ok" ? derived.confidence : null,
provenance: derived.provenance,
reason:
derived.status === "insufficient" ? derived.reason : null,
},
};
}),
),
);
const map: Record<string, (typeof results)[number]["payload"]> = {};
for (const r of results) map[r.key] = r.payload;
annotate({
action: { name: "insights.derived.batch" },
meta: {
requested: items.length,
ok: results.filter((r) => r.payload.status === "ok").length,
},
});
// `metrics` is a map keyed by the per-request token so the client reads
// back exactly what it asked for (`VITALS_BASELINE:WEIGHT`, `READINESS`).
return apiSuccess({ metrics: map });
});
+94
View File
@@ -0,0 +1,94 @@
/**
* v1.10.0 — generic derived-wellness-metric route.
*
* `GET /api/insights/derived?metric=<DERIVED_METRIC_ID>[&type=<MeasurementType>]`
* serves the compute-once `Derived<T>` value for any metric registered
* in `derived/registry.ts`. Mirrors the v1.8.7.1 `metric-status` route
* precedent: `apiHandler` wrapper, Zod `safeParse` on the query, a closed
* registry enum (unknown id → 422 via `returnAllZodIssues`), cookie OR
* Bearer auth, `userId` narrowed from the session/Bearer (never a query
* field).
*
* The `data` payload is the flat `Derived<T>` union so iOS can decode +
* combine values across metrics: `{ metric, status, value?, coverage,
* confidence?, provenance, reason? }`. Numbers are pure compute over the
* rollup tier (Tier-1, no narrative) — no provider call, no cache table.
*
* Wave 1 implements `VITALS_BASELINE` end-to-end; other registered ids
* return a `not_implemented` insufficient until their compute lands in a
* later wave (never a 500, never a fabricated value).
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
import { apiSuccess, returnAllZodIssues } from "@/lib/api-response";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { prisma } from "@/lib/db";
import {
computeDerivedMetric,
loadBaselineProfile,
DERIVED_METRIC_IDS,
type DerivedMetricId,
} from "@/lib/insights/derived";
export const dynamic = "force-dynamic";
// Closed enum derived from the registry so the route + registry cannot
// drift — an id added to the registry is accepted automatically, an
// unknown id 422s rather than silently resolving to no metric.
const derivedQuerySchema = z.object({
metric: z.enum(DERIVED_METRIC_IDS as [string, ...string[]]),
// Optional sub-target for metrics that baseline a single chosen vital
// (VITALS_BASELINE). Validated against the engine's supported set in
// the dispatcher; an unsupported value yields an `insufficient`, not a
// 422, so the contract stays forgiving for iOS combinations.
type: z.string().optional(),
});
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
await requireAssistantSurface("insightStatus");
const parsed = derivedQuerySchema.safeParse({
metric: request.nextUrl.searchParams.get("metric"),
type: request.nextUrl.searchParams.get("type") ?? undefined,
});
if (!parsed.success) {
annotate({
action: { name: "insights.derived.invalid-metric" },
meta: { issue_count: parsed.error.issues.length },
});
return returnAllZodIssues(parsed.error, 422);
}
const metric = parsed.data.metric as DerivedMetricId;
// Profile read once via the shared loader (the same one the batch route
// and the nightly score jobs use), passed into the pure compute function
// — never re-fetched per metric.
const profile = await loadBaselineProfile(prisma, user.id);
const derived = await computeDerivedMetric({
metric,
userId: user.id,
profile,
type: parsed.data.type ?? null,
});
annotate({
action: { name: "insights.derived" },
meta: { metric, status: derived.status },
});
// Flatten the discriminated union for the wire: `metric` tags it,
// `value`/`reason` are nullable so iOS decodes one stable shape.
return apiSuccess({
metric,
status: derived.status,
value: derived.status === "ok" ? derived.value : null,
coverage: derived.coverage,
confidence: derived.status === "ok" ? derived.confidence : null,
provenance: derived.provenance,
reason: derived.status === "insufficient" ? derived.reason : null,
});
});
+24
View File
@@ -11,6 +11,11 @@ import {
detectGlp1Plateau,
buildGlp1PlateauPrompt,
} from "@/lib/insights/glp1-plateau";
import {
detectDerivedBriefingSignals,
buildDerivedBriefingPrompt,
} from "@/lib/insights/derived-briefing";
import { getAgeFromDateOfBirth } from "@/lib/analytics/pulse-targets";
import {
buildUserPrompt,
type ComparisonSnapshot,
@@ -199,6 +204,10 @@ export const POST = apiHandler(async (request: NextRequest) => {
// LLM never sees the excluded blocks.
insightsExcludeMetrics: true,
locale: true,
// v1.10.0 — profile for the derived-signal briefing detector.
dateOfBirth: true,
gender: true,
heightCm: true,
},
});
@@ -397,6 +406,21 @@ export const POST = apiHandler(async (request: NextRequest) => {
if (plateauContext) {
userPrompt += buildGlp1PlateauPrompt(plateauContext, locale);
}
// v1.10.0 — fold a notable derived wellness signal (readiness / recovery
// shift, confidence-gated) into the briefing as a SYSTEM CONTEXT block.
// Reads the one derived contract; null (the common case) costs nothing.
const derivedSex =
dbUser?.gender === "MALE" || dbUser?.gender === "FEMALE"
? (dbUser.gender as "MALE" | "FEMALE")
: null;
const derivedBriefing = await detectDerivedBriefingSignals(userId, {
ageYears: getAgeFromDateOfBirth(dbUser?.dateOfBirth ?? null),
sex: derivedSex,
heightCm: dbUser?.heightCm ?? null,
});
if (derivedBriefing) {
userPrompt += buildDerivedBriefingPrompt(derivedBriefing, locale);
}
let result;
let workingProviderType: string;
+1 -1
View File
@@ -4,7 +4,7 @@
* Returns a chronological merge of every GLP-1-relevant event the user
* has logged: dose changes, injections (with site if recorded),
* inventory events, and side-effect-tagged mood entries from the
* trailing 90 days. Used by /insights/medikamente's TherapyTimeline
* trailing 90 days. Used by /insights/medications' TherapyTimeline
* component. Web-only users without a GLP-1 medication get
* `hasGlp1: false` so the component hides cleanly.
*/
@@ -60,6 +60,7 @@ import { annotate } from "@/lib/logging/context";
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
import { __resetAuditDedupMemoForTests } from "@/lib/audit-dedup";
import { DEFAULT_INSIGHTS_LAYOUT } from "@/lib/insights-layout";
import { SUB_PAGE_SLUGS } from "@/lib/insights/sub-page-metric";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
@@ -122,7 +123,7 @@ describe("GET /api/insights/layout", () => {
version: 1,
tiles: [
{ id: "overview", visible: false, order: 0 },
{ id: "blutdruck", visible: true, order: 1 },
{ id: "blood-pressure", visible: true, order: 1 },
],
},
} as never);
@@ -141,12 +142,42 @@ describe("GET /api/insights/layout", () => {
order: 0,
});
expect(body.data.tiles[1]).toEqual({
id: "blutdruck",
id: "blood-pressure",
visible: true,
order: 1,
});
expect(body.data.tiles.length).toBe(DEFAULT_INSIGHTS_LAYOUT.tiles.length);
});
it("normalises a legacy German tile id stored by a ≤ v1.7.x client to its canonical English id on read", async () => {
// A layout persisted before the v1.8.0 rename (or by an iOS client
// still speaking the German ids). The resolver must surface the
// canonical English id so the GET contract is current-build clean
// without forcing a re-PUT.
vi.mocked(prisma.user.findUnique).mockResolvedValue({
insightsLayoutJson: {
version: 1,
tiles: [
{ id: "overview", visible: true, order: 0 },
{ id: "blutdruck", visible: true, order: 1 },
{ id: "stimmung", visible: false, order: 2 },
],
},
} as never);
const res = await callGet();
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { tiles: Array<{ id: string; visible: boolean; order: number }> };
};
const ids = body.data.tiles.map((t) => t.id);
// Legacy ids collapse to their English replacement…
expect(ids).toContain("blood-pressure");
expect(ids).toContain("mood");
// …and the German originals never leak back out.
expect(ids).not.toContain("blutdruck");
expect(ids).not.toContain("stimmung");
});
});
describe("PUT /api/insights/layout — happy path", () => {
@@ -157,8 +188,8 @@ describe("PUT /api/insights/layout — happy path", () => {
version: 1,
tiles: [
{ id: "overview", visible: true, order: 0 },
{ id: "blutdruck", visible: true, order: 1 },
{ id: "puls", visible: false, order: 2 },
{ id: "blood-pressure", visible: true, order: 1 },
{ id: "pulse", visible: false, order: 2 },
],
};
const res = await callPut(makeReq(payload));
@@ -168,7 +199,7 @@ describe("PUT /api/insights/layout — happy path", () => {
};
expect(body.data.tiles[0]?.id).toBe("overview");
expect(body.data.tiles[0]?.order).toBe(0);
expect(body.data.tiles[2]?.id).toBe("puls");
expect(body.data.tiles[2]?.id).toBe("pulse");
expect(body.data.tiles[2]?.visible).toBe(false);
expect(prisma.user.update).toHaveBeenCalledTimes(1);
@@ -179,6 +210,152 @@ describe("PUT /api/insights/layout — happy path", () => {
expect(updateCall.where.id).toBe("user-1");
expect(updateCall.data.insightsLayoutJson).toBeTruthy();
});
it("accepts a body carrying legacy German tile ids and persists the canonical English ones", async () => {
// Non-breaking iOS contract: a client still sending the pre-v1.8.0
// German ids must NOT 422. The route validates the legacy ids and
// `serializeInsightsLayout` normalises them to English before the
// row persists, so the stored blob is always canonical.
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
const payload = {
version: 1,
tiles: [
{ id: "overview", visible: true, order: 0 },
{ id: "blutdruck", visible: true, order: 1 },
{ id: "medikamente", visible: true, order: 2 },
],
};
const res = await callPut(makeReq(payload));
// No 422 — the legacy ids pass validation.
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { tiles: Array<{ id: string }> };
};
const returnedIds = body.data.tiles.map((t) => t.id);
expect(returnedIds).toContain("blood-pressure");
expect(returnedIds).toContain("medications");
expect(returnedIds).not.toContain("blutdruck");
expect(returnedIds).not.toContain("medikamente");
// The persisted blob is canonical too.
const updateCall = vi.mocked(prisma.user.update).mock.calls[0]?.[0] as unknown as {
data: { insightsLayoutJson: { tiles: Array<{ id: string }> } };
};
const persistedIds = updateCall.data.insightsLayoutJson.tiles.map(
(t) => t.id,
);
expect(persistedIds).toContain("blood-pressure");
expect(persistedIds).toContain("medications");
expect(persistedIds).not.toContain("blutdruck");
expect(persistedIds).not.toContain("medikamente");
});
});
describe("PUT /api/insights/layout — full metric-slug universe", () => {
// v1.8.7.1 — the layout tile-id enum derives from `SUB_PAGE_SLUGS`, so
// the long-tail HealthKit + body-composition + mobility + audio slugs
// the routed tab strip already exposes are now valid layout ids. iOS
// can persist a layout covering the full metric set rather than 422ing
// on the ~25 slugs the fixed allow-list did not know about.
const NEWLY_ACCEPTED_SLUGS = [
"blood-glucose",
"skin-temperature",
"respiratory-rate",
"flights-climbed",
"walking-speed",
"vascular-age",
"headphone-audio",
"muscle-mass",
"daylight",
] as const;
it("accepts a layout that includes every previously-rejected sub-page slug", async () => {
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
const tiles = NEWLY_ACCEPTED_SLUGS.map((id, order) => ({
id,
visible: order % 2 === 0,
order,
}));
const res = await callPut(makeReq({ version: 1, tiles }));
// No 422 — these are all canonical sub-page slugs now.
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { tiles: Array<{ id: string; visible: boolean }> };
};
const returnedIds = body.data.tiles.map((t) => t.id);
for (const slug of NEWLY_ACCEPTED_SLUGS) {
expect(returnedIds).toContain(slug);
}
});
it("accepts a layout covering the ENTIRE slug universe in one PUT", async () => {
vi.mocked(prisma.user.update).mockResolvedValue({} as never);
const tiles = ["overview", ...SUB_PAGE_SLUGS].map((id, order) => ({
id,
visible: true,
order,
}));
const res = await callPut(makeReq({ version: 1, tiles }));
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { tiles: Array<{ id: string }> };
};
const returnedIds = new Set(body.data.tiles.map((t) => t.id));
// Every slug the web tab strip enumerates round-trips through the PUT.
for (const slug of SUB_PAGE_SLUGS) {
expect(returnedIds.has(slug)).toBe(true);
}
expect(returnedIds.has("overview")).toBe(true);
});
it("round-trips the new slugs back through GET after a save", async () => {
const savedTiles = NEWLY_ACCEPTED_SLUGS.map((id, order) => ({
id,
visible: true,
order: order + 1,
}));
vi.mocked(prisma.user.findUnique).mockResolvedValue({
insightsLayoutJson: {
version: 1,
tiles: [{ id: "overview", visible: true, order: 0 }, ...savedTiles],
},
} as never);
const res = await callGet();
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { tiles: Array<{ id: string }> };
};
const ids = body.data.tiles.map((t) => t.id);
for (const slug of NEWLY_ACCEPTED_SLUGS) {
expect(ids).toContain(slug);
}
});
it("still rejects a genuinely-unknown id even with the wider set", async () => {
const res = await callPut(
makeReq({
version: 1,
tiles: [
{ id: "blood-glucose", visible: true, order: 0 },
{ id: "not-a-metric-at-all", visible: true, order: 1 },
],
}),
);
expect(res.status).toBe(422);
const body = (await res.json()) as {
details: { issues: Array<{ path: string }> };
};
expect(
body.details.issues.some((i) => i.path.startsWith("tiles")),
).toBe(true);
});
});
describe("PUT /api/insights/layout — 422 multi-issue envelope", () => {
+13 -6
View File
@@ -27,7 +27,7 @@ import {
resolveInsightsLayout,
serializeInsightsLayout,
DEFAULT_INSIGHTS_LAYOUT,
INSIGHTS_TILE_IDS,
ACCEPTED_INSIGHTS_TILE_IDS,
type InsightsLayout,
} from "@/lib/insights-layout";
import { Prisma } from "@/generated/prisma/client";
@@ -38,11 +38,18 @@ import { redactSensitiveFields } from "@/lib/observability/redact-payload";
import { shouldEmitAuditRow } from "@/lib/audit-dedup";
import type { NextRequest } from "next/server";
// Derive the enum from `INSIGHTS_TILE_IDS` so the schema + the default
// layout cannot drift — the same root-cause class that produced the
// v1.4.16 A5 silent-422 on dashboard widgets when `achievements` was
// added to the layout but not to the validation enum.
const tileIdEnum = z.enum(INSIGHTS_TILE_IDS);
// Derive the enum from `ACCEPTED_INSIGHTS_TILE_IDS` so the schema + the
// default layout cannot drift — the same root-cause class that produced
// the v1.4.16 A5 silent-422 on dashboard widgets when `achievements`
// was added to the layout but not to the validation enum.
//
// v1.8.0 — the accepted set is canonical English ids PLUS the legacy
// German aliases, so an iOS client still PUTting `blutdruck` / `puls` /
// … passes validation rather than tripping a 422 on the rename.
// `serializeInsightsLayout` normalises any legacy id onto its canonical
// English replacement before the row persists, so the stored blob is
// always canonical regardless of which id the client sent.
const tileIdEnum = z.enum(ACCEPTED_INSIGHTS_TILE_IDS);
const layoutSchema = z.object({
version: z.literal(1),
@@ -23,9 +23,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = resolveMedicationComplianceStatusLocale(resolved);
// v1.8.3 — read-only: serve the cache, enqueue generation out of band on
// a miss. The GET never awaits the provider, so opening /insights/<metric>
// can no longer pin the main thread behind a cold LLM round-trip.
const result = await generateMedicationComplianceStatusForUser(user.id, {
locale,
force: false,
readOnly: true,
});
annotate({ action: { name: "insights.medication-compliance-status" } });
@@ -0,0 +1,127 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
},
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
// Stub the heavy generator so the route test stays isolated from the
// real status pipeline.
vi.mock("@/lib/insights/metric-status", () => ({
generateMetricStatus: vi.fn(async () => ({
hasProvider: true,
text: "ok",
cached: true,
updatedAt: new Date().toISOString(),
})),
resolveMetricStatusLocale: () => "en",
}));
import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/db";
import { generateMetricStatus } from "@/lib/insights/metric-status";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const, locale: "en" },
};
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
function makeReq(metric?: string): NextRequest {
const url = new URL("http://localhost/api/insights/metric-status");
if (metric !== undefined) url.searchParams.set("metric", metric);
return new NextRequest(url);
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue(null as never);
});
describe("GET /api/insights/metric-status", () => {
it("returns 200 + envelope for a valid registered metric", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq("RESTING_HEART_RATE"));
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { text: string; hasProvider: boolean } | null;
error: string | null;
};
expect(body.error).toBeNull();
expect(body.data?.text).toBe("ok");
expect(generateMetricStatus).toHaveBeenCalledWith(
expect.objectContaining({
metric: "RESTING_HEART_RATE",
userId: "user-1",
readOnly: true,
}),
);
});
it("422s on an unknown metric without calling the generator", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq("NOT_A_METRIC"));
expect(res.status).toBe(422);
expect(generateMetricStatus).not.toHaveBeenCalled();
});
it("422s on a missing metric param", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq());
expect(res.status).toBe(422);
expect(generateMetricStatus).not.toHaveBeenCalled();
});
it("422s when a specialised metric is requested through the generic route", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callGet(makeReq("WEIGHT"));
expect(res.status).toBe(422);
expect(generateMetricStatus).not.toHaveBeenCalled();
});
it("401s when unauthenticated", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const res = await callGet(makeReq("SLEEP_DURATION"));
expect(res.status).toBe(401);
});
it("403s + errorCode when insightStatus is disabled", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.appSettings.findUnique).mockResolvedValueOnce({
assistantEnabled: true,
assistantCoachEnabled: true,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: false,
assistantCorrelationsEnabled: true,
assistantHealthScoreExplainerEnabled: true,
} as never);
const res = await callGet(makeReq("SLEEP_DURATION"));
expect(res.status).toBe(403);
const body = (await res.json()) as { meta?: { errorCode?: string } };
expect(body.meta?.errorCode).toBe("assistant.disabled.insightStatus");
});
});
@@ -0,0 +1,86 @@
/**
* v1.8.7.1 — generic per-HealthKit-metric assessment route.
*
* `GET /api/insights/metric-status?metric=<METRIC_ID>` serves the
* data-driven assessment for any metric registered in
* `metric-status-registry.ts` (RESTING_HEART_RATE, SLEEP_DURATION, …).
* The seven specialised metrics keep their own `*-status` routes; this
* single generic route covers the ~30 HealthKit pages without one route
* per metric.
*
* Read-only by construction (v1.8.3 freeze fix): a cache miss enqueues an
* out-of-band generation and serves the last-good (stale-while-revalidate)
* text, never blocking on the provider. An unknown `metric` 422s via the
* closed registry enum.
*
* Unlike the seven legacy `*-status` routes, this one carries OpenAPI
* coverage (the route schema lives in `src/lib/openapi/routes.ts`),
* establishing the pattern the legacy routes can be backfilled onto later.
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
import {
apiSuccess,
returnAllZodIssues,
} from "@/lib/api-response";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { resolveServerLocale } from "@/lib/i18n/server-locale";
import { requireAssistantSurface } from "@/lib/feature-flags";
import {
generateMetricStatus,
resolveMetricStatusLocale,
} from "@/lib/insights/metric-status";
import {
METRIC_STATUS_IDS,
type MetricStatusMetricId,
} from "@/lib/insights/metric-status-registry";
export const dynamic = "force-dynamic";
// Closed enum derived from the registry so the route + registry cannot
// drift — an id added to the registry is accepted automatically, and an
// unknown id 422s rather than silently resolving to no card.
const metricQuerySchema = z.object({
metric: z.enum(METRIC_STATUS_IDS as [string, ...string[]]),
});
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
await requireAssistantSurface("insightStatus");
const parsed = metricQuerySchema.safeParse({
metric: request.nextUrl.searchParams.get("metric"),
});
if (!parsed.success) {
annotate({
action: { name: "insights.metric-status.invalid-metric" },
meta: { issue_count: parsed.error.issues.length },
});
return returnAllZodIssues(parsed.error, 422);
}
const metric = parsed.data.metric as MetricStatusMetricId;
const localeParam = request.nextUrl.searchParams.get("locale");
const resolved = await resolveServerLocale({
request,
userLocale: user.locale ?? null,
override: localeParam,
});
const locale = resolveMetricStatusLocale(resolved);
const result = await generateMetricStatus({
metric,
userId: user.id,
locale,
force: false,
readOnly: true,
});
annotate({
action: { name: "insights.metric-status" },
meta: { metric },
});
return apiSuccess(result);
});
@@ -23,9 +23,13 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = resolveMoodStatusLocale(resolved);
// v1.8.3 — read-only: serve the cache, enqueue generation out of band on
// a miss. The GET never awaits the provider, so opening /insights/<metric>
// can no longer pin the main thread behind a cold LLM round-trip.
const result = await generateMoodStatusForUser(user.id, {
locale,
force: false,
readOnly: true,
});
annotate({ action: { name: "insights.mood-status" } });
Loaded 100 of 709 files, more files were not shown because too many files have changed in this diff. Show more