Commit Graph
229 Commits
Author SHA1 Message Date
Marc-André BombeckandClaude Opus 4.7 901f44e6dc feat(charts): mood chart polish with emoji glyphs at data points
Same Apple-Health visual leap as the other charts, plus the mood-
specific affordance: an emoji glyph at every daily score so a week's
worth of mood reads at a glance without consulting the legend.

What changed:
- ComposedChart replaces LineChart so a gradient-filled Area paints
  under the score line. The mood gradient uses the lavender token
  (--dracula-lavender / #d6acff) which matches the existing line
  stroke. Sibling 0×0 SVG mirrors the gradient for SSR-discoverability.
- Personal baseline reference line: median mood over the visible
  window (≥5 points required). Faint dashed line labelled "Your
  normal" / "Dein Mittel".
- Rich tooltip via RichChartTooltip — date label, score value with
  text-label ("4.0 (Good)"), delta-vs-baseline sub-line.
- Emoji dot per score: 1 → 😖, 2 → 🙁, 3 → 😐, 4 → 🙂, 5 → 😄.
  The Recharts `dot` prop accepts a function returning an SVG node;
  we render <text> centred over (cx, cy) so the glyph sits on the
  line. data-slot="mood-emoji-glyph" + data-score for visual probes.
- 600ms ease-out animation on first render, suppressed when
  prefers-reduced-motion is set.
- Sparse-data placeholder via ChartEmptyState for <3 data points.

1 new test pins the gradient-defs SSR contract; existing
mood-chart-aggregation tests still green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:30:40 +02:00
Marc-André Bombeck b863e2cc3d fix(ui): tap-targets reach 44px on tour, notification, backups buttons (v1.4.15 H4)
WCAG 2.5.5 Level AAA target-size floor for non-essential controls is
24×24 px and Level AA pointer-target is 24×24 with 24 px gap, but the
mobile-app convention everyone follows is the 44×44 hit-area Apple
HIG / Material recommend. The default `<Button size="sm">` in the
shadcn-base lands at `h-8` (32 px) — readable on desktop, tight on
phones, especially in the most-touched admin/settings/onboarding
surfaces called out in the v1.4.15 design review.

Cross-cutting `button.tsx` `h-9 → h-11` was rejected as too risky
mid-marathon (every UI affected, dozens of layout assumptions). The
targeted alternative bumps the listed call-sites with `min-h-11`
overrides: tour Skip / Back / Next, notification re-enable + send-
test, backups Restore / Download / Run-now / Upload. Admin-only
recent-audit-preview is a `<Link>` not a `<Button>` and is left
alone.

The shadcn `min-h-` Tailwind utility wins over the variant `h-`
because both apply but `min-h-` only floors. So desktop visuals stay
within ~4 px of the previous render while mobile reaches the 44 px
floor.
2026-05-10 00:29:44 +02:00
Marc-André Bombeck 2afe3c47ce fix(onboarding): scope tour-launcher sessionStorage keys by user id (v1.4.15 H4)
Both `healthlog-tour-session-dismissed` and `healthlog-tour-referrer`
were un-scoped global keys, so a browser shared by two HealthLog
identities (admin impersonating a target user, family laptop, etc.)
inherited the first user's "tour dismissed for this session" flag —
the second user logged in and silently never saw the spotlight tour.

Both keys are now suffixed with `:${userId}`, so each identity's
state stays independent. The two builders (`tourSessionDismissedKey`
and `tourReferrerKey`) are exported so the wizard's `persistAndExit`
shares the same wire format and a unit test pins the scheme against
future drift.

One-off cost: every currently-open tab re-fires the tour once on the
next load because the legacy un-prefixed keys are no longer read.
Acceptable tax for multi-tenant correctness ahead of v1.5.
2026-05-10 00:27:20 +02:00
Marc-André Bombeck 7f1a4ded25 fix(validation): moodEntry.tags must parse as JSON string-array (v1.4.15 H2)
`MoodEntry.tags` is stored as a JSON-array-as-string in
`mood_entries.tags`. The backup schema accepted any string here, so a
malformed blob (or a tampered backup) would persist into the DB and
crash downstream readers that blindly `JSON.parse` it. Restore-time
validation now refines the field to one of:

  - null (or omitted) — no tags on this entry
  - "" — legacy moodLog wire format (treated as null)
  - a JSON string that parses to an array of strings

Anything else fails Zod with a 422 from the restore endpoint instead
of bubbling out of `prisma.createMany` with an opaque message. New
unit-test file covers the three accept cases plus three reject cases
(non-JSON, JSON object, JSON array of non-strings).
2026-05-10 00:27:20 +02:00
Marc-André BombeckandClaude Opus 4.7 d914f766dc test(settings): coverage for renamed/consolidated sections
Phase B6 commit 4 of 4.

* `sections.test.tsx` gains two SSR smoke tests for the renamed
  `<ThresholdsSection>` (was `<ThresholdsSettingsSection>`) — one
  asserts EN heading + editor mount-point, one asserts the DE
  heading. The mock for the inner editor was already updated in
  commit 2 of this phase.
* New `sections-i18n-parity.test.ts` walks every slug in
  `SETTINGS_SECTION_SLUGS` and asserts both `.title` and
  `.description` resolve to non-empty strings in EN AND DE — and
  that the DE description is not a verbatim copy of the EN one.
  The test caught a real instance: notifications.description was
  "Telegram, ntfy, Web Push." in both locales because the channel
  names are proper nouns. Rewrote the description in both locales
  so it actually reads as German vs. English while still listing
  the channels.

Settings tests: 63/63 green. Typecheck clean. Lint clean (12
pre-existing warnings carried over from the baseline gate, 0 errors).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:26:57 +02:00
Marc-André BombeckandClaude Opus 4.7 a432cb2e26 refactor(settings): consistent naming + i18n key namespace
Phase B6 commit 2 of 4.

* `thresholds-settings-section.tsx` (route wrapper) renamed to
  `thresholds-section.tsx` so the filename + default export match
  the slug — every other section in `src/components/settings/`
  follows the `<slug>-section.tsx` `<SlugSection>` convention.
* The historic inner editor at `thresholds-section.tsx`
  (`<ThresholdsSection>`) is moved out to
  `thresholds-editor-section.tsx` (`<ThresholdsEditorSection>`)
  so the names stop clashing.
* Rewrites three muddy section descriptions in EN + DE:
  - account: lists every concern the section actually covers
  - api: drops the misleading "headless clients" / "Drittanbieter"
    framing for "your own scripts and apps"
  - advanced: post-B7 there's no Import surface here — describes
    the danger zone honestly.

No user-facing setting removed, no slug renamed, no i18n key removed.
Settings smoke tests still green; the route mount goes through
`<ThresholdsSection>` exactly as before, just from the renamed file.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:26:57 +02:00
Marc-André BombeckandClaude Opus 4.7 74c2eb8bff feat(charts): BP/weight/pulse polish (gradient, baseline, rich tooltip)
The HealthChart wrapper is the single component the dashboard uses for
every numeric vital — BP systolic/diastolic, weight, pulse, body fat,
sleep, steps. This commit upgrades it once with the v1.4.16 visual
leap so all those metrics jump together.

What changed:
- ComposedChart replaces LineChart so a gradient-filled Area can
  paint under the line. Each metric gets its own
  chart-gradient-inline-{type} <linearGradient> definition; default
  35 percent top alpha → 0 percent bottom matches the Apple Health
  Trends look. A sibling 0×0 SVG mirrors the gradient so SSR markup
  carries the slot for visual-regression and e2e probes.
- Personal baseline reference line: 90-day rolling median per type,
  painted as a faint dashed line labelled "Your normal" / "Dein
  Mittel". The new computePersonalBaseline() helper returns null when
  fewer than 5 points exist so a baseline never renders off noise.
- Rich tooltip via the new RichChartTooltip primitive: rounded card
  with drop shadow, per-row coloured dot, tabular-nums value cell, and
  a delta-vs-baseline sub-line ("+3 mmHg vs. your normal"). Auxiliary
  rows from the moving-average / trend overlays are filtered out so
  the card stays focused on the primary metric.
- 600ms ease-out animation on first render via Recharts'
  isAnimationActive prop, suppressed when prefers-reduced-motion is
  set at the OS level (new src/lib/charts/reduced-motion.ts helper
  with 4 unit tests).
- Sparse-data placeholder via ChartEmptyState when fewer than 3
  daily points exist — a near-empty chart looks broken, the
  placeholder reads as intentional.

In-target zone shading was already wired via the existing valueBands
prop and stays untouched. The dashed peer's labelling is unchanged.

7 new tests pin the contract (4 baseline-helper, 2 SSR markup, 1
gradient-id namespacing).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:26:13 +02:00
Marc-André Bombeck fdac9e2517 fix(admin): scrub raw Prisma error from restore-failed response (v1.4.15 H1)
The catch block around the restore transaction echoed the raw error
message back to the admin client (`Restore transaction failed: <full
prisma message>`). Even on an admin-only endpoint that leaks column
names, constraint names and query fragments to anyone with admin
access — lower than CRITICAL but unnecessary surface for a future
supply-chain or impersonation scenario.

Response now returns a stable "Restore failed" 500. The verbose text
still lands in the audit-log row (admin-readable, forensic) and in
the Wide Event under `meta.restoreFailReason` (operator-readable),
so root-cause investigation is unaffected.
2026-05-10 00:23:33 +02:00
Marc-André BombeckandClaude Opus 4.7 2611bb4fae feat(db): User.aiProviderChain for ordered fallback config
Add a JSONB column on the users table that stores an ordered list of
provider preferences for multi-provider redundancy. Each entry carries
{ providerType, priority, enabled }; credentials still live in the
dedicated encrypted columns so AES-256-GCM key rotation keeps working
unchanged. Null preserves the legacy single-provider resolution path.

Ships a defensive parser/serializer pair with a sensible default chain
(codex -> openai -> anthropic -> local -> admin-openai) so a malformed
JSON on disk falls back to the default rather than 500-ing insight
generation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:20:12 +02:00
Marc-André BombeckandClaude Opus 4.7 6520ae4e0f feat(admin): sidebar entry for app-logs
Adds the `app-logs` row to `<AdminShell>` so the new section shows up
in the admin sidebar (desktop) and mobile section strip alongside
Login Overview and Backups. Uses `lucide-react`'s `FileText` icon
because nothing else in the bundle reads as "structured log lines".

The mobile-strip / desktop-sidebar pattern follows the conditional
admin-only nav established in v1.4.15 A1 and v1.4.16 A1: the global
sidebar still surfaces a single `/admin` link, and the per-section
nav lives inside the admin shell.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:10:00 +02:00
Marc-André BombeckandClaude Opus 4.7 d5c891244b fix(export-section): point download buttons at the new plain-segment endpoints
The four `/api/export/*` route handlers landed under plain segments
(`/api/export/measurements` instead of `/api/export/measurements.csv`)
because vitest's resolver chokes on dotted route segments. The
`<ExportSection>` component still pointed at the old dotted paths —
which 404'd in the browser even though the routes themselves were
healthy. Realign the four endpoint URLs so the consolidated Settings →
Export UI actually downloads.

Filename + Content-Disposition still carry the `.csv` / `.json`
extension so the browser writes a correctly-named file.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:09:37 +02:00
Marc-André BombeckandClaude Opus 4.7 4cc3d8d45e feat(admin): app-log preview surfaces last 1h of structured events with filter + JSON inspector
Wires the in-memory ring buffer (`src/lib/logging/in-memory-buffer.ts`)
into `transports.emitEvent()` so every wide event that survives the
sampler also lands in a 500-entry per-process buffer. Adds the
`app-logs` admin section slug, the renderer case, and the route entry
exports needed for the new section component to mount.

The buffer is volatile and per-process — a worker-only event won't
show up in the web buffer, and a restart drops everything. The section
header copy spells that out so admins know to keep Loki configured for
durable diagnostics. Egress through `/api/admin/app-logs` runs every
event through `redactSecrets()` so a stray Bearer / hlk_ / sk- token
in an `error.message` never leaks to the admin UI; storage stays raw
to keep the diagnostic value when shipped to Loki.

The companion buffer + transports tests live under
`src/lib/logging/__tests__/in-memory-buffer.test.ts` and
`transports-buffer.test.ts` (committed separately as part of the
buffer scaffolding). The route-level tests in
`src/app/api/admin/app-logs/__tests__/route.test.ts` cover newest-
first ordering, traceId / level / action filters, the `limit` cap,
secret redaction on egress, and the Zod-rejected invalid `level` case.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:09:22 +02:00
Marc-André BombeckandClaude Opus 4.7 226cac4c02 docs(planning): mark phase B3 (host-load chart) complete
Host-load chart above /admin/system-status renders the last 2h of
load1, memory %, and disk-IO % from a per-minute pg-boss sampler.
Schema migration 0032_host_metric, /api/admin/host-metrics endpoint,
HostMetricsChart component (Recharts wrapper, next/dynamic from the
consumer), system-status section wired with the chart on top, EN+DE
i18n keys, 13 unit + 6 integration tests.

Three commits landed cleanly under their own titles (db, jobs, api);
the chart + wiring + i18n got absorbed into another agent's commit
due to a parallel-agent staging race during the verification gate's
stash/restore loop. Functionally everything is on origin/main.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:08:32 +02:00
Marc-André BombeckandClaude Opus 4.7 8ac5602837 docs(planning): Wave-A verification gate report + STATE update
Local clean-clone verification confirms Wave-A introduced no
regressions: typecheck/lint/unit/integration all green at origin/main
HEAD `94c748d`. CI Security & Quality consistently passes; the failing
Integration tests + e2e workflows are pre-existing infrastructure issues
(failure shape identical at v1.4.15 release commit `0985c93`), not
Wave-A source regressions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:08:04 +02:00
Marc-André BombeckandClaude Opus 4.7 8d9f86462f docs(planning): mark Wave-B B5a (medical-reference grounding) complete
5 atomic commits on origin/main land the curated reference bundle,
schema validation, prompt injection, citation-coverage logging and
the UI footnote. PROMPT_VERSION bumped to 4.16.0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:05:40 +02:00
Marc-André BombeckandClaude Opus 4.7 a66c128dd9 feat(insights): citation footnote on recommendations with medical reference
When a recommendation carries a `referenceId` pointing into the
curated medical-reference bundle, render a small footnote underneath
linking to the guideline. Format: "Source: ESH 2023 — ESH 2023
Guidelines for the Management of Arterial Hypertension" (locale-
routed title), with a tiny external-link icon, opens in a new tab via
target="_blank" rel="noreferrer". Per the v1.4.16 research doc §7
the URL never opens in an in-app webview.

