Commit Graph
1043 Commits
Author SHA1 Message Date
Marc-André Bombeck 24d88858e9 docs(ios-handoff): D-AI Layer — iOS and server responsibility boundaries
The remaining two files of D. 06-ios-responsibilities.md enumerates the five
domains the iOS app owns (HealthKit, Keychain, APNs, offline cache, deep
links) plus the MDR-critical 'don't cross this line' warnings.
07-server-responsibilities.md is the inverse — 22 domains the server
already handles, so iOS Claude knows what NOT to reinvent.
2026-05-14 23:35:22 +02:00
Marc-André Bombeck 39c0242a85 docs(ios-handoff): B-Data&Auth — data-model + auth + locked-contracts + errors + glossary 2026-05-14 23:33:31 +02:00
Marc-André Bombeck a756c51be8 docs(ios-handoff): A-Foundation — README skeleton + philosophy + repo-tour + architecture + API contracts 2026-05-14 23:33:20 +02:00
Marc-André Bombeck 9bfbbdf345 docs(ios-handoff): C-UI&State — web-UI tour + design system + state mgmt + pattern cookbook + i18n 2026-05-14 23:32:12 +02:00
Marc-André Bombeck 24cd5cece1 docs(ios-handoff): D-AI Layer — coach, insights, health-score mental model
Three of D's five files. The Coach + Insights + Health-Score surfaces are
server-resident; iOS Claude must consume, not reimplement. Documents the
layered prompt builder, GROUND RULES 1-15 (including W4d/W19c safety
contracts that hold the EU MDR line), the safety-contract matrix loader,
cache-invalidation rules, source-attribution provenance, and the
deterministic asOf discipline introduced in v1.4.25 Fix-G.
2026-05-14 23:30:50 +02:00
Marc-André Bombeck 6153be04cf docs(ios-handoff): C-UI&State design system + state mgmt + i18n 2026-05-14 23:28:12 +02:00
Marc-André Bombeck 0a9257357b docs(planning): W22 release-redo phase report 2026-05-14 23:20:18 +02:00
Marc-André Bombeck 49f71c9215 chore(release): expand v1.4.25 with Wave 4-5 and reconcile features
Rewrites the v1.4.25 CHANGELOG section to cover the ~90 commits since
v1.4.24 across onboarding rebuild, GLP-1 medication tracking end-to-end
(drug knowledge, Research Mode with MDR acknowledgment dialog,
estimated drug-level chart, side-effect taxonomy, cadence + compliance,
EMA titration ladder, pen-and-vial inventory with a 30-day clock),
Personal Records detection worker + badge + push opt-in, workout batch
ingest, Withings Activity + Sleep v2 syncs, EMA drug knowledge layer,
log-redaction path-segment rule that closes the Withings webhook
secret leak, GLP-1 convenience endpoint hardening, native first-party
Coach + insights system prompts across six locales with a refusal-probe
matrix, OpenAPI drift-gate hard-fail flip, 380 dead i18n keys removed,
shared helpers + section wrapper consolidations, dashboard top-tile
polish, design polish to WCAG 2.5.5 + AA contrast.

Updates the test count footer to the current 3828 unit / 344 files /
~170 integration / 9 new migrations (0051-0059) + 1 hardening (0060).
Adds the refusal-probe matrix metrics (1800+ assertions x 15 GROUND
RULES x 6 locales x 20+ paraphrasings).

