Commit Graph
6301 Commits
Author SHA1 Message Date
Marc-André BombeckandClaude Opus 4.7 d2cdf9d664 feat(dashboard): InsightsCardPreview matches insights page visual language
Replaces the orphan v1.4.0 InsightsCard with a leaner
<InsightsCardPreview> that surfaces only the top 1-2 severity-ordered
recommendations + a "View all" CTA pointing to /insights. Same visual
language as the page (Dracula sparkle glyph, severity-coloured left
border, ring-variant confidence meter inline).

The legacy InsightsCard handled its own data fetching against the
deprecated changed/stable/drivers/nextSteps shape; preview now takes
an `insight: InsightResult | null` prop so the dashboard wires its
existing `/api/insights/generate` data without redundant fetches.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 02:05:10 +02:00
Marc-André BombeckandClaude Opus 4.7 0c287f1545 feat(insights): polished loading + empty + error states
Loading state replaces the spinner-only placeholder with a 3-card
skeleton grid that mirrors the final layout, so the page doesn't
visually jump when content lands. Each placeholder pulses with a
100ms staggered delay.

Empty state gains an illustrated sparkle glyph + a centred copy block
(max-w-prose) so the affordance reads as an invitation rather than a
muted dead-end.

Error state moves from a flat banner to a card with a discoverable
retry button (data-slot=insight-retry-button) when an onRegenerate
handler is supplied.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 02:02:46 +02:00
Marc-André BombeckandClaude Opus 4.7 b76351e1a8 feat(insights): polished summary typography with inline-chart sparklines
Bumps the InsightAdvisorCard summary surface to text-base / leading-
relaxed and constrains it to max-w-prose so the prose stays readable
on a wide viewport. Wraps the existing chart-token renderer in a
new mini flag so the summary's inline charts shrink to sparkline
form (h-[140px], no range tabs); per-finding inline charts keep the
full chart so the user can still interact with the data series.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 02:01:15 +02:00
Marc-André BombeckandClaude Opus 4.7 9e8be4b359 feat(insights): recommendations grid with severity ordering + animated reveal
Replaces the flat <ol> list inside InsightAdvisorCard with a responsive
2-col grid wrapper that severity-orders the recs (urgent → important →
suggestion → info), paints a Dracula-token left border per severity,
and staggers a 100ms fade-in across the row so the cards sweep in on
first render. Hover on desktop lifts the card by 0.5px and grows the
shadow.

Internal slots of RecommendationCard untouched — the severity border +
hover-lift + animation-delay live on a thin shell wrapper around the
card so the B5c/d/e plumbing (rationale, confidence, feedback) keeps
working unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:59:18 +02:00
Marc-André BombeckandClaude Opus 4.7 4d7d0748fa feat(insights): page hero with gradient header + generation timestamp + personal-baseline indicator
Wraps the /insights heading in a Dracula-gradient hero band with the
"Generated <relative-time>" caption, "Based on your last 90 days"
personal-baseline indicator, and a regenerate slot. Pure shell so the
page only passes timestamps in. Animation uses the existing
animate-insight-in keyframes which already gates on
prefers-reduced-motion.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:54:35 +02:00
Marc-André BombeckandClaude Opus 4.7 c8e76399ba docs(planning): mark Wave-B B5e (user-feedback loop) complete
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:47:40 +02:00
Marc-André BombeckandClaude Opus 4.7 887928211b feat(admin): AI quality preview showing per-(severity x provider) helpful-rate
v1.4.16 phase B5e: ship the `/admin/ai-quality` route that surfaces
the daily aggregator's helpful-rate per (severity x metricSourceType
x provider x prompt-version) bucket. Renders as a compact 7-column
table with severity tinted by clinical-importance colour and the
helpful-rate column tinted green/yellow/orange by 0.8/0.5
thresholds.

New endpoint `GET /api/admin/ai-quality` (requireAdmin-gated) returns
the raw `AppSettings.adminAiInsightsFeedbackSummary` blob so the
v1.4.17 ratchet that consumes the same shape for prompt-tuning can
read what the worker writes without an envelope-reshape step.

Empty state ("no summary yet" / "buckets[] is empty") rendered as a
quiet message rather than a fake zero row so the operator can tell
"no feedback" apart from "all-zeros". Loading + error banners follow
the existing host-metrics pattern.

Section wiring:
  - new `ai-quality` slug in ADMIN_SECTION_SLUGS (between
    integrations and feedback so the IA flows General → Integrations
    → AI Quality → Feedback Inbox)
  - new Sparkles icon entry in admin-shell
  - new switch case in [section]/renderer.tsx
  - EN+DE i18n keys: admin.section.ai-quality.{title,subtitle} +
    admin.aiQuality.{title,loading,loadError,empty,windowLabel,
    generatedAtLabel,col*}

Tests:
  - 5 new ai-quality-section tests (loading, empty-null, empty-buckets,
    table-render with multiple buckets, error)
  - 1 admin-sections smoke test ensures the empty branch renders +
    1 slug-list parity test

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:44:47 +02:00
Marc-André BombeckandClaude Opus 4.7 5117266756 docs(planning): mark Wave-B B5d (confidence score) complete
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:42:50 +02:00
Marc-André BombeckandClaude Opus 4.7 173c3e1d9c test(insights): rec-card-confidence test plays nice with B5e thumbs
After B5e wired the feedback thumbs into rec-card-feedback-slot, the
B5d test needs the same useAuth + useMutation + tanstack-query SSR
mocks that the existing rec-card.test.tsx carries. The test that
asserted "rec-feedback-slot is empty" is relaxed to "rec-feedback-slot
is still rendered" — B5e legitimately fills it now, and the slot's
mere presence is what B5d needs to guarantee its plug-in point stayed
intact.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:40:29 +02:00
Marc-André BombeckandClaude Opus 4.7 d343ab5dc2 test(insights): coverage for confidence computation + meter rendering
End-to-end integration test that pins the wrapper-override contract
across the full stack:

  1. MockAIProvider returns a payload where the model claims
     confidence=99.
  2. generateInsight() parses + overwrites with the deterministic
     value (n=9, recencyDays=0, ratio=null → 65).
  3. InsightAdvisorCard renders the parsed payload through
     RecommendationCard → ConfidenceMeter.
  4. The rendered card shows the SERVER-computed band ("medium" /
     yellow), NOT the model-claimed 99 ("high" / green). The
     aria-label announces "Confidence: 65 of 100".

