Commit Graph
729 Commits
Author SHA1 Message Date
Marc-André BombeckandClaude Opus 4.7 f1e6630958 chore(format): prettier sweep across develop
Mostly table column normalisation under docs/audit/ + planning, object-
literal expansion in src/lib/ai/coach/snapshot.ts after the W4 F6 Apple
Health metric block landed, and small wrap/unwrap line adjustments in
the device + APNs routes / tests touched across W3/W4/W5 sessions.
No behavioural change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 08:27:51 +02:00
Marc-André BombeckandClaude Opus 4.7 5dcd3954a0 docs(planning): record Wave 6 reconcile + v1.4.23 backlog
11 reconcile commits across Sessions A/B/D/E/F closed 1 CRIT and
all 9 HIGH findings. STATE.md ticks Wave 6; v1423-backlog.md
captures the deferred MED + LOW items + the settings-cog-vs-thumbs
debate for v1.4.24.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:45:58 +02:00
Marc-André BombeckandClaude Opus 4.7 1a46bfe78a chore(security): MED cluster — Coolify URL scrub + isCurrent device-id + SLEEP_DURATION migration note
- Coolify runbook + audit briefs scrub the live deploy URL to a
  placeholder (Sec-MED-2). Real values live in repo secrets.
- /api/auth/me/devices isCurrent now compares against the session's
  device id, not the unauthenticated X-Device-Id header (Sr-MED-5).
- Migration 0036 sleep-duration unit shift documented + verification
  command added to the coolify-auto-deploy howto.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:44:12 +02:00
Marc-André BombeckandClaude Opus 4.7 650f150353 fix(coach): feedback references coach_messages, drops plaintext column
Reviewer note: W5 H7 wrote Coach assistant prose plaintext into
recommendation_feedback.recommendation_text. Same prose lives
encrypted in coach_messages — backups captured the leak.

Migration 0042_coach_feedback_message_ref adds nullable coachMessageId
(FK + cascade) and drops recommendation_text. Aggregator joins +
decrypts on read; admin view reads through the same path.

Fixes: Sr-H3 (Wave-6 v1.4.23 senior-dev review)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:38:17 +02:00
Marc-André BombeckandClaude Opus 4.7 deadc73863 perf(analytics): groupBy + cursor-paged BP aggregate
Reviewer note: src/app/api/analytics/route.ts fanned out 17+
unbounded prisma.measurement.findMany per request — growth linear
in HealthKit-days. Replace with prisma.groupBy where possible;
chunked-paged with take=5000 where running-window slope or paired
correlations require row-level access. Wide-event annotation
analytics.bp_aggregate.row_count for slow-query attribution.

Fixes: Sr-H1 (Wave-6 v1.4.23 senior-dev review)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:37:49 +02:00
Marc-André BombeckandClaude Opus 4.7 d25e50eaf3 fix(devices): wrap revoke cascade in a single transaction
Both DELETE /api/devices/[id] and DELETE /api/auth/me/devices/[id]
performed the same four-write cascade (refresh-token lookup, refresh
revoke, access-token revoke, device delete) as separate Prisma calls.
A partial failure between the third and fourth write left the device
row alive with all its tokens revoked - the user's iPad showed in the
device list as "still registered" but every request returned 401.

Extract the cascade into a shared revokeDeviceCascade() helper and
wrap the writes in prisma.$transaction so they commit atomically.
Both routes now call the helper; the audit-log via tag and the wide
event action name stay route-local.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:27:47 +02:00
Marc-André BombeckandClaude Opus 4.7 dfffe6bb3b refactor: simplify batch (S-02 to S-04)
Three small reuse wins from the W6 simplify review:

- openapi/registry.ts swaps the lazy require() for a static import.
  The ESLint disable + as-cast carried no real benefit; the only
  callers always loaded the route table anyway.
- Extract useCoachPrefs() into a shared hook so the settings sheet
  and message thread share one queryKey + one fallback shape. Removes
  the drift between the two existing inline blocks.
- Replace the 9-deep wantsX boolean ladder in coach snapshot with a
  single CoachScopeSource -> MeasurementType[] map. Drives both the
  WHERE type IN (...) build and the appleHealthBlocks gate, so adding
  a new metric is one entry instead of three parallel edits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:23:43 +02:00
Marc-André BombeckandClaude Opus 4.7 3ee6dab6fa fix(coach): skeleton + save toast on prefs sheet
Render a skeleton shell while the persisted Coach prefs are loading
so the form never paints DEFAULT_COACH_PREFS as a ghost between mount
and the query resolving. Emit a sonner toast on save success before
closing the sheet so the action is visibly acknowledged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:23:22 +02:00
Marc-André BombeckandClaude Opus 4.7 a2dfc5e256 fix(measurements): show source badge on mobile card too
The Apple Health pink chip rendered only inside the desktop `<Table>`
cell. iOS users — the audience that actually consumes Apple Health
data — land on the mobile card branch and saw no source indicator at
all, risking duplicate hand-entries on top of synced rows. Add a
compact badge inline with the timestamp on the mobile card so the
distinction lands at every viewport. Component test asserts the
`measurement-source-badge` testid appears twice (desktop + mobile)
so the next layout refactor can't silently drop one branch.

Also extends the `POST /api/devices` unit test mocks for the
NotificationChannel auto-upsert added in the previous commit, plus a
new test that pins the same-user apnsToken collision path returning
201 idempotently (the cross-user path keeps its 409).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:16:18 +02:00
Marc-André BombeckandClaude Opus 4.7 d5202e5dd8 fix(devices): enforce global apnsToken uniqueness via partial index
Two collision paths let the same APNs token attach to multiple Device
rows for one user, fanning a single push out to two rows and double-
charging the APNs quota:

  1. The cross-user-hijack guard filtered `NOT: { userId }` so it
     skipped same-user collisions entirely.
  2. The `apns_token` index was non-unique.

