Commit Graph
1777 Commits
Author SHA1 Message Date
Marc-André Bombeck 2b4e2177be chore(routes): remove orphan /api/medications/intake-summary endpoint
The GET handler had no fetch caller and the queryKeys.medicationIntakeSummary
entry was never consumed in any useQuery. Strip the route file, the
factory entry, the medicationDependentKeys reference, and an outdated
quick-add doc comment.
2026-05-21 12:01:11 +02:00
Marc-André Bombeck 24568c805b perf(summaries-slice): consume monthly rollup buckets for long-window slice
Wires readBestGranularityRollups into computeSummariesSlice to populate
the year-ago 30-day baseline (avg30LastYear) per type. The field was
hardcoded null up to v1.4.39 because the 90-day windowed aggregate
cannot reach back a year and the live measurements walk over a 395-day
per-type window is exactly the cold-path cost the rollup tier was meant
to absorb.

Coverage-fallback mirrors the W-MOOD posture: per-type calls route
through YEAR (skipped for the 395-day window — floor 731 d) -> MONTH
-> WEEK -> DAY and return null when no granularity carries any bucket
overlapping the [now-395d, now-365d) slice. count / mean compose
linearly across any granularity so the derived baseline is
mathematically equivalent to the per-row average over the same window.

Adds year_over_year_types annotate count alongside the existing
slim_summaries path tag so operators can verify the wire-up in
production wide-events without redeploying instrumentation.
2026-05-21 12:00:56 +02:00
Marc-André Bombeck 0ec4a99322 chore(jobs): remove dead TELEGRAM_CLEANUP_QUEUE handler and registration
The queue had a handler, registration, and worker binding but no
producer anywhere in the codebase — zero boss.send calls and no cron
schedule. The doc comment claimed the Telegram sender schedules
cleanup but the sender never called boss.send. Strip the constant, the
interface, the handler, the allQueues entry, and the worker bind.
2026-05-21 11:58:36 +02:00
Marc-André Bombeck 317d56181b test(auth-registration-status): pin all four discovery branches
The route is read-only and its envelope shape (`registrationEnabled`
boolean) gates iOS sign-in + web onboarding. Four branches walked:
  1. singleton row exists with registrationEnabled: true → reports true
  2. singleton row exists with registrationEnabled: false → reports
     false (admin-disabled tenant, invite-only)
  3. singleton row missing → reports schema default true (fresh self-
     hosted instance, no-config baseline)
  4. findUnique throws → reports false (fail-closed; critical defense
     against a DB blip silently unlocking sign-up on a tenant that
     disabled registration)

No code change; the route's current behaviour is correct. Pin it
before someone refactors fail-closed → fail-open by accident.
2026-05-21 11:53:04 +02:00
Marc-André Bombeck 08cf854960 fix(dashboard-summary): recompute compliance rollup after bulk projection backfill
Mirrors the intake-route call site (v1.4.40 close of v1.4.39.4 hook
gap). `projectAndReadTodaysIntakes` runs the same idempotent
projection helper the intake route uses; without this hook the
compliance rollup stayed pre-projection on the second call site too.

Fires `recomputeMedicationComplianceForEvent` once per distinct
`(medication_id, dayKey)` after the bulk `createMany`, best-effort
inside the helper's try/catch so a populator hiccup doesn't surface
as a 5xx on the dashboard summary.
2026-05-21 11:52:54 +02:00
Marc-André Bombeck e8a0947638 docs(planning): W-RSC v1.4.40 phase report 2026-05-21 11:52:50 +02:00
Marc-André Bombeck de1e65d4a1 fix(medications-intake): recompute compliance rollup after bulk projection backfill
Closes the v1.4.39.4 hook gap surfaced by the QA reconcile pass. The
`scope=today` branch's bulk `createMany` mints fresh
`(medicationId, scheduledFor)` PENDING rows when the morning
projection lands; without this hook the compliance rollup for the
affected `(user, medication, day)` tuples stays at its pre-projection
`scheduled` count, inflating the apparent compliance % until the user
actually logs against the new row.

Fires `recomputeMedicationComplianceForEvent` once per distinct
`(medication_id, dayKey)` (coalesced by Set) so a 5-meds-3-times-a-
day projection drops 15 createMany rows down to ≤3 recompute round-
trips. Best-effort: errors stay caught inside the helper so a
populator hiccup doesn't surface as a 5xx on the intake request.
2026-05-21 11:52:42 +02:00
Marc-André Bombeck ca7d00ffbf perf(insights-generate): consume mood-rollup tier via features extractor
Audit Critical Finding #2 (round-v1439-arch-qa-infra-db). The mood
block inside `extractFeatures` ran an unbounded
`prisma.moodEntry.findMany({ where: { userId } })` and folded the
entire history into the AI feature payload for /api/insights/generate.
On power-user accounts the walk dominated the cold-mount budget.

Swap to `readMoodDayRollups(userId, fiveYearsAgo)` so the feature
payload reads one row per calendar day. The downstream consumers
(`avg7` / `avg30` / `trend30` / `coverage` / cross-metric
correlations) all operate at per-day resolution, matching the rollup
shape. `latest` score reads a single `findFirst` (bounded). Coverage-
fallback runs a bounded one-year live walk + fires
`ensureUserMoodRollupsFresh` so the next request lands on the rollup
tier (same posture as /api/mood/analytics post-v1.4.39).