A second case pins the small-data shield: with n=1 the wrapper
hard-caps at <=15, the meter renders the draft pill (red), and the
"Draft" tag is visible in the markup — Apple's quiet-when-unsure
affordance flows through end-to-end.

Coverage now includes:
  - Unit: computeConfidence() — 12+3 fixtures (input matrix +
    monotonicity + integer invariants) (commit 1).
  - Wrapper: 6 cases pinning the override contract (commit 2).
  - Component: 17 cases on ConfidenceMeter band rendering, both
    variants, EN/DE aria-label, clamp behaviour (commit 3).
  - Card wiring: 8 cases on slot fill, low-confidence caption,
    feedback-slot left untouched (commit 4).
  - Integration: 2 cases on full-flow override + draft band
    (this commit).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:40:29 +02:00
Marc-André BombeckandClaude Opus 4.7 63cfd8e2f7 feat(insights): RecommendationCard renders ConfidenceMeter in named slot
The `data-slot="rec-confidence-slot"` placeholder reserved by B5c is
now filled with `<ConfidenceMeter value={rec.confidence} />`. The
slot stays empty when `rec.confidence` is undefined (legacy cached
payloads predate the field) so a missing value never gets dressed up
as a draft pill.

Below 50, the expanded rationale card surfaces a "Low confidence —
based on limited data" caption so the rec stays visible but framed
as preliminary. The caption suppresses above 50 — the meter alone
speaks. Below 25 the meter itself is replaced by a draft pill
(handled inside `<ConfidenceMeter>`); the caption still applies
because draft <= low.

The B5e feedback-thumbs slot
(`data-slot="rec-feedback-slot"`) is untouched. The wiring test
explicitly asserts the feedback slot is still present and empty so
the parallel-running B5e agent has a stable plug-in point.

Threshold lives in a single named const
(`LOW_CONFIDENCE_CAPTION_THRESHOLD = 50`) co-located with the band
ladder in `<ConfidenceMeter>` so a future tune-pass can adjust the
ratchet in one place.

8 component tests cover: meter renders in slot at 85, slot stays
empty when confidence is undefined, medium/low/draft band rendering,
caption shows below 50, caption hidden above, German caption
translation, feedback-slot untouched.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:40:29 +02:00
Marc-André BombeckandClaude Opus 4.7 7ec10308b8 feat(insights): ConfidenceMeter component (bars + ring + draft pill below 25)
Renders the deterministic 0..100 score from `computeConfidence()` as
either a 5-bar meter (default) or a 28x28 SVG ring. Color bands:

  - >=80: green ("high"), 5 bars / full ring
  - 50..79: yellow ("medium"), 3-4 bars
  - 25..49: orange ("low"), 2 bars / partial ring
  - <25: red "Draft" pill REPLACES the meter — Apple's
    quiet-when-unsure affordance per research §2.A. The rec is
    drafted but the model isn't asserting it.

Bars rise in height across the row (4 / 6 / 8 / 10 / 12 px) so the
"more is more" cue is independent of color, satisfying the
non-color-vision a11y baseline. SVG ring uses stroke-dasharray with
the dracula band-stroke per band so the same color story is reused.

aria-label always announces the numeric score
("Confidence: 67 of 100" / "Vertrauen: 67 von 100"), even in the
draft-pill state, so screenreaders aren't blind to the visual band
distinction.

Inputs are clamped: NaN / Infinity / negative -> 0 (draft); >100 ->
100 (high). The component is otherwise a pure render — no state, no
effects.

5 i18n keys per locale: confidence, confidenceAria (interpolates
{value}), confidenceHigh, confidenceMedium, confidenceLow,
confidenceDraft. EN+DE parity test green.

17 component tests cover all 5 value bands (high/medium/low/draft +
band edges), both variants (bars/ring), aria-label translation in
EN+DE, and clamp behaviour at the negative + >100 ends.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:40:29 +02:00
Marc-André BombeckandClaude Opus 4.7 af21d4d4a8 feat(ai): wrapper overrides recommendation confidence with deterministic computation
After zod parse, `generateInsight()` invokes `computeConfidence()` for
every recommendation and overwrites `rec.confidence` — the model's
self-reported number is discarded. Calibrated probabilities are not
a small-LLM strength, so this is the deterministic substrate the
v1.4.17 feedback ratchet will tune.

The wrapper does not have direct access to the user's bucket-series
data, so an optional `confidenceContext` resolver lets the caller
(typically the route layer) supply per-rec `ConfidenceInputs` derived
from `metricSource.n` + the freshest bucket + the deviation magnitude
vs. the user's 90-day baseline. When the resolver is omitted, the
wrapper falls back to inputs derivable from the parsed payload alone:

  - n: `metricSource.n` (or 0 — triggers the n<3 hard-cap)
  - recencyDays: 0 (defensive default; assumes window ends "now")
  - deviationStdRatio: null (neutral 15-point signal contribution)

The override fires regardless of resolver presence so the contract
is "the confidence value on the response NEVER comes from the LLM".

A new structured Wide-Event annotation
(`ai_confidence_override_event` = `confidence.override.applied`)
carries per-rec `{id, model, computed}` triples so admin observability
can chart drift between the model's claimed confidence and the
deterministic value.

`annotateCitationCoverage()` now runs before `applyConfidenceOverride()`
so the existing citation/rationale-coverage tests can still match
against `mock.calls[0]`. The citation-coverage test that asserted
`toHaveBeenCalledTimes(1)` was relaxed to look up the right call by
meta-key rather than by ordinal.