Replaces the stale "Deferred to v1.4.26" section. Items that already
shipped in Wave 4-5 (OpenAPI hard-flip, onboarding rebuild, native
FR/ES/IT/PL Coach prompts, PR detection worker, workout ingest,
Withings Activity + Sleep v2) are out of the deferred list and into
Added / Changed / Fixed / Security / Refactor. The remaining v1.4.26
backlog reads accurately.
2026-05-14 23:19:26 +02:00
Marc-André Bombeck 068b49e709 docs(planning): Fix-N reconcile phase report
Closes the W21 reconcile pass. Captures the six commits, the 49 new
test assertions, three documented deviations (inventory-section
keeping its details shell, medication-form parseDose left alone,
apiError signature broadening), and final-gate evidence.
2026-05-14 23:12:05 +02:00
Marc-André Bombeck df719caa2f fix(medications): derive side-effect category server-side + drift-guard test
simp-M1 — the side-effect category and entry tuples in the Zod
validators no longer restate the Prisma enum keys verbatim. Both
arrays now derive from MedicationSideEffectCategory and
MedicationSideEffectEntry via z.nativeEnum, so adding a new entry
only requires touching the Prisma schema + the taxonomy mapping.

code-M1 — drift-guard test asserts the three sources (Prisma enums,
taxonomy module, validators) cover the same keysets. Catching drift
at test-time prevents the silent 422-vs-DB-accept mismatch that bit
the previous shape.
2026-05-14 23:11:06 +02:00
Marc-André Bombeck 8399c47874 refactor(api): adopt assertMedicationOwnership + rate-limit option-bag across 9 medication routes
Hoist the ownership-check boilerplate that nine medication sub-routes
were each carrying inline into the shared route-guard helper, and align
the three W19 routes that hand-wrote the rate-limit header loop on the
new apiError option-bag form.

Routes touched:
- titration: shared guard + replaced parseDoseString with the shared
  parseDoseMgOrNull + replaced the inline GLP1_DRUGS reverse-lookup
  with findDrugIdByBrand.
- side-effects: shared guard + option-bag headers + dropped the
  client-supplied 'category' field per code-M6 (server derives via
  categoryForEntry).
- inventory: shared guard + option-bag headers.
- cadence: shared guard layered on top of the W21 Fix-O timezone wiring.
- intake (POST + GET): shared guard.
- compliance: shared guard.
- phase-config (GET + PUT + DELETE): shared guard.
- api-endpoint (GET + PUT): shared guard.
- glp1: shared guard replacing Fix-K's inline copy + option-bag headers.

apiError now accepts { headers: Record<string,string> } in its third
argument bag; the headers flow through NextResponse and are stripped
from the meta envelope so the existing { errorCode, ... } meta usage
keeps its shape.
2026-05-14 23:09:50 +02:00
Marc-André Bombeck 2b712429c0 refactor(ui): adopt shared readError + ResearchModeStatus + design-system Select
- advanced-section: drops the local ResearchModeStatus interface in
  favour of the shared DTO, replaces the nested ternary that built the
  toggle's status caption with a researchModeStatusLabel helper
  threaded through the shared gate-state classifier.
- WelcomeCarousel / GoalsChipPicker / SourceCardGrid / BaselineForm:
  import the shared readError helper instead of the four hand-rolled
  copies — the request-failed fallback shape now evolves in one place.
- BaselineForm: swap the gender native <select> for the
  shadcn-radix Select component so the picker matches the rest of the
  form library (focus rings, keyboard nav, theme tokens).
2026-05-14 23:04:37 +02:00
Marc-André Bombeck d6456a30eb refactor(medications): extract MedicationDetailSection wrapper across 4 components
Lock the shared chrome (border + header row + dotted divider + body
band) into one wrapper so the three Wave-4b panels (Titration,
Scheduling, SideEffects) stop drifting on padding, border opacity,
and aria-wiring rules.

- src/components/medications/medication-detail-section.tsx (new) —
  composes the section shell with a stable titleId / headerExtras
  contract.
- TitrationSection — drops the hand-rolled templateFill helper (the
  i18n t() function already accepts the params bag); adopts the
  wrapper.
- SchedulingSection — adopts the wrapper; grows cadence-timeline
  cells to a 44 px tap-target per WCAG 2.5.5 while keeping the 12 px
  visible cell.
- SideEffectsSection — adopts the wrapper; swaps the native <select>
  for the shadcn-radix Select so the picker matches the rest of the
  form library.
