The /targets page composed everything inline in a 790-line page.tsx.
Break it into focused primitives under src/components/targets/ so the
W3e redesign can iterate per-card without growing the page file:
- target-card.tsx — the redesigned card composition. Headline + verbal
status pill, big-number row with inline trend chevron, range bar,
consistency strip, recency + streak chips (both conditional on real
data), per-card Coach CTA gated by aiEnabled, source link footer.
MOOD_STABILITY swaps the raw σ headline for a verbal label via the
moodStabilityLabel helper. Fixed card order is owned by the page;
this component is presentational.
- range-bar.tsx — extracted intact from page.tsx. Same behaviour, same
data-slot. Now carries its own test suite.
- consistency-strip.tsx — NEW. 7 dots (one per Berlin-tz day), each
filled / amber / red / hollow per the day's band classification.
Caption flips between "X of 7 in range" and "X of 7 logged" when
cadence is the more informative signal. Accessible: <ul role="list">
with per-dot aria-labels seeded from i18n. No empty-state copy
inside the strip — Marc directive: hide entirely when insufficient.
- target-coach-button.tsx — NEW. Per-card "Ask Coach about this" CTA
that returns null when aiEnabled is false. No greyed-out button,
no tooltip placeholder — the gate is total per Marc's
"no broken-button state" directive.
Supporting helpers (each unit-tested):
- src/lib/targets/mood-stability-label.ts — pure σ → verbal-label
threshold logic (< 1.0 stable, < 2.0 variable, ≥ 2.0
highlyVariable). Thresholds documented in the helper and confirmed
in the W3e plan.
- src/lib/ai/coach/target-prompts.ts — 8 metric × 2 locale templates
for the per-card Coach prefill. Falls back to a general template for
glucose contexts. PROMPT_VERSION unchanged (the assistant-facing
prompt does not shift; only user-side prefills do).
- src/lib/ai/coach/target-scope.ts — per-target CoachScope.sources
mapping. Derived metrics (BMI → weight, MOOD_STABILITY → mood) point
at the underlying source; unmapped targets return an empty array
so the drawer falls back to defaults.
i18n keys added: targets.consistency.* (cap + dot aria + relative day
+ insufficient-data), targets.card.{lastMet,streak}, targets.relativeDay.*,
targets.summary.{weekTitle,weekTitleAll,streakHighlight},
targets.coach.cta, targets.mood.stability.* — all EN + DE.
Tests: 17 cases across 5 suites (consistency-strip render variants,
target-coach-button gate branches, range-bar zone painting,
target-card full-data + insufficient-data + aiEnabled-off +
MOOD_STABILITY verbal-headline, mood-stability-label thresholds).
Page.tsx still uses the old inline composition for now — Phase 5
wires it to the new components.
The Zielwerte redesign needs three new per-target signals so the page
can answer "how consistent am I" without a chart:
- daysInRange7d / daysLogged7d — Berlin-tz day buckets over the last
week. The client renders 7 dots, one per day, filled when the day's
mean reading landed in the green band, hollow when logged but
out-of-band, dimmed when the day had no reading.
- consistency7d — the day-by-day band classification array the strip
reads directly (avoids re-deriving from sums client-side).
- daysInRange30d / daysLogged30d — same rollup over 30 days for the
page summary line and the optional details popover.
- lastMetGoalAt — Berlin-tz date the user most recently hit the
target band, or null when no in-range day in the last 30. Surfaces
the maintainer-tester case the W5 reconcile flagged (today lands
in-range by luck but the user has not actually hit goal in weeks).
- streakDays — consecutive in-range days ending today. Capped at 365.
- insufficientData — true when the target has < 3 readings in 30d
OR < 1 day logged in 7d. The client hides the strip + percentage
when set so we never surface a misleading "0 of 7" caption.
Schema also adds `pageSummary: { targetsMetThisWeek, totalTargets,
streakHighlight }` for the new account-level header. "Met this week"
threshold is daysInRange7d >= 4 — half of a logged week, lenient
enough to feel earnable. Streak highlight surfaces the longest
current streak ≥ 3 days.
Implementation collapses the v1.4.22 two-window (60-day) fetch back to
a single 30-day fetch — the now-removed delta-vs-last-month was the
only reason for the second window. The route is one Prisma query
shorter than v1.4.22. The shared `rollupConsistency` /
`rollupFromDayMap` helpers also pay off Senior-Dev M2 (the 7-pass
per-type computation collapses to one bucket-by-day pass per metric).
Per-day band rules:
- Continuous metrics (weight, pulse, sleep, body fat, glucose, steps,
mood) — classify the day's mean against the same green band the
RangeBar paints. Orange band reuses the pulse / glucose
configurable orange when available; otherwise symmetric ±30%.
- BP / BP-in-target — sys+dia paired within 5 min, day is "in" when
every pair clears the target, "near" when at least one does.
- MEDICATION_COMPLIANCE — day-level intake rollup. ≥ 99% taken = in,
≥ 50% = near, otherwise out. Days with zero scheduled doses
return null so they don't break the streak.
The v1.4.22 C1 inline sparkline + "Δ vs. last month" caption never
earned their place on /targets. The W5 reconcile filed four findings
against them (Design M2 — sparkline ignores min-points threshold so 3
points read as "lots of activity"; M7 — SVG aria-hidden hides the only
motion cue from screen readers; L3 — preserveAspectRatio="none"
distorts the y axis; Senior-Dev M2 — 7 sequential Array.filter passes
on the route). The replacement primitive (a 7-day consistency strip)
lands in the next phase; this commit just removes the dead weight.
Drops:
- Sparkline component, TargetItem.points30d, TargetItem.deltaVsLastMonth
- The 60-day fetch and the per-type sparklinePoints / deltaVsLastMonth
helpers in the route handler
- targets.deltaVsLastMonth, targets.deltaVsLastMonthFlat,
targets.deltaUnavailable i18n keys (EN + DE)
- targets-sparkline.test.tsx (the consistency-strip suite replaces it
in phase 3)
v1.4.25 W7 phase 6 — proposal §4 Option C as default-value layer.
The registration form now reads
Intl.DateTimeFormat().resolvedOptions().timeZone and sends it with
the signup payload. The server:
1. Validates the value against Intl.supportedValuesOf via
isValidTimezone().
2. On any invalid value (or absence), resolves the admin-
configured server default (AppSettings.defaultUserTimezone) and
uses that.
3. On no admin default, the resolver falls back to the
'Europe/Berlin' string, which is also the User.timezone column
default — so the worst case still produces the legacy
pre-v1.4.25 behaviour.
The Zod registerSchema gains an optional 'timezone' string field
capped at 64 chars (matches the longest IANA canonical zone
identifier plus headroom). Audit-log entry now carries the resolved
zone so an operator can spot a Tokyo user mis-attributed to Berlin
if browser detection fails.
No new tests — the existing register-route integration coverage is
thin, and the v1.4.25 W7 phase 7 integration test in
Pacific/Auckland covers the full signup → measurement → export
round-trip end-to-end.
`pnpm format:check` flagged two files touched in the previous W3 +
W3b commits — `src/components/insights/insights-tab-strip.tsx` (the
new tab strip) and `src/lib/charts/x-axis-density.ts` (the rebuilt
tick-density helper). Prettier normalised the Tailwind class-name
ordering and the multi-line function signature; no behaviour change.
v1.4.25 W7 phase 5 — proposal §5 admin half.
GET /api/admin/settings now returns defaultUserTimezone (null = use
Europe/Berlin fallback). PUT accepts the field:
- empty string clears the column (resolver falls back)
- non-empty must pass isValidTimezone(); otherwise 422
- successful writes invalidate the server-default resolver cache
so the registration handler sees the new value on the next
signup without waiting 60s for the TTL
The admin form gets a third row in the General Settings section
between 'default language' and the toggles, mirroring the user
picker UX (native select over Intl.supportedValuesOf, fallback
'Europe/Berlin (default)' option clears the override). 3 new i18n
keys per locale (defaultUserTimezone +
defaultUserTimezoneDescription + defaultUserTimezoneFallback);
descriptions follow proposal §5: 'Used for new accounts that don't
carry a browser-detected zone. Does not affect existing users.'
Tests: 3 new cases in src/app/api/admin/settings/__tests__/route.test.ts
covering valid IANA write, empty-string clear, and invalid-zone
rejection.
v1.4.25 W7 phase 4 — proposal §5.
Adds a per-user timezone picker to /settings#account between
date-of-birth and language. The control is a native <select> over
Intl.supportedValuesOf('timeZone') with a 'use browser timezone'
button that pre-fills detectBrowserTimezone(). Older engines without
Intl.supportedValuesOf fall back to a free-text input — every Chrome
99+/Safari 15.4+/Firefox 99+ ships the API so the fallback is
defensive only.
Form save uses Promise.all over two PUTs:
- /api/auth/profile (email, height, dob, gender)
- /api/auth/me/timezone (single field, dedicated route)
The split keeps the timezone validation + resolver cache
invalidation on a clean path; profile errors don't poison the
timezone write and vice versa.
The new route PUT /api/auth/me/timezone:
- requireAuth gates the cookie + Bearer paths
- 422 on any string the runtime's Intl.DateTimeFormat rejects
- 200 on success, returns the persisted value
- audits 'user.timezone.update' with previous + next
- invalidates the resolver cache so the next read sees the new
value within one tick instead of waiting 60s for the TTL
i18n: 4 new keys (timezone, timezoneHint, timezoneDetect,
timezoneInvalid) in messages/de.json + messages/en.json. Hint copy
follows proposal §5: 'Used for chart axis labels, reminder times,
export timestamps, and AI Coach context. Stored data is unchanged.'
Tests: 6-case suite on the new route covers auth, valid + invalid
zones, empty / missing field, and whitespace trimming.
Marc reported the German "Einnahmetreue" component label visibly
overlapping the band-coloured component-value pill at the right of
the row on `lg+` viewports. The card's `lg:w-[220px]` width left only
~64px for the label column after the progress bar (`flex-1`) and the
right-side value pill (`w-8`) consumed the rest — fine for short
labels like "BP" / "Mood" but cropped for the longer German strings.
Two coordinated changes:
- Card width: `lg:w-[220px]` → `lg:w-[260px]` (~18 % wider on `lg+`).
- Label column: `w-16` (64px) → `w-24` (96px) with a `truncate`
fallback for any future localisation that pushes the label past
96px.
Net result: the label column has ~50 % more pixel budget than before,
which puts "Einnahmetreue" comfortably inside its slot. The card's
internal grid (label / bar / value) preserves the same gap rhythm so
the visual proportions stay familiar.
Two coupled fixes pinned by Marc on the v1.4.25 W3 walkthrough:
1. Trends row equal-height
The three trend cards (BP / Weight / Mood) on /insights sit in a
`grid-cols-1 md:grid-cols-3` grid. The `min-h-[300px]` floor
guarantees a sensible mobile height, but the AI annotation prose
varies card-to-card on desktop, leaving the tallest card pushing
only its own row member down — siblings stayed short. Added
`md:auto-rows-fr md:items-stretch` on the grid container and
`h-full` on each direct child so the row pins every card to the
tallest member's height.
2. Mood chart gridline density parity
The mood chart's YAxis pins ticks to [1,2,3,4,5] (mood scale). By
default Recharts syncs CartesianGrid coordinates with YAxis ticks,
so the mini variant painted five horizontal lines while the
BP/Weight/Pulse minis painted six (their auto-generated YAxis
ticks land on ~six bands in typical health ranges). Added a
`horizontalCoordinatesGenerator` that emits six evenly-spaced
lines inside the plot area so the trends row reads as a single
rhythm.
Both changes are presentational — no chart data shape changes, no
behaviour changes, no API touched.
v1.4.25 W7 phase 3.4 — proposal §3 symptom 10.
The schema patterns on every 'format: date-time' field already
accept both 'Z' and '±HH:MM' suffixes (the Zod sources use
{ offset: true }), so the wire contract is technically correct. The
discoverability problem is that consumers reading the spec assume
'date-time' implies UTC.
Adds an explicit 'Date-time contract' paragraph to the API
description naming the convention: server responses emit the
requesting user's offset when a user context is present (exports,
doctor-report PDF), background-job-authored payloads emit 'Z',
clients must accept both.
Regenerated docs/api/openapi.yaml via pnpm openapi:generate; check
passes.
v1.4.25 W7 phase 3.3 — closes proposal §3 symptom 8.
renderDoctorReportPdfBytes now accepts an optional userTz in its
DoctorReportRenderOptions. The PDF route resolves the patient's
stored timezone via the v1.4.25 W7 resolver and threads it through
makeFormatters so date/time rows render in the user's zone.
A US patient generating a report at home in Boston now sees Eastern
time rows, not Berlin. Existing Berlin-region users see no
behaviour change — the User.timezone default is Europe/Berlin and
the formatter falls back when userTz is empty.
Client-side caller (settings dialog) is untouched in this commit — a
follow-up wave wires the auth-context value through the dialog
component.
Marc directive 2026-05-14: the page-level regenerate affordance has to
stay reachable while the user is reading the per-metric cards. Up to
v1.4.24 it lived inside the hero band's action row, which scrolled
away as soon as the user moved past the briefing.
What changed:
- New `src/components/insights/insights-tab-strip.tsx` carries the
six metric pills + the regenerate icon button. The strip is
`sticky top-0` with `bg-background/95 backdrop-blur` so it lives
above every section as the user scrolls.
- Right slot: a 44×44 icon-only `<RefreshCw>` button with
`aria-label={t("insights.regenerateAnalysis")}` and a sonner
success toast keyed to the falling edge of `regenerating`
(rising-edge guard via a ref so the toast only fires when an
in-flight regen finishes, not on every render).
- The hero strip's `onRegenerate` / `regenerating` props are gone;
its action row is now Weekly-report + Ask-the-Coach only. The
JSDoc comment block points to the new tab strip for the
regenerate affordance.
- `src/app/insights/page.tsx` mounts `<InsightsTabStrip
onRegenerate={advisor.regenerate} regenerating={...} />` and
drops the inline `InsightsSectionNav` function (its logic moved
into the new component verbatim).
- Two new translation keys added under the `insights.*` namespace:
`regenerateAnalysis` ("Analyse neu starten" / "Re-run analysis")
drives the aria-label + title; `regenerateSuccess` ("Analyse
wurde neu erstellt" / "Analysis refreshed") drives the toast.
The existing hero-strip test that pinned the regenerate slot was
flipped — the slot must NOT render under any prop combination. The
insights-polish test that asserted `<HeroStrip onRegenerate={advisor.regenerate}>`
was rewritten to assert the wiring is on `<InsightsTabStrip>` and that
the `<HeroStrip>` JSX block carries no `onRegenerate` prop.
v1.4.25 W7 phase 3.2 — extends the shared locale formatter to accept
an optional second argument carrying the per-user display timezone.
makeFormatters(locale) — unchanged, still renders in Europe/Berlin.
makeFormatters(locale, userTz) — renders in the user's zone.
The empty-string and undefined cases both fall back to
DISPLAY_TIMEZONE so admin tools, the legacy client wrapper in
src/lib/format.ts, and audit-log viewers keep behaving identically.
Three tests cover Asia/Tokyo wall-clock + date roll-over and the
empty-string fallback. No production callers yet — wire-up happens
in the per-surface commits that follow (doctor-report PDF, Coach
snapshot, chart axes).
v1.4.25 W7 phase 3.1 — closes the export half of issue #167.
CSV/JSON exports previously emitted timestamps via .toISOString(),
producing 2026-05-15T09:00:00.000Z. Excel and LibreOffice drop the
trailing Z silently and render the bare datetime in the viewer's
locale, so a Warsaw user reads UTC as local time — 11:00 entries
display as 09:00 in their spreadsheet.
Export helpers now accept an optional userTz argument and emit
ISO-8601 with the user's UTC offset
(2026-05-15T11:00:00+02:00). The offset survives the round-trip and
the on-screen value is unambiguous regardless of the spreadsheet's
defaults. Routes resolve the user's stored timezone via the v1.4.25
W7 phase 2 resolver and thread it through formatMeasurements /
formatIntakeEvents / formatMoodEntries.
Backward-compatible: userTz is optional. When omitted (admin tools,
canonical-backup-on-disk shape) the helpers fall back to
.toISOString(), keeping the legacy contract for the JSON full-backup
route that the upload-restore validator depends on.
Surfaces touched:
- src/lib/export.ts (3 formatters + helper)
- src/app/api/export/measurements/route.ts
- src/app/api/export/medications/route.ts (intake history block)
- src/app/api/export/mood/route.ts
- src/app/api/export/route.ts (legacy aggregate route)
Tests: 5 new cases in src/lib/__tests__/export.test.ts covering
Berlin / Auckland / New_York offsets, the no-userTz fallback, and
the mood-entry case where the stored YYYY-MM-DD date column stays
unchanged (see proposal §6.3 for the read-side rationale).
v1.4.25 W7 phase 2 — adds src/lib/tz/resolver.ts with:
- resolveUserTimezone(userId) reads User.timezone with a 60s
process-level cache and falls back to the server default.
- resolveServerDefaultTimezone() reads AppSettings.defaultUserTimezone
with the same TTL, falling back to 'Europe/Berlin'.
- detectBrowserTimezone() — client-only Intl helper.
- formatInUserTz(date, tz, shape) emits ISO-8601-with-offset (for
exports — issue #167 fix), wall-clock (for chart axis labels),
datetime (for PDFs / notifications), and date-only (parallel to
berlinDayKey but parameterised).
- userDayKey(date, tz) — day-bucket helper parallel to
berlinDayKey() but user-scoped.
- isValidTimezone() / listSupportedTimezones() for write-path
validation and the picker UI.
29-test suite covers cache hit/miss, fallback chain, invalid tz
handling, DST (Berlin Jan = +01:00, May = +02:00), Pacific/Auckland
(UTC+12), America/New_York (UTC-04 in May), and the Berlin-vs-Auckland
midnight round-trip that makes the per-user feature visible.
The /insights page rendered both <InsightAdvisorCard> (the polished
severity-ordered recommendations grid + per-rec rationale + confidence
meter + medical-citation footnotes shipped in v1.4.16 phase D
reconcile) AND <InsightStatusCard title={t("insights.generalStatusTitle")}>
(the v1.4.15 text-only summary). The page comment at the advisor
wiring acknowledged the status card "was intended to be replaced"
during D-reconcile but the status mount was never removed, so users
saw two cards saying the same thing — one labelled
"KI-Gesundheitsanalyse" and one labelled "Allgemeiner
Gesundheitszustand".
Removed:
- The <section id="section-general"> block + its <InsightStatusCard>.
- The `generalStatus` useQuery + the unused `GeneralStatusData`
interface.
- The `generalStatus?.updatedAt` entry from freshestUpdatedAt(); the
other six per-section caches still feed the hero's "Generated …"
caption.
- The "section-general" entry from the sticky pill nav (it had
nothing left to scroll to).
Kept:
- The /api/insights/general-status route + the underlying
generateGeneralStatusForUser lib — the reminder worker still
pre-warms the daily general-status cache for users opted in to the
briefing notification. Added a JSDoc @deprecated note on the route
pointing new callers at <InsightAdvisorCard> /
useInsightsAdvisorQuery().
- The insights.generalStatusTitle + insights.generalStatusBadge.*
translation keys — they're still referenced by the per-section
badge labels (insights.generalStatusBadge.good / .watch /
.critical map traffic-light states on every metric section, not
just the dropped general one).
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>
- 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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
`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>
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>
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>