6 new wrapper tests cover: model value discarded, wrapper-fills when
absent, resolver path overrides default, n<3 hard-cap survives strong
signal, missing `metricSource.n` -> n=0 floor, resolver receives each
rec in payload order.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:40:29 +02:00
Marc-André BombeckandClaude Opus 4.7 0cb0373e59 feat(ai): deterministic confidence-score computation per recommendation
Each recommendation now carries an optional `confidence: 0..100`
integer in `aiRecommendationSchema`. New `src/lib/ai/confidence.ts`
exposes `computeConfidence({ n, recencyDays, deviationStdRatio })`,
the deterministic formula the wrapper will use to override whatever
number the model picks.

Score breakdown (sum, max 100):
  - n contribution: log10-saturating curve, capped at 40. n<3 hard-
    caps the whole score at 5*n (max 15) so a three-sample window
    never produces a confident-looking meter.
  - recency contribution: 30 at <2d, decays linearly to 0 at 30d.
  - signal contribution: 30 at |z|>=1.5, scaled linearly to 0 at
    z=0; null ratio (no baseline yet) returns a neutral 15.

Schema is `.optional()` so:
  - The wrapper can fill it post-validation regardless of what the
    LLM emitted — the model's calibrated probability is unreliable.
  - Legacy cached payloads from before B5d landed still parse.

Integer-only and bounded so the meter component renders without
clamping; a renegade provider that emits 101 or 67.5 fails parse and
triggers the wrapper's corrective retry.

15 fixtures cover the input matrix: n hard-cap (n=0..2), n=3 floor,
mid-range (n=14, n=20), saturation (n=100 plateau, n=10000 cap),
recency clamp (45d -> 0), null-ratio neutral, negative-z magnitude,
plus monotonicity-in-n + integer-in-bounds invariants.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:40:29 +02:00
Marc-André BombeckandClaude Opus 4.7 71ffe3022f feat(jobs): daily feedback aggregator writes per-(severity x provider) summary to AppSettings
v1.4.16 phase B5e: ship the pg-boss `feedback-aggregator` queue that
runs daily at 04:00 Europe/Berlin (after the rate-limit, idempotency,
audit-log cleanups). Aggregates the last 30 days of
`RecommendationFeedback` rows into per-(severity, metricSourceType,
providerType, promptVersion) buckets and writes a JSON summary to
the singleton `AppSettings.adminAiInsightsFeedbackSummary` row.

Summary shape:
  { generatedAt, windowDays, buckets:
    [{ severity, metricSourceType, providerType, promptVersion,
       helpful, notHelpful, total, helpfulRate }] }

Bucketing is split into a pure `buildFeedbackBuckets()` helper so the
admin's ad-hoc analysis tools can reuse it without going through
Prisma. helpfulRate is rounded to 2 decimals; sort order is
deterministic (severity → metricSourceType → providerType →
promptVersion) so the admin UI's row order stays stable across
aggregator runs.

Single-user-default-on policy (research §3): the aggregator runs
unconditionally for the user's own ratings. Cross-user prompt-tuning
stays admin-only via `requireAdmin()` gating on the consuming
endpoint; the aggregator just produces the data. Prompt mutation
itself is a v1.4.17 ratchet — this commit only delivers the loop
infrastructure.

Worker handler degrades gracefully on failure: warns instead of
throwing so a single-tick error doesn't poison the queue and block
the next cleanup window. Wide-Event annotations: feedback_buckets,
feedback_total_rows, feedback_window_days.

Tests: 5 new unit tests (3 bucketing scenarios + 2 aggregator
default-window + custom-window).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:39:59 +02:00
Marc-André BombeckandClaude Opus 4.7 47ca1e41e0 feat(insights): RecommendationCard renders feedback thumbs in named slot
v1.4.16 phase B5e: fill the `data-slot="rec-feedback-slot"` reserved
by B5c. The RationaleCard now mounts `<RecommendationFeedback>` when
the rec carries every attribute the feedback endpoint validates —
id, severity, metricSource.type, and a metricSource.timeRange that's
in the four-window vocabulary (`last7days` / `last30days` /
`last90days` / `allTime`).

Defence-in-depth via `asFeedbackTimeRange()`: a rec with an
out-of-vocabulary timeRange (e.g. `"lastFortnight"` from a future
provider that drifted) leaves the slot empty rather than rendering a
feedback row that would 422 on submit. Same gate handles legacy recs
without an id — the slot stays empty so plain-string recs from
v1.4.14/v1.4.15 cached payloads can't suddenly produce thumbs that
have nothing to attribute server-side.

