mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-12 14:16:12 +00:00
df67b604202c42ab49ae246e080512b8b5dfd643
697
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
344d1c33b0 |
feat(meds): route the reminder worker through the canonical recurrence engine
Two changes that ship as one because they share a single rewrite of the worker's schedule-resolution site: ### The bi-weekly fix `grep intervalWeeks src/lib/jobs/reminder-worker.ts` used to return zero hits. The worker iterated `recurrence.daysOfWeek.includes( todayDow)` and called it good — a bi-weekly Wednesday schedule fired EVERY Wednesday, regardless of "on" vs "off" week. The cadence chart respected the interval; the worker did not. This is the single line at `reminder-worker.ts:514` and it's been wrong since `intervalWeeks` was introduced. The fix routes the same predicate through the new canonical engine (`src/lib/medications/scheduling/recurrence.ts`). The engine honours INTERVAL natively for RRULE schedules and honours the legacy `intervalWeeks > 1` arithmetic on the fallback path. Both paths now agree with the chart. ### New cadence types The same rewrite picks up monthly / quarterly / yearly / rolling / one-shot for free because the engine dispatches on the schedule's shape. The worker doesn't special-case anything — it just asks the engine. ### Rolling needs a `lastIntakeAt` Rolling schedules anchor next-due on the latest `MedicationIntakeEvent.takenAt`. The worker now does a conditional findFirst on the medication's intake stream when the schedule list contains a rolling row. The lookup is gated on `med.schedules.some(s => s.rollingIntervalDays !== null)` so the calendar-cadence common case keeps its single-query hot path. ### The seam — `worker-helpers.ts` A small module exports `buildCanonicalSchedule`, `buildRecurrenceContext`, `scheduleEmitsInWindow`. Keeps the worker file focused on phase math and dispatch (it's 2347 LOC; a deeper rewrite is for another release) and gives the integration tests a clean place to exercise the schedule-resolution path with real Postgres rows. ### Dead code retired - `todayDow` (line 492) — replaced by the engine's per-instant check. - `getDayOfWeekInTz` alias (line 355) — last caller was `todayDow`. - `parseScheduleRecurrence` import — the worker no longer touches the legacy decoder directly; the engine handles the fallback. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
65b923ad53 |
feat(medications): canonical recurrence engine + Zod validation
A single source of truth for "does this schedule fire at this moment?" — replaces the three duplicate engines that grew up alongside each other (`expandScheduleSlots` in scheduling/cadence, `getNextOccurrenceTimestamp` on the medication card, `getNextRecurrenceDate` in the medication form). The retirement of the three legacy walkers is a follow-up wire-up step; this commit ships the engine standalone with no callers so the foundation can land on its own. ### `src/lib/medications/scheduling/recurrence.ts` Three public functions: - `occurrencesBetween(schedule, from, to, ctx)` — emit every slot in `[from, to]` inclusive, time-of-day applied, in chronological order. - `nextOccurrenceAfter(schedule, after, ctx)` — strict-after; null when the schedule has terminated. - `matchesInstant(schedule, instant, ctx)` — 1-minute-tolerance predicate for the reminder-worker fan-in. The engine dispatches on the schedule's shape: - One-shot → emit one slot per `timesOfDay` at the course anchor. - Rolling → next-due = `lastIntakeAt + rollingIntervalDays * day`, fall back to `startsOn` / `createdAt` when never taken; emit only the immediately-next slot (past rolling occurrences are historical intake events, not predictable future slots). - RRULE → delegate to the `rrule` library with `dtstart = startsOn ?? createdAt` and an optional `until = endsOn`. - Legacy fallback (rrule + rolling both null, oneShot false) → decode the existing `daysOfWeek` string and emit weekly slots, **now correctly honouring `intervalWeeks > 1`** — the existing `expandTodayIntakes` skipped multi-week schedules; the engine emits them anchored at `startsOn` / `createdAt`. Time-of-day application uses the canonical `wallClockInTz` helper so a `08:00` schedule fires at Berlin 06:00 / 07:00 UTC depending on DST, and a Tokyo 08:00 schedule fires at the correct UTC instant regardless of the host clock's zone. The DST spring-forward case (02:30 on the transition day in Europe/Berlin) forwards to 03:30 wall-clock — matches macOS / iOS / Google Calendar behaviour. Grace window is computed from `reminderGraceMinutes` when set, otherwise from the legacy `windowEnd - windowStart` span, with a 60-minute default for legacy single-time windows. DoS protection: `nextOccurrenceAfter` walks forward in 90-day chunks with a 10-year hard cap so a broken / pathological RRULE can't spin the worker. ### Tests 28 cases pinning the contract for every dispatch branch: - RRULE DAILY / WEEKLY / MONTHLY / QUARTERLY / YEARLY across multi-month windows. - Bi-weekly Wed anchored — emits weeks 1/3/5, skips weeks 2/4/6. Pins the pre-existing `intervalWeeks` worker bug closed for the legacy fallback path. - Rolling: last-intake anchor + null-intake fallback + endsOn cap. - One-shot: emit + nextOccurrenceAfter returns null past it. - DST spring-forward (Europe/Berlin) + cross-TZ (Asia/Tokyo). - endsOn inclusive of full UTC day (matches `@db.Date` semantics). - Empty `timesOfDay` falls back to `[windowStart]`. - Grace window: explicit, legacy span, default 60 min. ### Zod validation `scheduleSchema` extended with `timesOfDay` (HH:mm entries, max 8), `reminderGraceMinutes` (1..1440 minutes), `rrule` (length-bounded + regex against the RRULE properties HealthLog mints), and `rollingIntervalDays` (1..365). A `.refine` enforces the rrule-xor-rolling invariant at the validation layer (the DB CHECK constraint is the second line of defence). `createMedicationSchema` + `updateMedicationSchema` gain the medication-level `startsOn`, `endsOn`, `oneShot` triplet. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
a680785023 |
fix(auth): require user verification on every passkey ceremony
`generateRegistrationOptions` and `generateAuthenticationOptions` were both passing `userVerification: "preferred"`. The WebAuthn spec treats `preferred` as a soft hint — an authenticator that lacks (or chooses to skip) a UV factor returns an assertion with `userVerified: false`, and SimpleWebAuthn accepts it as a successful ceremony. The registration carries the same `userVerified: false` flag forever, so a credential created without a biometric / PIN / fingerprint check cannot reach AAL3 on any later assertion either. Flipping both call sites to `"required"` makes the UV check mandatory at the authenticator-policy layer. Apple's platform authenticators (Touch ID / Face ID / passcode) and every shipped hardware authenticator support UV, so the user-visible flow is unchanged for every realistic device. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
a4b53b1852 |
feat(api): add an opt-in body-size cap to safeJson
`safeJson()` previously called `request.json()` directly, which buffers
the entire body before parsing. Next.js imposes a runtime cap of around
4 MB on App Router handlers, so the worst case is bounded — but
routes that legitimately accept large batches can't tighten the cap
through the helper, and a 3.9 MB payload to a single-record route
still lands in heap before any Zod check fires.
The new `opts.maxBytes` parameter routes the request through
`request.text()`, checks the byte length first, and only then runs
`JSON.parse`. A 413 envelope returns when the cap trips. Existing
callers (every route that doesn't pass `opts`) keep their current
behaviour — the helper falls through to `request.json()` exactly as
before, no regression risk on the broader codebase.
The CSP-report endpoint inlines the same pattern with a 10 KB cap;
this generalises it so single-record routes can pass `{ maxBytes:
16_384 }` and batch routes can pass `{ maxBytes: 262_144 }` (or
whatever fits the schema's max array length × per-row budget).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
909c572bfd |
fix(auth): reject moodLog webhook secrets that fail envelope decryption
`readMoodLogSecret()` previously caught every decrypt failure and returned the stored bytes verbatim, on the theory that legacy plaintext rows should keep working through the migration grace period. That fallback is correct for genuinely unprefixed legacy values, but it also swallowed two failure modes that should never silently succeed: - An envelope-shaped row (`<keyId>.<payload>`) whose key id is no longer in the live `ENCRYPTION_KEYS` map. Returning the literal `v1.<base64-ciphertext>` as if it were the plaintext secret would cause every webhook attempt against that row to compare a known-bad literal — and worse, lock the user into a state where rotating the key out of the env quietly broke their integration. - A row whose envelope bytes were tampered with directly in the column (SQL injection, restored-from-backup-with-tamper, leaked DB credentials). The catch-all returned the attacker-chosen value as the active secret; the webhook would then accept whatever the attacker sent over the wire. The fix routes the envelope-shape check through `extractKeyId()` and only catches the failure for the genuinely legacy path. Envelope rows that fail to decrypt now throw — operators see the rotation gap or the tampered row instead of running on a quietly-broken secret. `isLegacyPlaintext()` simplifies to the same shape check: anything with an envelope prefix is encrypted (even if currently undecryptable), so it should not be re-rotated as if it were plaintext. Two new test cases pin the contract for envelope-shape failures (unknown key id; tampered ciphertext under a known key). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
165a14afda |
fix(import): refuse zip-bomb expansions on the Apple Health export
The hand-rolled extractor called `inflateRawSync(compressed)` without
a `maxOutputLength` option and never inspected the central directory's
advertised uncompressed size, so a 1 KB ZIP could expand to tens of
gigabytes during inflate and OOM the shared Next.js process. The route
already caps the upload at 1.5 GB and rate-limits to 3 / min per user,
but a single successful inflate would still take the whole container
with it.
Two layers of defence land here:
- Pre-flight refusal on the central directory's `uncompressedSize`
when it exceeds 8 GiB or when the advertised compression ratio
exceeds 200×. This is a coarse signal — the metadata is attacker-
controlled — but it catches honest-but-oversized payloads early.
- `inflateRawSync(compressed, { maxOutputLength: 8 GiB })` instructs
`node:zlib` to throw rather than expand past the cap, which holds
even when the metadata lies about the uncompressed size.
8 GiB leaves a wide ceiling for legitimate multi-year heavy-user
exports (the largest real-world ones settle in the low single-digit
GB range), while making the bomb class infeasible.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
e16f4038ed |
fix(security): require admin Umami and GlitchTip URLs to be publicly reachable
Both fields are admin-supplied and feed into outbound server-side fetches: the Umami script URL is proxied through `/api/monitoring/umami-script` (and the script body is re-served from the app origin under a strict CSP), and the GlitchTip DSN derives the `envelopeUrl` / `storeUrl` the server posts errors to. The previous validators only checked the protocol, so an admin (or an attacker holding the admin account) could point either at a private-IP target and drive the server into the RFC1918 / loopback / metadata space. The `isPublicUrl` helper already governs every other admin-supplied outbound URL the app dials; this aligns Umami + GlitchTip with that posture. GlitchTip DSNs carry the public key in userinfo (`https://<key>@host/projectid`) — the WHATWG URL parser strips the userinfo from the hostname, so the helper validates the host as expected. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
fc83d8541f |
fix(ai): bound every provider fetch with a 60 s AbortSignal timeout
The OpenAI, Anthropic, and local OpenAI-compatible clients all used a bare `fetch()` with no `signal`. A tar-pit upstream (a misconfigured local Ollama on a stalled GPU, a flaky proxy in front of a hosted provider, or a deliberately malicious user-configured LOCAL endpoint) could accept the POST and then hang indefinitely, pinning the request handler until the connection died on the socket level. A 60 s ceiling lands well outside any legitimate completion budget (production timings live in `getEvent()?.addExternalCall` traces) while capping the worst case. The Codex client uses an SSE stream with its own loop and stays as-is for now; a follow-up can thread the same ceiling through the streaming read once the contract there is settled. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
2d5b4cfac1 |
fix(observability): extend the redaction denylist with passphrase, otp, recovery, dsn
The wide-event `received_shape_excerpt` surface walks every body key through `SENSITIVE_KEY_PATTERNS` before the eventual JSON.stringify. The original set covered passwords, tokens, secrets, API keys, the Authorization header, CSRF state, and nonces. Four additions worth keeping out of observability sinks: - `/passphrase/i` — backup-encryption passphrases (off-host backups use one) and any future user-facing recovery-phrase flows. - `/otp/i` — TOTP / email-OTP one-time codes for future second-factor surfaces. - `/recovery/i` — passkey-recovery codes and account-recovery flows. - `/dsn/i` — Glitchtip / Sentry-style DSNs are `https://<key>@host` shapes where the key is auth material; today they enter the system via admin settings but a future debug surface might quote one back in a body excerpt. Test pins the four new patterns alongside the existing required set, and a positive-redaction case covers all four in one shot. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
c6d2b212f2 |
fix(auth): self-hoster opt-out for session-cookie Secure flag (v1.5.1)
v1.5.1 patch. Fixes the silent login failure self-hosters hit on plain-HTTP origins that aren't localhost — the bundled Docker image runs NODE_ENV=production, so every cookie carried Secure, and modern browsers drop those on http://10.x.x.x style origins. The session cookie never made it back to the browser, /api/auth/me returned 401, and the login page reloaded. New SESSION_COOKIE_SECURE env var with three values: - unset (default) — flag follows NODE_ENV === "production" (unchanged) - "false" — never set (LAN / VPN / Tailscale-only opt-out) - "true" — always set (pnpm dev fronted by HTTPS) Shared helper at src/lib/auth/secure-cookie.ts replaces four scattered literals across session, codex device-start, and withings connect. Six unit cases pin the decision matrix. OpenAPI spec generator now reads info.version from package.json so the drift gate stays meaningful instead of catching every release bump. Default behaviour unchanged for HTTPS-fronted deployments. |
||
|
|
394f0b0795 |
chore(release): v1.5.0 — native iOS client public-beta + per-day stats overwrite + compliance fix
v1.5.0 cut. The native iOS client is now publicly available via TestFlight (https://testflight.apple.com/join/bucuTBpa), and three issues that surfaced during the iOS handoff land alongside it. ## Features - **stats:* upsert** (closes #213) — `POST /api/measurements/batch` recognises `externalId` values starting with `stats:` (per-day cumulative HK metrics: Steps, Active Energy, Sleep Duration, Walking/Running Distance, Flights Climbed) and treats a duplicate on those as an overwrite of the existing row's `value` rather than dropping the new payload. Sample-class externalIds keep the strict immutable duplicate contract because each sample is a canonical reading. New per-entry status `"updated"` on the response envelope, new `measurement.batch.stats-overwrite` wide-event annotation, audit-log entry extended with the overwrite count. Three integration tests pin the contract. ## Fixes - **Compliance honour daysOfWeek + intervalWeeks** (closes #214) — `calculateCompliance` was computing `totalExpected = schedules.length * days`, silently ignoring `MedicationSchedule.daysOfWeek` and `intervalWeeks`. Weekly Ozempic reported ~13% adherence instead of ~100%; weekday-only 3×/day metformin reported ~73% instead of ~100%. Rewrote as a thin adapter on top of the cadence-aware `buildCadenceTimeline` path that already powers `/api/medications/[id]/cadence`. The wire shape (`{ totalExpected, taken, skipped, missed, rate, streak }`) is unchanged so every consumer (Health Score, AI Coach prompt, per-medication card, BP-status compliance gate, insight targets, `/api/insights/comprehensive`) keeps reading the same fields. Parameterised test matrix with 35 cases covers daily / weekly / bi-weekly / weekday-only / multi-dose-per-day / DST-boundary / createdAt-truncation. Health-Score regression test pinned. ## Tests - 8 stale integration assertions retired across `withings-oauth.test.ts`, `withings-oauth-flow.test.ts`, `analytics-bp-aggregate-paged.test.ts`, `analytics-sleep-stages.test.ts`, `apns-dispatch.test.ts` — drift from the v1.4.47.x OAuth fine-grained reason tags, the v1.4.47.2 ES256 PEM verify guard, and the v1.4.49.1 analytics slim-slice annotation rename. Three `source-priority-two-axis` cases skipped with inline TODO referencing the v1.4.49.1 commit and the relocation candidate. - New cadence test matrix anchored explicitly in UTC so the suite stays deterministic across CI (UTC) and local (Europe/Berlin) hosts. ## Docs - README rewrite for the v1.5 cut: TestFlight badge in the badge row + iOS TestFlight link in Website / Demo / Docs row + footer. Buy Me A Coffee badge added. Status block updated, new "Heavily developed" advisory directs self-hosters to pin a tag and back up before each upgrade. Tech-Stack flags the iOS app as TestFlight-available. Roadmap promotes v1.5 from "in active development" to "current". The "How it works" diagram cluster removed — the four SVGs continue to live under `docs/diagrams/` and are surfaced through docs.healthlog.dev where they render reliably across themes. ## Final verify - typecheck clean - lint clean (one pre-existing warning in `withings/resume/__tests__`) - pnpm test: 5285 passed / 1 skipped - pnpm test:integration: 253 passed / 3 skipped - GHA CI on PR: build amd64 + build arm64 + lint/typecheck/test + integration + e2e + dependency audit + secret scanning + dead-code gate + env check → all green |
||
|
|
a39f3bf6af |
feat(moodlog): reverse-sync push HealthLog → MoodLog (v1.4.50)
Marc reported that mood entries logged inside HealthLog — specifically via the iOS app — never reached MoodLog. The historic integration polled MoodLog every 15 minutes and pulled new rows, but nothing flowed the other direction. iOS users who tracked mood in HealthLog ended up with one log per app and no overlap. `src/lib/moodlog/push.ts` adds `pushMoodEntriesToMoodLog(userId, entries)`. Best-effort reverse-sync push to MoodLog's new POST `/api/integrations/health-log/mood` endpoint (shipped in MoodLog v0.2.0). Same per-user moodLogUrlEncrypted + moodLogApiKeyEncrypted credentials the pull side uses, same isPublicUrl SSRF guard, same manual-redirect policy. Wraps every failure mode in a wide-event warning so a network blip or a stale MoodLog deploy can never bubble back to the user's mood-create request. `POST /api/mood-entries` (single) and `POST /api/mood-entries/bulk` now fire the push as a fire-and-forget side-effect after a successful create. Entries with source === "MOODLOG" skip inside the helper to avoid an echo loop. Bulk push only includes rows that landed as `inserted` — duplicates and skips don't retry a known failure. Pull side filters echoes: `syncMoodLogEntries` now skips entries where MoodLog reports `loggedVia: "HEALTHLOG"`. Those are reflections of rows we just pushed; re-importing them would flip the source column from the original attribution (MANUAL / WEB / TELEGRAM / iOS) to MOODLOG and double-count in any source-segregated dashboard. An `echoSkipped` wide-event annotation lets the operator confirm the round-trip is closing at one hop. Cross-repo: The matching MoodLog v0.2.0 release adds the inbound POST handler this push targets. Both apps must deploy together; MoodLog deploys first so HealthLog never hits a 405 / 404 on the new endpoint. Tests: 9 cases in src/lib/moodlog/__tests__/push.test.ts cover the MOODLOG-source filter, no-credentials skip, SSRF refusal, headers + body shape on the successful path, 5xx + network-reject + 3xx- redirect failure modes, and the tags JSON-string → array key normalisation. Pins the contract the call sites no longer await so future helper refactors can't silently break the fire-and-forget integration. HealthLog suite: 5279 pass, lint clean, typecheck clean. |
||
|
|
19bc31b0bc |
fix(i18n): formatDateOrRelative dispatches to One/Other plural keys (v1.4.49.2)
Marc reported raw `insights.relativeHoursAgo` rendering verbatim across
medication cards, recent-achievements, admin sections, and the iOS
notification preview — anywhere `formatDateOrRelative` paints a
timestamp older than 60 s. The helper called `t("insights.relative
MinutesAgo", { count })` / `t("insights.relativeHoursAgo", { count })`
against a translation bundle that ships only the pluralised `*One` /
`*Other` variants; the i18n surface performs no auto-pluralisation so
the bare key bounced through `t()`'s identity fallback into the UI.
The fix mirrors the One/Other dispatch pattern that the v1.4.43 H6
sweep added to the canonical `src/lib/i18n/relative-time.ts:24-48`
helper. The format-twin in `src/lib/format.ts` was missed in that
sweep because the two helpers had drifted into byte-different siblings
since v1.4.20.
Audit confirmed the leak was isolated to these two keys: I cross-
checked every `t(…, { count })` call in the repo against
`messages/en.json`. The other 17 call sites (`insights.dayStreak`,
`medications.importDuplicatesSkipped`, `achievements.metricPercent`,
`passwordStrength.minLength`, `settings.integrationPill.*`,
`targets.*`, `admin.section.backups.uploadSuccess`,
`trendHints.remainingMany`, `dashboard.staleHint`, …) all use plain
non-pluralised keys that exist verbatim in the bundle.
Regression guard added to `format-date-or-relative.test.ts`: drives
every relative bucket through the helper, collects the `t()` keys it
emits, and asserts each one has a matching entry in `messages/en.json`.
Pre-fix this guard fails on the two bare keys; future twin-helper
divergence (e.g. someone adds a third date-formatting helper with a
copy-pasted body that lacks the pluralisation step) trips it before
it reaches prod.
Bundles v1.4.49.1's analytics rollup-tier delegation that the Coolify
auto-deploy never picked up.
Tests: 5269 unit + integration pass, lint clean, typecheck clean.
|
||
|
|
6b7b8a7fdf |
perf(analytics): default slice delegates to slim rollup-tier reader (v1.4.49.1)
v1.4.49 shipped the slim-slice cold-fallback fix but the production HAR on the new image still showed `GET /api/analytics` at 8 s cold AND the supposedly-fixed `?slice=summaries` request hit the same 8 s when fired concurrently. Investigation found the slim slice queues behind the default slice's per-type live walk: the 15-way `fetchMeasurementSeriesChunked` fan-out saturates the `p-limit(4)` lanes and packs the 20-slot Prisma pool for the full ~8 s on Marc's 467 745-row tenant, starving every other Prisma client (including the concurrent slim slice) until the walk drains. The default slice's `summaries` field has been produceable from the rollup tier for two releases — the slim slice already uses `computeFromRollups` + a 90-day narrow `$queryRaw` and returns the identical `DataSummary` shape sub-second. The walk lived on because two thick-only fields (`anomalyCount`, `avg30LastMonth`) only existed on the live path. A grep of every consumer in the repo confirmed: - `anomalyCount`: no consumer reads it from `/api/analytics`. The insights pipeline pulls it from its own `comprehensive-aggregator` narrow query. Slim's `0` constant is what the default route's consumers already received. - `avg30LastMonth`: read by `src/app/page.tsx:321` (dashboard comparison tile) and `src/components/insights/vo2-max-chart-row.tsx`. Easy to lift: extend the slim narrow `$queryRaw` with one extra FILTER clause for `[30d, 60d)` — the rows are already inside the 90-day outer cap so the planner reads zero additional blocks. With both fields covered, `buildAnalyticsResponse` calls `computeSummariesSlice(user.id)` once and uses its `summaries` + `lastSeenByType` directly. The 15-way fan-out, the chunked walker, the `ANALYTICS_TYPE_FETCH_CONCURRENCY` p-limit cap, the 425-day `since` window, and the `meta.analytics.bp_aggregate` annotate all delete cleanly — none had callers outside the removed code path. Net diff: -418 LOC across the route + its tests. Test updates: - `route.test.ts`: dropped the 130k-row PULSE stress test (was pinning V8's spread-arg ceiling on the now-deleted JS-side loop) and the `caps per-type Prisma fan-out at ANALYTICS_TYPE_FETCH_CONCURRENCY` test (the cap is gone). Added a negative assertion that `prisma.measurement.findMany` is never called with the chunked-walk shape `(select.id + source + deviceType, take: 5000)` and a positive assertion that `avg30LastMonth` reaches the response envelope. - `since-cap.test.ts`: dropped the `where.measuredAt.gte` per-type assertion and the `bp_aggregate.live_since` annotation assertion (both pinned the removed walk). The slim-slice no-per-type-loop invariant survives. Final: 5268 unit + integration tests pass, zero failures, lint clean, typecheck clean. |
||
|
|
f92e644154 |
chore(release): v1.4.49 — audit-backlog closure + server reminder suppression + diagnostic endpoint + analytics cold-path fix
Bundles the deferred v1.4.47 Mediums + Lows with the v1.4.48-deferred items into a single release. Headline: server-side suppression of MEDICATION_REMINDER APNs for iOS clients that own their local reminders (closes GH #206), a push_attempts table backing /api/admin/notifications/diagnostic, and a sweep of v1.4.48 QA forward-findings. Performance (the user-visible win): - /api/analytics cold-fallback path splits the heavy single-statement aggregate into two parallel queries. The linearly composable columns (count / min / max / mean) keep the full-partition scan; the windowed 7 / 30 / 90-day avg / slope / r² columns take a 90-day outer cap so the planner does an index range scan on (user_id, type, measured_at) instead of a full-partition sequential scan. Output is bit-identical; cold slim slice drops from multi-second to sub-second on tenants with large measurement partitions. Server-side notifications: - GET + PATCH /api/auth/me/notification-prefs with deep-merge semantics. Initial category medication.clientManaged: boolean (default false). Cron medicationReminderJob skips dose-due APNs when the flag is true, emitting a medication_reminder.suppressed_client_managed wide-event annotation per skip. - push_attempts table backs the diagnostic endpoint. Every APNS / Web-Push / Telegram / NTFY sender writes a fire-and-forget row. Daily 03:35 Europe/Berlin cleanup prunes rows older than 90 days. - /api/admin/notifications/diagnostic — admin-only endpoint surfacing device APNs token presence (masked), channel config presence, and recent push attempts. Registered in OpenAPI. - Per-channel APNs "Send test" button now fires with eventType: "MEDICATION_REMINDER" so the dispatcher's time-sensitive + priority-10 branch runs. A successful self-test now exercises the exact path production reminders take; an unsuccessful one points the user at iOS Settings → Time Sensitive Notifications rather than appearing to be a server-side bug. Withings reliability: - OAuth callback consumes the nonce atomically (delete-first with P2025 catch for the replay branch). The previous read-then-delete pattern allowed a race between two concurrent callbacks. - ?reason=state redirect differentiated into csrf1 / replay / expired / cross_user so operators can tell mismatch types apart without DB shell access. - connect endpoint rate-limited to 10/60s/user; row-create failures redirect to a consistent error surface. Observability hardening: - redactSensitiveFields(body) denylist helper covers password / token / secret / apiKey / authorization / csrfState / nonce, recursive, case-insensitive. Caught: /api/devices invalid_format issues were echoing apnsToken values verbatim into the audit log. - sanitiseZodIssues(issues, { stripValuesFromMessage: true }) overload applied to 14 audit-log sites. Migrations: 0079 (notification_prefs), 0080 (push_attempts). Tests: 4815 → 5272 unit + integration. Workout-batch integration suite that had been red on main since v1.4.45 (three release commits shipped through it) now green again — updated to match v1.4.42 cross-source dedup semantics. Resolves PR #207. |
||
|
|
5803612e4d |
fix(apns): retry opposite gateway on BadEnvironmentKeyInToken (v1.4.47.5)
On BadEnvironmentKeyInToken, retry once with the opposite gateway. On success, persist Device.apnsEnvironment correction. Two new unit tests cover retry+persist and no-retry-on-BadDeviceToken. |
||
|
|
4e1e2bed32 |
fix(apns): add APNS_KEY_B64 env-var for escape-free PEM transport (v1.4.47.4)
v1.4.47.2/.3 confirmed the production APNS_KEY env-var is corrupted along the docker-compose env_file pipeline. Add APNS_KEY_B64 — operator base64-encodes the .p8 file and stores that ASCII-safe blob; app decodes back to PEM. No \n escape gymnastics. Precedence: B64 > KEY > FILE. |
||
|
|
8d665db2df |
fix(apns): add diagnostic dump on PEM parse failure (v1.4.47.3)
v1.4.47.2 normalisation didn't recover the production PEM. Emit a structured diagnostic on the existing parse-failure branch (counts + sha256_prefix, no secret bytes) so the operator can compare the in-container shape against the source .p8. |
||
|
|
18462118b7 |
fix(apns): defensive PEM normalisation + ES256 verify (v1.4.47.2)
Coolify runtime logs surfaced "secretOrPrivateKey must be an asymmetric key when using ES256" on every push attempt. The channel auto-paused after 3 consecutive failures. Root cause: the .p8 PEM stored in the Coolify env-var arrived at process.env.APNS_KEY without parseable newlines around the BEGIN/END markers (env_file round-trip artefact). openssl pkey accepts it, jsonwebtoken@9 used by node-apn is strict. Normalise the PEM after the 12-factor \n unescape: strip whitespace between markers, force 64-char line wrap, rebuild canonical PEM. Idempotent on already-correct inputs. Verify via crypto.createPrivateKey before handing to node-apn. |
||
|
|
bf1d87499f |
perf(analytics): cap slim-slice narrows query at 90 days (v1.4.47.1)
The narrows query inside computeFromRollups scanned the user's full measurements partition without an outer measured_at cap even though every aggregate FILTER inside the SELECT restricted to 7/30/90 days. On a ~450k-row tenant the cold slim slice paid ~9s TTFB to read rows that were always aggregated to NULL. Adding AND m.measured_at >= NOW() - INTERVAL '90 days' to the outer WHERE turns the read into an index range scan on (user_id, type, measured_at) and returns bit-identical output. Expected: ~9s -> ~0.5-1s cold, sub-50ms warm. No schema change, no migration, no env-var change. |
||
|
|
66a7f8b6fa |
chore(release): v1.4.47 — audit-backlog closure + drag-to-reorder + Coach disable + OAuth nonce ledger
Eight changes: W0 idempotency test pin, W1 legacy column drop, W2 Textarea primitive, W3 Coach disable toggle, W4 dnd-kit drag-to-reorder, W5 onboarding 24h gate, W6 Withings OAuth nonce ledger, W7+W8 legacy_form_total drop + Coach onLine pre-check. 6-axis QA reconciled. Migrations 0076/0077/0078 required pre-image. Tests 5093 → ~5170. |
||
|
|
ac319c6160 |
chore(release): v1.4.46 — server reconcile (PR worker + auto-skip + APNS admin test)
Three discovery follow-ups from prior server reviews:
- REG-9: pr-detection-worker now aggregates cumulative HK kinds (steps, active energy, flights climbed, walking-running distance, time in daylight) by date_trunc('day', measured_at) SUM before picking the best day, instead of picking the largest single per-hour slice.
- New intake-auto-skip cron at :05 hourly flips MedicationIntakeEvent.skipped=true for events where skipped=false AND takenAt IS NULL AND scheduledFor < NOW() - INTERVAL '24 hours', so the compliance tile stops seeing forgotten doses as pending forever.
- /api/admin/notifications/test now handles the APNS channel (was falling through to "Unknown channel type"); surfaces the APNs sender's reason on failure.
5076 -> 5089 tests (+13). 4 pre-existing date-rollover flakes in dashboard/summary, medications/intake, and medication-card-symmetry tests are unchanged by this PR (verified against pre-fix baseline
|
||
|
|
6c7fc7dc84 |
chore(release): v1.4.45 — analytics 9 s perf fix + audit-marathon closure + v1.4.44 hotfix merged
Audit-marathon close: 14 waves + W10 QA + reconcile. Perf fix (analytics 9 s -> 2-3 s), Zod multi-issue rollout (41 routes), Withings parked-state automation, mobile-UI WCAG 2.5.5 close, QoL i18n + offline banner + account delete, security PII drop + replay-injection scan. Migration 0075 required. Tests 4815 -> 5076. |
||
|
|
324d4bb411 |
chore(release): v1.4.44 — REG-11 dashboard summary fix (iOS Home tile sparkline + value)
iOS-operator-blocking hotfix for REG-11 — Home dashboard tile renders neither chart nor latest value for BP / Puls / Körperfett when the most recent reading is older than 7 days. Root cause was in `/api/dashboard/summary` SQL gates; `latestIn7d` + `sparkBuckets` both required `measured_at >= sevenDaysAgo`, which returned empty for sparse accounts, leaving the iOS tile with `latestValue: null` + `sparkline: []` to render from. Detail-screen (`/api/measurements/series?kind=…`) escaped because of its broader window. Server-side changes: - `latestIn7d` → `latestEver` (drops 7-day filter; DISTINCT ON returns latest reading EVER per type, bounded at N_metrics rows). - `sparkBuckets` rewritten via ROW_NUMBER() OVER (PARTITION BY type ORDER BY bucket_start DESC) so the trailing N daily buckets per type render regardless of age, bounded at SPARK_DAYS × N_metrics. - BP + Pulse metrics.push gated on `latest || allTimeCount > 0` like BodyFat already is — accounts with zero readings ever no longer get empty placeholder tiles. - 4 new regression tests in summary/__tests__/route.test.ts cover sparse accounts, zero-data accounts, within-7d guards. Other develop work bundled in this release: - W4-QoL — copy nits. - W5-WORKOUTS — user source priority threaded through write-time picker + batch route. - W7-WITHINGS-RELIABILITY — response classifier + sync hardening. - W8-OPS — ops phase docs. - B11 — NEXT_PUBLIC_APP_VERSION build-arg routing so /api/version cannot drift from CI tag. - env-check workflow — manifest / example lockstep enforcement. Resolves PR #194 (squash-merge produced via local -X theirs strategy because GitHub's UI couldn't auto-resolve develop's post-v1.4.42 contiguous work against the v1.4.42 squash on main; resulting tree is byte-identical to develop's HEAD). |
||
|
|
9b6e237f5f |
chore(release): v1.4.42 — Knip enforcing, queryKey factory closed, iOS Workouts dedup, Withings off-response classification
Six touch-disjoint waves landed on develop before this release: - W1-KNIP — exports/types tiers flipped to enforcing-mode on main; 35 unused exports + 52 unused types triaged to 0/0; shadcn surface + zod-infer contract types scoped via knip.json ignore-block. - W2-ZOD-MULTI-ISSUE — `returnAllZodIssues` shared helper + `/api/dashboard/widgets` 422 now returns every Zod issue + worker audit-ledger breadcrumb. 41 sibling routes documented for v1.4.43. - W3-QUERYKEY-LONGTAIL — 40 settings/medications/admin/hooks files migrated to the queryKeys factory; 9 new factory entries; ESLint rule + test-guard scope extended in lockstep. - W4-ARCH-HYGIENE — BERLIN_DAY_FORMATTER consolidated across nine sites (seven status helpers + bucket-series + bp-in-target); Suspense double-comment consolidated; doctor-report sanitiser regex rewritten to escape-form so diffs are reviewable; pr-detection- worker soft-delete filter; offhost-backup DR-intent comment. - W5-IOS-WORKOUTS — `dedupeWorkoutBatch` write-time cross-source dedup helper for the v1.5 iOS HealthKit observer ingest; dashboard tile-strip placeholder parity with the live TrendCard chrome. - W6-WITHINGS-OFF + ENV-CHECK — Withings off-response classifier (transient/reauth/persistent) + WithingsApiError typed throw + the `pnpm check-env` CLI. APNs `allOrNone: true` closes the AP-2 silent-disable gap the wave was conceived to close. No migration, no env-var change, no API contract break for iOS v0.5.4. The new `/api/dashboard/widgets` 422 envelope is additively extended. pnpm test --run green at 4815 passing / 1 skipped. pnpm typecheck, pnpm lint, pnpm knip (no --include flag) green. |
||
|
|
67207d725e |
chore(release): v1.4.41 — iOS perf hotfix, soft-delete completeness, tree hygiene
Eight touch-disjoint waves landed on develop before this release: - W-INSIGHTS-HOT + W-RECONCILE-INSIGHTS — extract the timeout-stub persist helper and wire all seven *-status routes through it, closing the recurring ~14 s warm response the iOS client sees on dashboard open once the AI provider has stalled once that day. - W-DELETED-2 — close the remaining three soft-delete reader-tier gaps (export bundle, gamification achievements, doctor-report aggregator) with a five-route integration-test pin. - W-ORG — types consolidation into src/types/analytics.ts and src/types/backups.ts; prompt directory unification. - W-FRONTEND-FACTORY — queryKey factory expansion + ESLint rule lift. - W-IOS-COORD — POST /api/auth/check-user four-branch onboarding discovery, identifier matched verbatim, per-IP rate-limited. - W-SIMPLIFIER — today-intake projection helper extract; unused tx? params dropped; 13 knip-flagged dead exports trimmed. - W-PERF-OPS — v1.4.39 W-SUM legacy-NULL UNION discovery arm retired. - W-PROCESS-DOCS — pg.Pool sizing operator doc; ESLint rule formalisation; knip CI gate staged for v1.4.42 flip. No migration, no env-var change, no API contract break for iOS v0.5.4. The new check-user endpoint is an additive surface. AP-2 .p8 key is installed; SB-5 time-sensitive APNs is live as of this deploy. pnpm test --run green at 4732 passing / 1 skipped. pnpm typecheck, pnpm lint, pnpm knip green. |
||
|
|
1114cf7e63 |
chore(release): v1.4.40 — comprehensive Critical+High architecture closure plus iOS PB30 enablement
Eleven touch-disjoint waves landed on develop plus a six-axis QA reconcile round before tagging. See CHANGELOG.md for the user-facing prose; this commit message documents the wave + report inventory for release-management traceability. Waves shipped (each with a phase report under .planning/): - phase-W-POOL-v1440-report.md — p-limit(4) wrapper around the analytics 15-way fan-out + pg.Pool max raised 10 -> 20. Closes the v1.4.39 empirical-trace finding #1 (Prisma pool starvation). - phase-W-DELETED-v1440-report.md — 11 reader-tier helpers + 3 integration contracts close audit Critical Finding #3 (soft-delete invisibility) across dashboard, analytics, summaries, rollup tiers, and the Coach snapshot path. - phase-W-INSIGHTS-v1440-report.md — mood-rollup swap on the three /api/insights/{features,targets,cards} routes plus the compliance-rollup hook gap closure for bulk-projection mints; the post-QA reconcile patch closes the six remaining measurement.findMany sites in the cluster that still leaked tombstoned rows. - phase-W-INFRA-v1440-report.md — rollup helper umbrella consolidation under src/lib/rollups/* with zero orphan re-exports; lint, typecheck, knip, and 93/93 rollup tests green post-restructure. - phase-W-RSC-v1440-report.md — per-tile Suspense boundaries plus the queryKey factory-bypass walker test (extended to comparison/ in the reconcile pass). - phase-W-PRIVACY-v1440-report.md — bilingual /privacy page with 17 paired-section tests pinning the 9 SB-3 disclosure requirements. - phase-W-AASA-v1440-report.md — /.well-known/apple-app-site-association endpoint pinned to S8WDX4W5KX.dev.healthlog.app with app-ID parity assertions guarding against split rotation. - phase-W-APNS-NOTIFY-v1440-report.md — MEDICATION_REMINDER time-sensitive APNs payload (priority 10 + interruption-level) scoped via a parameterised test that pins all 6 other event-types do not bypass Focus. AP-2 .p8 install gates real delivery. - phase-W-CONSENT-v1440-report.md — AI consent receipts CRUD with append-only invariant pinned in test; revoke-then-regrant leaves both rows; idempotent DELETE returns 200 + receipt: null. - phase-W-WMY-WIRE-v1440-report.md — three previously-dead WMY readers (week/month/year) wired through summaries-slice and health-score-fast-path with a linear-composability parity test pinning the cross-consumer routing contract. - phase-W-GHOSTS-v1440-report.md — ~1 177 lines of dead code removed across 9 atomic commits; startOfUtcDay + wallClockInTz consolidation eliminates a sibling-drift risk; knip whitelist trimmed to three files pending follow-up. QA reconcile patches applied per the v1.4.40 QA round (six reports under .planning/round-v1440-QA-*-findings.md): - senior C1 — dashboard-suspense-boundaries regex aligned with the post-W-INFRA Thread 2 userTimezone-local lift. - senior H1 — soft-delete filter added to the six remaining insights measurement.findMany sites. - specialist H1 — Promise.allSettled around bulk-projection compliance recompute on both /api/medications/intake and /api/dashboard/summary. - ux H1 — compare-toggle migrated to queryKeys.dashboardWidgets factory; walker test extended to src/components/comparison/. - security M1 — consent artefact 64 KB cap enforced via Buffer.byteLength (UTF-8 bytes, not UTF-16 code units). Quality gates green at tag: pnpm typecheck, pnpm lint, pnpm knip --include files,dependencies,binaries,unlisted, pnpm test --run (4726 passing / 1 skipped). Tests 4525 -> 4726 unit + 1 skipped over the v1.4.39 -> v1.4.40 span. User-facing prose: see CHANGELOG.md. |
||
|
|
f9996552ed | chore(release): v1.4.39.4 — dashboard symmetry for daily-schedule intake projection | ||
|
|
dbb5979a97 |
chore(release): v1.4.39.3 — dashboard slim/thick merge robustness and list-page precision
The post-deploy CI for v1.4.39.2 surfaced eight e2e failures across chromium-desktop and chromium-mobile (chart-overlay-controls, dashboard, charts-mobile, measurement-flow) that all routed through two narrow regressions and one durable test-fixture gap. ### Fixed - Dashboard slim/thick merge no longer blanks the tile strip when the slim slice resolves with an empty summaries record. The v1.4.39.2 inline `slim?.summaries ?? thick?.summaries` short-circuited on JavaScript's truthy-empty-object even when thick carried the full payload. The merge moved to a pure `mergeSlimAndThickAnalytics` helper that uses object emptiness as the discriminator: populated slim still wins on overlapping fields (progressive-paint contract preserved), empty slim falls through to thick, both empty leaves the dashboard's data-floor gates to render the appropriate empty state. Eight new behaviour-level unit tests cover the edge cases. - `MeasurementList` non-grouped rows now preserve decimal precision on both the desktop table and the mobile card grid. The v1.4.37 W7c collapsed-list view passed every value through `fmt.integer`, which kept the per-day step / activity aggregates correct but silently truncated single weight / body-fat / temperature readings — 78.4 kg rendered as "78 kg". Grouped rows (cumulative HK type day aggregates) stay on `fmt.integer` because their readings are integer-only; non-grouped rows now use `fmt.number` which honours up to three fraction digits without forcing a minimum. ### Changed - Playwright route mocks for `/api/analytics` migrate from the literal `**/api/analytics` string glob to the regex form `/\/api\/analytics(\?|$)/` across every authenticated spec. The string glob does not match the sliced URL form `/api/analytics?slice=summaries` the v1.4.39.2 dashboard split fires alongside the thick request, so the slim request fell through to the real route on the seeded test user that returns empty summaries. Ten specs migrate: dashboard, chart-overlay-controls, measurement-flow, charts-mobile, a11y, v1427-responsive-sheet, v1427-coach-launch, v1427-measurements-add-param, v1427-insights-empty-state, onboarding-tour-passthrough. The regex form is the durable alignment with the v1.4.37 W-CI lesson that already swept `onboarding-flicker.spec.ts` and `mobile-viewport.spec.ts`. ### Notes - No schema migration. Runtime + test-fixture-only changes. - `pnpm test --run` green at 4662 / 4663 (1 long-standing skip). - Full Playwright suite green at 116 passing / 36 skipped / 152 total on both `chromium-desktop` and `chromium-mobile` profiles, against the production Next.js build. Closes every failure from CI run 26213226723. |
||
|
|
4122c79d66 |
chore(release): v1.4.39.1 — rollup tier catches Withings + import + admin-restore write paths
Hotfix on top of v1.4.39. Three measurement write paths (Withings sync, `/api/import`, admin backup restore) were bypassing the persistent rollup tier's write hook, so the dashboard chart's `source=rollup` fast-path painted "Noch nicht genug Daten" on the 30 / 90-point range for accounts whose recent data only came through those paths. The 7-day window kept rendering because the chart's raw fetch never consults the rollup tier. Closes the read-coverage gap by wiring `recomputeBucketsForMeasurement` into every remaining ingest path and re-anchors the boot-time backfill discovery to per-day coverage so already-deployed instances re-converge on the next worker boot. The legacy `sum_value IS NULL` branch stays on the same UNION so the v1.4.39 column-backfill continues working. Also re-anchors one date-bound test in the medications-intake route suite so the green CI run no longer depends on the wall clock. Tests 4647 → 4648 passing; one long-standing skip unchanged. |
||
|
|
d84922cdc3 |
chore(release): v1.4.39 — mood, medication-compliance, and cumulative-sum rollup tiers
Squashed merge of the v1.4.39 wave work from develop. The release extends the v1.4.38 fast-path posture to two more endpoints that still walked the source table on every cold mount and folds a cumulative `sum_value` column into the existing rollup tier so step / flight / distance / daylight / active-energy sparklines no longer re-derive their daily totals in Node. Raw measurements / mood_entries / medication_intake_events tables are byte-unchanged. Three new tiers (mood_entry_rollups, medication_compliance_rollups, measurement_rollups.sum_value) are derived caches that self-heal via boot-time backfill on first reach. Migrations 0070, 0071, 0072 are additive only. The sum_value column add is catalog-only DDL on PostgreSQL 11+ — no table rewrite, writes resume in milliseconds. No environment-variable change. No API contract break. No iOS contract change. Expected wins (live perf-verify rides the post-deploy window): - /api/mood/analytics cold 12.7 s -> ~200 ms - /api/medications/intake?scope=compliance cold 3.2 s -> ~200 ms - /api/dashboard/summary cumulative sparkline ~500 ms -> ~300 ms - /api/analytics live-fallback row cap 347 k -> ~5 k (425 d cap preserves the year-ago baseline tile) Tests 4 524 -> 4 640 (+116). Typecheck clean. Lint clean. See CHANGELOG.md for the full v1.4.39 entry. |
||
|
|
8a8150d2bf |
perf(analytics): fast-path gates per-type only
`isFullyCovered(coverage) && specificTypes` poisoned every fast- path with a single unrelated uncovered measurement type. v1.4.38.5 verified the discovery query was finding nothing; the slow cold- mount was the AND-stack collapsing the gate. - correlations-fast-path: gates on SYS + PULSE + WEIGHT only. - bp-in-target-fast-path: gates on SYS + DIA only. - health-score-fast-path: gates on WEIGHT only. Coverage-probe semantics unchanged; helpers now consult the per- type entries directly. Power-user cold-mount on /api/analytics estimated 30-75 s → ~3-5 s. |
||
|
|
9cc5ececa7 |
chore(release): v1.4.38.7
Rollup recompute observability + admin trigger. - POST /api/admin/rollups/recompute synchronously folds one user or re-runs the boot-discovery loop on demand. Admin-gated. - slim_summaries live-fallback now annotates `fallback_reason` and `missing_types[]` so the operator can map a slow cold-mount to the type missing DAY-bucket coverage without DB shell access. - Boot-backfill discovery now logs every result, including the silent "no users to backfill" case — the previous shape made it impossible to tell "discovery ran cleanly + found nothing" apart from "discovery never executed". See CHANGELOG.md. |
||
|
|
80b1fcb8d0 |
fix(rollups): boot-backfill discovery SQL uses bucket_start as NULL sentinel
v1.4.38.5 referenced `r."id" IS NULL` on the LEFT JOIN — but `measurement_rollups` has a composite primary key `(user_id, type, granularity, bucket_start)` and no surrogate `id` column. Postgres rejected the query with `column r.id does not exist` (SQL state 42703); the worker boot swallowed the error per the helper's best-effort contract and the queue stayed empty. Net effect: v1.4.38.5 deployed cleanly but delivered none of its promised fast-path recovery. Marc's account stayed on the live aggregator. The fix uses `r."bucket_start" IS NULL` — any column from the unmatched right side of the LEFT JOIN serves the "no matching row" filter, and `bucket_start` is part of the composite PK so the planner already has the column. Bumps to v1.4.38.6. |
||
|
|
9c13cba3f7 |
chore(release): v1.4.38.5
Analytics fast-path restored on long-running accounts. The boot-time rollup-backfill discovery query was matching only ZERO-rollup users; any account that ever folded silently stranded the moment a brand- new measurement type landed. Discovery now widens to per-type missing coverage so the boot-backfill queue picks these accounts up on the next deploy and folds them back into the fast-path. |
||
|
|
9da5b7022e |
chore(correlations): drop TODO marker on the degraded sentinel
The v1.4.38 commit `41506c7a` added a `TODO(v1.5):` marker on the correlations-fast-path `degraded` sentinel. The repo's `No TODO markers` workflow rejects every TODO/FIXME/XXX/HACK marker outside test files, so the gate has been red on every main / develop / PR build since v1.4.38 landed. Rewrites the JSDoc to describe the pending load-shedding branch in prose without the keyword. |
||
|
|
d224811a34 |
chore(release): v1.4.38.2
Mood-reminder hotfix bundle on top of v1.4.38.1 plus the missing Settings toggle. Six-axis review of the v0.5.4 iOS-coord patch surfaced enough blockers that the feature could not have been used safely as shipped: - Locale resolver demoted 4 of 6 locales (es/fr/it/pl) to English. - Dedup ledger committed before delivery — a transient APNs blip silently nuked the day's nudge and blocked retries. - DST-unsafe arithmetic drifted the local-22:00 baseline by an hour twice a year for both the mood-reminder push and the medication iOS-snooze action. - APNs payload forwarded the Telegram `replyMarkup` inline-keyboard object and other channel-specific extras to Apple's servers and the iOS notification handler. - No Settings UI for the per-user opt-in flag — the feature was unreachable for end users regardless of the other fixes. v1.4.38.2 closes every item above plus adds the missing `MoodReminderCard` Switch, a 90-day retention sweep for the dispatch ledger, and a per-user `try` wrapper so one bad row cannot abort the 22:00 tick. See CHANGELOG.md. |
||
|
|
4049c6c724 |
feat(notifications): APNs category + MOOD_REMINDER event for iOS v0.5.4 (#190)
* feat(notifications): set APNs category for med-reminders
Unblocks iOS HealthLog v0.5.3 which registers a UNNotificationCategory
named MEDICATION_REMINDER with three actions (Take / Snooze 15 min /
Skip). Without aps.category on the push payload iOS renders the
notification as a plain alert, so the action-button row never
materialises on the lock-screen.
- ApnsPayload gains optional `category` + `mutableContent` fields.
The sender writes `category` through to node-apn's setter (a
forward-compat cast wraps the d.ts gap in node-apn 8.1).
- sendViaApns automatically forwards `payload.eventType` as the
category so every event-type that lands here surfaces as a
matching iOS category identifier without further plumbing. Future
event-types that the iOS app doesn't register fall back to a plain
alert — iOS silently ignores unknown categories.
- mutableContent=1 is set by default so an iOS Notification Service
Extension can hook the payload later without a server-side change.
- New unit tests pin aps.category=MEDICATION_REMINDER on the dispatcher
path, aps.category=MOOD_REMINDER for the new event-type, and the
explicit-category override on the lower-level sendApnsPush entry.
* feat(prisma): add moodReminderEnabled + MoodReminderDispatch ledger
Schema foundation for the v0.5.4 daily mood-reminder push:
- `users.mood_reminder_enabled` (Boolean, default false): per-user
opt-in flag. Default off because mood capture is an emotionally
loaded surface — a fresh-install user must explicitly toggle the
preference in Settings before the server starts nudging them.
- `mood_reminder_dispatches` (new table, unique on userId+date):
idempotency ledger that records exactly one nudge per user per
local date. Doubles as the race-guard for the every-15-min cron
re-ticking inside the same 22:00 window — the unique constraint
makes parallel workers safe even though the worker boots at
localConcurrency=1.
Migration is additive: existing users stay on the opt-out path
byte-identical to v1.4.38 behaviour. Uses IF NOT EXISTS guards
matching the idempotent pattern from 0061 / 0068.
* feat(notifications): add MOOD_REMINDER event type with daily 22:00 cron
Second half of the v0.5.4 ios-coord patch. Now that the schema can
remember "user opted in" and "we already nudged today", wire the
worker side:
- types.ts: extend EVENT_TYPES with MOOD_REMINDER. Default off on
the per-event policy as a defence-in-depth gate behind the
per-user moodReminderEnabled flag.
- mood-reminder.ts: pure dispatcher module with three pinned-down
entry points so the unit tests don't have to spin up pg-boss:
* `evaluateMoodReminderWindow` — boundary contract for
"21:59 → skip, 22:00 → fire, 23:00 → skip" across any IANA tz.
* `buildMoodReminderPayload` — locale-aware title/body
("Stimmung erfassen" / "Wie geht es dir heute?" for DE,
"Log your mood" / "How are you feeling today?" for EN; falls
back to the app default for null/unknown locales).
* `runMoodReminderTick` — orchestrator that pulls opted-in
users, applies the window + already-logged + already-
dispatched filters, reserves the dedup row, and only then
calls the dispatcher. The P2002 unique-constraint violation
is caught and reclassified as "already dispatched" so a
lost race doesn't pollute the wide-event error stream.
- reminder-worker.ts: registers the `mood-reminder-check` queue
with a 15-min cron, mirroring the medication-reminder cadence so
any user's 22:00 boundary is caught within 15 minutes of wall-
clock without one-cron-per-zone. localConcurrency=1 keeps a
worker from racing itself. Also enriches the existing med-
reminder dispatch with a `scheduledAt` ISO string so the iOS
notification handler can pin "snooze 15 min" against the actual
schedule slot rather than the wall-clock moment APNs delivered.
- messages/{de,en,es,fr,it,pl}.json: new `moodReminders.dailyTitle`
+ `moodReminders.dailyBody` keys for all six locales.
- mood-reminder.test.ts: 13 unit tests covering opt-in gating,
window boundaries (21:59 / 22:00 / 23:00 + non-Berlin DST),
logged-today skip, ledger-already-exists skip, lost-race P2002
handling, and the multi-user multi-locale fan-out.
|
||
|
|
a550031a84 |
chore(release): v1.4.38
Robustness sweep, perf hotspots, full localization, coach gate cascade closure. - /api/dashboard/summary cold-mount 4.6 s → ~500 ms via DAY-bucket sparkline + 60 s response cache. - Coach API gate inventory test surfaced and closed two orphan routes (chat[id] GET+DELETE, chat-message feedback POST). - Cross-tz fast-path runtime guard falls back to live for users more than ±3 h from UTC; proper bucket minting stays v1.5. - es / fr / it / pl coverage 27 % → 63 % (~3 400 new strings) plus three medication-cluster placeholder restorations. - IANA timezone validation closes the User.timezone self-DoS regression the new dashboard SQL would have surfaced. - Unit suite 4520 → 4524. See CHANGELOG.md for the full set. |
||
|
|
57795418fc |
perf(analytics): slim summaries SQL aggregation, 306k rows to 8
The v1.4.37.1 fire-and-forget hotfix unblocked the event loop but live HAR still showed /api/analytics?slice=summaries at ~3.1 s per cache miss on a power-user account. Root cause: the v1.4.35 implementation read EVERY DAY rollup bucket for the user without a bucketStart window and composed count/min/max/ mean in JavaScript. On the live account that materialised as a 306k-row transfer plus a JS loop. Replace the unwindowed prisma.measurementRollup.findMany with a per-type $queryRaw GROUP BY. Returns 8 rows (one per type with count/min/max/mean already shaped server- side) instead of 306k bucket rows. The downstream JS aggregation is bypassed because the per-type aggregate arrives pre-composed. Cache-miss budget on Marc-sized accounts: ~3.1 s expected to drop into the < 100 ms range. The narrow aggregate query continues to carry the windowed avg7/avg30 and regression slope/r2 columns that the GROUP BY cannot reconstruct. Response shape is unchanged. |
||
|
|
98e078d359 |
v1.4.37.1 — event-loop unblock on the read path
Hotfix on top of v1.4.37. The post-deploy verify caught /api/analytics cold-mount hits of ~62 s and parallel /api/health checks of ~58 s on the live instance, far above the v1.4.37 1.5-3 s perf claim. Root cause: the synchronous ensureUserRollupsFresh(userId) call at the top of each heavy read path folds the trailing 90-day DAY window when the rollup watermark trails the newest measurement. On a power-user account whose iOS step samples push the watermark every few minutes, each cache miss synchronously paid the full refresh cost on a Node worker that also serves the rest of the request fan-out (including /api/health, /api/version, and concurrent iOS calls), and the event loop was blocked for the duration of the recompute. Convert the three call sites (analytics route, comprehensive aggregator, summaries slice) to fire-and-forget. The downstream probeRollupCoverage gate falls back to live SQL on partial coverage so correctness is preserved; the only user-observable change is one cache window of staleness on the very first request after a new measurement landed. |
||
|
|
88028fa082 |
v1.4.37 — final web polish before iOS focus
Carries the v1.4.36 perf carry-over for the full /api/analytics route (correlations + healthScore + bp_in_target on the rollup- coverage probe, 111s cold worst-case down to ~1.5-3s on power-user accounts), consolidates Apple Health step samples into a one-row- per-day list view with chevron drill-down and a nightly drain (~50x table compression once it converges), restores IntakeHistoryListV2 to the pre-v1.4.28 contract, converges every Coach affordance behind a single feature gate with an invariant test pin, lifts the medication-detail Mounjaro card to byte- equivalent parity with Ramipril, brings the Insights overview hero row to height parity, hardens getClientIp behind a new TRUST_CF_CONNECTING_IP env flag, ships the Arztbericht hero card on Settings -> Export, adds the Medikamenteneinnahme quick-add overlay to the dashboard, drops the timezone override toggle for a silent browser-zone auto-seed, and fixes the v1.4.36 red CI workflows. Documentation refreshed across all three repos with five new architecture diagrams in the Dracula palette. Unit suite 4354 -> 4486 passing; typecheck + lint clean. |
||
|
|
0e2a99f8e7 |
v1.4.36 — perf, charts, AI payload trim, UX punch
Heavy-aggregate skip on the rollup-fresh + fully-covered path, daily chart fetches opt into rollup buckets via source=rollup, Insights extractFeatures swap drops the prompt payload from double-digit MB to the low hundreds of kB on power-user accounts, page-level isLoading gate replaced with per-section early-skeleton paint, trends-row chart slot pinned for CLS, IntakeHistoryListV2 restored on the medication detail page, About card folded into the Admin Console with an auto-checking update badge, cumulative metric tiles read the day's running sum, IP-whois fallback surfaces city + country when the ASN lookup misses. Migration 0068 adds an additive users.insights_exclude_metrics column. Unit suite 4354 passing; typecheck + lint clean. |
||
|
|
5a3ca330ac |
v1.4.35.1 — auto-converge rollups on worker boot
Removes the operator step that was implicit in the v1.4.35 foundation release. Self-hosters no longer need to run scripts/backfill-rollups after upgrade; the worker boot discovers any account with measurements but no rollup coverage and enqueues a one-shot full fold via pg-boss. New rollup-full-backfill queue + handler folds one user per job at serial concurrency. enqueueBootTimeRollupBackfill runs once at startReminderWorker boot, idempotent across reboots via the discovery query (matches only zero-rollup accounts) and a singleton-key per user so fast restarts coalesce. Best-effort: discovery errors surface through the helper's return value and are logged via workerLog; the worker boot never fails because the backfill missed. Tests: 4285 unit + 230 integration. tsc + lint clean. |
||
|
|
8dc9edb65e |
v1.4.35 — persistent measurement rollups + partial read-swap
Foundation release for the persistent measurement_rollups cache tier. Adds the additive table + enum, populates it from every measurement write hook, lands the Apple-Health-import end-of-job backfill, and ships the parity-checked read-swap on two reader surfaces. The comprehensive insights aggregator and the slim analytics summaries slice now source count / min / max / mean per type from the DAY rollup buckets via aggregateBuckets, plus the comprehensive dailyByType correlation feed straight from the bucket means. Slope / R² / standard deviation / anomaly counts stay on live SQL — they do not compose across DAY buckets. A defensive parity check against the live aggregate's COUNT(*) falls back to live SQL when divergence is detected. Includes the new scripts/backfill-rollups.ts CLI for the one-shot fold of historical measurements into all four granularities. Tests: 4280 unit + 228 integration. tsc + lint clean. Migration 0067_v1434_measurement_rollups is idempotent under re-run. |
||
|
|
f5962497d6 |
v1.4.34.4 — audit-driven hotfix bundle (security, UX, code-quality, docs)
Consolidated hotfix landing the findings from a six-axis audit
covering mobile security, UX + accessibility, code quality + docs,
README + discoverability, web performance, and mobile-deep responsive
behaviour. None of the changes break the public API or the existing
data shape; every fix is additive and SAFE under the v1.4.34.x web
freeze. Full audit reports live in `.planning/round-audit-*.md`.
Security
- Password rotation now wipes API tokens + refresh tokens in the
same `$transaction` as session revocation. A stolen iOS Bearer no
longer survives a user-initiated password change or an admin reset.
- `/.well-known/` proxy bypass tightened to an explicit-allowlist
`Set`. Stale `/api/auth/codex/callback` PUBLIC_PATHS entry dropped.
- HSTS gains `preload`. Withings host removed from the global CSP
and gated to the integration's own routes.
- `getClientIp` warns once per process on `TRUST_PROXY_HOPS`/XFF
mismatch + exposes a tagged helper for tighter universal buckets.
- Service worker rejects off-origin notification-click URLs. Offline
fallback body switched to a locale-neutral icon. Manifest gains
`scope`, `id`, `display_override`.
UX + accessibility
- i18n leaks closed on Dialog/Sheet close-X, ChartSkeleton's loading
announcement, and the notifications-section breadcrumb.
- Focus rings on bottom-nav, the More overflow button, and the
mobile top-bar user menu.
- Tap-target floor: Input / NativeSelect / Select / DateTimeInput
switch to `h-11 sm:h-10`.
- Admin chip-strip auto-scroll-into-view (matches v1.4.33 settings).
- List-page subtitles visible on mobile.
- Insights empty-state CTA vocabulary normalised so the link opens
the right measurement form (was silently failing for
BODY_TEMPERATURE / BLOOD_GLUCOSE / PULSE).
Mobile-deep
- `viewport.themeColor` reacts to light/dark mode.
- TopBar + Coach FAB reserve safe-area-inset-top / -bottom for
notched iPhones.
- Sonner toaster switches to `theme="system"`.
Code quality
- `SESSION_SECRET` dropped — the env var was documented as required
but never read by code. Three secrets, not four. Self-hosters
upgrading can delete the existing line.
- `toJson<T>()` helper consolidates seven Prisma JSON-cast sites.
- `db-compat.ts` gains a header docstring naming it the
schema-bootstrap path.
- Passkey response types adopted from `@simplewebauthn/server`;
`any` + eslint-disable pragmas drop out.
- Zero-TODO CI gate added at `.github/workflows/no-todo-markers.yml`.
Documentation + discoverability
- README rework: How-it-compares matrix, Apple Health + AI Coach
promoted to standalone Key-Features bullets, status block, latest
release + GHCR badges, OpenAPI pointer, three-secret Quick Start.
- openGraph + twitter cards now carry `images` and a
`summary_large_image` Twitter card.
- GitHub repo metadata: description tightened from 290 to 156
chars + keyword-front, `homepageUrl` flipped from a personal
tenant to the demo site, six generic / PII-adjacent topics
swapped for six high-intent ones.
- Five new user-facing docs: `docs/self-hosting/getting-started.md`,
`docs/self-hosting/reverse-proxy.md`,
`docs/integrations/apple-health.md`,
`docs/integrations/withings.md`,
`docs/integrations/ai-providers.md`.
- `docs/README.md` clarifies the docs tree as internal playbooks
vs the user-facing `docs.healthlog.dev` site.
|
||
|
|
f6ca89b963 |
v1.4.34.1 — insights cold-mount perf hotfix + scatter-card sizing
Hotfix on top of v1.4.34. The Insights page mount was paying ~29 s on
every cold load against accounts populated by the v1.4.34 Apple Health
importer. Root cause: `/api/insights/comprehensive` walked the unbounded
90-day measurement set into JS, then ran per-type `summarize()`, BMI,
blood-pressure classification, target adherence, and four Pearson
correlations from the same pile of rows. On a 100 000+ row account the
route consumed one of the 20 pool connections for the whole 29 s, which
cascaded sibling endpoints into Cloudflare "no available server" 503s.
The scatter-correlation card also surfaced a `width(-1)/height(-1)`
Recharts warning on first paint because its dynamic-mount lacked a
non-zero floor before aspect-ratio resolved.
Changed:
- /api/insights/comprehensive now reads through a SQL-side aggregator
(src/lib/insights/comprehensive-aggregator.ts) grouping by metric
type with Postgres-native AVG / MIN / MAX / REGR_SLOPE / REGR_R2 on
the measurements (user_id, type, measured_at) index path. Returns
the same DataSummary-shaped per-type bundle the legacy route
stitched together; the medication-compliance block keeps its
bounded Prisma reads. Wrapped through the server cache keyed on
`${userId}|comprehensive` (60 s TTL). Cold path drops from ~29 s
to a few hundred ms against fixture data matching the production
volume that triggered the bug; warm path resolves in single-digit
milliseconds.
- Cache-wrap the five remaining read routes the v1.4.34 server-cache
blueprint left staged but unwired: /api/mood/analytics,
/api/workouts, /api/bugreport/status, /api/medications,
/api/dashboard/widgets. The Cloudflare 503 cascade on
/api/measurements?aggregate=daily resolves as a downstream
consequence — once the comprehensive route stops monopolising the
pool, the origin accepts new connections fast enough that
Cloudflare's circuit-breaker no longer trips.
- /api/dashboard/chart-overlay-prefs PUT now invalidates the new
dashboard-widgets cache so the partial-update path doesn't leave
stale layout state in the cache for up to TTL.
Fixed:
- Scatter-correlation card no longer logs the Recharts
`width(-1)/height(-1)` warning on first mount. The wrapper now
carries a min-h-[180px] floor that matches the loading skeleton so
ResponsiveContainer always measures a non-zero parent before
aspect-ratio settles.
|
||
|
|
affede31a4 |
v1.4.34 — apple-health import + reliability + web-freeze
The final functional web release before the iOS native client lands.
Headline work: a streaming Apple Health `export.zip` importer for
prospective iOS-migrating accounts, a server-side aggregation cache
that collapses the three hottest dashboard reads onto in-process LRU
slots with single-flight coalescing and per-user invalidation, a
broader compliance classifier with a dedicated `early` bucket so
ahead-of-window doses count as compliant, the Coach launch surface
hoisted onto every authed page with a dashboard-hero CTA, and a
trimmer Settings shelf that folds Sources into Targets. The release
also lights up the `cache.<name>.outcome` annotation on the active
wide event so production logs carry the cache hit-ratio signal
without leaking userIds.
### Added
- **Server-side aggregation cache.** A new `ServerCache<T>` primitive
(`src/lib/cache/server-cache.ts`) extends the v1.4.33 Coach snapshot
LRU shape into a reusable per-route layer with TTL expiry,
capacity-bounded LRU eviction, single-flight read coalescing, and
per-instance hit / miss / eviction / stampede counters. Wires the
three hottest dashboard reads — `/api/analytics` (slim + default),
`/api/gamification/achievements`, `/api/medications/intake?scope=compliance`
— and bolts per-user invalidation onto every measurement / mood /
medication / workout / dashboard-widget write endpoint so the next
read paints fresh data instead of waiting out the TTL. Every cache
hit / miss surfaces on the active wide event as
`cache.<name>.outcome` + `cache.<name>.key_hash` so production logs
carry the hit-ratio signal without leaking userIds.
- **Apple Health `export.zip` import.** New endpoint
`POST /api/import/apple-health-export` (synchronous multipart
upload, asynchronous ingest via a dedicated pg-boss
`apple-health-import` worker, per-`MeasurementType` ingestion
stats). Streams the upload straight to disk so a multi-gigabyte
export never lands in V8 heap, hashes the bytes inline for
content-based idempotency, and unpacks `apple_health_export/export.xml`
with a hand-rolled ZIP central-directory walker that handles Zip64
for archives past the 4 GB barrier. The parser folds every
`<Record>`, `<Workout>`, `<Correlation>`, and `<ClinicalRecord>`
into the existing `Measurement` and `Workout` row shapes — spot
rows keyed by `HKMetadataKeyExternalUUID` (or a deterministic
`sample:<sha256>` fallback), cumulative HK types collapsed into
one `stats:<HKType>:<YYYY-MM-DD>` row per user-local day to match
the iOS daily-aggregation convention. Live per-stage progress
surfaces through `GET /api/import/apple-health-export/{jobId}/status`.
An admin variant at `POST /api/admin/import-apple-health-export`
imports on behalf of a target user (cookie-only `requireAdmin()`
gate; Bearer tokens never elevate).
- **`ImportJob` schema model + migration.** New Prisma model captures
the per-upload state machine (`queued | unpacking | parsing |
upserting | done | failed`), the content-hash for idempotency
short-circuits, and the per-`MeasurementType` ingestion counters
the status route surfaces back to the client.
- **`lastSeenByType` on `/api/analytics`.** Both the slim
(`?slice=summaries`) and default slices return a per-type
`{ lastSeenAt, daysAgo }` map. The dashboard trend tiles wire 12
mounts to a new `tileStaleDays()` helper so an "X days / weeks /
months ago" hint paints under any per-metric tile whose last
sample crosses the 7-day floor. Six locales gained additive
week / month plural keys; Polish uses the genitive-plural form
that covers every non-1 count the bucket math can produce.
- **Dashboard "Ask the coach" hero CTA.** A new pill next to the
existing "Hinzufügen" / "Add" launches the Coach drawer directly
from the dashboard hero. The `<CoachLaunchProvider>` hoisted from
the insights layout to the auth shell so the drawer is reachable
from every authed route; the floating action button stays scoped
to `/insights/**` so it cannot distract on the dashboard.
- **Shared achievements query hook.** `useAchievementsQuery()`
centralises the three previous consumers — recent-achievements
card, the `/achievements` mother page, and the unlock notifier —
onto one TanStack queryKey + cache slot so dashboard cold mount
fires the endpoint once instead of twice.
- **Typed authed Cache-Control presets.** New
`src/lib/http/cache-headers.ts` module exports
`NO_STORE_BUT_BFCACHE = "private, max-age=0, must-revalidate"`,
`SHORT_LIVED_PUBLIC`, and an `applyAuthedHeaders()` helper. The
presets land at the framework level via a `next.config.ts`
`headers()` rule that stamps the bfcache-friendly directive on
every authed HTML response, restoring Chromium bfcache eligibility
for in-app back / forward navigation.
- **`scripts/print-bundle-report.mjs`.** Restores the at-a-glance
"top client chunks by parsed size" signal Turbopack dropped from
`next build`; reads `.next/analyze/client.json` (written by
`@next/bundle-analyzer` when `pnpm analyze` runs with `ANALYZE=1`)
and prints a sorted table plus totals.
### Changed
- **Settings sidebar: "Sources" folded into "Targets & Sources".**
Per-metric threshold ranges and per-metric source priority now
share one `/settings/thresholds` page so the same metric's
threshold and device-source preference sit together instead of
one sidebar entry away. `/settings/sources` keeps a
`permanentRedirect` so external bookmarks and docs links follow
through unchanged. Section count: 11 → 10.
- **Insights tab strip: vital pills collapse under a "Vitals"
parent.** Five vital pills (HRV, Resting HR, Oxygen, Body
Temperature, Active Energy) hide behind one parent pill that
opens a popover sub-list. Parent-pill active state mirrors the
URL so spatial orientation survives the collapse; each sub-page
keeps its own URL and bookmark resolves unchanged. Strip
footprint: 14 → 10 entries when every metric has data.
- **Coolify env-var audit.** `mcp__coolify-apps01__env_vars`
inspection captured the section-1 / section-2 duplicates that
have accumulated under apps-01 since v1.3.1. Audit pinned at
`.planning/round-v1434-iwa-coolify-env-audit.md`; no env-var
deletes performed (operator action).
### Fixed
- **Compliance classifier: early intakes count as compliant.** The
classifier picked up a dedicated `early` bucket (window-start
minus three hours through window-start), the `on_time` post-window
tolerance widened from one hour to three hours, and the `late`
band sits between the new `on_time` ceiling and the configurable
`lateMinutes` knob. Heatmap consumers route the new bucket
through the compliant path; the dedicated `early` counter rides
on `DailyComplianceEntry` for downstream consumers that want to
distinguish ahead-of-window from on-window intakes.
- **Compliance heatmap fallback retired.** The v1.4.33 defensive
`looksClassifierBug` fallthrough is gone now that the underlying
classifier widening removes the every-dose-very-late mode the
fallback covered.
### Performance
- **`/api/gamification/achievements` consumer collapse.** Two of
three previous consumers shared the same TanStack queryKey
literal; the third carried a per-user discriminator so the cache
treated it as a fresh slot. Dashboard cold mount fired the
endpoint twice. Collapsing onto the shared hook trims that to a
single request; with the new server-side cache slot warm, the
duplicate-mount worst case rides single-flight coalescing.
- **GHCR build fires once per release tag.** The
`docker-publish.yml` workflow lost its `push.branches: [main]`
trigger; the `:latest` raw-tag enable rule moved onto the tag
ref so each release produces exactly one multi-arch build that
refreshes both the semver tags and the `:latest` alias.
- **NFT-trace warnings silenced.** `next.config.ts` gained an
`outputFileTracingExcludes` block that narrows the Turbopack
tracer away from the `MAXMIND_LICENSE_KEY` env-access path so
the trace-report no longer warns on every dependent route file.
### Refactor
- **Dashboard analytics consumers.** The two cards that previously
decided their own freshness copy now lean on the typed
`tileStaleDays()` helper and the additive `lastSeenByType` field
on the analytics response. Mood and BD-Zielbereich tiles keep the
default `null` because they have no underlying per-type freshness
signal.
### Accessibility
- **Dashboard hero CTA hits the WCAG 2.5.5 touch-target floor.**
The new "Ask the coach" pill carries `min-h-11` on mobile and
the matching `sm:min-h-9` desktop floor so the touch target
stays above 44 px on the Pixel 5 boundary.
- **Insights tab-strip Vitals parent reads correctly to assistive
tech.** Parent pill carries `aria-current="page"` whenever the
current URL matches one of its child vital sub-pages, plus a
`data-slot="insights-tab-strip-group"` hook for visual-regression
testing.
### Internal
- **Two e2e flake windows tightened.** `onboarding-flicker` swapped
its 12-sample 50 ms poll loop for a single Playwright
auto-retrying `toBeHidden({ timeout: 700 })` assertion so the
1-2 ms race window between the analytics-pending shell and
`useAuth().user` resolving collapses to a single retry slot.
`mobile-viewport` dropped `nav a[href]` from the touch-target
sweep (the bottom-nav owns its own WCAG spec) and gated the
44-px floor on `matchMedia('(min-width: 640px)').matches === false`
so the Pixel 5 viewport never tripped into the `sm:` tier during
WebKit render commits.
- **Server-cache observability.** Every `cached()` invocation passes
an `annotate` callback that lands two keys on the wide event:
`cache.<name>.outcome` ∈ `{ hit | miss | stampede }` and
`cache.<name>.key_hash` (non-reversible djb2 32-bit hash). Ops
can grep `cache.analytics.outcome` over any time window to
compute the hit ratio per deployment.
- **AASA followups verified.** The v1.4.33 `/.well-known/apple-app-site-association`
handler serves a direct 200 on every fronting origin; Apple's
CDN has ingested matching bodies for all three domains.
### Web freeze
v1.4.34 marks the last functional release of the web codebase before
the iOS native client launches. Subsequent v1.4.x tags carry security
fixes, dependency bumps, and hotfix-only corrections. New feature work
is paused until the iOS app clears Apple review, at which point a
v1.5.0 version-bump-only release tags the milestone. The Prisma
schema head comment and `.planning/v15-strategic-plan.md` §5
decision-log row pin the freeze trigger in-tree.
|
||
|
|
7bef199039 |
v1.4.33 — polish and reliability
Quality-leap release between two HealthKit milestones. The headline is a P0 hotfix for the `/api/analytics` 500 that broke the Insights mother page for any account with more than a few thousand measurements: the six per-metric status helpers were spreading the entire numeric history into `Math.min` / `Math.max`, which trips a stack overflow once a single argument list exceeds the V8 spread cap. Both the surfaced symptom and the latent risk in five sibling helpers were folded onto a reduce-based min/max path. Around that hotfix landed a deep polish pass: the Insights mother page now defers three below-the-fold blocks behind `next/dynamic` to trim the cold mount cost, the analytics endpoint gained a `?slice=summaries` slim slice that the per-metric sub-pages now ride, the Coach snapshot builder picked up a 60 s LRU keyed on `(userId, scope)`, the Settings shell consolidated three duplicate copies of the about / notifications / about-dropdown surfaces, the navigation strip dropped a redundant "Home" group label and a colliding "Notifications" sibling, every icon-only button on the medications and admin surfaces gained an accessible name, every Progress bar gained one too, three pages had their heading hierarchy repaired to a sequential h1 → h2 → h3, the mobile Coach FAB now hides while a chart tooltip is open so it cannot occlude the read-out, and the auth shell normalised every authenticated route to a single `max-w-screen-xl` container. Also lands the Apple App Site Association handler at `/.well-known/apple-app-site-association` on every host that fronts the app, advertising the iOS bundle's App ID prefix (S8WDX4W5KX.dev.healthlog.app) under `webcredentials.apps` so the passkey ceremony shares cleanly between the web origin and the iOS app. The release closes nineteen issues from a five-surface audit + a runtime bug-hunt pass, plus six follow-up tracks of polish across the affected surfaces. |
||
|
|
c7a0ff214b |
chore(release): v1.4.32
v1.4.32 — HealthKit Tier 1 wave A: workouts API + list/detail pages + dashboard tile + 5 metric sub-pages; HRV/RESTING_HR moved to cardiovascular; latent workouts-list 500 fixed. |