`InsightResult.recommendations` widens to accept either the legacy
plain-string shape OR a structured `{ text, referenceId? }` object so
existing rendering paths keep working while the new citation surface
plugs in through the same component. `getMedicalReferenceById()`
returns undefined for unknown ids — the UI silently drops the
footnote in that case rather than rendering a broken link (defence
in depth on top of the schema validation).

i18n keys `insights.recommendation.source` and
`insights.recommendation.viewSource` land in both EN and DE.

6 component tests pin the no-footnote / EN-locale / DE-locale /
unknown-id-defence / multi-rec paths.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:04:24 +02:00
Marc-André BombeckandClaude Opus 4.7 94c748d804 refactor(doctor-report): entry-point relocated under /settings/export
The doctor-report PDF entry-point used to share the Advanced section
with CSV/JSON exports — three buttons crammed onto one row with no
filter UI in front of them. v1.4.16 phase B7 promotes export to a
first-class settings section, so the doctor-report card now lives
inside `<ExportSection>` (its own card with the date-range dialog
prominently surfaced via "Configure & generate").

`<AdvancedSection>` is reduced to the danger-zone card alone — the
"wipe all data" surface should never live next to a one-click export
button anyway. The matching e2e spec follows the move from
`/settings/advanced` to `/settings/export` and now drives the dialog
through the submit step instead of expecting an inline button.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:53:17 +02:00
Marc-André Bombeck 2877710b37 feat(api): /api/admin/host-metrics returns last 2h of host load + memory
Backs the new chart above /admin/system-status. Reads HostMetric rows
captured by the per-minute sampler and returns the window the chart
asks for via `?since=` (30m / 1h / 2h / 6h / 12h / 24h, default 2h).