Confidence-meter slot (B5d's territory) is untouched — that's
filled by the parallel B5d worker.

Tests: 3 new rec-card scenarios pin the wiring (thumbs render when
fully attributed, hidden when no id, hidden on bad timeRange).
Existing rec-card tests retrofit `useMutation` + `useAuth` mocks so
the component's TanStack Query mutation stays inert during SSR.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:37:25 +02:00
Marc-André BombeckandClaude Opus 4.7 ca84fb7da1 feat(insights): thumbs-up/down feedback component with optimistic updates
v1.4.16 phase B5e: ship the `<RecommendationFeedback>` component that
plugs into the `data-slot="rec-feedback-slot"` reserved by B5c's
RecommendationCard. Two icon buttons (thumb-up / thumb-down) under
each rec; TanStack Query mutation against `/api/insights/feedback`.

State machine:
  default → submitting-{up,down} → submitted-{up,down}  (success)
                                  → already-rated-{up,down}  (409)
                                  → default              (network err, silent)

On success the buttons morph into a "Thanks for your feedback"
confirmation row with a green check + the chosen verdict's
glyph for context. On 409 (server says the user already rated this
exact rec text in a prior session) the row renders the prior
verdict highlighted and the buttons stay un-clickable — the
aggregator already has the signal.

Local cache via localStorage keyed on
`(userId, recId, truncatedRecText)` so a page refresh doesn't allow
re-rating before the server's 409 fires. The local cache is best-
effort; the server-side dedup (rec_feedback_user_rec_text_key
unique constraint) is the source of truth.

Auth-resolution race: when `useAuth()` returns null on first render
(in-flight fetch), the component re-syncs state from the local
cache during the next render — via setState-during-render, NOT
inside useEffect, to honour the project's
`react-hooks/set-state-in-effect` lint rule.

Accessibility: both buttons are real `<button type="button">`,
focusable, Enter/Space-activatable. aria-label translates to EN+DE.

i18n: 5 new keys under `insights.recommendation.*`:
  feedbackHelpful, feedbackNotHelpful, feedbackThanks,
  feedbackConfirmed, feedbackAlreadyRated.
EN+DE parity verified by the existing i18n parity guard.

6 component tests (renders both buttons, aria-labels, German labels,
submitted-up confirmation, already-rated highlight, type=button form
safety).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:34:20 +02:00
Marc-André BombeckandClaude Opus 4.7 8255e3e49a feat(api): /api/insights/feedback persists thumbs with provider attribution
v1.4.16 phase B5e: ship the POST endpoint that backs the per-rec
thumbs-up / thumbs-down UI. Body is the four rec-attributes the
client just rendered (id, text-snapshot, severity, metric-source +
time-range) plus the boolean verdict; server-fills providerType +
promptVersion via `resolveFeedbackAttribution()` so the client cannot
poison the daily aggregator's slice by claiming a thumbs-down was
attributed to a rival provider.

Idempotent via the existing `withIdempotency()` wrapper — a retry
with the same Idempotency-Key replays the cached response with
`X-Idempotent-Replay: true`. The dedup unique key on the model
(userId, recommendationId, recommendationText) returns 409 when the
same rec-text is re-rated — that's by design, the aggregator wants
per-text signal not per-id signal so a regeneration that rewrites
the same id with new text re-rates cleanly.

The attribution helper prefers `chainProviderType` over `providerType`
in the latest insights.generate audit row so when the B5b multi-
provider chain falls through to a secondary, the feedback row
reflects the working provider not the configured one. Falls back to
"unknown" + the current PROMPT_VERSION constant when no audit row
exists yet — the aggregator buckets that separately.

Audit row: action `insights.recommendation.feedback`, details carry
the feedback id, severity, helpful, providerType, promptVersion.

Tests:
  - 7 unit tests for the Zod request schema (valid path, severity
    poisoning, time-range poisoning, empty fields, stringified bool,
    extra-field stripping)
  - 5 unit tests for `pickProviderType()` priority + fallback
  - 4 integration tests: 201 happy path with provider attribution,
    409 dedup, 422 validation, fallback to unknown when no audit row

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:30:06 +02:00
Marc-André BombeckandClaude Opus 4.7 badc893853 feat(db): RecommendationFeedback model with GDPR cascade + provider attribution
v1.4.16 phase B5e: ship the table that backs per-recommendation
thumbs-up / thumbs-down feedback. Each row captures (userId, recId,
recText) with snapshotted severity + metric-source attributes plus the
provider + prompt-version that produced the rec — server-fills the
attribution from the user's most recent cached payload so the client
can't tamper.

Dedup key (userId, recommendationId, recommendationText) lets a
regeneration that rewrites the same id with new text re-rate cleanly
while blocking accidental double-submission of the same (id + text).

Indexes: (userId, createdAt) for the per-user timeline and
(severity, helpful, createdAt) for the daily aggregator's slice. Both
are needed by the v1.4.16 admin AI quality preview.

GDPR: ON DELETE CASCADE through users; cascade-delete integration
test now seeds and asserts a feedback row.

Same migration adds AppSettings.adminAiInsightsFeedbackSummary — the
JSON blob the daily aggregator (next commit) writes a per-(severity x
provider x prompt) helpful-rate to. Null until the aggregator runs
or until there is feedback in the 30-day window.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:25:57 +02:00
Marc-André BombeckandClaude Opus 4.7 170c62aac9 docs(planning): mark Wave-B B5c (per-rec explainability) complete
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:19:23 +02:00
Marc-André BombeckandClaude Opus 4.7 fed2e7ea54 test(insights): coverage for RecommendationCard expand + rationale rendering
Full-flow integration test:

  1. MockAIProvider returns a strict payload with rationale on every
     rec.
  2. generateInsight() validates + parses without retry (single
     provider call).
  3. The parsed payload is mapped onto the InsightResult UI shape
     and fed through InsightAdvisorCard.
  4. Assert the rec card is rendered, severity badge surfaces,
     chevron is collapsed by default (aria-expanded="false").

Second case pins the legacyPayload CTA path: a string-only
recommendations[] array (the v1.4.14/v1.4.15 InsightResult shape)
with `legacyPayload` flagged surfaces the regenerate banner.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:17:15 +02:00
Marc-André BombeckandClaude Opus 4.7 10a67ff6c8 feat(insights): RecommendationCard with expandable rationale + mini-chart of data window
Each recommendation now lives in its own collapsible card. Collapsed
state shows: severity badge + rec text + named slot for the future
B5d confidence-ring + chevron toggle. Expanding reveals the
Oura-style "Contributors" panel:

  - 3 rationale rows (Window / Compared to / Deviation)
  - mini-chart pinned to the rec's data window via HealthChart's
    new `mini` + `windowOverride` props (or MoodChart's mirror props
    for mood-typed metrics)
  - citation footnote (B5a) when referenceId resolves
  - named slot for the future B5e feedback-thumbs

Default state: collapsed. ChevronDown / ChevronUp toggle aria-expanded
and a 200ms ease-out animation reveals the rationale block.

Recs without rationale (legacy payloads) and plain-string recs render
as a non-expandable list item with the inline citation footnote
preserved — defence in depth so a stale cached payload still
surfaces its source even though the rationale block is empty.

InsightAdvisorCard renders the new component and surfaces the
legacyPayload CTA when the route flagged the cached blob as pre-B5c
shape — clicking the regenerate button is the single trigger; we
never auto-regenerate.

InsightRecommendation type widens to optionally carry rationale +
metricSource + severity + id (mirrors the strict
aiRecommendationSchema). Optional in the UI type because legacy
cached payloads predate them; the server-side schema enforces
presence on fresh generations.

Layout slots are deliberately named so B5d (confidence) and B5e
(feedback) plug into named positions without touching this file:

  - data-slot="rec-confidence-slot"  → B5d ConfidenceRing
  - data-slot="rec-feedback-slot"    → B5e RecommendationFeedback

11 new tests in `recommendation-card.test.tsx` pin the contract
(severity badge, default-collapsed, rationale row labels in both
locales, mini-chart routing for BP / mood, slot positions, legacy
fallback). Existing 6 citation-footnote tests still green via the
inline-footnote fallback path.

7 new EN+DE i18n keys under `insights.recommendation.*`:
  rationale, rationaleWindow, rationaleComparedTo, rationaleDeviation,
  rationaleExpand, rationaleCollapse, legacyPayloadCta.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:17:15 +02:00
Marc-André BombeckandClaude Opus 4.7 680f84c426 feat(charts): mood chart mini-mode + windowOverride
Mirrors the health-chart B5c mini contract for the mood chart:

  - mini: drops the range tabs, the toggle row (moving-average / trend
    / target-bands), and shrinks the chart height to 140px so it fits
    inside the rationale card without dominating it. Emoji glyphs
    + lavender gradient + tooltip survive intact.

  - windowOverride: pins the rangePoints state to the rationale enum
    value on mount.

The mood chart's metric-source key is "mood" (not a measurement-type
enum value), so the recommendation-card metric-mapping helper routes
mood-rationale charts here rather than through HealthChart.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:17:15 +02:00
Marc-André BombeckandClaude Opus 4.7 7f54c0cad3 feat(charts): mini-mode + windowOverride prop for embedded rationale charts
The Oura-style RecommendationCard (B5c) embeds a small chart pinned
to the recommendation's rationale.dataWindow. HealthChart gains two
opt-in props:

  - mini: drops the range tabs, the moving-average / trend / target-
    band toggle row, and shrinks padding (h-[140px] vs h-[240px]).
    Tooltip + gradient + personal-baseline behaviour stay intact so
    the small chart still tells the same visual story.

  - windowOverride: pins the rangePoints state to the rationale enum
    value (last7days / last30days / last90days / allTime) regardless
    of any parent UI state. Mini mode hides the range tabs anyway,
    so the user can't manually override the pinned window.

