Moves the language select into the same `grid sm:grid-cols-2` row as
date of birth and drops the standalone language wrapper plus its
`sm:max-w-xs` clamp. The profile form now carries a uniform two-cell
rhythm from top to bottom instead of alternating between paired and
single-cell rows. Updates the mobile-consistency e2e assertion to match
the new contract: dob + language MUST share a grid row.
Consolidates the six R1 audit reports (R1.1 dashboard, R1.2 settings/admin,
R1.3 coach/insights, R1.4 notifications, R1.5 iOS offline-first research,
R1.6 backlog sweep) plus the 17 backlog items pulled forward into a single
fix-surface plan with seven touch-disjoint buckets, a file-touch collision
matrix with zero same-line collisions and four sequenced edits, and a
Round 3 dispatch sequence (5 parallel + 2 sequenced). Decides /api/audit-log
to DELETE as an orphan endpoint, parks all four iOS server-side preps
(syncVersion, deletedAt, GET /api/sync/state, ETag) to v1.4.28, and adds
22-offline-first-architecture.md to the iOS handoff doc-pack carrying R1.5's
research forward for the iOS-side reader.
Public privacy-policy page at /privacy enumerates every Apple
HealthKit identifier the iOS app reads, names every third-party
sub-processor, and restates the EU MDR + GDPR boundaries. Unblocks
Apple BLOCKER 2 of the iOS App Store Connect submission by giving
the registered Privacy URL a real page to point at.
Logs the production-alarm hotfix shipped in `fec02aa` under a new
"Resolved by v1.4.26" section so the backlog stays honest about what
landed on develop after the v1.4.25 tag.
Legacy v1.4.24-and-earlier Withings connections sit on `user.metrics`
only. W17b/c added `syncUserActivity` + `syncUserSleep` against the
scope-gated `/v2/measure?action=getactivity` and `/v2/sleep?action=get`
endpoints without a scope guard, so every cron tick for a legacy user
hit a guaranteed 403. The catch-block classified the 403 as transient
(the refresh token still worked; only the resource call failed), pg-boss
retried, and the 3-strike admin alert paged Telegram for every affected
user.
Both routines now short-circuit at entry: read `WithingsConnection.scope`,
call `hasActivityScope` from `src/lib/withings/client.ts`, and on miss
park at `error_reauth` via `recordSyncFailure({ kind: "reauth_required",
errorCode: "scope_missing" })` and return 0. The Settings reconnect
banner already in place tells the user what to do; subsequent cron ticks
short-circuit cheaply on `isReauthRequired`.
Defence-in-depth: a 403 reaching the catch-block (race where scope was
revoked between OAuth and the next sync without invalidating the refresh
token) now classifies as `reauth_required` instead of `transient`, so
pg-boss stops retrying and the 3-strike alert stays quiet.
Tests: +4 scope-skip / 403-classification cases per routine (8 total),
defaulting the existing field-mapping + idempotency tests to a
scope-is-fine connection so they stay focused on the write path.
Largest feature delta in the v1.4.x line. Insights expands into seven dedicated metric sub-pages; GLP-1 medication tracking lands end-to-end (drug-level chart with Research Mode acknowledgment, EMA titration ladder, cadence + compliance, side-effect taxonomy, pen/vial inventory); cross-source priority becomes a two-axis resolver; per-user timezone threads through ten analytics surfaces; Withings activity + sleep v2 sync; onboarding rebuilt as a nested-route wizard; Personal Records ship end-to-end; Health Score provenance accordion; Coach runs native first-party prompts across six locales with a 1800-assertion refusal-probe matrix; OpenAPI drift gate hard-fails; multi-arch GHCR image. Migrations 0043 through 0060 are additive and forward-only. PROMPT_VERSION 4.24.0 → 4.25.0 with GROUND RULE 9 (refuses dose recommendations) and GROUND RULE 15 (refuses drug-level estimates with MDR + MDCG 2021-24 cites).
See CHANGELOG.md for the full per-section delta.
Replace the seed skeleton with the final navigation map for the
21-file doc-pack.
Inventory: 21 rows pinned against the actual filenames + final
token estimates (total ~89400 tokens / ~57000 words).
Question → File map: 38 real entries mapping concrete iOS-Claude
questions to file + section anchors. Covers source-priority,
MeasurementType enum, MDR boundary, APNs flow, Withings OAuth,
HealthKit batch ingest, Coach SSE, Health Score, PR detection,
migrations 0051-0060, OpenAPI hard-flip gate, error codes,
Idempotency-Key, rate-limiting, PROMPT_VERSION,
RESEARCH_MODE_DISCLAIMER_VERSION, TanStack Query, chart hex literals,
locale keys, dev server, Simulator API token, v1.4.26 inventory.
Reading-orders-by-goal: 16 scenarios with file lists + estimated
cumulative tokens. Cold-start, tag-a-release, new endpoint, Coach
feature, Apple Health sync, workout ingest, GLP-1 work (critical
research-first), pre-PR gate, screen design, Settings → Sources,
Health Score tile, Withings reconnect, onboarding wizard, CI setup.
Stop-here-markers index: per-file summary of what each file's STOP
HERE block (or inline warnings) covers, so iOS-Claude can lookup
and exit.
TL;DR refresh: 2 sentences pinning v1.4.25 stack + v1.5 = iOS +
deeper Apple Health.
Cross-link audit: every <file>.md reference in every sibling now
resolves to a real file. 16 broken references found + patched in
the prior commit.
Sibling docs (00..20 except README) referenced 16 file names that don't
exist in the final pack — names like 10-coach-pipeline.md, 12-ai-coach.md,
15-withings-bridge.md, 17-personal-records.md, 18-onboarding.md,
19-deploy-runtime.md, 02-architecture.md, 03-system-overview.md,
10-architecture.md, 12-ai-providers.md, 13-medical-content.md,
09-ui-state.md. Every one mapped to a real file in the final pack;
patched all cross-links in:
- 00-philosophy.md (STOP HERE table)
- 01-repo-tour.md (deploy link + STOP HERE table)
- 02-server-architecture.md (6 Detail-in references + STOP HERE table)
- 03-api-contracts.md (STOP HERE table)
- 04-data-model.md (prerequisites + What is NOT in this file)
- 05-auth-flows.md (What is NOT in this file)
- 06-ios-responsibilities.md (prerequisites)
- 07-server-responsibilities.md (prerequisites)
- 08-locked-contracts.md (What is NOT in this file)
- 11-web-ui-tour.md (prerequisites)
- 12-design-system.md (prerequisites)
- 13-state-management.md (prerequisites)
- 14-coach-mental-model.md (prerequisites)
- 17-error-handling.md (What is NOT in this file)
- 18-pattern-cookbook.md (prerequisites)
- 19-i18n-system.md (prerequisites)
- 20-glossary.md (multiple Coach + provider references)
Every cross-link in the doc-pack now resolves to an existing file or to
a section heading inside an existing file.
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.
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.
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.
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.
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.
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.
- 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).
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.
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.
`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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
`<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.
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.
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.
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.