Existing test fixture updated to mock `moodEntryRollup` + the
warm-up; six features tests stay green.
2026-05-21 11:52:32 +02:00
Marc-André Bombeck 594cd22ff5 docs(planning): W-DELETED v1.4.40 report — soft-delete invisibility across reader tiers
Inventory of touched files, test matrix, and commit map for the
v1.4.40 soft-delete-filter sweep that closes Senior Infra+DB audit
Critical Finding #3.
2026-05-21 11:52:29 +02:00
Marc-André Bombeck 45a8399822 perf(insights-comprehensive): consume mood-rollup tier
Audit Critical Finding #2 (round-v1439-arch-qa-infra-db). The 90-day
`prisma.moodEntry.findMany` block fed two downstream consumers:
`dailyMoodEntries` for mood × metric correlations, and `moodSummary`
for the dashboard mood block. Both read at a per-day resolution.

Swap to `readMoodDayRollups(userId, ninetyDaysAgo)` so the route reads
one row per calendar day instead of one per entry. Coverage-fallback
runs a bounded 90-day live walk + fires `ensureUserMoodRollupsFresh`
so the next request lands on the rollup tier (same posture as
/api/mood/analytics post-v1.4.39). `moodSummary` now feeds per-day
mean DataPoints into `summarize()` on both branches, matching the
rollup-tier convention shipped in v1.4.39 (QA UX-H1).