The pure helper resolveMiniRangePoints() (`mini-window.ts`) maps the
rationale enum onto the existing per-points TIME_RANGES_KEYS values.
Single source of truth so future schema changes touch one file.

7 new tests in `health-chart-mini.test.tsx` pin the contract:
- enum-to-points mapping for all 4 windows
- mini mode hides toggles + range tabs
- non-mini mode still renders them (regression guard)
- windowOverride seeds the rangePoints state on mount

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:17:15 +02:00
Marc-André BombeckandClaude Opus 4.7 c8b30c112d feat(ai): legacy insight payload detection with regenerate CTA
Cached insight blobs persisted before B5c shipped don't carry the
new `rationale` field — the strict parser would reject them, and
auto-regenerating on every cache-hit would burn rate-limit tokens
silently. Instead the route now detects the legacy shape and
surfaces a `legacyPayload: true` flag in the response so the UI
can render a one-time "regenerate for new explainability features"
CTA. User-initiated regeneration stays the trigger.

`isLegacyInsightPayload(payload)` lives in `src/lib/ai/legacy-payload.ts`
and is intentionally lenient: any rec missing rationale (or the
v1.4.14/v1.4.15 string-only InsightResult shape) flags. Empty
recommendations[] is NOT legacy — it's a legitimate refusal payload.

The annotate() Wide-Event also carries `legacyPayload` on cached
hits so the admin AI quality dashboard can chart the migration
ratio over time. v1.4.17 can flip auto-eviction on once the
ratio drops near zero.

7 new tests in `legacy-payload-detection.test.ts` pin the contract.
Existing 223 AI tests still green; typecheck clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:17:15 +02:00
Marc-André BombeckandClaude Opus 4.7 13f1ae5c0b feat(ai): corrective retry covers missing rationale fields
When a first-attempt response omits the rationale object (or emits
empty comparedTo / deviation strings), the corrective reprompt
now names the three rationale fields explicitly so the model has
a targeted fix instead of guessing what changed. The reprompt also
restates that rationale.dataWindow MUST equal metricSource.timeRange
— bracket-mismatch is the most likely model-side bug now that the
shape is new.

The wrapper's post-validation `annotate()` block additionally
emits three new Wide-Event meta fields:

  - ai_rationale_total_recommendations
  - ai_rationale_with_rationale
  - ai_rationale_missing_recommendation_ids

Strict-parsed payloads always have rationale on every rec (the
schema rejects otherwise), so the missing-ids array is an
observability tripwire — it will only populate if a legacy payload
ever rides through .passthrough() on a back-compat path.
v1.4.17 admin AI dashboard plots rationale-coverage alongside the
existing citation-coverage breakdown.

4 new tests in `rationale-wrapper.test.ts` pin the contract:
- corrective retry message names dataWindow / comparedTo / deviation
- empty deviation triggers retry (not just absent rationale)
- annotate() carries the new ai_rationale_* keys on success
- rationale-coverage = totalRecommendations on a fully-shaped payload

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:17:15 +02:00
Marc-André BombeckandClaude Opus 4.7 c39a527b8e feat(ai): system prompt requires rationale per recommendation
The output-format block now advertises the new `rationale` shape
(dataWindow / comparedTo / deviation) and a fifth GROUND RULE
mandates that every rec carry one. The dataWindow MUST equal
metricSource.timeRange so the UI's mini-chart can pin to the same
window the rec was derived from — bracket-mismatch prevention is
cheaper to enforce in the prompt than to detect post-parse.

