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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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.
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).
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.
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>
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.
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>
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.
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.
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>
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>
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.
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.
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>
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>
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.
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>
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.
`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).
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>
Phase B6 commit 3 of 4.
The audit (`docs/audit/v1416-settings-audit.md` §2.5 + §2.6) found no
live duplicate user-facing toggle between `/settings` and `/admin`:
- Notification channels: per-user credentials in `/settings/notifications`,
system-wide enable/disable in `/admin` via the global-services API.
Different scope, no overlap.
- AI providers: per-user override in `/settings/ai`, system default in
admin AI settings. Different scope, no overlap.
- Channel test buttons appear in both `<NotificationStatusCard>` and
the per-channel cards (`<TelegramCard>` etc.) but they're different
intents (post-failure smoke vs. post-config smoke), kept.
- The export buttons (CSV/JSON, doctor-report PDF) used to live in
Advanced AND Export — the duplication was already collapsed by
phase B7 when the consolidated Export section shipped.
What this commit actually does is document the rule in `CLAUDE.md`
so future agents don't re-introduce a duplicate. Dead i18n keys
(`settings.adminAreaTitle`, `settings.adminAreaDescription`,
`settings.openAdminConsole`) are marked stale in the audit doc and
will be removed in a follow-up hygiene PR — leaving them in place
keeps the i18n locale-parity test green for now.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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>
Single-pass audit of every /settings/<slug> route + section component
+ i18n keys. Documents inventory, naming drift, top/bottom-split
anti-patterns, duplicate functionality, settings-vs-admin scope rule,
and the three follow-up refactor commits. AI section flagged for B2,
Export section already handled by B7.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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>
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.
Two keys were added to en.json in `a66c128` (B5a citation footnote)
but never mirrored in de.json, so the locale-parity guard test went
red on every push and German users saw the raw key name in place of
the citation label. This restores parity by adding "Quelle" + the
"in neuem Tab öffnen" tooltip without touching feature scope.
The component appends the colon at render time, so the value is
"Quelle" rather than "Quelle:" — the locale-integrity test plus the
existing citation-footnote rendering test both go green.
Two unrelated root-causes were keeping the Integration tests and e2e
workflows red on every push to main since `d8c549e` (50+ runs).
1. Integration: `.github/workflows/integration.yml` had `ENCRYPTION_KEY:
0000…` as a bare YAML scalar. YAML 1.2 parses a run of zeros as the
integer 0 — so the runner exported `ENCRYPTION_KEY=0`, and
`decodeKey()` rejected it as "must be hex (>= 32 chars) or base64
(32 bytes)". 6 tests in admin-backups-* and integration-status
failed at module load. Quoting the value forces a literal string.
2. e2e: the global-setup seeded user had `onboarding_tour_completed`
left at its default `false`, so the spotlight tour mounted a
full-viewport `role="dialog"` overlay (z-index 200) on every
authenticated spec. Playwright's hit-test then caught the tour's
skip-button instead of the intended target — every spec that
clicked sidebar / quick-add / logo timed out. Setting the column
to `true` in the upsert keeps the tour off the dashboard for the
rest of the suite. The two `onboarding-flicker.spec.ts` mocks
that fulfil `/api/auth/me` from inside the spec also need the
field, since they replace the seeded payload.
Workflow change is comment + quoted strings only — no secrets, no
runtime cost.
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>