Per-row response shape is what Recharts can plot directly:
  - capturedAt          ISO-8601
  - loadAvg1            number
  - memUsedPercent      0..100, rounded to 2 decimals
  - diskReadBps / diskWriteBps  number | null

Disk fields are derived server-side from the cumulative byte counters
the sampler captured. Computing the per-second delta in the route
keeps the chart component stateless and means a hypothetical CLI / iOS
admin view gets the same units. The first row in any window has no
predecessor, so disk fields are null. A negative delta — counter reset
on host reboot — also surfaces as null instead of a misleading negative
BPS spike.

`meta.memTotalBytes` carries the most recent total so the tooltip can
render an absolute "4.2 GiB / 8 GiB" without a second round-trip.

requireAdmin()-gated: host telemetry is admin-only, never exposed via
Bearer tokens. apiHandler wrapper handles the wide-event annotation
("admin.host-metrics.list") and request-id propagation for free.

6 integration tests against the testcontainer Postgres pin auth
gating, the 2h default window, the diskBps derivation across a
counter-reset, the `?since=30m` filter, and the empty-DB happy path.
2026-05-09 23:52:43 +02:00
Marc-André BombeckandClaude Opus 4.7 53aade981a feat(ai): post-validation logs citation-coverage rate per insight generation
After the schema parse and citation cross-check pass, the wrapper
counts how many recommendations make a normative claim ("target",
"should", "normal range", "above", "below") and how many of those
carry a `referenceId` pointing into the curated medical-reference
bundle. The result lands in the active Wide-Event meta annotation
under `ai_total_recommendations`,
`ai_normative_recommendations`,
`ai_cited_normative_recommendations` and
`ai_uncited_normative_recommendation_ids` so the admin AI quality
dashboard can chart citation-coverage over time.

Observational only in v1.4.16 — a normative rec without a referenceId
is logged, never raised as a parse error. Phase B5c will flip the
check to required for severity >= "important".

15 unit tests pin the keyword heuristic (EN + DE), the coverage
counts across cited / uncited / observational mixes, and the
`generateInsight()` integration that emits the annotation only on
success (skipped on schema-failure throw).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:51:59 +02:00
Marc-André BombeckandClaude Opus 4.7 a512650158 feat(settings): /settings/export dynamic route wired into sidebar
The new `export` slug is now part of `SETTINGS_SECTION_SLUGS`, so the
dynamic `/settings/[section]/page.tsx` route picks it up via
`generateStaticParams()` and the existing 404-on-unknown guard. The
shell sidebar gains a Download-iconed entry between API and Advanced;
the placeholder fallback also learned the new icon so a future slug
addition can't crash type-checking.

The shell-test suite now expects ten sections (was nine) and asserts
that `/settings/export` is a real link in the rendered nav. Old
"advanced" copy already trimmed in the previous commit, so the export
entry is the new home for every "give me my data out" path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:51:33 +02:00
Marc-André BombeckandClaude Opus 4.7 f1bd8014d8 feat(jobs): host-metric sampler captures load + memory every minute, 7d retention
Powers the 2-hour host-load chart Marc asked for above the
/admin/system-status section. The pg-boss `host-metric-sample` queue
runs `* * * * *` and writes one HostMetric row per tick.

Sampler implementation:
  - `os.loadavg()` → load_avg_1/5/15 (rounded to 2 decimals)
  - `os.totalmem() - os.freemem()` → mem_used_bytes / mem_total_bytes
  - On Linux: parses /proc/diskstats and sums sector counters across
    physical block devices (skipping loop/ram/dm-/md/sr/fd/nbd/zram
    pseudo-devices that double-count). Multiplies by the canonical
    512-byte sector size for raw bytes
  - On macOS / Windows / inside containers without /proc: disk fields
    are NULL, the chart gracefully degrades

The disk-stats reader is injected so the unit test can stub it without
touching `node:fs`. `runHostMetricTick()` does the insert + the
`deleteMany` for rows older than HOST_METRIC_RETENTION_DAYS (default 7,
env override capped at >= 1d to guard misconfigs).

Wired into reminder-worker.ts alongside the other recurring queues.
The worker handler swallows errors to a Wide-Event warning rather than
re-queueing, because a single missed tick costs a minute of chart data
— not worth a retry storm.

8 unit tests pin retention env handling, the disk-stats null/throw
fallback paths, and the create + deleteMany call shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:50:08 +02:00
Marc-André BombeckandClaude Opus 4.7 621109cf20 feat(settings): export-section consolidates doctor-report, CSVs, JSON backup
Adds the consolidated `<ExportSection>` component for the new
`/settings/export` route — one card per export type (Doctor Report PDF,
Measurements CSV, Medications CSV with optional intake-history toggle,
Mood CSV, Full JSON backup) with date-range filters where applicable.

Mobile-first: cards stack on small viewports and switch to a 2-column
grid on `md+`. Each card carries a stable `data-testid` so the e2e
suite can target them without relying on the localised label.