Both EN + DE prompts updated symmetrically. PROMPT_VERSION stays
at 4.16.0 since B5a already bumped it for this milestone — the
content extension is a same-version revision, not a behavioural
shape change that warrants 5.0.0.

6 new prompt-assertion tests pin the contract:
- output-format block names the three rationale fields
- enum values (last7days...allTime) mentioned for both locales
- ground rule "MUST carry a rationale" present in EN + DE
- "factual" / "sachlich" language guard against placeholders

Existing 213 AI tests still green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:17:15 +02:00
Marc-André BombeckandClaude Opus 4.7 8a438a0680 feat(ai): schema requires rationale (window + comparedTo + deviation) per recommendation
Each recommendation now carries a 3-field `rationale` object that
powers the upcoming Oura-style "Contributors" expand-card:

  - dataWindow: which time window the rec is based on (matches the
    metricSource.timeRange enum so the UI mini-chart can pin to it)
  - comparedTo: what the user's data is being compared against
    (the user's own baseline or a guideline ceiling)
  - deviation: size + direction of the deviation that triggered
    the rec

Empty `comparedTo` or `deviation` is rejected so the model cannot
emit a placeholder rationale card. Optional `referenceId` rides
along for defence-in-depth; the rec-level referenceId stays the
canonical citation source.

`findRecommendationsMissingRationale()` lets the route detect
legacy (pre-B5c) cached payloads so the UI can show a "regenerate
for new explainability features" CTA. User-initiated regeneration
stays the trigger; nothing auto-runs.

10 new tests in `rationale-schema.test.ts` pin the contract:
- rationale required on every rec
- comparedTo / deviation reject empty strings
- dataWindow rejects unknown enum values
- legacy payload detector returns missing rec ids only
- mixed payloads flag only the legacy entries

Existing test fixtures in `generate-insight.test.ts`,
`reference-id-schema.test.ts`, `citation-enforcement.test.ts`,
and `citation-coverage-logging.test.ts` updated to include
rationale on every well-formed rec — typecheck-clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:17:15 +02:00
Marc-André BombeckandClaude Opus 4.7 612ee364db docs(planning): mark Wave-B B2 (AI provider UX cleanup) complete
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:13:45 +02:00
Marc-André BombeckandClaude Opus 4.7 3848b625af test(e2e): AI provider dropdown switches the rendered config form
Locks in the B2 contract: /settings/ai exposes the active-provider
Pulldown, switching the dropdown swaps the form below it (Codex →
OpenAI → Anthropic → Local), and the fallback chain card surfaces
all configured rows with their stable data-chain-row markers.

The spec mocks every backend endpoint the section reads so the run
needs no real Codex / OpenAI keys in CI. data-testid markers on each
config form keep the assertions independent of the locale.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:11:35 +02:00
Marc-André BombeckandClaude Opus 4.7 70206b9bf5 test(insights): integration coverage for PUT /api/insights/provider-chain
Two scenarios pinned end-to-end against the postgres testcontainer:
saving a valid reordered chain persists the JSON column with priority
normalised to 1-indexed insertion order, and saving an empty chain
rejects with 422 + leaves the column untouched. No fetch mocks; the
route runs against the real Prisma client so a future schema drift on
User.aiProviderChain trips the suite immediately.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:10:19 +02:00
Marc-André BombeckandClaude Opus 4.7 23f4ee5b1e feat(settings): AI provider section with single dropdown driving form below
Replaces the v1.4.15-vintage two-card layout (Codex connect at the top,
personal-provider form at the bottom) with the dropdown-driven UX
called out in feedback_settings_no_split.md: one Pulldown picks the
active provider, the form below adapts to that choice, and the
fallback chain at the bottom reorders / toggles entries with arrow
controls.

Five provider config forms live in this file (Codex, OpenAI, Anthropic,
Local, Admin OpenAI) and share a single card frame so transitions feel
like updating one concept rather than swapping pages. The Codex form
keeps the device-code flow + OAuth callback handling unchanged. OpenAI
gets a model dropdown plus a collapsed Base URL override (advanced).
Anthropic and Local mirror that shape with the right credentials. The
fallback chain calls the new PUT /api/insights/provider-chain to
persist reorders.

The Select is URL-synced via ?provider=… so deep links work, the SSR
test can drive each branch deterministically, and a refresh keeps
the user on the form they were editing. Native <select> elements
keep the SSR-only render-to-static-markup test happy without bringing
a portal-based Radix tree into play. No new dependency — dnd-kit is
not in package.json so reorder uses up/down arrow buttons.

EN + DE i18n keys land alongside; the i18n parity guard test sees
both locales and the existing settings.ai.providerChain.types.* tree
keeps the per-provider labels stable across the chain summary and
the new chain-management UI.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 01:09:07 +02:00
Marc-André BombeckandClaude Opus 4.7 3e037b4d42 feat(api): PUT /api/insights/provider-chain persists user fallback chain
The B5b read-only endpoint now has a write counterpart so the new
Settings → AI dropdown UX can save reorder + enable/disable changes.
Server-side priority is recomputed from insertion order (so the UI's
visual contract — "first row = priority 1" — cannot drift from what
gets persisted), unknown provider types and duplicates 422, and an
empty chain is rejected outright. parseProviderChain still falls
back to the default chain when the persisted JSON is malformed,
so a stale-tab resubmit cannot poison generation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:58:05 +02:00
Marc-André Bombeck 8352c6daa3 docs(planning): update Wave-C report with e2e remaining-failures details
Records the three additional root causes uncovered after the first
e2e fix landed: desktop-only specs leaking into the mobile project
plus the missing `/api/dashboard/widgets` stub in onboarding-flicker
spec.
2026-05-10 00:51:02 +02:00
Marc-André Bombeck 00848b7ed5 fix(e2e): skip desktop-sidebar specs on mobile + stub /api/dashboard/widgets
Three remaining e2e failures after the global-setup tour-completed fix
all came from cross-project sharing — specs that target desktop-only
DOM (the `aside[aria-label="Sidebar"]` logo + Achievements link)
were running in the chromium-mobile profile too, where the sidebar
is `hidden md:flex` by design. Added `test.skip(viewport.width < 768,
...)` guards so each spec only runs in the project that can satisfy
its contract.

The fourth failure was the `/api/dashboard/widgets` endpoint that the
A5 tile-strip work added since `onboarding-flicker.spec.ts` was
written. Without a stub the unauthenticated dashboard 500s on this
query and React Query's error boundary swallows the page render
before `<GettingStartedChecklist>` mounts. Added the stub to both
flicker specs (complete + incomplete-onboarding paths).
2026-05-10 00:50:00 +02:00
Marc-André Bombeck 71652ec751 docs(planning): mark Wave-C complete (catch-up + CI red root-cause)
Wave C dispatch closed: integration + e2e workflows green again
(YAML-parsed-as-integer ENCRYPTION_KEY plus tour-overlay click
interception); 5 of 8 deferred HIGH items applied (H3 charts skipped
per ownership, H1/H2 senior splits deferred); 3 of 5 deferred MED
mobile items applied (BP grouping + DOM weight deferred to v1.5);
docker-publish hang root-cause was qemu-arm64 SIGILL — dropped arm64
from platforms; Coolify image-digest auto-deploy documented + deferred
to v1.5 with concrete plan.

`pnpm test` 1303/1303, `pnpm test:integration` 53/53 locally,
typecheck clean, lint 12 pre-existing warnings.
2026-05-10 00:46:31 +02:00
Marc-André BombeckandClaude Opus 4.7 0d08e33fa1 docs(planning): mark Wave-B B5b (multi-provider redundancy) complete
Hard-fail cascade across the configured chain landed on origin/main
across four atomic commits. Runner caches the last working provider
(1h TTL) so a 401 on a lapsed Codex OAuth doesn't burn a round-trip
on every reload for the next hour. Settings -> AI surfaces a small
read-only summary of the chain; full management UX is owned by B2.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:41:07 +02:00
Marc-André Bombeck 072eee6997 fix(nav): bottom-nav 5+More overflow protects 44px tap targets
The 7-item bottom nav collapsed each touch target to ~50 px wide on
a 375 px viewport — only just-passing WCAG 2.5.5's 44 px floor and
visibly cramped on iPhone-13-mini-class screens. The mobile audit
(`.planning/phase-A5-mobile-findings.md`) recommended 5+More.

Primary strip keeps the four most-used surfaces plus Insights:
Home, Measurements, Mood, Medications, Insights. Targets and
Achievements move into a Radix `<Sheet>` triggered by a sixth
"More" entry. Order matches the v1.4.15 layout for the four core
items so muscle memory holds.

The More button mirrors the same `min-h-11 min-w-11` hit area;
`aria-haspopup="dialog"` + `aria-expanded` keeps screen-reader
behaviour tight; the sheet renders bottom-anchored with safe-area
padding so the inner links stay reachable above the iPhone home
indicator. Active styling lights the More entry whenever any of
its overflow children is the current route, so the user always
knows which strip-level link "owns" their position.
2026-05-10 00:39:59 +02:00
Marc-André BombeckandClaude Opus 4.7 d2bda42a3b test(ai): provider fallback covers happy path, hard-fail cascade, cache
End-to-end integration test for the multi-provider redundancy runner.
Boots the postgres testcontainer, seeds a user with both an OpenAI key
and an Anthropic key plus an explicit chain (openai -> anthropic),
intercepts upstream HTTP calls via fetch-spy, and exercises three
scenarios:

1. Hard-fail-then-success cascade. OpenAI primary returns 401, the
   runner walks to Anthropic, the route surfaces a 200 with
   `chainProviderType: "anthropic"` and `fallbackHopCount: 1` recorded
   in the audit log.

2. All-fail cascade. Every chain entry returns 503, the route surfaces
   a 503 with the "temporarily unavailable" envelope.

3. Last-working cache. After scenario 1 the runner remembers Anthropic
   was the working provider; the next call (cache bypass forced via
   nulled `insightsCachedAt`) reorders the chain so Anthropic is tried
   first and only ONE upstream fetch fires (not two — the doomed
   OpenAI 401 round-trip is skipped).

Test routing on URL substring (`/chat/completions` for OpenAI,
`/messages` for Anthropic) instead of headers so the assertion is
robust against any future header-shape drift in the clients.
Constrained to user-level providers because the testcontainer
migration history pre-dates several `app_settings` columns added
through schema-only edits — touching admin-openai resolution would
blow up before the chain runner even sees the request.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:39:39 +02:00
Marc-André Bombeck 65b4bf9679 fix(admin): system-status load-failed pairs alert with Retry button
When `/api/admin/status` 500s (rolling deploy, transient DB blip),
the section's error state previously rendered a static "refresh the
page" message — forcing a full reload + cookie revalidation just to
recover from a 5-second hiccup. Pairing the alert with an inline
Retry button (`refetch()` from React Query) lets the admin recover
in-place without losing scroll position or any other open admin tab.

The button is `min-h-9` desktop-tight (this is admin, not mobile-
critical), shows a spinner while `isFetching`, and disables itself
during the request. The German + English message strings drop the
"refresh the page" tail since the button now does that work.
2026-05-10 00:37:08 +02:00
Marc-André Bombeck d7c2b2a67b fix(tabs): horizontal scroll on mobile prevents overflow (insights + admin)
Mobile audit (`.planning/phase-A5-mobile-findings.md`) flagged the
`<TabsList>` primitive as overflowing the viewport on `/insights`,
`/admin` and several `/settings/*` surfaces — six i18n-driven tab
labels at typical German widths blow past 375 px before the inline-
flex shrink-wraps. Labels can't be truncated deterministically (they
include "Auswertungen", "Sicherheit & Privatsphäre"-style strings)
and word-wrap inside a tab is the worst possible look.