Drop the `NOT: { userId }` clause so the lookup catches both cases —
cross-user collisions still 409, same-user collisions fall through to
the existing legacy-token upsert path. Pair with migration 0041
introducing a partial UNIQUE index over `apns_token IS NOT NULL` and
dropping the redundant non-unique sibling. Apple's APNs contract
guarantees one token per (device, app), so global uniqueness matches
the upstream invariant.

Migration is strictly additive at the rolling-upgrade boundary; the
NULL-allowed partial-index shape preserves legacy iOS rows without an
APNs handshake. Schema-side comment documents why the partial index is
introduced via raw SQL (Prisma can't express it natively) and warns
against re-adding the non-unique sibling.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:13:47 +02:00
Marc-André BombeckandClaude Opus 4.7 13977bcc70 fix(devices): auto-upsert APNS NotificationChannel on registration
The dispatcher's APNS branch only fires when a NotificationChannel of
type APNS exists for the user, but no production code path created one.
Every iOS install needed a manual settings toggle that doesn't exist,
making the v1.4.23 W3 APNs cascade unreachable in real traffic.

When `POST /api/devices` accepts an apnsToken, eagerly upsert the
channel row with an encrypted empty config — the per-device token and
environment live on the Device row by design, so the channel only
exists to flip the dispatcher's gate. Mirrors the legacy Telegram
on-first-dispatch auto-migration but eager so the very first reminder
after registration routes through APNs.

Adds an integration test that registers a device with apnsToken and
asserts the channel row exists, registers without one and asserts
absence, and re-registers the same apnsToken and asserts idempotency
(channel count stays at one).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:12:02 +02:00
Marc-André BombeckandClaude Opus 4.7 54865075a5 fix(admin): surface coach-feedback in sidebar nav
The coach-feedback slug was registered in ADMIN_SECTION_SLUGS and the
page rendered correctly via /admin/[section], but the entry was never
added to the hand-maintained ADMIN_SECTIONS array. Operators could only
reach the view by typing the URL directly. Add the entry next to
ai-quality so the two AI-quality views sit together, and add a drift
guard test that walks ADMIN_SECTION_SLUGS and asserts every slug has a
matching nav entry. Same drift class would recur on the next admin
section addition without the guard.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 02:09:26 +02:00
Marc-André BombeckandClaude Opus 4.7 72829b1db5 docs(planning): record W5 hygiene wave + STATE tick
Eight commits closed all seven items from `.planning/v1422-backlog.md`.
STATE entry documents the per-item changes; new
`phase-W5-v1423-report.md` captures the H5 deploy decision, the H7
admin view path + the first useful question it answers, and the
OpenAPI registry additions (3 routes — H4 GET + PUT, H7 POST).

Test deltas: 2191 → 2223 unit (+32), +2 integration files, no
regressions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:52:46 +02:00
Marc-André BombeckandClaude Opus 4.7 05c7f1474d feat(coach): per-message thumbs feedback + admin aggregate view
The v1.4.22 prose rewrite shipped without a way for users to signal
whether the new tone is landing. v1.4.23 H7 closes that loop with a
light-touch thumbs row + an admin first-week dashboard.

Schema: extend `RecommendationFeedback` with a polymorphic
`target_type` column (default "recommendation" so legacy rows stay
representative) plus a nullable `reason` field. New index on
(target_type, created_at) so the aggregator can scan per-surface
buckets without a full sweep. Migration `0040_recommendation_feedback_target_type`.

Route: POST /api/insights/chat/messages/:id/feedback. Body
{ rating: "helpful" | "unhelpful", reason?: string }. Verifies
ownership (404 on cross-account messages — no existence leak),
decrypts the message body for the dedup key, and writes the row with
target_type="coach" + a metric-source string encoding the user's
active prefs (`coach:tone=warm:verbosity=default`). Per-user 60/h rate
limit. 409 on a P2002 (already_rated) so a double-click is a no-op.

Aggregator: new `buildCoachFeedbackBuckets()` slices Coach rows by
(promptVersion, tone, verbosity). The summary blob the worker writes
to AppSettings.adminAiInsightsFeedbackSummary now carries both
`buckets` (pre-existing) and `coachBuckets` (H7 addition). Targets
the same singleton row so no second worker handler is needed.

Admin view: `/admin/coach-feedback` (new section slug) renders the
Coach buckets as a small DataTable (prompt version × tone × verbosity
× helpful × not-helpful × n × helpful-rate). Helpful-rate column
tinted via Dracula tokens (green ≥80%, yellow ≥50%, orange below).
First useful question this answers: "Is the v1.4.22 prose rewrite
landing well, or did the warm tone overshoot?" If the helpful-rate
for PROMPT_VERSION 4.23.x drops below 50% within the first 100
ratings, v1.4.24 walks the persona back.

UI: `<ThumbsUp>` / `<ThumbsDown>` buttons (lucide icons, no emoji)
under each persisted assistant bubble. Streaming bubbles + refusals
+ error bubbles skip the row so users can't rate before the message
lands on disk. Localised "Thanks for the signal." after submit.

OpenAPI: spec carries the new POST route + the request schema.
Coverage now includes the H4 + H7 routes — three additions over
v1.4.22 baseline.

Tests +9 unit (aggregator Coach-bucket slicing, admin section
render-paths) plus an integration round-trip for the route.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:51:27 +02:00
Marc-André BombeckandClaude Opus 4.7 1faee95c84 fix(insights): tighter Pearson surfacing gate (n>=20)
The Pearson p-value derives from the Fisher's-Z normal approximation.
At low df (df < 18, n < 20) the normal approx is generous in the
wrong direction — at df=12 a true p≈0.04 reports as p≈0.025, sneaking
past the p<0.05 surfacing gate. The v1.4.22 product-lead memo flagged
this as Code-MED-03 with a deadline of "before v1.5/v1.6 auto-
discovery ships" because the false-positive cost compounds when
correlations get auto-generated.

Two paths considered:
  - Rigorous: drop in a 30-LOC incomplete-beta implementation so the
    p-value is accurate at every df. Cleanest fix, no test churn.
  - Conservative: raise `MIN_PAIRED_N` from 14 to 20 so the borderline
    band is excluded entirely. Smaller patch, no maths-library
    dependency.

v1.4.23 ships the conservative fix. The rigorous incomplete-beta
swap is queued as a v1.4.24 candidate; if usage data from the
v1.4.16 B5e feedback aggregator later shows users miss the
borderline cards, the rigorous path lands then.

Trade-off: a small set of borderline-significance correlation cards
stop rendering. Acceptable for v1.5 — the prompt-injection guards +
warm Coach prose make it more important to under-report than over-
report patterns.

Tests +1 (`pearson` n=15 → insufficient pin) plus an existing
`correlateBpCompliance` n=13 test renamed to n=15 + the noise-fixture
extended from 15 to 20 entries to clear the new gate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:38:54 +02:00
Marc-André BombeckandClaude Opus 4.7 0eda1de16f chore(schema): deploy medication_schedules.days_of_week column
The schema declared `MedicationSchedule.daysOfWeek` (mapped to
`days_of_week`) but no migration ever created the column. Code
paths in src/components/medications/*, src/app/api/medications/*,
src/app/api/admin/notifications/reminder-check/*, and the
achievements route all reference it via the comma-separated
"0,1,3,5" recurrence string.

Pre-v1.4.23 deploys silently survived because the existing query
sites only selected the column on SELECT — Postgres would have
failed loudly the moment a user actually saved a non-default
recurrence string via the medication form.

Migration `0039_medication_schedule_days_of_week` adds the column
nullable, default NULL. NULL means "daily" — `parseScheduleRecurrence(null)`
already returns the all-7-days set, so existing rows get the correct
semantics without backfill.

H5 decision rationale: deploy (Option A) over drop (Option B). The
field is referenced by 9 source files across 4 user-visible surfaces
(medication form, card, intake list, reminder dispatcher). Removing
it would force a UI rewrite of the recurrence picker and break
existing test fixtures. Deploying matches the schema's stated intent
and unblocks the v1.4.21 senior-dev review's MED-5 flag.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:36:27 +02:00
Marc-André BombeckandClaude Opus 4.7 3f60c81b9e feat(coach): per-user prompt-tuning surface (settings cog returns)
The v1.4.22 B5 audit removed the placeholder cog from the Coach
drawer header because it had no real wiring. v1.4.23 H4 returns
the cog with an actual settings surface backed by a per-user
preferences row.

Schema: nullable JSONB column `users.coach_prefs_json` (migration
0038_coach_prefs). Null = legacy v1.4.22 defaults; non-null carries
`{ tone, verbosity, excludeMetrics, showEvidenceByDefault }` validated
by the Zod schema in `src/lib/validations/coach-prefs.ts`.

Routes: GET + PUT `/api/auth/me/coach-prefs`. PUT validates the body,
persists the canonical defaulted form, and emits an
`auth.me.coach-prefs.put` annotation with the four-knob meta. OpenAPI
registry covers both verbs; the spec regenerates without drift.

Coach prompt builder: `getCoachSystemPrompt(locale, prefs)` prepends a
per-user OVERRIDE paragraph for non-default tone (neutral / concise)
and verbosity (brief / detailed). Concise tone forces brief verbosity
regardless of the explicit selection — concise == short. Default
prefs leave the prompt unchanged so the v1.4.22 train stays in place.

Snapshot builder: reads the prefs row BEFORE any measurement query
and intersects `excludeMetrics` with the resolved scope. The model
never sees data the user opted out of — that's the load-bearing
order: filter first, query second.

UI: settings cog in the drawer header opens a right-edge `<Sheet>`
with three Select pickers (tone, verbosity) and one Switch column
(per-metric exclusions + showEvidenceByDefault). Save calls the PUT
route and invalidates the `["coach-prefs"]` query so the next reply
honours the new defaults without a reload. EN + DE i18n keys for
every label and hint.

Message-thread reads the same `["coach-prefs"]` cache and toggles the
`open` attribute on the evidence `<details>` element when
`showEvidenceByDefault` is true.

Tests +24 unit (coach-prefs schema, system-prompt prefix, snapshot
mock for new prefs row). Integration round-trip seeds a session,
PUTs a non-default prefs shape, asserts the GET reflects the saved
values + the DB row carries the canonical defaulted form.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:35:45 +02:00
Marc-André BombeckandClaude Opus 4.7 9413d29303 refactor(coach): drawer prefill becomes a controlled prop
The v1.4.20 implementation reset the composer by mounting the
`<CoachDrawer>` with `key={prefill}`. That weaponised React's
key-reset to flush internal state every prefill change — Sr-HIGH-4
flagged it as a smell because the next refactor that touches the
drawer's mount point silently loses the reset semantics.

Replace with the controlled-prop pattern React documents at
https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes:
new `useResettableValue` hook reads the controlled prefill, mirrors
it via a sibling useState pair, and seeds the composer with the new
value when the prop changes. Render-phase setState — ESLint-clean
against `react-hooks/set-state-in-effect`. The user can still type
freely; the drawer only resets when the parent changes which
suggested-prompt chip is active.

`nextResettableValue` exposes the comparison contract as a pure
helper so the unit test can pin the (Object.is) semantics without
standing up a React renderer.

The `<CoachDrawer key={…}>` is gone from the insights page mount.

Tests +5: pure-function coverage of unchanged value (no reset),
prefill change (reset), null↔empty transition (reset), suggestion
chip → cleared prefill (reset), and NaN-to-NaN edge case (no reset
under Object.is).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:24:56 +02:00
Marc-André BombeckandClaude Opus 4.7 fa0774835e perf(api): chunked BP aggregate replaces unbounded findMany
The W2-of-v1.4.20 BD-Zielbereich fix needed the complete sys + dia
series to compute the all-time + prior-month + prior-year windows,
so it pulled both tables via single-shot `findMany`. For a 5-year
power user (~9 000 rows per side) that's a 50-100 ms Prisma round-
trip and a ~2 MB working-set allocation per /api/analytics request.

Switch to a cursor-paged 5 000-row chunked read via the new
`fetchBpSeriesChunked()` helper. The accumulated `BpReading[]` is the
same shape `computeBpInTargetWindows()` already consumed; the
working-set ceiling is now `BP_CHUNK_SIZE` instead of unbounded. Safety
bound at 1 000 pages = 5 M rows so a cursor-staleness bug can't loop
forever.

Wide-event annotation `analytics.bp_in_target.row_count` (+ per-side
`sys_rows` / `dia_rows`) lets ops attribute slow requests to outlier
users without rerunning the DB queries.

Integration test seeds a 6 000-row dataset (3 000 sys + 3 000 dia)
spanning a chunk boundary and asserts the response shape stays the
same — last30Days, last7Days, allTime windows all carry the
hand-derivable percentages.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:21:20 +02:00
Marc-André BombeckandClaude Opus 4.7 58ae9bca42 feat(coach): partial-malformed observability on sentinel parser
The W3-of-v1.4.22 sentinel parser silently dropped malformed rows and
fired `coach.keyvalues.parse_failed` only when the entire block was
unusable. Mixed-format drift (one row breaks, the other six parse)
landed without any signal. Surface it.

- `SentinelParseResult.malformedEntries[]` records each skipped row
  with a typed reason (`missing_colon` / `value_overflow` /
  `label_overflow` / `no_END_marker` / `byte_overflow` /
  `schema_invalid`). Block-level failures (truncation, missing close
  marker) land here as synthetic entries so the wide-event always
  carries a typed cause.
- Per-row label and value caps moved out of the Zod schema into the
  parser so the row-level reason can be `label_overflow` /
  `value_overflow` rather than the catch-all `schema_invalid`.
- Chat route splits the annotation: `coach.keyvalues.parse_partial`
  when at least one row parsed AND at least one row failed, the
  existing `coach.keyvalues.parse_failed` stays for full-block
  failures. Both annotations carry the per-line reason array.
- Backwards-compatible `parseKeyValueLine` wrapper preserved.

Tests +5: label_overflow, value_overflow, byte_overflow,
mixed-malformed entry assertions, and a tryParseKeyValueLine
direct-API surface check.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:20:01 +02:00
Marc-André BombeckandClaude Opus 4.7 921cb7d42f docs(planning): tick Wave 4 + record OpenAPI/Coach/native/Coolify report
Wave 4 closes the v1.4.23 foundation track. F5 (OpenAPI 3.1 drift
gate, warn-only for v1.4.23), F6 (Coach schema slot for Apple Health
metrics + PROMPT_VERSION 4.23.0), F7 (per-device refresh-token reuse
detection + device-management endpoints), and F8 (Coolify auto-deploy
runbook) all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:13:59 +02:00
Marc-André BombeckandClaude Opus 4.7 6d894a3179 ci(deploy): document the Coolify auto-deploy contract end-to-end
Two halves of the contract — workflow-side webhook (v1.4.22 C3 force=true
already in place) and Coolify-side image-digest watch toggle — must
both be on for tag pushes to land on production without an SSH retag.
The runbook in .planning/coolify-auto-deploy-howto.md now spells out
both pieces verbatim plus the verification curl + host-side fallback.

The workflow gains a single ::notice:: line after the webhook call so
future Actions runs surface the timestamp + sha for triage without
opening the verbose log.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:12:06 +02:00
Marc-André BombeckandClaude Opus 4.7 1bb5a45521 feat(api): device management endpoints for native + web settings
Adds GET /api/auth/me/devices to list a user's paired devices
(label, lastSeen, channels, isCurrent marker) plus matching DELETE
routes at /api/auth/me/devices/[id] and /api/devices/[id]. Revoke
cascades: every refresh token bound to the device is killed alongside
its paired access tokens, then the device row is deleted.

Cross-user attempts return 404 (no enumeration leak). The duplicated
/api/devices/[id] endpoint is the native-friendly URL the iOS client
calls on APNs token rotation, mirroring the W3 open question.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:11:30 +02:00
Marc-André BombeckandClaude Opus 4.7 05fe89575f fix(auth): refresh-token reuse-detection scopes to originating device
Pre-1.4.23, a replay attempt on a single device's stale refresh token
revoked every refresh token the user owned — signing them out of every
device. The legitimate two-device case (iPad + iPhone, one drops into
airplane mode and rotates) hit the same code path. v1.4.23 scopes the
blast radius to rows matching the offending refresh row's deviceId so
only the suspect device is signed out.

Legacy tokens issued before v1.4.23 carry deviceId=null and fall back
to the wider revoke — a safety hatch we keep until the last 60-day
refresh token from the old policy expires.

The native-client routes already forward X-Device-Id on every refresh,
so the legitimate path always carries a deviceId. A missing deviceId
on a replay is itself a suspicious signal, hence the conservative
fall-through.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:08:27 +02:00
Marc-André BombeckandClaude Opus 4.7 f2bc4f478a feat(coach): Apple Health metric slots + PROMPT_VERSION 4.23.0
Extends the strict insight schema, Coach snapshot pipeline, and
provenance envelope with the seven Apple Health categories that landed
in Wave 2 (HRV, sleep, resting HR, steps, active energy, flights,
distance, VO2 max, body temperature). All fields are additive and
optional — web-only accounts pay zero extra SQL and the prompt's new
GROUND RULE 12 instructs the model to stay silent when the snapshot
doesn't carry the HealthKit blocks.

Ratchets PROMPT_VERSION 4.22.0 → 4.23.0 and refreshes the
sourceMetric / trendAnnotations enums in both EN + DE. Two new test
files pin the prompt body and the snapshot fan-out.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 01:07:03 +02:00
Marc-André BombeckandClaude Opus 4.7 2fbc0650a6 ci: warn-only OpenAPI spec drift check
Adds an OpenAPI generation step to the Security & Quality workflow
that flags drift between the Zod registry and the committed
docs/api/openapi.yaml. Runs with continue-on-error: true so v1.4.23
informs without blocking; v1.4.24+ flips it to a hard gate once the
registry has caught up with the legacy hand-maintained spec.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:59:10 +02:00
Marc-André BombeckandClaude Opus 4.7 6a22064668 feat(openapi): register iOS-touched routes from Zod schemas
Wires the v1.4.23 baseline route table — auth/login, passkey verify,
refresh, measurements GET + POST + batch, devices POST, insights
comprehensive — into the new generator. Schemas reuse the existing
validation files via Zod v4's `.meta()`, so the iOS DTO contract stays
single-source-of-truth.

The freshly emitted spec covers ~880 lines (down from the 5468-line
hand-maintained legacy preserved in `openapi-v1422-legacy.yaml`).
Future routes get added incrementally via `src/lib/openapi/routes.ts`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:58:57 +02:00
Marc-André BombeckandClaude Opus 4.7 a8b233bf86 chore(deps): add zod-openapi + yaml@2 — OpenAPI generator base
Wires the OpenAPI 3.1 generator scaffolding ahead of the iOS-touched
route registrations. `zod-openapi` (samchungy variant, picked in W1
stream-3) reads Zod v4's native `.meta()` so schemas can stay in their
original validation files; `yaml@2` with `sortMapEntries: true` keeps
the emitted spec stable across re-runs.

`pnpm openapi:generate` overwrites `docs/api/openapi.yaml` from the
registry; `pnpm openapi:check` exits non-zero on drift. The legacy
hand-maintained spec is preserved at `docs/api/openapi-v1422-legacy.yaml`
so the iOS contract reference doesn't disappear during the
incremental migration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:56:32 +02:00
Marc-André BombeckandClaude Opus 4.7 a859661686 feat(api): POST /api/devices accepts apnsToken + apnsEnvironment
Extends the device-registration body schema with the paired APNs
identity fields the iOS client populates once it has an APNs token from
`application:didRegisterForRemoteNotificationsWithDeviceToken:`.
Validation rejects half-supplied requests (`apnsToken` without
`apnsEnvironment` or vice versa) with 422 and enforces hex format on
the token — catching the common iOS implementation bug where the token
gets serialised through Swift's `Data.description` (which renders
`<deadbeef cafebabe>` with spaces and angle brackets) instead of the
hex-join shape Apple's docs spec.

The cross-user-hijack guard from CLAUDE.md is duplicated at the
APNs-token layer: a registration whose `apnsToken` is already owned by
another user returns 409 with reason `apns_token_owned_by_other_user`.
APNs tokens aren't secrets, so trusting wire input would let any
client who learns one redirect another user's pushes — same threat
model as the existing `token` guard, applied to the new field.

Audit-log details for `devices.register` now carry `hasApnsToken` and
`apnsEnvironment` so admin trails surface APNs pairing events without
leaking the raw token. Five new route tests cover the validation +
hijack paths (paired-or-omitted, hex regex, create-with-pair,
cross-user-409, the original 401/422/409/201 contracts stay green).

Ticks STATE.md F4 and lands `.planning/phase-W3-v1423-report.md`
covering the six W3 commits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:48:27 +02:00
Marc-André BombeckandClaude Opus 4.7 9088cbd789 test(notifications): APNs sender unit + dispatcher integration coverage
23 unit tests under `senders/__tests__/apns.test.ts` exercise:
  * env-var loader — all-or-none guard, inline-PEM `\n` unescape, file
    fallback path, cache, APNS_PRODUCTION override
  * Provider lazy-init + per-gateway cache (sandbox vs production stay
    isolated; APNS_PRODUCTION funnels every send through production)
  * permanent-failure detection (`Unregistered`, `BadDeviceToken`,
    `DeviceTokenNotForTopic` flip `shouldDisable: true`; transient
    reasons stay false)
  * `sendViaApns()` dispatcher entry — fan-out, dead-row cleanup,
    hard-vs-soft channel-reject classification, HTML stripping

3 integration tests under `tests/integration/apns-dispatch.test.ts`
drive the real dispatcher against a Postgres testcontainer with a
stubbed `@parse/node-apn` Provider:
  * Round-trip: notification fans out via APNs and the channel-state
    machine records `lastSuccessAt` + clears any cooldown
  * Failure path: `Unregistered` deletes the dead Device row,
    auto-disables the channel with the captured reason, and writes the
    `notification.channel.auto_disabled` audit-log entry
  * Cascade: a disabled APNS channel falls through to Telegram on the
    next dispatch — the apns send-mock stays untouched

Adds `senders/__mocks__/apns.ts` — a deterministic mock with queued
per-token responses + recorded calls so future test files can swap the
real sender for a fixture-driven double without touching `@parse/node-apn`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:44:26 +02:00
Marc-André BombeckandClaude Opus 4.7 9c2119e48b feat(notifications): APNs joins the dispatcher cascade
Wires `sendViaApns()` into `dispatcher.sendToChannel()` as the fourth
channel-type alongside Telegram, ntfy, and Web Push. Per-user channel
selection works exactly as before — a user with `APNS` enabled in
`NotificationChannel` and no preference override receives APNs alerts;
a user who pairs an iPhone but disables APNs in Settings doesn't.

Cascade order is now deterministic: APNs → Telegram → ntfy → Web Push.
The order matters because each channel runs best-effort and the user
sees notifications fan out in that sequence; sorting in `dispatchNotification`
keeps the delivery sequence stable across dispatches even when Postgres
returns the channel rows in physical order. Unknown channel types sort
last so a stale enum value can't preempt a real channel.

The `CHANNEL_TYPES` tuple, `CHANNEL_TYPE_LABELS` map, and
`ChannelConfig` union pick up `APNS` / `Apple Push (APNs)` /
`ApnsChannelConfig` (an empty record by design — the per-device APNs
token + environment live on the `Device` row, not on the channel
config). On `shouldDisable: true` from the sender, the dispatcher's
existing channel-state machine flips `disabledReason` and bumps
`consecutiveFailures` through `recordChannelHardReject()` — no new
state-machine code needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:39:13 +02:00
Marc-André BombeckandClaude Opus 4.7 7f70856e2b feat(notifications): APNs sender mirrors web-push contract
Adds `src/lib/notifications/senders/apns.ts` so the dispatcher can fan
notifications out to a user's iPhone via Apple's push gateway. The
sender exposes two surfaces:

  * `sendApnsPush({ deviceToken, environment, payload })` for one-shot
    delivery — the helper the iOS-targeted reminder pipeline calls
    directly.
  * `sendViaApns(userId, payload)` mirrors `sendViaWebPush(userId,
    payload)` so the dispatcher can route APNS through the same
    `SendOutcome` contract: at-least-one-success → ok, every device
    permanently rejected → hard channel reject + auto-disable, anything
    else → soft failure that feeds the existing exponential-backoff
    schedule.

Provider lifecycle is one `apn.Provider` per gateway (`sandbox` vs
`production`), lazy-initialised so the JWT-signing-key parse doesn't
happen at boot. `@parse/node-apn` regenerates the bearer JWT every
~50 minutes inside the Provider, so the singleton is safe — the
explicit `resetApnsForTesting()` helper exists so unit tests can
re-read env vars between cases.

Permanent failure detection covers `Unregistered`, `BadDeviceToken`,
and `DeviceTokenNotForTopic`; the dispatcher branch deletes the dead
Device row before returning, mirroring the web-push 410 cleanup. The
env-var loader is all-or-none with a one-shot warning when the
operator started configuring and stopped — half-finished Coolify env
blocks surface in the logs the moment they matter.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:37:57 +02:00
Marc-André BombeckandClaude Opus 4.7 70789170cf feat(schema): APNs device columns + dispatcher channel-type extension
Adds the per-device APNs identity pair (`apnsToken` + `apnsEnvironment`)
to the Device model so the dispatcher can fan a notification out to a
user's iPhone via Apple's push gateway. The iOS client decides whether
the token belongs to the sandbox or production gateway at registration
time — the server never auto-detects, mirroring the W1 stream-2
recommendation.

Migration 0037 is strictly additive: both columns nullable, a CHECK
constraint pairs them so neither can be set without the other, and a
single-column index on `apns_token` backs the dispatcher's per-user
lookup plus the cross-user-hijack guard already enforced in
`POST /api/devices`. The `NotificationChannel.type` column stays a
free-form string — adding "APNS" as the fourth channel-type is a
TypeScript-side change in the next commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:35:58 +02:00
Marc-André BombeckandClaude Opus 4.7 bb76ea4f98 chore(deps): add @parse/node-apn for APNs send-side scaffolding
Adds the APNs Provider library the v1.5 iOS app needs so per-metric
alerts can land via Apple's push service alongside the existing
Telegram → ntfy → Web Push cascade. Bundles the env-var contract
(APNS_KEY_ID / APNS_TEAM_ID / APNS_BUNDLE_ID plus one of APNS_KEY or
APNS_KEY_FILE) in .env.example so a fresh deploy knows the four
required values up front. The dispatcher wiring + sender ship in
follow-up commits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:34:16 +02:00
Marc-André BombeckandClaude Opus 4.7 49c1a41c08 test: cast analytics GET handler in sleep-stages integration test
The W2 commit shipped with `as never` casts on the request + params
arguments, which let the runtime test pass but failed strict tsc
because `apiHandler<() => Promise<Response>>` narrows the wrapper's
signature down to its inner handler's. Cast through `unknown` so the
wrapper-side `request.url` read works and tsc is satisfied.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:28:24 +02:00
Marc-André BombeckandClaude Opus 4.7 2ce1a85622 docs(planning): tick Wave 2 + record backend foundation report
STATE.md flips F1 / F2 / F3 to done with the inline narrative needed
for the next wave to pick up cleanly: 7 net new measurement types
(W1's 6 plus BODY_TEMPERATURE the iOS DTO already shipped), unit
shift on SLEEP_DURATION from hours to minutes, the new SleepStage
enum + composite dedup index.

W2 report enumerates the six commits, the +19 unit / +8 integration
test delta, the migration name + SQL summary, the W1 recommendations
adopted verbatim, and the open questions for the maintainer about
the iOS DTO contract (the rename HEALTHKIT → APPLE_HEALTH stays the
load-bearing item).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:26:23 +02:00
Marc-André BombeckandClaude Opus 4.7 5470649d01 feat(analytics): per-stage sleep aggregation in /api/analytics
Apple Health stores sleep as one Measurement row per stage per night,
so the existing single-value SLEEP_DURATION summary would treat each
stage as its own datapoint and grossly understate the per-night total.
The route now sums per Berlin day before summarising — one summary
datapoint per night, value equal to total minutes asleep.

A new optional `sleepStages` block surfaces the per-stage breakdown
over the trailing 30 days when stage-tagged rows exist (and `null`
otherwise so the existing UI keeps painting the totals-only path).
The block reports total minutes, the night count covered, and the
per-stage minute sums so the upcoming insights surface can render
"averaged across N nights" captions truthfully.

Two integration tests cover both shapes — a four-stage night
aggregating to 880 minutes with a populated stages map, and a
manual-source no-stage row keeping `sleepStages` at null.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:25:01 +02:00
Marc-André BombeckandClaude Opus 4.7 86a80c5280 feat(ui): Apple Health source badge + restore-route enum sync
The measurements list now paints `APPLE_HEALTH` rows with a Dracula-
pink chip whose accent matches the iOS app's brand. The localised
label ships in both English and German via the new
`measurements.sourceAppleHealth` key; the helper falls back to the
SCREAMING_SNAKE value for unknown sources so a missing key would
surface immediately instead of silently rendering blank.

Admin backup restore guards (`MEASUREMENT_TYPES`,
`MEASUREMENT_SOURCES`) gain the seven new HealthKit-shaped types and
the new source value so a restore from a backup that contains Apple
Health rows doesn't get rejected as malformed.

A new badge regression test mirrors the existing BP-badge guard:
asserts the localised label paints, the Dracula-pink utility classes
land, and the bilingual locale still renders the same brand spelling.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:22:58 +02:00
Marc-André BombeckandClaude Opus 4.7 5cc0a00eaf feat(api): batch measurement ingest for the iOS Apple Health sync
`POST /api/measurements/batch` accepts up to 500 HealthKit-shaped
entries per call, runs each through the new mapping helper, and writes
them under `source = APPLE_HEALTH` with the inbound sample UUID as the
external id. The composite unique index on
`(user_id, type, source, external_id)` does the per-entry dedup;
`Idempotency-Key` covers the batch-level retry case so the iOS observer
queue can replay in flight without double-writing.

Per-entry status (`inserted` / `duplicate` / `skipped`) lets the
client advance its sync cursor accurately even when individual rows
land on different paths. Skip reasons cover unknown HealthKit
identifiers and out-of-plausible-range values so a single bogus sensor
reading never rejects an otherwise clean batch.

Insertion uses chunked `createMany` with `skipDuplicates: true` so a
race between two concurrent retries reconciles cleanly via the unique
index instead of failing the transaction. Wide Event annotation logs
`processed / inserted / duplicates / skipped` for ops visibility.

Six integration tests against a real Postgres testcontainer cover the
happy path, the per-entry duplicate path, the over-cap 422, mixed
unmappable + out-of-range entries, per-stage sleep rows, and
`Idempotency-Key` replay.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:20:37 +02:00
Marc-André BombeckandClaude Opus 4.7 30c0f76a34 feat(measurements): Apple Health identifier mapping helper
New `src/lib/measurements/apple-health-mapping.ts` translates inbound
HealthKit samples into the row shape the `Measurement` model expects.
Symmetrical to the Withings `MEASURE_TYPE_MAP` but keyed by HealthKit
string identifier so the upcoming batch endpoint can do a single
table lookup per entry.

Each mapping carries its canonical DB unit, a unit-conversion helper
(identity for SI-aligned types, ×100 for HealthKit's 0..1 fraction
quantities), an aggregation hint for downstream summarisation, and
flags the explicit-consent metrics (HRV, VO2 Max, sleep) so the audit
trail can pick them out.

Sleep is the one category type — the helper returns one row per stage
with the new `sleepStage` column populated; per-stage minutes go
straight in as `value`. Unknown identifiers return `null` so the
batch endpoint can mark the entry as skipped instead of failing the
whole batch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:17:56 +02:00
Marc-André BombeckandClaude Opus 4.7 95209ebf79 feat(schema): Apple Health measurement types + sleep stages + dedup index
Extend MeasurementType with the seven HealthKit-shaped values the iOS
batch ingest needs (HRV, resting HR, active energy, flights climbed,
distance, VO2 max, body temperature) and add APPLE_HEALTH to the
MeasurementSource enum. Sleep duration unit shifts from hours to
minutes so per-stage HKCategorySample rows persist without precision
loss; the new SleepStage enum mirrors the existing GlucoseContext
column shape and a CHECK constraint scopes it to SLEEP_DURATION rows.

The composite unique index `(user_id, type, source, external_id)`
gives the new batch endpoint an idempotent dedup key while the legacy
`(user_id, type, measured_at, source)` index continues to back the
manual UI's no-duplicate-at-the-same-wall-clock guard. NULL externalId
rows stay distinct under Postgres semantics so manual entries never
collide.

Migration is strictly additive: new enum values append, new columns
are nullable, no rows mutate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 00:15:56 +02:00
Marc-André BombeckandClaude Opus 4.7 8569a1879f docs(planning): v1.4.23 marathon scaffold — pre-iOS prep + hygiene
Backend foundation for v1.5 iOS Health app integration: Apple Health
measurement enum extension (HRV / Sleep / Resting HR / Steps / Active
Energy / Flights / Distance / VO2 max), MeasurementSource gains
apple_health, batched ingest endpoint /api/measurements/batch with
idempotency + dedup, APNs scaffolding (config + sender + Device model
extension + dispatcher wiring), OpenAPI 3.1 spec drift CI gate, Coach
schema slot for new metrics (PROMPT_VERSION 4.23.0), refresh-token
per-device revocation + /api/auth/me/devices, Coolify auto-deploy fix
for real. Plus 7 hygiene items from v1.4.22 backlog.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 23:56:41 +02:00
Marc-André BombeckandClaude Opus 4.7 b02343b0d2 docs(planning): close v1.4.22 milestone
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 22:51:56 +02:00
Marc-André BombeckandClaude Opus 4.7 d71e87983e chore(release): v1.4.22
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 22:32:02 +02:00
Marc-André BombeckandClaude Opus 4.7 bbdc3fbd00 style: prettier on W5 reconcile touchpoints
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 22:30:53 +02:00
Marc-André BombeckandClaude Opus 4.7 b094eaa2ae docs(planning): record Wave 5 reconcile + v1.4.22 backlog
Wave 5 reconcile pass complete: 7 HIGH applied inline, ~6 MEDs
applied inline, remaining MED + LOW deferred to
`.planning/v1422-backlog.md` under "Wave 5 reconcile carry-over".

- `.planning/phase-W5-v1422-reconcile-report.md`: 10 commit SHAs
  with cross-references to each finding, test count delta
  (+14 unit tests, +3 integration tests; final 2111 / 245 files),
  per-bucket HIGH / MED / LOW disposition, and items the
  maintainer should weigh in on (CSP scope, insights split, sentinel
  parser malformed-enum priority, /me resync stays as fall-back).
- `.planning/v1422-backlog.md`: every deferred MED + LOW with a
  one-line trace per item, organised by review bucket.
- `.planning/STATE.md`: Wave 5 ticked complete; tail updated to
  point at the W5 review files + reconcile report.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 22:26:21 +02:00
Marc-André BombeckandClaude Opus 4.7 6c0c69cbce fix: MED-cluster — SameSite=Strict, exact-match PUBLIC_PATHS, Berlin tz, streaming race
Six MEDs grouped per the W5 reconcile brief:

- Sec-MED-1: `hl_onboarding` cookie now `SameSite=Strict` (no
  cross-site flow depends on it; sibling `healthlog_session` stays
  `Lax` for the Withings OAuth callback).

- Sec-MED-2: `/onboarding` PUBLIC_PATHS match tightened from loose
  `startsWith("/onboarding")` to exact path + subroute guard
  (`pathname === "/onboarding" || pathname.startsWith("/onboarding/")`).
  A future `/onboarding-export` route can no longer inherit the
  silent-pass-through. Same guard mirrored on the redirect short-
  circuit. Two new proxy tests pin the contract.

- Code-MED-3: lift `berlinDayKey()` from
  `src/app/api/analytics/route.ts` to a shared
  `src/lib/analytics/berlin-day.ts` and route the targets
  sparkline-bucketing through it. The targets route used to bucket
  by UTC `YYYY-MM-DD` so a 23:30-Berlin reading on Tuesday landed
  in Wednesday's bucket. Four new unit tests pin DST + UTC-midnight
  edge cases.

- Code-MED (streaming race): on slow connections SSE `done` fires
  before the invalidate-refetch resolves, producing a 200-500ms
  duplicate-bubble render. Add a 150ms grace window on the
  message-thread that suppresses the persisted twin while the
  streaming bubble is still in flight.

- Code-MED-2: drop dead i18n keys `insights.coach.settings` and
  `insights.coach.settingsTooltip` (W3 removed the cog; the keys
  had zero call sites and would carry confusing legacy if v1.4.23's
  prompt-tuning panel picks a different key shape).

- Code-LOW-5: centralise `["user", "dashboardWidgets"]` query key
  in `queryKeys.dashboardWidgets()` and migrate the three call
  sites (dashboard, insights, settings/dashboard-layout-section).
  Same query-key-collision discipline as `queryKeys.analytics()`.

Closes Sec-MED-1, Sec-MED-2, Code-MED-2, Code-MED-3, Code-MED-3
(streaming race), Code-LOW-5.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 22:23:04 +02:00
Marc-André BombeckandClaude Opus 4.7 1631d8042c refactor: simplify-pass apply-yes cleanup
Five independent atomic edits from the W5 simplify review, grouped
in a single commit since none pull weight as a compound theme:

- coach-input: collapse `!disabled && value.trim().length > 0`
  triplication onto a single `canSubmit` (S-01).
- hero-strip: extract the duplicate weekly-report Button shell into
  a shared label fragment with the Link wrapping conditionally
  (S-02).
- api-token-overview-section: extract `<TokenStatusBadge size>` so
  the desktop table and mobile card list stay in lock-step on the
  revoked / expired / active 3-way ternary (S-03).
- trends-row: hoist the dynamic-load chart skeleton to a shared
  `ChartSkeleton` component (S-04). No chart-visual change —
  placeholder only.
- correlation-row: collapse the grid className ternary onto `cn()`
  with a conditional `md:grid-cols-2` (S-05).

Test count unchanged (2105).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 22:17:29 +02:00
Marc-André BombeckandClaude Opus 4.7 65a8b5a8b6 fix(coach): pin medical disclaimer at bottom of message thread
v1.4.22 B4 moved the disclaimer ("Coach replies are generated.
Clinical decisions belong with your doctor.") into the sources-rail
footer. The rail only paints at `xl+` viewports; on `<xl` (every
laptop and every mobile) the disclaimer was reachable only by
opening the chevron tray. That dropped the medical-disclaimer reach
from "every Coach session" to "the subset of users who tap a
chevron" — material regression for clinical-adjacent UI.

Pin a small persistent line at the bottom of the message thread so
the disclaimer paints regardless of viewport. The rail footer stays
for desktop users; the redundancy is intentional.

Closes Design-H3, Design-M4.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 22:15:27 +02:00
Marc-André BombeckandClaude Opus 4.7 651a529cdd fix(insights): collapse BP tile to single secondary row at <sm
The BD-Zielbereich tile is the only tile that ships an `avgAllTime`
sub-value (W2 A1+A2). Combined with the comparison-delta callout
above it, the tile rendered four stacked rows below the headline on
mobile: the comparison delta, then 7d/30d/all-time on a single
flex row that wrapped to three lines at 280 px (Galaxy Fold). The
BP tile read 2× as dense as every other trend card.

At `<sm`: hide the all-time span on the 7d/30d row, hide the
standalone comparison-delta callout, and render a single combined
secondary row beneath: "All-time 11% · Δ −0.4 last month". Full
layout returns at `>=sm` for users with the screen real-estate.

Closes Design-H2.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 22:14:47 +02:00