i18n keys live under `settings.sections.export.*` in EN + DE and the
old "advanced.description" copy was tightened so the upcoming wiring
commit can move the export entry-point out of `/settings/advanced`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:49:38 +02:00
Marc-André BombeckandClaude Opus 4.7 7fbfca672e feat(ai): system prompt includes curated medical references for citation grounding
Builds a SOURCES block dynamically — only references whose
applicability overlaps the metrics in the current snapshot get
listed, so a weight-only call doesn't burn tokens on ESH BP guidance.
Each line carries the id (lowercase, parser-validated), org, year,
title (locale-routed) and direct URL so the model can cite by id.

Adds a GROUND RULE that tells the model to set
`recommendation.referenceId` to the matching SOURCES id when making a
target-range or normative claim, and to leave it empty for purely
observational comparisons. The schema check from the previous commit
rejects fabricated ids — defence in depth on the prompt instruction.

Plain `getStrictInsightsSystemPrompt(locale)` stays unchanged for
back-compat with the existing assertions and any call-site that
hasn't migrated yet. The new
`buildSystemPromptWithReferences(locale, metrics)` is the path
forward.

10 unit tests pin the SOURCES-block contents, locale-routed titles,
deduplication when metrics repeat, and that the existing scope-
hardened guards (refusal pattern, citation cross-check) survive.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:49:25 +02:00
Marc-André BombeckandClaude Opus 4.7 466b8b5604 feat(ai): schema accepts validated referenceId pointing into the medical-reference bundle
Recommendations now carry an optional `referenceId` that the parser
checks against the curated bundle from the previous commit. A
fabricated id ("invented-guideline-2099") fails parse so the model
cannot synthesise a citation for a guideline that does not exist —
defence in depth on top of the prompt-side instruction.

Optional in v1.4.16 so existing payloads still validate; v1.4.16
phase B5c ratchets it to required when severity >= "important". Also
bumps PROMPT_VERSION to 4.16.0 for the system-prompt update landing
in the next commit.

8 unit tests pin the accept-known / reject-fabricated / mixed-payload
behaviour and the round-trip preservation of referenceId through the
strict response schema.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:47:48 +02:00
Marc-André BombeckandClaude Opus 4.7 27f3933344 feat(ai): curated medical-reference bundle for citation grounding
Recommendations that assert a normative claim ("BP target < 140/90",
"BMI 18.5-24.9") need to point at the guideline they came from. This
adds the static reference bundle the schema and prompt will hang
citations off in the next two commits.

Bundle covers AHA / ESH / ESC / WHO / DGE / ADA across blood pressure,
weight, pulse, mood and medication buckets. Each entry carries an EN
+ DE title, a direct https URL, the publication year, and the metric
buckets it applies to. `selectReferencesForMetrics()` picks the
overlap so a snapshot focused on BP only sees the relevant references
in the system prompt.

15 unit tests pin shape, slug uniqueness, https URL validity, year
sanity, bucket coverage and the selector helpers — so a typo in a URL
or a missing bucket fails CI before the model ever sees it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:46:21 +02:00
Marc-André BombeckandClaude Opus 4.7 2da0703a46 fix(geo): preserve umlauts in city names (login-overview no longer renders "Nrnberg")
In /admin/login-overview I caught a row that should have rendered
"Nürnberg, DE" showing up as "Nrnberg, DE" instead — the umlaut was
gone. The geo source (ipwho.is) returns the city as proper UTF-8 over
the wire, and the audit-log render path is a straight pass-through, so
the corruption had to be in the geo helper itself.

Two defensive fixes, in lib/geo.ts:

1. Decode the response body as UTF-8 explicitly via `arrayBuffer()` +
   `TextDecoder('utf-8')` instead of `Response.json()`. The latter
   defers its charset decision to whatever the upstream
   `Content-Type: application/json; charset=…` claims, which an
   intermediate proxy can strip or rewrite — exactly the kind of
   transit-layer surprise that produces "Nrnberg" out of "Nürnberg"
   when the byte stream stays UTF-8 but the parser thinks it's
   latin-1. Reading via TextDecoder bypasses that entirely; a
   malformed byte surfaces as a parse failure, not silent character
   loss.

2. Send `Accept-Language: de, en;q=0.5` on the lookup request.
   ipwho.is and ip-api both honour it, and without the hint ip-api
   falls back to the English ASCII fold ("Nuremberg" instead of
   "Nürnberg"). German is preferred (DACH-skewed user base) with
   English as a safety net for cities that don't have a German name.

Also audited the rest of src/ for ASCII-fold patterns that could chew
umlauts elsewhere — `String.prototype.normalize("NFD")`, slugify
calls, `[^a-zA-Z0-9]/g` strips: zero hits. So this is the only fix
needed for now.

Regression tests: roundtrip 7 known-umlaut cities (Nürnberg, München,
Düsseldorf, Köln, Würzburg, Bückeburg, Weißenfels) plus eszett, plus
a Content-Type-without-charset case to lock in the explicit UTF-8
decode, plus an Accept-Language assertion.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:37:27 +02:00
Marc-André BombeckandClaude Opus 4.7 9b01c86e30 feat(charts): medication chart matches other charts (7d trend + indicator + target-range)
Marc: "Bei Medikamenten zum Beispiel wird jetzt nicht 7-Tage-Schnitt,
Trend und Zielbereiche angezeigt. Das möchte ich natürlich für alle
Charts."

The medication-compliance chart shipped in v1.4.15 A4 (replacing the
static placeholder) was missing the trend chip + target-range
visualization the BP/weight/mood charts already paint. Bringing it to
parity:

- 7-day trend chip in the header: signed delta in percentage points
  with a metric-aware sentiment colour (rising compliance → green,
  falling → orange) and an arrow icon. Mirrors the bg-muted/40 chip
  pattern HealthChart uses for its weekly/monthly bucket label.
- New `computeMedicationTrend7d()` helper computes the delta as the
  mean of the most-recent 7 daily rates minus the mean of the prior 7
  (capped at a 14-day window). Mean-difference rather than slope so a
  single outlier day doesn't wag the indicator.
- Target-range visualization: added a 100 % goal ReferenceLine (green,
  solid-ish) ALONGSIDE the existing 80 % minimum-acceptable threshold
  (yellow, paler dash). Two lines together visualise the target range
  the way HealthChart's targetZone band does for BP/weight tiles.

Tests:
- 6 new unit tests pin computeMedicationTrend7d() including direction,
  delta, the 14-day cap, short windows, stable noise rejection.
- The existing chart-render snapshot is extended with an explicit
  assertion that the trend chip is suppressed in the empty state
  (so the empty-state header doesn't paint a misleading "0 pp"
  indicator).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:32:01 +02:00
Marc-André BombeckandClaude Opus 4.7 af77e5ecf8 fix(insights): trend on "all" filter computes meaningful delta (split-half comparison)
Marc reported clicking "All" on a chart's range buttons displayed
"+0.0 kg/Woche" even when his weight clearly drifted across years.

Root cause: `weeklyDelta = (lastTrend - firstTrend) / windowDays *
7` is mathematically correct but the per-week rate becomes
vanishingly small for multi-year windows (~0.07 kg/week for
10 kg over 3 years), and the 1-decimal `fmt.number(delta, 1)`
formatter rounds it to "0.0".