The list now scrolls horizontally on mobile via `overflow-x-auto` +
`touch-pan-x` (iOS PWA gesture). `max-w-full` prevents the inline-
flex from forcing the parent wider. Desktop renders identically
because the existing parent containers all give the strip enough
room to lay out without scrollbars. Vertical-tabs orientation keeps
its `overflow-x-visible` to avoid double-overflow with the
flex-column layout.
2026-05-10 00:37:08 +02:00
Marc-André BombeckandClaude Opus 4.7 d87ac3a639 docs(planning): mark Wave-B B1a (charts visual leap) complete
Apple-Health-style polish lands across all dashboard chart wrappers
in v1.4.16: gradient fills, 90-day personal baseline, rich tooltips
with delta-vs-baseline, 600 ms first-render animation respecting
prefers-reduced-motion, sparse-data empty state. Mood chart picks
up emoji glyphs at every data point; medication chart picks up the
gradient + rich tooltip on top of A6's existing target/threshold
reference lines.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:35:16 +02:00
Marc-André BombeckandClaude Opus 4.7 613d6619df feat(settings): minimal display of active AI provider + configured chain
The AI section now renders a small read-only summary of the user's
fallback chain: "Active provider: ChatGPT (Codex)" plus "Configured
chain: ChatGPT (Codex), OpenAI (your key), Admin OpenAI". When the
in-process cache reroutes to a fallback (the primary 401'd in the
last hour), the line gains "(cached: OpenAI)" so the user can see the
runner has shifted without digging through the wide-event log.