- inventory-section — drops the local InventoryState string-union in
  favour of the Prisma MedicationInventoryState enum; replaces the
  reimplemented daysRemainingInUse with the widened pure helper.
- DrugLevelChart — adopts shared ResearchModeStatus,
  findDrugIdByBrand, and parseDoseMg (the local parseDoseMg is
  re-exported for test backwards-compat).
- inventory state-machine — widens daysRemainingInUse to accept
  either the full InventoryItemView or a thin { firstUseAt } shape.
2026-05-14 23:02:28 +02:00
Marc-André Bombeck c8ee4cb9fc feat(medications): shared helpers — readError + route-guards + dose-string + research-mode-types
Hoist five duplicated helpers into single source modules so each
contract evolves in exactly one place:

- src/lib/api/read-error.ts — replaces the four hand-rolled copies
  in the onboarding flow (Welcome / Goals / Source / Baseline).
- src/lib/medications/research-mode-types.ts — shared ResearchModeStatus
  DTO + tri-state gate helper consumed by both the DrugLevelChart
  and the Settings advanced section.
- src/lib/medications/route-guards.ts — assertMedicationOwnership
  for the eleven medication sub-routes, preserving the 404 leak
  shape across the privacy boundary.
- src/lib/medications/dose-string.ts — unified parseDoseMg + null
  variant replacing the DrugLevelChart and titration-route parsers.
- src/lib/medications/glp1-knowledge.ts — adds findDrugIdByBrand
  reverse lookup so the brand-to-id pattern stops being open-coded
  at every chart render.

28 new unit tests across the five helpers.
2026-05-14 22:54:25 +02:00
Marc-André Bombeck 5f5b8dfb49 chore(medications): delete unused research-mode-staleness module + add PR worker null-slot dup regression
`research-mode-staleness.ts` shipped in W19c-Safety as a sibling helper
for a future 90-day re-acknowledgment gate on the GLP-1 drug-level
chart. The wiring step never landed — the helper has zero production
importers (only its co-located test consumed it). The version-bump
re-prompt path in `/api/auth/me/research-mode/route.ts` already
covers the regulatory contract (a copy or EMA-EPAR ratchet forces
the dialog), so the calendar-staleness gate is intentionally deferred
to v1.4.26 and the unused module ships off-codebase rather than
sitting orphaned through the release.

Also pin the PR-detection worker's null-slot dedup contract against
a back-to-back invocation regression. The personal_records unique
index uses NULLS NOT DISTINCT on `(userId, metricType, metricSlot,
achievedAt)` — measurement-type PRs (slot = NULL) must coalesce
across consecutive worker invocations even when the candidate row
sits at the exact same achievedAt. A future refactor that drops the
NULLS-NOT-DISTINCT semantics would silently double-insert; this test
fails fast if that happens.

Fix-O / code-M5 + dead-H4 + senior-M3 + L2.
2026-05-14 22:43:53 +02:00
Marc-André Bombeck 2a65f2b179 feat(medications): thread timeZone into cadence + compliance helpers
The W19e pure cadence + compliance helpers used `Date.setHours`,
`getDay`, and `setHours(0, 0, 0, 0)` for every local-day boundary,
window-time application, and streak day-key. Those methods read the
host process's system time — every medication detail page on the
cadence route returned values relative to whatever zone the server
ran in (Europe/Berlin in prod, often UTC in CI), not the user's. A
Tokyo user reading the same data saw their 08:00 window land at
16:00 wall-clock and the day-of-week filter ran off the Berlin
weekday.

Thread an optional IANA `timeZone` argument through
`expandScheduleSlots`, `pairDoses`, `buildCadenceTimeline`,
`computeNextDose`, `missedDoses`, and `complianceChips`. Every local
operation now resolves through `Intl.DateTimeFormat`. When the
argument is omitted the helpers fall back to system-local — every
existing unit test (system-local by construction) keeps its
assertions green. The cadence route resolves the user's zone via
`resolveUserTimezone(user.id)` and forwards.