Fix: extract a pure `computeWindowTrend()` helper at
`src/lib/analytics/window-trend.ts`. For windows ≥ 90 days we
additionally surface a split-half delta — the mean of the
second half of the visible series minus the mean of the first
half. That number cannot round to zero unless the metric truly
didn't move, and it's exactly what Marc wants to see when he
asks "what changed across all my data?". For short windows the
per-week rate stays the only display because it's still the most
actionable metric there.

The chart trend line surfaces both: "WEIGHT: +0.1 kg/week
(0.1 %/week) · Total +5.4 kg (6.7 %)" on the All view of a
multi-year account.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:31:18 +02:00
Marc-André BombeckandClaude Opus 4.7 93e712dc60 fix(dashboard): top-tile selector actually filters the tile-strip
Marc reported the toggles in Settings → Dashboard didn't filter
the dashboard tile-strip on reload — the v1.4.15 A4 claim was
correct in spirit but broken in the API contract.

Root cause: `widgetIdEnum` in
`src/app/api/dashboard/widgets/route.ts` was missing
`achievements` even though the default layout has it. Every PUT
that included the achievements widget therefore failed schema
validation with 422 — the toast surfaced "Layout konnte nicht
gespeichert werden" but the user never noticed because the toggle
visually flipped (local draft state) before the network call. On
reload the saved layout was the previous one, so the filter looked
like a no-op.

Fix:
- Extract `DASHBOARD_WIDGET_IDS` as the single source of truth in
  `src/lib/dashboard-layout.ts`. The Zod enum in the API route is
  built from it so the two lists cannot drift again.
- Hide the tile-strip wrapper entirely when the user toggled off
  every tile (Marc's constraint: "immer die gesamte Spalte breit
  und immer der gleichen Höhe ausfüllen" — an empty grid wrapper
  was leaving a thin gap on the page).

Tests: contract test pinning that every widget id in
DEFAULT_DASHBOARD_LAYOUT round-trips through serialize → resolve,
plus an explicit assertion that `achievements` is in the default
layout.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:31:00 +02:00
Marc-André BombeckandClaude Opus 4.7 4df6dac036 fix(charts): "7-Tage-Trend" label + numeric trend indicator on every chart incl. mood
Marc reported v1.4.15 A4 didn't fully land:
- DE label still read "7-Tage-Schnitt" / "7T-Schnitt" in places
- mood tile showed no numeric trend delta even though other tiles did

i18n rename:
- de.json + en.json: trend7dShort, movingAverage7d, moodMA all read
  "7-Tage-Trend" / "7-day trend". The legacy "7T:" / "7d:" header on
  the avg7 line is preserved for tiles that haven't been migrated to
  the trend7Delta API.

trend-delta fallback:
- summaryToTrend7Delta() now falls back to slope30 (projected onto
  7 days) when slope7 is null. Mood entries are typically logged
  less than daily, so slope7 needs ≥ 2 points within the trailing
  7-day window — for sparser users that came back null and the tile
  silently dropped the delta indicator. slope30 still answers "is
  this metric drifting?" so we project that onto the 7-day window
  for label parity.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:30:42 +02:00
Marc-André BombeckandClaude Opus 4.7 577d8dd29f fix(insights): BD-Zielbereich computes correctly for real measurement data
The BD-Zielbereich tile rendered 0% for users whose readings sat below
the ESH 2023 narrow goal band (Sys 120-129 / Dia 70-79 for under-65).
Marc's actual production data has many readings like 117/79 — textbook
normotensive, well-controlled — that v1.4.15 A4 still counted as OUT
of target because sys < sysLow (120). 5 of 10 of his last-30-day pairs
should be in-target by clinical interpretation; v1.4.15 reported 0.

Root cause: "in target" was defined as the narrow goal band, which is
the ESH treatment goal for hypertensive patients ON therapy — NOT the
desirable range for a normotensive HealthLog user. Users (and the
dashboard label) intuitively mean "BP is well-controlled = at or below
the ceiling, not implausibly hypotensive".

Fix: change semantics from `sysLow <= sys <= sysHigh && diaLow <= dia <=
diaHigh` to `90 <= sys <= sysHigh && 50 <= dia <= diaHigh`. The 90/50
floors guard against counting symptomatic hypotension as "good control".
Centralised the check in `isBpReadingInTarget()` so the 6 historical
call sites (analytics route, blood-pressure-status, features,
general-status, insights/cards, insights/comprehensive, insights/targets)
share one definition — pre-fix they had 5 independent inline copies of
the narrow-band formula, easy to drift on a future refactor.

Tests:
- 6 new unit tests pin the new ceiling+floor semantics including Marc's
  exact production fixture (10 paired readings -> 50% under v1.4.16,
  was 0% under v1.4.15).
- New `tests/integration/bp-in-target.test.ts` seeds Postgres
  testcontainer with Marc's reading shape + null-tolerance + hypotension
  edge cases.

Cache invalidation already correct: `measurementDependentKeys` includes
`analytics()` so adding a BP measurement invalidates the tile's
TanStack Query cache.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:28:54 +02:00
Marc-André BombeckandClaude Opus 4.7 277a5aa0e7 fix(admin): api-tokens table no horizontal overflow on Pixel-5 viewport
v1.4.15 A2 hid columns + tightened card padding, but Marc still saw a
scrollbar on prod at /admin/api-tokens on Pixel-5 (393 CSS px). The
fundamental issue is that even with three columns visible, long
permission lists or token names could push the scroll wrapper wide
inside the card. Mirror the `<UserManagementSection>` pattern instead:
gate the desktop `<table>` behind `hidden md:block` and render a real
mobile card-list at <md.

The mobile card-list:
- One <li> per token, padding p-3, no horizontal scroll wrapper.
- Token name uses `truncate break-all` so even a hex-suffixed name
  wraps within card width.
- Permission badges sit in a `flex-wrap` row.
- Last-used + Created collapse to short meta lines (no nowrap).
- Status badge floats next to the name on the same flex-wrap row.

Tests:
- `api-token-overview-responsive.test.tsx` rewritten to assert the new
  invariants: hidden md:block on the desktop table; md:hidden on the
  card-list <ul> with `data-testid="admin-tokens-mobile-list"`; no
  overflow-x-auto inside the mobile container; meta paragraphs wrap.
- New e2e spec `admin-api-tokens-mobile.spec.ts` mocks a worst-case
  payload (long username, multiple permissions, long token name) and
  asserts `documentElement.scrollWidth <= window.innerWidth + 1` at the
  Pixel-5 viewport on /admin/api-tokens.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:25:34 +02:00
Marc-André BombeckandClaude Opus 4.7 77fe256d9e fix(nav): admin sub-items don't expand from gravatar dropdown or admin-link click
Mirror the Settings entry pattern verbatim: the global sidebar's Admin
entry is now a single link with no sub-item expansion at any route.
v1.4.15 A1 had gated the expansion behind `onAdminPage`, but Marc
re-flagged it — the in-shell `<AdminShell>` already provides per-section
nav inside the page, so the global sidebar duplicating it on `/admin/*`
was unwanted UX. Removing the entire `{onAdminPage && <ul>...</ul>}`
block also kills the perceived link between the gravatar dropdown and
sidebar state — they're independent concerns now.