The full management UX (drag-to-reorder, on/off toggles, add/remove
provider entries) is owned by phase B2 — this surface is deliberately
tight so the two phases don't collide. The card hides itself when no
provider is configured at all so accounts that haven't set up AI
don't see an empty header. EN + DE i18n keys added under
settings.ai.providerChain.*; provider-type labels are localised so
"Local model" reads "Lokales Modell" in German.

The new GET /api/insights/provider-chain endpoint is the data source.
Returns the resolved chain in priority order plus the cached active
provider (when set), wrapped in the standard apiSuccess envelope.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:34:39 +02:00
Marc-André Bombeck cc0f3436ff fix(ci): docker-publish reliable on main-branch (drop qemu-arm64)
The main-branch build hang since v1.4.14 was qemu-arm64 SIGILL-crashing
Next.js static-page-generation workers — `Next.js build worker exited
with code: null and signal: SIGILL` at 64-66/86 pages, every time
under load. V8's optimising tier emits CPU instructions that qemu's
user-mode emulation cannot reliably translate, and Node 22 + Alpine
3.21 hit it deterministically. Tag-builds appeared to "work" only
because they sometimes finished the static phase before the crash
window; main-branch builds rarely got that lucky and looked like
hangs.

Marc's prod target is x86_64 (Coolify on apps-01, every other
self-hosted HealthLog we know of). The arm64 image was a courtesy
build for OSS users, not production. Dropping it removes the qemu
flake completely and brings build time from 17-30 min back to ~12 min
typical.

v1.5 plan (`docs/audit/v1416-auto-deploy-fix.md`): re-add arm64 via a
matrix that uses GitHub-hosted `ubuntu-24.04-arm` runners (free for
public repos, native arm64, no qemu). The current concurrency-group +
per-ref gha cache scope from v1.4.15 C3 stays in place.
2026-05-10 00:34:33 +02:00
Marc-André Bombeck 4be6465e6c docs(deploy): v1.4.16 auto-deploy follow-up audit + DEFER to v1.5
The git-push trigger that causes Coolify container churn during marathon
work is the GitHub-App "Auto Deploy" toggle on the application — it
fires on every push to `main`, including doc-only commits. Disabling
it leaves the Actions-driven webhook (already shipped in v1.4.15) as
the sole trigger.

The Coolify v4-beta MCP API does not expose this toggle programmatically.
Marc-side UI flip is the realistic fix; doing it now without API access
would require either a Watchtower install (larger blast radius — vetoed
in the v1.4.15 audit and re-vetoed here) or hand-issuing a Coolify token.

Audit doc lays out the manual step + the v1.5 plan to automate it once
the API exposes `auto_deploy_enabled`. Marc can flip the toggle whenever
convenient; does not block v1.4.16 release.
2026-05-10 00:34:33 +02:00
Marc-André BombeckandClaude Opus 4.7 80086130de feat(charts): medication chart polish (gradient + animation + rich tooltip)
Closes the v1.4.16 B1a polish across all dashboard charts. The
medication-compliance chart already shipped 7-day-trend + target/
threshold reference lines from A6; this commit brings it into visual
parity with BP/weight/pulse/mood:

- ComposedChart replaces LineChart; a gradient-filled Area paints
  under the compliance line. The medication gradient uses the purple
  Dracula token, matching the existing line stroke.
- Rich tooltip via RichChartTooltip — date label, compliance
  percentage with tabular numerals, delta-vs-target sub-line that
  reads "−15 pp vs. target" so the gap to 100 % is immediately
  visible.
- 600ms ease-out animation on first render, suppressed when
  prefers-reduced-motion is set.
- Sparse-data placeholder via ChartEmptyState for <3 daily points.
  Existing "no scheduled doses" empty state is preserved (the user
  could have a long history of skipped scheduled days that drops
  the chart to fewer than 3 actionable points).

The 80 % minimum-acceptable threshold and 100 % goal ReferenceLines
from A6 stay untouched; gradient plus those lines now make the
"target range" feel like a band rather than a pair of guides.

1 new test pins the gradient SSR contract.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:33:09 +02:00
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é BombeckandClaude Opus 4.7 ae13dc0fb2 docs(planning): mark phase B6 (settings naming-audit) complete
STATE.md gets the four B6 commits + audit doc link + status block.
phase-B6-report.md was the v1.4.15 doctor-report report; rewritten
for the v1.4.16 phase.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 00:29:22 +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