Regression tests pin the 08:00 wall-clock contract across Berlin /
Tokyo / Los Angeles and check that a "Mondays only" schedule lands
on each zone's local Monday.

Fix-O / code-H2.
2026-05-14 22:42:37 +02:00
Marc-André Bombeck 701fd5f251 fix(withings): anchor activity sync at noon UTC for tz-safe bucketing
Withings reports per-day aggregates with `date` as `YYYY-MM-DD`. The
v1.4.25 W17b writer anchored `measuredAt` at the day's 23:59:59 UTC so
the row would sort at the end of the day in chronological reads. That
shape mis-bucketed positive-offset users: a row from `date=2026-05-12`
arrived as 2026-05-13 08:59:59 in Tokyo, off-by-one for every
dashboard tile that reads the row in user-local time.

Anchor at noon UTC (`12:00:00Z`) instead — the standard "calendar-day
with no clock" representation per RFC 3339 §5.6. The instant lands
inside the local calendar day for every supported user timezone in
the practical [-11, +12) range (Honolulu through Tokyo), so the
analytics layer day-keys the row to the same calendar day every user
reads it in.

Regression test covers the four canonical user zones; the existing
end-of-day assertion is updated.

Fix-O / senior-M2.
2026-05-14 22:38:01 +02:00
Marc-André Bombeck 4c4fa645b1 docs(db): rewrite Migration 0057 PG11+ default-backfill comment
The original comment claimed that `DEFAULT 0` "only applies to *new*
inserts on PostgreSQL — existing rows are not backfilled". That's
wrong for PG11+: the fast-path `ADD COLUMN ... DEFAULT` materialises
the default for every existing row in O(1) time without rewriting the
table. The comment confused future readers about why the Wizard mount
treats `NULL` as 0 (defensive against the legacy ambiguity, not
because of any general PG behaviour).

Rewrite to match reality, and point at Migration 0060 as the follow-on
that flips the column to NOT NULL.

Fix-O / code-M8.
2026-05-14 22:36:33 +02:00
Marc-André Bombeck 3f7a8ce6a6 feat(db): Migration 0060 backfills onboardingStep + flips to NOT NULL
Migration 0057 shipped `onboarding_step INTEGER DEFAULT 0` as nullable so
the additive DDL avoided a long table rewrite during the W14b deploy.
The wizard mount code and the POST route then carried defensive
null-handling branches (read-side `?? 0`, write-side `OR step IS NULL`)
to keep legacy pre-W14b rows working. That left a tri-state surface the
route had to widen on every step-0 advance.

Backfill every NULL row to 0 (the same value the read-path already
substitutes), then `ALTER COLUMN ... SET NOT NULL`. schema.prisma drops
the `?` so the Prisma type-surface mirrors the DB. The conditional
update WHERE in `/api/onboarding/step` collapses to the strict-equality
form on every step — the legacy null branch becomes unreachable code
and is removed.

Fix-O / senior-M1.
2026-05-14 22:35:57 +02:00
Marc-André Bombeck a238ae48d1 fix(design): pin acknowledgment dialog footer + i18n back-button + drop GoalsChipPicker storage block
Three small surface fixes consolidated because each is a one-touch
change on a separate file:

- `ResearchModeAcknowledgmentDialog`: the entire `DialogContent`
  scrolled at `max-h-[90vh] overflow-y-auto`, which pushed the
  Acknowledge / Cancel CTAs below the fold on phone-class viewports.
  Move scrolling onto the body section only so the header and footer
  stay pinned.
- Medication history page back-button rendered the literal "Zurück"
  instead of going through `t()`. Wire the new `medications.back`
  key across all six locale bundles.