Two parity tests added to `__tests__/route.test.ts`: rollup fast path
skips the raw findMany, and the coverage-fallback runs the live walk
exactly once when rollups are empty.
2026-05-21 11:52:21 +02:00
Marc-André Bombeck f8de4b05fd perf(insights-targets): consume mood-rollup tier and floor distinct measurement scan
Audit Critical Finding #2 + High finding 3 (round-v1439-arch-qa-infra-db).
The mood block at the bottom of the route used to run an unbounded
`prisma.moodEntry.findMany({ where: { userId } })` on every mount —
pulling every mood the user had ever logged into Node only to bucket-
average them in JS. The `findMany({distinct:['type']})` for 'absolute
latest measurement per type' carried no `measuredAt >=` floor either,
so on a 347 k-row tenant Postgres still had to sort the full set
before the driver applied DISTINCT ON (Prisma's `distinct` doesn't
compile to PG's `DISTINCT ON`).

This commit:
  - swaps the mood findMany for `readMoodDayRollups(userId, since)`
    plus a single `findFirst` for the latest score; coverage-fallback
    runs a bounded 30-day raw walk + fires `ensureUserMoodRollupsFresh`
    so the next request lands on the rollup tier (same posture as
    /api/mood/analytics post-v1.4.39)
  - adds a 365-day floor to the latest-ever-per-type read so the
    driver-side distinct walk stays bounded
  - pins all three behaviours in `__tests__/route.test.ts` (4 new
    tests: rollup fast path, coverage-fallback bounded walk, no-mood
    branch, distinct floor present)
2026-05-21 11:52:09 +02:00
Marc-André Bombeck 691443e264 test(query-keys): pin factory enforcement and dedup behaviour
Three test suites land together:

1. queryKeys factory contracts for the four new v1.4.40 entries
   (`authMe`, `userThresholds`, `chartData`, `dashboardMedicationCompliance`)
   — pin the byte-stable shapes so a future rename of any literal
   lands a matching test failure rather than silently breaking cache
   layout.

2. `measurementDependentKeys` / `medicationDependentKeys` bundle
   membership — `["chart-data"]` and
   `["dashboard-medication-compliance"]` prefixes now ride the
   bundles so a mutation evicts every per-chart and per-compliance
   cache in one pass (audit-C2 + audit-L4).

3. Factory-bypass guard — walks `src/components/charts`,
   `src/app/page.tsx` and `src/hooks/use-auth.ts` and fails if a
   literal `queryKey: [...]` slipped past the factory. Acts as a
   lint-style enforcement check in the absence of a custom ESLint
   rule. The guarded directory list is intentionally scoped tight to
   the files this wave migrated; a follow-up wave can extend it as
   it routes the remaining admin/settings/medications surfaces
   through the factory.

Plus a dashboard Suspense-boundary structural test that pins the
per-tile `<Suspense fallback={...}>` wrappers, the module-scope
`DASHBOARD_QUERY_OPTS` hoist, and the `useMemo` around the hour-of-day
derivation. A refactor that drops any of those three structural
guarantees lands red CI rather than silently regressing the
streaming-composition contract.

All 16 + 5 new assertions green; tests 4565 → 4586.
2026-05-21 11:50:37 +02:00
Marc-André BombeckandClaude Opus 4.7 a3b0dc920b test(consent): pin endpoint behaviour and append-only invariant
Cases covered:

- POST 401 unauth, 400 invalid kind, 400 non-ISO signedAt, 400 oversize
  artefact (>64 KB), 200 inserts row + strips artefact from response.
- GET 401, 400 invalid kind, null when nothing granted, latest row by
  kind, full keyspace projection when ?kind is omitted.
- DELETE 401, flips revokedAt on the latest active row, idempotent
  no-op when nothing to revoke, master toggle revokes per-kind.

The headline test is the append-only invariant: a revoke + re-grant
cycle leaves the original row in place (with revokedAt set), mints a
fresh row, and a subsequent GET points at the re-grant — never at the
revoked predecessor. Prisma's `delete` is asserted to never be called
on a receipt, which is the legal-team guarantee the audit trail relies
on.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 11:49:22 +02:00
Marc-André BombeckandClaude Opus 4.7 d6809e3d54 feat(consent): POST + GET + DELETE endpoints at /api/consent/ai
Wires the iOS onboarding + Settings "AI deaktivieren" flow to the
persistence layer landed in the previous commit:

- POST /api/consent/ai — accepts { kind, artefact, signedAt }, persists
  a fresh receipt, returns id + serialised row (artefact stripped from
  the response so the signed token doesn't echo over network paths it
  doesn't need to cross).

- GET /api/consent/ai/latest?kind=… — latest non-revoked receipt for
  the given kind. Omit ?kind to get the full three-kind keyspace
  keyed by kind, with null slots for kinds the user hasn't granted.

- DELETE /api/consent/ai/latest?kind=… — flips revokedAt on the
  latest active row. Idempotent: a no-op returns 200 with null receipt
  rather than 404 so the iOS toggle can hammer the endpoint without
  spurious error states. Omit ?kind for the master "deaktivieren alle
  KI-Funktionen" sweep across every kind.

Both grant + revoke write to auditLog so the trail is reconstructible
even if the receipts table is rebuilt from a backup.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 11:49:11 +02:00
Marc-André BombeckandClaude Opus 4.7 8692a97e3f feat(consent): CRUD helper for AI consent receipts
Adds the persistence layer for the AI consent audit trail required by
App-Store Guideline 5.1.2(i) and GDPR Art. 7:

- src/lib/validations/consent.ts — Zod schemas with a three-kind
  discriminator (ai_full / ai_insights_only / ai_coach) and a 64 KB cap
  on the opaque artefact so a misbehaving client can't fill the audit
  table with multi-megabyte rows.

- src/lib/consent/receipts.ts — append-only helpers: createReceipt,
  latestActiveReceipt, latestActiveReceiptsByKind, revokeLatest.
  Revoke flips a single field on the existing row; a re-grant always
  mints a fresh row, keeping the historical chain intact for legal
  review.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 11:48:56 +02:00
Marc-André Bombeck 55fefb1d72 test(integration): pin soft-delete invisibility across analytics, dashboard, rollup tiers
Pins the v1.4.40 W-DELETED contract end-to-end against the real
Postgres testcontainer. Three contracts:

  1. The slim summaries slice's narrow aggregate + DISTINCT ON latest
     reads exclude tombstoned rows. Fixture parks a 99.0 sentinel
     row that would explode min/max if leaked.
  2. The dashboard summary route's per-type groupBy + latestIn7d
     DISTINCT ON ignore the tombstone — the WEIGHT tile's
     `latestValue` shows the live row, not the tombstoned 99.0.
  3. `recomputeBucketsForMeasurement` produces a DAY bucket with
     count=2 (not 3) when one of three same-day rows is soft-
     deleted, and the bucket mean reflects the live two rows only.

Also pins the Coach snapshot's measurement read against the same
filter — tombstoned rows must never reach the AI prompt where they
would surface as live data the user thinks they removed.
2026-05-21 11:48:40 +02:00
Marc-André Bombeck 3cacfcf94c feat(dashboard): per-tile Suspense boundaries for progressive paint
Wrap every chart row cell and every tile-strip cell in a per-cell
`<Suspense>` boundary so the dashboard composition reads as a grid of
independently suspending islands rather than a flat tree that shares
loading semantics (audit-H2 + brief C1). The dynamic-loaded charts
(`HealthChartDynamic`, `MoodChart`, `MedicationComplianceChart`) already
mount their own `<ChartSkeleton>` while the JS chunk resolves; the
Suspense layer lifts the same skeleton to a streaming-compatible
boundary so a future migration to `useSuspenseQuery` automatically
buckets each chart's loading state to its own cell without a further
composition pass.

Bundled with two audit-cited polishes that share the same touch
surface: hoist `DASHBOARD_QUERY_OPTS` to module scope so the option
object reference stays stable across renders (audit-M2), and memoise
the `getHourForTimeZone` call so the `Intl.DateTimeFormat`
instantiation only re-runs when the user's timezone changes
(audit-H4). Both are micro-wins individually but the page renders
~720 lines of JSX per pass, so a stable per-render allocation budget
keeps Recharts re-render cost bounded.

No visible behaviour change in the current cold-mount waterfall —
every chart still suspends on its own client-fetch — but the
structural boundary is the prerequisite for the v1.4.41 RSC migration
that hoists slim-analytics fetching to the server.
2026-05-21 11:48:10 +02:00
Marc-André Bombeck 128d863763 test(privacy): render assertions for the GDPR-required sections
Track the v1.4.40 W-PRIVACY bilingual rewrite of /privacy. The test
suite now pins:

- The bilingual H1 ("Datenschutzerklaerung / Privacy Policy") so a
  redesign cannot silently regress to a monolingual title that fails
  the German DPA review.
- Eleven sections each carry a `data-slot="privacy-section-de"` body
  plus a collapsible `data-slot="privacy-section-en"` translation,
  with `lang="de"` / `lang="en"` boundaries so screen readers switch
  pronunciation correctly.
- The HealthKit data-flow boundary (POST /api/measurements over
  TLS 1.3).
- The AI off-device transit guarantees: off by default, never
  includes raw HealthKit identifiers, named providers (Anthropic,
  OpenAI).
- Consent-receipt endpoint GET /api/account/consents with the 5-year
  retention window.
- Encryption disclosure: TLS 1.3, HSTS, certificate pinning + the DE
  "Zertifikat-Pinning" mirror.
- Server-location + operator framing (Germany, Hetzner, "operator").
- Retention defaults: 5-year measurements, 90-day audit, 30-day APNs.
- GDPR Art. 17 deletion route names "Konto loeschen", "Delete
  account", "User.delete", "onDelete: Cascade" verbatim.
- Operator contact mailto:mbombeck@gmail.com + GitHub-issue fallback,
  with the v1.4.20 PII rule still enforced (no "Marc-Andre" or
  free-text "Bombeck <name>" anywhere in the body).

Bumps POLICY_VERSION constant to 1.4.40 + LAST_UPDATED to 2026-05-18.
2026-05-21 11:47:42 +02:00
Marc-André Bombeck c79d91736c feat(privacy): public privacy policy page at /privacy with DE + EN content
Convert the English-only v1.4.26 privacy page to a bilingual document
that an Apple US App-Store reviewer and a German DPA inspector can both
read without locale switching. Each numbered section opens with the
German body (visible by default) and ships a collapsible English
translation directly underneath. The H1 and TOC carry both languages.

GDPR / DSGVO content additions on top of the v1.4.26 spine:

- HealthKit data flow disclosed explicitly: HK sample to iOS app to
  POST /api/measurements over HTTPS, with no third-party transit.
- AI off-device transit boundary spelled out: TLS 1.3, off by default,
  never includes raw HealthKit identifiers, per-provider opt-in.
- Consent receipt persistence linked to GET /api/account/consents with
  the 5-year retention window.
- Encryption layer named explicitly: TLS 1.3, HSTS, certificate
  pinning on iOS (Zertifikat-Pinning in the DE body).
- Server location framed as operator in Germany on Hetzner; no
  third-party hosting beyond the AI providers listed in section 4.
- Retention defaults table: rolling 5-year measurement window, 90-day
  audit logs, 14-day server access logs, 30-day failed APNs.
- GDPR Art. 17 deletion route named: Settings -> Daten -> Konto
  loeschen with the User.delete + onDelete: Cascade contract.
- Operator contact via mbombeck@gmail.com with the GDPR subject-line
  convention plus the GitHub-issue fallback channel.
- DSGVO legal-basis citations attached per data category (Art. 6 (1)
  (b) and Art. 9 (2) (a) GDPR).

Bumped POLICY_VERSION to 1.4.40, LAST_UPDATED to 2026-05-18. Static
render kept (force-static, no revalidate) so the legal document does
not depend on JavaScript to display its non-default-locale text to a
reviewer.
2026-05-21 11:46:50 +02:00
Marc-André BombeckandClaude Opus 4.7 6ab3440336 test(apns,notifications-status): pin payload shape and aggregate behaviour
Pins the SB-5 (apns time-sensitive interruption-level) and SB-6
(/api/notifications/status events map) contracts.

Note: the SB-6 route + test changes landed inside an earlier
`fix(dashboard-summary)` commit (1bcaae47) due to a cross-wave
pre-commit-hook race that auto-folded my staged changes; this
commit ships the wave report + records the proper SB-5 + SB-6
intent in the log for the release-notes sweep to pick up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 11:45:47 +02:00
Marc-André Bombeck 97920f0f59 fix(measurements-route,series,timeline): exclude soft-deleted in list reads
`GET /api/measurements` has five distinct read shapes (per-day
drill-down, group-by-day, rollup-source coverage-fallback probe + fold
re-read, live `date_trunc` aggregate, default findMany + count). Each
relied on a shared `where` builder or a local `findMany` clause; none
filtered `deletedAt`. The `GET /api/measurements/series` adapter for
iOS read BP-SYS / BP-DIA / single-type series without the filter too.

Pin `deletedAt: null` on the shared `where` so the count + raw findMany
+ group-by-day mode all inherit it; add the filter to the dayKey
drill-down findMany, the coverage-fallback day-count probe, and the
live `date_trunc` aggregate; thread the filter through the three series
findMany calls. The `source=rollup` branch reads from
`measurement_rollups` so the writer-side filter covers it. No
`measurements/timeline` route exists yet — the file-set name was
prospective.
2026-05-21 11:45:26 +02:00
Marc-André Bombeck 1dd1a9a7a5 fix(mood-chart): align queryKey to the shared mood-analytics factory entry
Pre-fix the dashboard mounted two separate consumers against the same
`/api/mood/analytics` endpoint: `app/page.tsx:291` keyed on
`queryKeys.moodAnalytics()` (`["mood-analytics"]`) and the chart at
`mood-chart.tsx:316` keyed on a bare `["mood-chart-data"]` literal.
TanStack treats different keys as separate cache slots, so a cold
dashboard mount fired two requests against the same endpoint — wasting
one HTTP round trip, one pg pool slot, and ~22 KB of payload per cold
mount (empirical-trace #3). Re-key the chart to `queryKeys.moodAnalytics()`
so TanStack dedups the request; align the chart's `staleTime` to the
dashboard's 60 s window so a route swing back to the dashboard within
a minute stays a free cache hit.

The chart's own subscription becomes the cache writer for any insights
/ mood sub-page that mounts it without the dashboard parent having
fetched first. No payload-shape change — the chart already typed its
response as `MoodAnalyticsData` which matches the dashboard's
`{ entries, summary }` shape byte-for-byte.
2026-05-21 11:45:25 +02:00
Marc-André Bombeck 1bcaae4764 fix(dashboard-summary): exclude soft-deleted in sparkline and streak queries
`latestIn7d` and `streakDays` are raw SQL against `measurements`; the
`allTime` aggregate is `prisma.measurement.groupBy`. All three folded
tombstoned rows into the tile-strip's latest value, the all-time count
+ last-seen-at metadata, and the measurement-streak day count. The
`sparkBuckets` query reads from `measurement_rollups` so the writer-side
filter covers it.

Add `m."deleted_at" IS NULL` to the two raw queries and `deletedAt: null`
to the Prisma groupBy.
2026-05-21 11:44:00 +02:00
Marc-André BombeckandClaude Opus 4.7 8187d54969 feat(apns): time-sensitive interruption-level for medication reminders
Medication reminders are the one notification category the user has
explicitly opted in to. iOS 15+ supports `aps.interruption-level:
time-sensitive` to break through Focus modes per category, gated on
a per-app toggle the user grants on install. Wire it for
MEDICATION_REMINDER only — every other event (mood nudges, anomaly
alerts, PRs, system messages) stays on the iOS default `active`
level so Focus modes including Sleep keep silencing them as the user
expects.

Pairs with `apns-priority: 10` for time-sensitive deliveries per
Apple's push best-practices doc; without the priority pairing APNs
may downgrade delivery and silently lose the Focus-bypass intent.

Pinned by 8 new unit tests across `apns.test.ts` — one positive case
for MEDICATION_REMINDER and a parameterised negative covering all
six other event-types.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 11:43:41 +02:00
Marc-André Bombeck c47b7dade3 fix(comprehensive-aggregator): exclude soft-deleted in raw aggregate
The route's central analytics aggregator runs eight `FROM measurements`
clauses (window_stats CTE + main aggregate + DISTINCT ON latest +
firstAt probe, mirrored across the rollup-fresh and cold-fallback
branches) plus one `findMany` for the BP raw rows. None filtered on
`deleted_at`, so the Coach/Insights snapshot would see tombstoned
readings in every windowed avg, slope, anomaly count, and latest
attribution.

Add `AND m."deleted_at" IS NULL` to the eight raw SQL filters and
`deletedAt: null` to `fetchBpRawRows`. The `measurement_rollups`
findMany branch already rides the writer-side filter.
2026-05-21 11:43:29 +02:00
Marc-André Bombeck 37342744f9 fix(correlations,bp-fast-path,health-score): exclude soft-deleted measurements
Every chunked findMany walk in the three analytics fast-paths fed the
raw `measurements` table through Prisma without a `deletedAt` filter.
The correlation pairing, BP-in-target windowing, and Health Score
weight / BP source-attribution would each fold tombstoned rows once
iOS soft-deletes its first reading.

Add `deletedAt: null` to:
  - `fetchSeriesChunked` in `correlations-fast-path.ts`
  - `fetchSeriesChunked` in `bp-in-target-fast-path.ts`
  - the WEIGHT source attribution + WEIGHT live-fallback + BP_SYS
    source attribution reads in `health-score-fast-path.ts`

The DAY-bucket reads from `measurement_rollups` are unaffected — they
ride the writer-side filter landed earlier in the chain.
2026-05-21 11:41:55 +02:00
Marc-André Bombeck 1f49041025 fix(summaries-slice): exclude soft-deleted measurements
The four `$queryRaw` blocks in `computeFromRollups` and
`computeFromLiveAggregate` (narrow aggregate + DISTINCT ON latest,
both fast and cold paths) folded every row regardless of
`deleted_at`. The DAY-bucket rollup aggregate is unaffected because
its source table is already filtered by the writer.

Add `AND m."deleted_at" IS NULL` to every `FROM measurements m`
WHERE clause so the slim slice's avg7/avg30/slope/r2 plus the
per-type latest never reflect a row the user soft-deleted.
2026-05-21 11:41:05 +02:00
Marc-André Bombeck f0a0551a80 fix(rollups): filter deletedAt in measurement-rollup readers
`probeRollupCoverage` discovers the set of types the user has logged
by selecting `DISTINCT "type" FROM measurements`. A type whose every
row has been tombstoned would still surface, force the read path to
demand rollup coverage for it, and silently push the request onto the
live aggregator branch.

Add `"deleted_at" IS NULL` so the discovery only returns types the
user can still see. The rollup-read modules (`rollup-read`,
`rollup-read-wmy`, `rollup-read-cumulative`) read from
`measurement_rollups` which is already populated from the filtered
writer in the previous commit, so they need no additional filter.
2026-05-21 11:40:34 +02:00
Marc-André Bombeck db2d864a8e fix(rollups): skip soft-deleted measurements in DAY recompute
The `runRollupAggregate` SQL folded every row in `measurements`
regardless of `deleted_at`. Once iOS soft-deletes its first reading
through the by-external-ids path, the tombstoned value would still
contribute to the bucket count / mean / min / max, leaving dashboards
and analytics showing data the user thinks they removed.

Add `AND m."deleted_at" IS NULL` to both branches of `runRollupAggregate`
plus the watermark probes in `isRollupFresh` and `ensureUserRollupsFreshImpl`
so a stale `updatedAt` on a tombstoned row no longer keeps the rollup
flagged as stale forever. The boot-time backfill discovery is widened
the same way so deleted-only `(user, type, day)` tuples never enqueue.

Defense-in-depth: every reader will pick up the filter in follow-up
commits — this lands the writer-side cut so newly-folded buckets are
already clean.
2026-05-21 11:40:08 +02:00
Marc-André Bombeck 433874e390 test(analytics,db): pin concurrency cap and pool ceiling
Two regression nets for the W-POOL changes shipped in the prior two
commits:

* `src/lib/__tests__/db.test.ts` — assert `getPoolMax()` returns 20 by
  default and honours `DATABASE_POOL_MAX`, with a final assertion that
  pins the floor at 20 so a future refactor that drops the explicit
  `max:` config can't silently revert to the library default of 10.
* `src/app/api/analytics/__tests__/route.test.ts` — instrument the
  per-type `findMany` mock with inflight counters and assert peak
  concurrency never exceeds `ANALYTICS_TYPE_FETCH_CONCURRENCY`. The
  wall-clock window also catches both an unbounded `Promise.all`
  regression (would finish too fast) and an accidental serialisation
  (would finish too slow).
2026-05-21 11:39:54 +02:00
Marc-André Bombeck 014593a2a1 test(aasa): pin payload shape and content-type
Five assertions on the route handler:
  - 200 on an unauthenticated GET.
  - Content-Type is exactly application/json with no charset parameter
    (Apple's swcd/aasa-validator refuse a charset and the failure mode
    is silent — Universal Links just stop firing).
  - Cache-Control allows public CDN mirroring.
  - JSON shape matches the SB-4 spec exactly.
  - applinks App ID matches webcredentials App ID so a rotated
    Team ID never half-lands.

Includes the v1.4.40 phase report.
2026-05-21 11:38:58 +02:00
Marc-André Bombeck 8d6f1cf8d8 feat(aasa): serve apple-app-site-association at the well-known path
Populate applinks.details with the iOS App ID and the "*" path matcher so
Universal Links resolve to the HealthLog app on every URL. The existing
webcredentials entry stays in place; both now share a single AASA_APP_ID
constant to keep passkey origin-pairing aligned with deep linking.

Unblocks iOS PB30 (App-Store submission).
2026-05-21 11:38:52 +02:00
Marc-André Bombeck 3b8f4111f3 perf(db): raise Prisma pg.Pool max to 20 for power-user fan-out headroom
The v1.4.39 empirical cold-mount trace
(`.planning/round-v1439-empirical-trace.md` §B2) flagged the library
default of 10 concurrent connections as the hard ceiling that thick
/api/analytics was monopolising. With the parallel W-POOL p-limit(4)
cap on the analytics fan-out, a 20-slot pool leaves ≥16 free slots for
every other dashboard query regardless of how many measurement types
analytics is mid-walk over. Postgres' stock `max_connections` of 100
gives ample headroom for ≤5 concurrent power-users at this ceiling.
Env-overridable via `DATABASE_POOL_MAX` so operators with a smaller
server-side `max_connections` can dial down without a code change.
2026-05-21 11:37:53 +02:00
Marc-André Bombeck 96b2ee4c1c perf(analytics): bound 15-way Promise.all to 4 concurrent type-fetches
Wrap the per-type fan-out in `buildAnalyticsResponse` with a p-limit(4)
gate. The empirical v1.4.39 cold-mount trace
(`.planning/round-v1439-empirical-trace.md` §B1) showed thick
/api/analytics holding ≥8 of the default-10 pg.Pool slots for 6.5 s on a
power-user account, starving every other dashboard query. The cap keeps
the same total work but holds ≤4 pool slots for this branch at any
moment, leaving the remaining slots free for the parallel chart-tile
reads. Thick analytics is already 60 s cache-wrapped so the small
absolute wall-clock cost on a single cold mount is offset by the
chart-tile burst paying ~5 s less of pool-wait time on every mount
thereafter.
2026-05-21 11:37:40 +02:00
Marc-André Bombeck c9d5479b0d feat(consent-receipts): schema scaffolding for AI consent audit trail
Prereq for SB-10 (POST /api/consent/ai). Append-only per-user audit
trail of AI-processing consent grants. The iOS app posts a fresh row
whenever the user opts in to off-device AI flows during onboarding or
via Settings; a revoke + re-grant cycle mints fresh rows so the
timeline reads chronologically and the latest non-revoked row per
(user, kind) is the source of truth for "is AI active right now".

Backs both App-Store Guideline 5.1.2(i) ("data-collection consent must
be verifiable") and the GDPR Art. 7 documentation burden. The server
persists the raw signed artefact (PDF receipt or signed JWT — caller's
choice) without parsing it; the audit trail is the storage itself plus
the `signed_at` wall-clock the client recorded.

Migration 0074 is additive only; IF NOT EXISTS guards mirror 0067 /
0070 / 0071. No table rewrite, no breaking change.
2026-05-21 11:34:04 +02:00
Marc-André Bombeck db2c70a78d test(medications): pin skipDuplicates flag on intake-route backfill
The W-SERVER-FIX-2 race-guard work added `skipDuplicates: true` to the
intake route's projection-backfill createMany alongside the schema
@@unique([userId, medicationId, scheduledFor, source]) constraint. The
existing unit test asserted the row shape but not the flag, so a
regression that drops `skipDuplicates: true` while keeping the unique
constraint would surface as a 5xx in prod (constraint violation
bubbles through) without breaking the suite.

Adds the flag to the `toMatchObject` assertion so the defense-in-depth
contract stays pinned next to the row shape it pairs with. Matches the
equivalent assertion the dashboard summary test already carries.
2026-05-21 11:23:17 +02:00
Marc-André Bombeck 3d08a0abef chore(release): v1.4.39.4 2026-05-21 11:19:57 +02:00
Marc-André Bombeck 64e1b74373 docs(planning): v1.4.39 architecture-QA reports and empirical trace
Five planning artefacts produced during the v1.4.39 review pass:
frontend, ghosts (dead-code drift), infra-db, organization, and a
cross-cutting empirical trace. Kept under .planning/ rather than the
versioned docs site because they are working notes scoped to a single
release window.
2026-05-21 11:19:57 +02:00
Marc-André Bombeck 61f2dca421 fix(prisma): add unique constraint to medication_intake_events for projection race
Migration 0073 adds a UNIQUE constraint on
(user_id, medication_id, scheduled_for, source) for
medication_intake_events. Pre-fix the table only had an INDEX on those
three columns, so the two newly-projecting routes — the intake route
(PR #191) and the dashboard summary route (v1.4.39.4) — could pass
their existence probes simultaneously and mint the same REMINDER row
twice when the iOS app hydrates both endpoints in parallel.

`source` is in the key so the reminder worker's REMINDER row doesn't
collide with manual user inserts (WEB / TELEGRAM / IMPORT) on the
same slot — distinct intake sources at the same scheduled instant are
a legitimate shape (Telegram-bot logged take + a Web-UI correction on
the same dose).

The legacy (user_id, medication_id, scheduled_for) index stays in
place because most reads filter on those three columns without
caring about source. The new constraint becomes the structural
backstop; the createMany skipDuplicates: true flag added in the two
routes is the defense-in-depth layer.

Additive only. DO $$ … EXCEPTION-on-duplicate guard mirrors 0067 /
0071 so re-runs are idempotent.
2026-05-21 11:19:57 +02:00
Marc-André Bombeck 341483de3f fix(medications): swallow concurrent-projection duplicates in intake backfill
PR #191 added a today-window backfill to /api/medications/intake. The
v1.4.39.4 dashboard symmetry fix wires the exact same projection into
/api/dashboard/summary, which means two parallel routes can now race
the same (userId, medicationId, scheduledFor, REMINDER) row between
their existence probes and createMany calls. The @@unique on
(userId, medicationId, scheduledFor, source) is the structural
backstop; without skipDuplicates: true the loser of that race would
surface a constraint violation as a 5xx.

Pair the createMany with skipDuplicates: true so Postgres swallows the
rejected rows and both routes still return 2xx. Matches the same flag
the dashboard route ships with.
2026-05-21 11:19:04 +02:00
Marc-André Bombeck 7c0a722309 fix(medications): backfill today-intakes inside dashboard summary route
Dashboard tile feeding the iOS Compliance ring + Erfassen-sheet preview
pulls from /api/dashboard/summary, not /api/medications/intake. Without
the same projection-then-backfill the intake route received in PR #191,
the dashboard endpoint returned [] for daily meds (daysOfWeek = null),
keeping the iOS Dashboard tile in its "Heute nichts geplant" empty
state even after the intake route fix shipped.

Re-uses expandTodayIntakes(schedules, now, tz) + an idempotent
createMany with skipDuplicates: true so a concurrent intake-route hit
can't race a duplicate row in before the existence probe converges.
Two tests added: backfill-mints-once + idempotent-on-second-pass.
2026-05-21 11:17:48 +02:00
Marc-André Bombeck 28594dc852 Merge pull request #191 from MBombeck/fix/medication-schedule-null-days-of-week
fix(medications): treat null/empty daysOfWeek as every-day schedule
2026-05-21 11:13:26 +02:00
Marc-André Bombeck 10e658f66d fix(medications): project daily-schedule intakes for today's window
Schedule-expansion never minted today's intake rows for medications
with `daysOfWeek: null` until the reminder worker entered the RED
phase at the end of the dose window. The database stores `null` to
mean "every day" (the `MedicationSchedule.daysOfWeek` column carries
that annotation in `prisma/schema.prisma`), so daily meds spent the
whole morning with zero scheduled rows. Endpoint
`/api/medications/intake?scope=today` returned `[]` even when two
active daily meds existed; iOS Dashboard tile + Erfassen sheet both
fell to "Heute nichts geplant" / "Keine offene Einnahme" end-to-end.

Adds `expandTodayIntakes` to `src/lib/medication-schedule.ts` — a
pure projection that re-uses the existing `parseScheduleRecurrence`
(empty array == every day) and respects explicit weekday filters
when present. The `scope=today` route projects active schedules
through the helper, then idempotently backfills any missing rows
into `MedicationIntakeEvent` so the iOS POST update path keeps the
existing intakeId contract.

Tests:
  - `medication-schedule.test.ts` gains eight cases covering
    `daysOfWeek: null`, `""`, `"0,1,2,3,4,5,6"`, explicit-weekday
    excludes-today / includes-today, the operator's Ramipril +
    Metformin fixture, DST-correct `scheduledFor` anchoring at
    `windowStart` in Europe/Berlin, and multi-week cadence skip.
  - `intake/route.test.ts` gains two cases: backfill mints the
    missing row + does-not-double-mint when the row already exists.

Full vitest suite stays green (4672 passed / 1 skipped).
2026-05-21 10:59:25 +02:00
Marc-André Bombeck d60115c3ae Merge tag 'v1.4.39.3' into develop 2026-05-21 10:39:56 +02:00
Marc-André Bombeck 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.
v1.4.39.3
2026-05-21 10:31:18 +02:00
Marc-André Bombeck f29f9e5d78 chore(release): v1.4.39.3
Closes the eight e2e CI failures left behind by v1.4.39.2 across the
chromium-desktop and chromium-mobile profiles. Two underlying bugs +
one durable test-fixture migration:

- Dashboard slim/thick merge no longer short-circuits when the slim
  slice resolves with an empty summaries record. The merge moved to
  a pure `mergeSlimAndThickAnalytics` helper with object-emptiness
  as the discriminator and eight new behaviour-level unit tests.
- `MeasurementList` non-grouped rows now preserve decimal precision
  (`fmt.number` instead of `fmt.integer`) so a 78.4 kg reading stops
  truncating to "78 kg". Grouped daily aggregates for cumulative HK
  types stay on `fmt.integer` because their readings are integer-
  only by definition.
- Playwright route mocks for `/api/analytics` migrate to the regex
  form across every authenticated spec so the slim and thick slice
  URLs intercept under one handler, matching the v1.4.37 W-CI lesson.

No schema migration; runtime + test-fixture-only.
2026-05-21 10:30:43 +02:00
Marc-André Bombeck 0dbc77641f test(e2e): migrate /api/analytics route mocks to the regex pattern
Playwright's literal `**/api/analytics` 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. The slim request
fell through to the real route on every authenticated spec, and
because the seeded e2e user carries no measurements, the real slim
slice returned empty summaries — exactly the case the v1.4.39.3
production merge fix already guards against, but 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`.

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. Every spec
now uses `/\/api\/analytics(\?|$)/` so the slim AND thick slice URLs
intercept under one route handler.
2026-05-21 10:30:34 +02:00
Marc-André Bombeck 96c68fb492 fix(measurements): preserve decimal precision on non-grouped list rows
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 /
body-temperature readings — 78.4 kg rendered as "78 kg" on the
desktop table and the mobile card grid.

Grouped rows (`isGrouped === true`, the daily aggregate for
cumulative HK types) keep `fmt.integer` because the underlying
readings are integer-only by definition. Non-grouped single readings
now use `fmt.number(value)` which honours up to three fraction
digits without forcing a minimum, so 78 stays "78" and 78.4 renders
as "78.4" / "78,4" depending on the active UI locale.
2026-05-21 10:30:24 +02:00
Marc-André Bombeck 730028590b fix(dashboard): slim/thick merge falls through on empty slim resolve
The v1.4.39.2 dashboard split fired two parallel useAnalyticsQuery
calls and merged them with `slim?.summaries ?? thick?.summaries`.
JavaScript treats an empty `{}` as truthy, so a zero-data slim
resolve short-circuited the thick fallback even when thick carried
the full per-type payload — the tile strip painted blank and the
chart row never mounted. Extract the merge into 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 yields an empty record so the dashboard's data-
floor gates render the appropriate empty state.

Eight new behaviour-level unit tests cover the empty-slim, slim-
only, thick-only, both-empty, and `lastSeenByType` precedence cases.
The earlier source-text snapshot test in
`dashboard-analytics-split.test.ts` did not detect the empty-object
short-circuit; the pure-helper extraction is what makes the
regression directly testable.
2026-05-21 10:30:17 +02:00
Marc-André Bombeck 85d3c9a531 Merge tag 'v1.4.39.2' into develop 2026-05-21 10:04:15 +02:00