Tests updated:
- `sidebar-nav.test.tsx` — every admin-route case now asserts ONLY the
  single `/admin` link is present, never sub-route links.
- New e2e spec `sidebar-admin-no-expand.spec.ts` covers (a) /admin/* shows
  one link, no sub-list; (b) clicking Admin from /dashboard navigates
  without flashing sub-items; (c) opening the gravatar user-menu does
  not expand sidebar admin sub-items.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 23:24:41 +02:00
Marc-André BombeckandClaude Opus 4.7 4dcaa08b42 chore(release): v1.4.15
Bumps version to 1.4.15 and adds the corresponding CHANGELOG entry
covering backup completeness, achievements UI, onboarding tour,
doctor-report v2, auto-deploy on GHCR push, empty-states sweep,
notification + integration status UI, AI hallucination guardrails,
mobile UX fixes, and the BD-Zielbereich percentage fix.

Includes the formatting drift left over by the v1.4.15 development
phases (Prettier sweep on touched files) and a typecheck fix in
`dashboard-layout.test.ts` so `pnpm typecheck`, `pnpm lint`,
`pnpm format:check`, `pnpm test`, and `pnpm test:integration` all
pass green on the release tag.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:27:13 +02:00
Marc-André BombeckandClaude Opus 4.7 d94756389f style(v1.4.15): prettier sweep on phase-D reconcile touched files
Class-order + line-length normalisation on tour.tsx, mock-client.ts,
and codex-slug-fallback.test.ts after the focus-trap / strict-schema /
inspect-helper-removal commits. No functional changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:17:17 +02:00
Marc-André BombeckandClaude Opus 4.7 79bb167333 fix(ai): MockAIProvider DEFAULT_RESPONSE conforms to v1.4.15 strict schema
Phase D senior-dev review HIGH H4: the mock's default response carried
the legacy v1.4.14 rich shape (classification, findings, correlations,
dataQuality, disclaimer). The v1.4.15 strict schema requires
{summary, recommendations, citations, warnings}. The default passed
only because of `aiInsightResponseSchema.passthrough()`; once v1.4.16
retires the passthrough, every test using the default mock would
silently start failing schema validation before its asserts ran.

Switch to a strict-schema-conformant default. Tests needing the
legacy shape opt in via `responses: [...]`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:16:33 +02:00
Marc-André BombeckandClaude Opus 4.7 66d2e0773a fix(a11y): break long Withings error strings inside status banner
Phase D design review HIGH H5: Withings refresh-token failures can
arrive as 250+ char URL-encoded JSON bodies. Without `break-words`
the inline span pushed the parent card past viewport width on mobile,
causing horizontal scroll on the Settings -> Integrations page during
a degraded state. Add `min-w-0 break-words` to the error span so
long error text wraps within the banner.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:16:07 +02:00
Marc-André BombeckandClaude Opus 4.7 646541245d fix(a11y): trap focus + restore + ring on onboarding tour
Phase D design review HIGH cluster (H1, H2, H3) on the v1.4.15 B5
onboarding spotlight tour:

- H1: tab cycles inside the tooltip's three actions (Skip/Back/Next),
  shift+tab honoured; on close the previously-focused element regains
  focus so Settings -> Account "Restart" returns the caret correctly
- H2: tooltip card gains `max-h-[80vh] overflow-y-auto` so DE copy
  with longer translations can scroll inside the card without ejecting
  the Next/Done button below the fold on small viewports
- H3: backdrop button gets `focus-visible:ring-2 ring-primary` so
  keyboard users see a visible focus signal when the tour is active

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:15:50 +02:00
Marc-André BombeckandClaude Opus 4.7 cd3b890067 refactor(v1.4.15): apply simplify-review safe suggestions
Drop dead exports + misleading comments + unreachable defaults flagged
by phase-D simplify review (autonomous-yes items only):

- channel-state: drop unused TEST_CONSTANTS re-export
- retry-policy: drop unused RejectKind type alias
- achievements: drop misleading "fallback" comment on exhaustive switch
- notification-status-card: drop unreachable default in stateBadgeFor
- withings: export isWithingsRefreshReauthFailure + dedupe inline
  classifier in /api/withings/status route
- codex-slug-cache: drop test-only inspectCodexSlugCache helper; tests
  read getCachedCodexSlug() instead

Findings 1, 2, 8, 9 deferred to v1.4.16 (require product call).
Finding 11 is an explicit anti-finding.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 22:14:43 +02:00
Marc-André BombeckandClaude Opus 4.7 4bba951121 feat(ai): fallback-chain slug discovery with 1h positive cache
Phase C1 (v1.4.15) — slug-drift defence per Marc's hard mandate:
"Die Integration des Slug Drift Risiko darf halt immer überhaupt nicht
sein." ("Slug-drift risk must NEVER happen.")

Background: the ChatGPT-Codex backend rotates its allow-list silently.
v1.4.7..v1.4.13 lost a week to chasing the rotation manually
(`gpt-5-codex` → `gpt-5.3-codex`). A single hard-coded `CODEX_MODEL`
flips invalid the moment upstream rotates it.

Solution — the client now walks an ordered fallback chain on every
fresh request series and caches the first slug that returns 200 +
`response.completed` for 1 hour. Subsequent requests skip the chain
walk entirely on a cache hit.

Spec: extends `docs/codex-protocol-spec.md` with new §7b documenting
the chain semantics, cache TTL, walk triggers (400 + "not supported
when using Codex with a ChatGPT account" / `model_not_found` /
"does not exist" / 404), non-walk responses (5xx, 429, 401-with-
refresh, `invalid_prompt`), and the all-failed structured-503 error
shape. Per Marc's v1.4.6 hard rule ("read source-of-truth before
iterating; no more 6-iteration line-fixes"), the spec was extended
FIRST and the implementation cross-referenced against it.

Implementation:

  - New `src/lib/ai/codex-slug-cache.ts` — process-local positive
    cache. Single-slot Map (per-account scoping is a one-line change
    when v1.4.16 multi-tenant rolls out). 1 h TTL. `getCachedCodexSlug`
    auto-evicts expired entries on read.
  - Rewritten `CodexClient.generateCompletion()` — walks the chain
    `[cached?, ...slugChain]` in order. On 401 → refresh + retry SAME
    slug (auth ≠ slug-state). On 400/404 with rejection body → drop
    cache, walk to next. On 5xx/429 → propagate immediately (walking
    won't help). On all-rejected → throw structured 503 with
    `attempted[]` list, `httpStatus: 503`, message "AI provider
    unreachable — all configured Codex slugs were rejected".
  - `CodexAttemptDiagnostics` exposes `{ attempted, cacheState,
    workingSlug }` for Wide-Event annotations the route can read via
    `client.getLastDiagnostics()`.
  - `CODEX_MODEL_FALLBACK_CHAIN` env override (comma-separated). When
    `CODEX_MODEL` is also set, it folds into chain position 0; the
    default chain (`gpt-5.3-codex` → `gpt-5-codex` → `gpt-5` →
    `gpt-4o`) survives behind it. Stable de-dup.

Tests: +20 across 2 new files.

  `codex-slug-cache.test.ts` (7 tests) — TTL-edge boundaries,
  invalidation, replacement semantics.

  `codex-slug-fallback.test.ts` (13 tests) — cold-cache happy path,
  walk on canonical 400 body, walk on `model_not_found`, walk on 404,
  no-walk on 500/429/401, all-rejected → 503-with-attempted-list,
  cache-hit shortcut, cache invalidation on rejection, isSlugRejection
  body classifier, loadFallbackChain env-pin merge.

The 5 existing `codex-client.test.ts` cases continue to pass without
edit — the new `slugChain` constructor parameter is opt-in and the
single-slug behaviour reduces to chain length 1.

Tests: 1028 → 1048 unit pass (+20). Typecheck clean for AI files.
Lint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:55:38 +02:00
Marc-André BombeckandClaude Opus 4.7 65faf1d156 feat(insights,dashboard): empty states for first-run views
Closes the last two surfaces from the C5 audit.

- /insights — Top-level "no data" path replaces a bare "No data
  available" sentence with EmptyState (TrendingUp icon) + "Add a
  measurement" CTA into /measurements. The BMI section's
  height-not-set fallback gets a compact plain-variant EmptyState
  (Ruler icon) + "Open account settings" CTA instead of a single
  grey line that looked like a bug.
- / (dashboard) — When trendCards.length === 0 AND charts.length ===
  0 (a brand-new account with no data and the Getting-started
  checklist already dismissed) the dashboard rendered an empty
  0-px tile strip below the welcome banner. Now paints an
  EmptyState with the same quick-entry dialog wired to the CTA so
  the user can log their first measurement without leaving the page.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:53:05 +02:00
Marc-André BombeckandClaude Opus 4.7 1d65f3b925 feat(lists): empty states for measurements, mood, medications, achievements (impl)
Follow-up to 9a74f8e — that commit's pathspec didn't pick up the
implementation files, only the new test. This commit lands the actual
EmptyState wiring described in the previous message:

- src/components/measurements/measurement-list.tsx — Activity icon,
  filter-aware empty state, optional onAddFirst CTA prop.
- src/components/mood/mood-list.tsx — Smile icon, mirroring filter
  semantics + optional onAddFirst.
- src/app/measurements/page.tsx + src/app/mood/page.tsx — pass
  onAddFirst so the empty-state CTA opens the same dialog as the
  header button.
- src/app/medications/page.tsx — refactor inline icon+text+button
  block to the EmptyState primitive (Pill icon).
- src/app/achievements/page.tsx — Trophy icon for the no-achievements
  state, reusing the existing noneUnlockedYet string.

Together with 9a74f8e the four feature lists now share a consistent
empty-state surface with the rest of the app.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:51:48 +02:00
Marc-André BombeckandClaude Opus 4.7 9a74f8e8f2 feat(lists): empty states for measurements, mood, medications, achievements
Wires the EmptyState primitive into the four feature lists. Each path
now exposes an icon + localized title + description + (where it
applies) a CTA bound to the parent dialog so brand-new accounts get a
single-click path to logging their first datapoint.

- /measurements — Activity icon, "Add your first measurement" CTA
  wired to the page's Add dialog. Filter-aware: switches to "no
  measurements match this filter" with a "Show all types" reset
  whenever a non-default type filter is active.
- /mood — Smile icon, "Log your first mood" CTA, identical
  filter-aware split for the mood-level filter.
- /medications — Refactor inline icon+text+button block to the shared
  primitive. Pill icon, "Add first medication" CTA → openCreate.
- /achievements — Trophy icon. Reuses the existing
  achievements.noneUnlockedYet string to keep C4 i18n sweep work
  minimal.

New unit test (measurement-list-empty) asserts the primitive mounts,
the Add-first CTA respects the optional onAddFirst prop (no orphaned
button when the parent doesn't wire it), and the reset-filter CTA
stays out of the default-filter render.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:51:10 +02:00
Marc-André BombeckandClaude Opus 4.7 4e85c38c4b feat(ai): scope-hardened system prompt with refusal pattern
Phase C1 (v1.4.15) — adds the v1.4.15 baseline scope-hardened prompt.

New file `src/lib/ai/prompts/insight-generator.ts` exports
`getStrictInsightsSystemPrompt(locale)` and a stable `PROMPT_VERSION`
tag (`4.15.0`) so future iterations ratchet the prompt without
breaking deterministic tests. The prompt's load-bearing instructions:

  - Role: clinical-context summariser ONLY. Explicitly forbids
    diagnosis, prescription and out-of-scope answers.
  - Out-of-scope refusal pattern: when the snapshot is empty or off-
    topic, the model returns a fixed JSON refusal payload (also
    exported as `OUT_OF_SCOPE_REFUSAL_EN/DE` so tests can pin it
    against the strict response schema).
  - Zero-hallucination guard: every recommendation MUST cite a
    specific snapshot field via `metricSource`; missing → omit.
  - Citation cross-check: every recommendation's metricSource must
    also appear in `citations[]` (enforced by the schema parser).
  - Generic guideline targets only: ESH/ESC 2024 < 140/90 mmHg, AASM
    ≥ 7 h sleep, Saint-Maurice 2020 ≥ 8 000 steps; explicitly
    forbids citing WHO as the source for a step number.
  - Doctor-consult call-to-action required for every actionable
    recommendation.
  - JSON-only output, no markdown fences.

The prompt is NOT yet wired into `/api/insights/generate`. The route
continues to consume the rich legacy schema (`{summary, classification,
findings, correlations, dataQuality, ...}`) which the existing
`<InsightAdvisorCard />` and `<InsightsCard />` UIs render. The
integration step is scheduled for v1.4.16 alongside the UI migration —
see `docs/audit/v1416-ai-roadmap.md` (lands in the next commit of this
phase).

Tests: +18 (1005 → 1023 unit). Pin both locale variants for
diagnosis/prescription forbiddance, citation cross-check instruction,
ESH/ESC 140/90 generic guidance, doctor-consult CTA, fabricate-no-
measurements rule, and out-of-scope refusal pattern. The refusal
payloads are also fed through the wrapper to prove the model can
return them verbatim and the wrapper passes them through cleanly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:50:56 +02:00
Marc-André BombeckandClaude Opus 4.7 0c20119c14 feat(admin): empty states for users, backups, login-overview, api-tokens, feedback
Replaces blank rectangles in 6 admin sub-routes with the EmptyState
primitive. Each surface now shows an icon, localized title +
description, and (where it makes sense) a primary action so a fresh
admin always knows what to do next.

- /admin/users — Users icon, filter-aware copy, "Show all users" reset
  CTA when a filter is active.
- /admin/backups — Database icon, "Backup now" duplicate CTA inside the
  empty card so the action is right next to the explanation.
- /admin/login-overview — ScrollText icon, splits "no auth events" from
  the safer "no failed sign-ins"; reset CTA on the failed-only filter.
- /admin/api-tokens — Key icon, copy points to native client sign-in
  and Settings -> Account where tokens are issued.
- /admin/feedback — Inbox icon, compact-size, per-tab description.
- /admin overview audit-preview — compact + plain so it nests inside
  the parent card without doubling the dashed border.

New unit tests for the users + backups paths assert the primitive
mounts (role=status / dashed border), the localized strings render,
and the reset/CTA actions appear only in the right contexts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:48:36 +02:00
Marc-André BombeckandClaude Opus 4.7 d657f798d0 feat(ai): enforce citation-from-data on every recommendation
Phase C1 (v1.4.15) — citation-from-data hard requirement.

Marc, verbatim 2026-05-09: "es muss sich halt irgendwie stützen auf
medizinische Dinge."  ("It must ground on medical facts / user data.")

Builds on the strict response schema (`src/lib/ai/schema.ts`) and
schema-enforced wrapper (`src/lib/ai/generate-insight.ts`) — which were
swept into sibling commit 5510ed5 by a parallel-agent index race
(documented across A2 / A4 / B1-B6 / C2 / C3 of the v1.4.15 marathon;
diff is correct on main, message scope misleading).

This commit adds a focused 11-test invariant suite that nails down the
contract end-to-end:

  1. Schema-level: recommendation without metricSource fails parse;
     empty metricSource.summary fails; missing type or timeRange fails.
  2. Cross-check: findUncitedRecommendations() flags any recommendation
     whose (type, timeRange) does not appear in citations[]. Partial
     match (type alone) is rejected — both fields must align.
  3. Wrapper end-to-end: orphan-citation triggers retry; second attempt
     either fixes the citation OR drops the recommendation (both
     valid per the retry-correction message; model is explicitly
     told an empty recommendations[] is acceptable).

The two-pronged guard (schema + cross-check) ensures the model cannot
fabricate a recommendation that points at "nothing" AND cannot cite
data it hasn't surfaced — closing the v1.4.16 medical-grounding work's
prerequisite.

Tests: +11 (988 → 999 unit). All AI tests green (67 / 67).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:47:37 +02:00
Marc-André BombeckandClaude Opus 4.7 5510ed529b docs(audit): v1.4.15 empty-states audit + i18n keys
Walks every list/table/tile a brand-new user hits and records the empty
path. 13 surfaces flagged for upgrade across admin, feature pages,
insights and dashboard. Adds matching EN+DE i18n keys
(emptyTitle/emptyDescription/CTA copy) under measurements, mood,
medications, admin.section.users/backups, admin login-overview/api-tokens,
admin.feedback, insights, dashboard.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:45:52 +02:00
Marc-André BombeckandClaude Opus 4.7 01a10de5d8 test(i18n): non-empty + non-placeholder parity assertion
Phase C4 audit found EN/DE locale files in perfect parity (1817 keys
each, 0 drift, 0 empty values, 0 TODO/FIXME placeholders) — the five
B-agents and the C2/C3 phases each shipped their own translations
inline.

This commit hardens the parity test to lock that state in:
- empty-string assertion (per locale, fails on `"key": ""`)
- key-equals-value assertion (fails when EN==DE==key.lastSegment, with
  an explicit allow-list for 5 legitimate cases: `settings.ntfy`,
  `classifications.{bp.Optimal,bp.Normal,pulse.Normal,bodyFat.Fitness}`)
- TODO/FIXME/XXX/TBD assertion (per locale)

EN-only key=value cases (e.g. `"of": "of"` where DE = `"von"`) are
deliberately NOT flagged — those are natural, since key names derive
from the EN word. The dual-locale check catches the real placeholder
pattern (`"bugReport": "bugReport"` in both locales) without false
positives.

Audit report: docs/audit/v1415-i18n-coverage.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:43:27 +02:00
Marc-André BombeckandClaude Opus 4.7 27310e4f9a refactor(ai): consolidate providers behind AIProvider interface
Phase C1 (v1.4.15) — provider abstraction review.

Adds `MockAIProvider` (`src/lib/ai/mock-client.ts`) so contract tests
can exercise the route-level interface without burning network calls
on every CI run. The mock satisfies `AIProvider`, lets tests queue a
list of canned responses, and records every `CompletionParams`
invocation for later assertion.

Adds a contract test file (`provider-contract.test.ts`) that walks
every concrete provider — Codex, OpenAI, Anthropic, Local, Mock — and
asserts each one returns a `CompletionResult` with the four
contract-required fields (`content`, `tokensUsed`, `model`,
`providerType`). Network is stubbed per provider; the test exists to
catch interface drift, not to retest each provider's wire format.

The route at `/api/insights/generate` already imports the abstract
`AIProvider` via `resolveProvider()`, so the consumer side needs no
change — this commit ratchets the contract with explicit tests so
future provider additions (medical-grounding, multi-provider redundancy
in v1.4.16) cannot silently regress the interface.

Tests: +7 (132 → 139 ai-domain). 972 / 972 unit pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:42:22 +02:00
Marc-André BombeckandClaude Opus 4.7 28467b2590 feat(doctor-report): practice name on cover page (persisted as user preference)
Marc wanted the addressee visible at first glance on the printout —
"Praxis Dr. Müller" should be the first thing the GP sees, so the
report doubles as a polite opening line.

- New optional free-text field "Praxis / clinic name" in the export
  dialog. The dialog pre-fills it with the user's last-used value so
  recurring exports don't require re-typing.
- Persisted as a user preference: new `User.lastReportPracticeName`
  column (migration `0031_user_last_report_practice_name`). The value
  is updated only on a successful POST that supplied a non-empty
  string — passing `null` does NOT clear the stored preference so the
  value sticks across years of follow-ups. Best-effort write: a DB
  failure here MUST NOT break the report (caught + ignored).
- `sanitisePracticeName()` enforces a strict envelope upstream: strips
  ASCII C0 + DEL controls (which jsPDF can't render), collapses
  whitespace, and hard-caps at 120 characters. Defends the PDF layout
  from runaway input + protects the PDF text stream from
  control-character corruption.
- PDF cover prints the line in 11pt bold above the separator when set;
  omitted entirely when `null` so the cover stays compact for
  self-archive use. Both client (`doctor-report-pdf.ts`) and server
  (`doctor-report-pdf-core.ts`) renderers carry the change so the
  visual output matches whichever path the user takes (browser
  download vs iOS Safari fallback).
- `/api/auth/me` now echoes `lastReportPracticeName` so the dialog
  pre-fills without an extra round-trip.
- Audit-log + Wide-Event annotations record `practiceNameProvided:
  boolean` (NOT the value itself — practice names are personal and we
  already store one canonical copy on the user record).

i18n: 6 new keys (`doctorReport.practiceLabel`, `doctorReport.dialog.{practiceLabel,practicePlaceholder}`)
in EN + DE.

Tests: 12 new unit cases covering sanitisation (whitespace, controls,
length cap, type guard), PDF cover rendering (DE label "Praxis:", EN
"Practice:", omission when null), API persistence (prisma.user.update
called with the right shape, audit detail flag set). 965 / 965 unit
pass, 31 / 31 integration pass. Lint 0 errors. Typecheck clean for B6
files (pre-existing dashboard-layout.test.ts errors are A4 territory).
v1.4.15 phase B6.

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