- `GoalsChipPicker` shipped a localStorage persistence block scoped
  by user id, but no consumer reads the same key. Drop the storage
  layer (and the unused `goalsStorageKey` /
  `ONBOARDING_GOALS_STORAGE_PREFIX` exports) until v1.4.26 lands the
  `User.onboardingGoals` column the picker is meant to feed.
2026-05-14 22:30:58 +02:00
Marc-André Bombeck 7c9b4b6563 fix(onboarding): conditional step write + 409 on concurrent advance
Two parallel tabs both reading `onboardingStep = 2` and both POSTing
`step: 3` would both succeed because the second write didn't re-check
the precondition — the wizard could double-advance and skip a step.
Move the write onto `updateMany` with the precondition embedded in
the WHERE clause: exactly one update lands, the loser sees count = 0
and returns 409 so the client can refresh and retry.

The WHERE clause covers `onboardingCompletedAt: null` so the same
guard catches a race with `POST /api/onboarding/complete`. The
`current === 0` branch widens the match to `step IS NULL OR step = 0`
so legacy pre-W14b accounts still advance from step 1.

Fix-M / code-M7.
2026-05-14 22:30:02 +02:00
Marc-André Bombeck 35cb488b6d fix(design): lift personal-record badge to WCAG AA contrast
The PR pill painted `text-dracula-green` (#50fa7b) on a
`bg-dracula-green/10` chip background. In dark mode that measured
around 2.6:1 — well under the 4.5:1 minimum WCAG 2.1 AA requires
for small text. Switch to the semantic `--success` token, which
resolves to a darker forest green on the light card (#14720a) and
to Dracula's neon green on the dark card, and lift the chip tint
from /10 to /15 for a sturdier edge. Both modes now clear AA.
2026-05-14 22:28:19 +02:00
Marc-André Bombeck 9ef1dd6e02 feat(api): legacy Withings webhook counter + migration URL in warning
The legacy ?secret=... route stays alive through v1.4.27 so existing
Withings subscriptions keep delivering while users re-subscribe. The
release-gate cannot tell when "legacy form usage has trended to zero"
because the route only emits a fire-and-forget Wide Event warning and
the warning text omits the destination URL anyone watching the access
log would need.

This pass adds:
- An in-memory `withings.webhook.legacy_form_total` counter scoped to
  the process (the right granularity for "since cold-start" usage).
- A `getLegacyFormTotal()` accessor + a test-only reset helper so the
  counter is observable without a backchannel.
- A `counters.withingsWebhookLegacyFormTotal` field on the existing
  `/api/admin/status` payload — the natural surface for ops counters
  alongside the user / measurement / worker blocks.
- The warning text now spells out `/api/withings/webhook/[token]` and
  the "re-subscribe with the path-segment token form" instruction.
- Two new assertions on the webhook test (counter increments on the
  query path, stays at zero on the header path, warning contains the
  migration URL) and one new assertion on the admin-status test.
2026-05-14 22:28:08 +02:00
Marc-André Bombeck 6f3b901c3e fix(workout): reject endedAt <= startedAt + zero-duration PR guard
A workout with `endedAt <= startedAt` produced a non-positive
`durationSec` that downstream consumers treated as a real zero —
worst case a fastest-5km PR of zero seconds, which would lock in
until manual cleanup. Add a `.superRefine` clause on
`createWorkoutSchema` so the ingest gate refuses the row.

The PR detector stays defensive against any pre-gate row or future
code path that bypasses the schema: MIN-direction slots now always
filter `durationSec > 0` regardless of which field carries the PR
value. A MIN slot sorts ascending, so the smallest value wins — a
zero-duration row would always be picked first.

Fix-M / code-M2.
2026-05-14 22:27:32 +02:00
Marc-André Bombeck 733fc2cec7 fix(design): align range-bar zone backgrounds with Dracula tokens
`<RangeBar>` painted its red / orange / green zones in raw Tailwind
palette (`bg-red-500/8`, `bg-yellow-500/12`, `bg-green-500/20`),
while the marker dot already drew from `var(--dracula-red|orange|green)`.
That split meant the zone backgrounds drifted out of the theme on
dark-mode and never tracked the rest of the token surface (PR
badges, alerts, status pills). Swap the zone tints to the matching
Dracula tokens and pin the absence of the legacy raw palette in the
existing extraction-contract test.
2026-05-14 22:27:30 +02:00
Marc-André Bombeck 4a7195a1bc fix(onboarding): 44px touch targets across wizard CTAs + carousel pager
Bring every back / skip / next / chevron / pager button on the
v1.4.25 onboarding wizard up to the 44x44 px WCAG 2.5.8 floor. The
previous `size="sm"` buttons measured 32 px tall, the chevron icons
were 32 px square, and each dot pager target was 10 px square — all
well under the target-size minimum for thumb-driven flows.

Carousel slides now derive their accessible name from the slide
title via `aria-labelledby`, so the polite live region (which
mirrors "Slide N of M") is the single source for position
announcements. The previous markup announced position twice on every
swipe: once from the slide's own `aria-label`, again from the
live region.
2026-05-14 22:26:46 +02:00
Marc-André Bombeck a400e5407b feat(api): tighten POST /api/medications/[id]/glp1 with Zod + audit + rate-limit
The GLP-1 convenience route shipped in W4d skipped the Zod / audit /
rate-limit triple the sibling inventory + side-effect POSTs ship with.
Hand-rolled `typeof === "number"` guards let NaN, Infinity, negative
doses, multi-megabyte notes, and 1970-era timestamps reach Prisma.

This pass adds:
- `glp1DoseChangePostSchema` + `glp1InventoryPostSchema` + the XOR
  `glp1PostBodySchema` in `src/lib/validations/medication.ts`.
- A 500-char cap on `note`, 200-char cap on `reason`, 100 mg cap on
  `doseValue`, integer cap on `delta`, and a +/-5-year window on
  `effectiveFrom`.
- The 30/min/user rate-limit copied from the sibling routes, keyed on
  `medication-glp1:post:<userId>`.
- `auditLog("medication.glp1.update", ...)` for every mutation, tagged
  with the affected row id and the dose / delta values.
- A test fixture mirroring the inventory + side-effect tests with
  thirteen assertions covering the new 422 paths, the rate-limit
  header, and both audit branches.
2026-05-14 22:26:14 +02:00
Marc-André Bombeck 1d5dcfb8b1 perf(inventory): bulk-update expired in-use items via updateMany
The daily cron sweep loaded every stale IN_USE row and issued one
`prisma.update` per row, recomputing the state in JS only to learn
what the selector already proved (state=IN_USE AND expiresAt < now ⇒
the row must transition to EXPIRED, because IN_USE implies
dosesRemaining > 0 and the expiresAt filter shows the deadline lapsed).
Collapse the round-trip onto a single `updateMany` so the cron's cost
is O(1) round-trips per user instead of O(stale rows).

Fix-M / code-H3.
2026-05-14 22:26:01 +02:00
Marc-André Bombeck 1b5906a504 fix(inventory): re-run state machine on markAsFirstUseAt PATCH
A back-dated first-use stamp whose 30-day in-use window has already
lapsed must land at EXPIRED, not IN_USE. The hand-rolled state
transitions in the PATCH route composed the next-row view but never
re-evaluated through the canonical state machine, so the route could
emit an IN_USE row whose expiresAt was already in the past. Wire
`computeInventoryState` over the composed view so every PATCH lands
on the same decision tree the intake hook and the daily expire cron
already share.

Test: ACTIVE pen + markAsFirstUseAt 45 days ago ⇒ EXPIRED.

Fix-M / code-H1.
2026-05-14 22:24:54 +02:00
Marc-André Bombeck 44e8229ff3 fix(logging): redact http.path + http.route in WideEventBuilder.setHttp
Closes the WITHINGS_WEBHOOK_SECRET leak (sec-C1): the api-handler
seeds http.path and http.route from url.pathname, which carries the
shared secret for /api/withings/webhook/<secret> requests. Routing
both fields through redactSecrets() at setHttp() time keeps the
secret out of stdout, the in-memory ring buffer, and Loki egress.
2026-05-14 22:24:42 +02:00
Marc-André Bombeck 8da6a4ae69 feat(logging): path-segment secret redaction via PATH_SECRET_PATHS registry
Adds a registry of URL path prefixes whose trailing segment is a
shared secret, seeded with the /api/withings/webhook/ entrypoint.
The redactSecrets() egress filter now rewrites those segments to
[REDACTED] before stdout, in-memory ring buffer, and Loki egress.
2026-05-14 22:23:49 +02:00
Marc-André Bombeck 4d5c735d18 fix(e2e): use canonical healthlog-locale cookie in locale-switch spec 2026-05-14 22:22:44 +02:00
Marc-André Bombeck c75a68a88c docs(planning): W21 reconcile plan 2026-05-14 22:20:35 +02:00
Marc-André Bombeck f88c275df4 docs(planning): W21 i18n runtime findings 2026-05-14 22:14:26 +02:00
Marc-André Bombeck 65319317cd docs(planning): W21 dead-code findings 2026-05-14 22:08:16 +02:00
Marc-André Bombeck e8139e9f93 docs(planning): W21 simplifier findings 2026-05-14 22:05:18 +02:00
Marc-André Bombeck 5448d19fee docs(planning): W21 code-review findings 2026-05-14 22:03:26 +02:00
Marc-André Bombeck 0f4431cbf1 docs(planning): W21 senior-dev findings 2026-05-14 22:02:38 +02:00
Marc-André Bombeck 94f97fa26a docs(planning): W21 product-lead assessment 2026-05-14 22:01:42 +02:00
Marc-André Bombeck 472da13da7 docs(planning): W21 design findings 2026-05-14 22:01:28 +02:00
Marc-André Bombeck 230e7531b0 docs(planning): W21 security findings 2026-05-14 22:01:16 +02:00
Marc-André Bombeck 51f23ef318 docs(planning): W18 Low + apply-with-care cluster phase report 2026-05-14 21:53:23 +02:00
Marc-André Bombeck 3b5f06d6b3 refactor(insights): extract useInsightStatus hook for sub-page status queries
Five insights sub-pages (blutdruck / bmi / gewicht / puls / stimmung)
each declared the same 13-line useQuery block plus an identical
StatusData interface. The hook routes through the existing queryKeys
factory so the cache keys stop drifting on the next typo. Medikamente
keeps its bespoke query because the compliance-status payload carries
a different shape (per-medication breakdown). Closes W10 simplifier
S12.
2026-05-14 21:51:26 +02:00
Marc-André Bombeck 7d625343f9 docs(planning): note safeRequestProp widening follow-up in W15 phase report 2026-05-14 21:51:04 +02:00
Marc-André Bombeck fcda115123 fix(api-handler): widen safeRequestProp narrow-catch to tolerate undefined requests
Follow-up to commit `61d156e7`. The narrow catch initially recognised
only the V8 private-field TypeError wordings, but unit tests routinely
invoke route handlers as `GET()` with no arguments — the wrapper then
reads `args[0]` as `undefined` and the read callback raises
`TypeError: Cannot read properties of undefined (reading 'url')`,
which is not a private-field error.

The classifier is renamed to `isTolerableRequestProbeError` and now
also matches the "cannot read properties of undefined / null"
TypeError shape (both modern V8 wording and the older
`Cannot read property 'X' of undefined` form). Any other TypeError
still rethrows so production regressions stay visible.

This restores the no-arg-direct-invoke contract that
`src/app/api/auth/me/source-priority/__tests__/route.test.ts` and
similar vitest suites rely on (`GET()` with no request to assert
the auth-gate path returns 401).

Verification:
  pnpm typecheck                                       → clean
  pnpm vitest run api-handler-safe-request-prop        → 11 / 11 pass
  pnpm vitest run src/app/api/auth/me/source-priority  → 6 / 6 pass
  pnpm vitest run (full unit)                          → 3751 / 3751
2026-05-14 21:50:29 +02:00
Marc-André Bombeck bbc0afd555 refactor(analytics): export ContributingSource so its callers stop spelling the union
The literal "manual" | "withings" | "appleHealth" was spelled in
six places across health-score.ts and the analytics route, plus once
in the card. The lib helper and the route now read from a single
ContributingSource alias; the card keeps its local copy on purpose so
the client bundle stays free of analytics imports. Closes W10
simplifier S9 (lib + route scope).
2026-05-14 21:48:24 +02:00
Marc-André Bombeck 4ab0d17808 docs(planning): W15 hygiene cluster phase report
Wave 5 hygiene wave summary covering the four atomic commits and
their verification matrix:
  fddb9754 — 380 dead i18n keys retired (25 false-positives kept)
  41c7425b — BASE_SYSTEM_PROMPT + INSIGHTS_SYSTEM_PROMPT removed
  61d156e7 — safeRequestProp narrow-catch + Tailwind @source base
  76dea94b — Cat-C comment path rewrite on /api/insights/targets
2026-05-14 21:48:11 +02:00
Marc-André Bombeck 76dea94bae chore: Cat-C typo and naming polish from W10 dead-code probe
W10's dead-code candidates report (§C2) flagged a half-quoted reference
inside `src/app/api/insights/targets/route.ts:807`. The comment claimed
the AI prompts lived at `src/lib/insights/prompts/{base-system,
general-status}.ts`, but those files actually sit under
`src/lib/ai/prompts/` and the brace-expansion abbreviation was both
wrong-pathed and easy to misread as a stray-brace typo.

The comment is rewritten in full path form so future readers can grep
the referenced files directly and so the source citation matches the
real location.

Verification:
  pnpm typecheck                         → clean
  pnpm lint                              → clean
  grep -rn 'general-status}' src         → zero hits
2026-05-14 21:46:48 +02:00
Marc-André Bombeck 781e6e180d docs(planning): W20-rest P6 polish phase report
Shipped 3 of 11 P6 polish items in this wave under touch-disjoint
constraints (W15 owns messages/*.json + system prompts, W18 owns
charts core / errors / audit-log / deviceType / drift-guard / CSS
anti-patterns / S1-S12):
  - P6-1 Pearson incomplete-beta replacement
  - P6-3 Coolify auto-deploy maintainer toggle
  - P6-8 GH translation-feedback issue template

Deferred to v1.4.26 (8 items + rationale):
  - P6-2 sentinel HK envelopes (no parser yet)
  - P6-4 Coach lastYear window (spec ambiguity + 9 surfaces)
  - P6-5 Coach prefill on row tap (Wave 4b stable footprint)
  - P6-6 per-night sleep-stage chart (W18 surface + new endpoint)
  - P6-7 locale-native date formats (i18n only — W15)
  - P6-9 hand-review FR/ES/IT/PL prose (i18n only — W15)
  - P6-10 Cat-B endpoint triage (per-endpoint maintainer go/no-go;
    7 recommendations enumerated in the report)
  - P6-11 mood verbal labels (already shipped in v1.4.25 polish pass;
    no remaining surfaces)
2026-05-14 21:46:41 +02:00
Marc-André Bombeck 030896755c refactor(settings): collapse moveSource + moveDeviceType into reorderLadder helper
The two reorder helpers were 21-line near-duplicates that drifted apart
twice during W8c before being realigned. Extracted the shared swap
into a generic reorderLadder<T>() helper so both callers reduce to
read-ladder, call helper, write back. Closes W10 simplifier S3.
2026-05-14 21:46:38 +02:00