chore(release): v1.4.25

Largest feature delta in the v1.4.x line. Insights expands into seven dedicated metric sub-pages; GLP-1 medication tracking lands end-to-end (drug-level chart with Research Mode acknowledgment, EMA titration ladder, cadence + compliance, side-effect taxonomy, pen/vial inventory); cross-source priority becomes a two-axis resolver; per-user timezone threads through ten analytics surfaces; Withings activity + sleep v2 sync; onboarding rebuilt as a nested-route wizard; Personal Records ship end-to-end; Health Score provenance accordion; Coach runs native first-party prompts across six locales with a 1800-assertion refusal-probe matrix; OpenAPI drift gate hard-fails; multi-arch GHCR image. Migrations 0043 through 0060 are additive and forward-only. PROMPT_VERSION 4.24.0 → 4.25.0 with GROUND RULE 9 (refuses dose recommendations) and GROUND RULE 15 (refuses drug-level estimates with MDR + MDCG 2021-24 cites).

See CHANGELOG.md for the full per-section delta.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-14 23:49:32 +02:00
1 parent de0689e419
commit 17b8d8d2c2
528 files changed
+104033 -6524

No files matched your search

@@ -0,0 +1,23 @@
-- v1.4.25 W7 — per-user timezone feature (Option B from
-- `.planning/feature-user-timezone.md`).
--
-- HealthLog already ships a `users.timezone` column (default
-- 'Europe/Berlin', NOT NULL) from the original schema, so the
-- per-user side of this feature is non-additive at the storage
-- layer: the existing column is the canonical "display timezone"
-- that the resolver in `src/lib/tz/resolver.ts` reads. No change is
-- required on `users`.
--
-- The admin-managed default for *new* accounts is the only new
-- column. It lives on the singleton `app_settings` row and is
-- nullable so the resolver can fall back to "Europe/Berlin" when an
-- operator never touches the setting. Validated against
-- `Intl.supportedValuesOf('timeZone')` upstream — the column is just
-- a varchar(64) bag.
--
-- Forward-only / additive: ALTER TABLE ADD COLUMN with a nullable
-- type and no default. Existing rows are untouched. Rollback would
-- be a manual DROP COLUMN.
ALTER TABLE "app_settings"
ADD COLUMN IF NOT EXISTS "default_user_timezone" VARCHAR(64);
@@ -0,0 +1,22 @@
-- v1.4.25 W7b — MoodEntry.tz column (proposal §7 Decision A).
--
-- HealthLog historically wrote `MoodEntry.date` (YYYY-MM-DD) under
-- the implicit Europe/Berlin assumption. Per-user timezone (Option B,
-- feature `feature-user-timezone.md`) makes that assumption wrong for
-- non-Berlin users — a 23:50 NZST reading would bucket into the
-- Berlin day, one day earlier than the user's own "today".
--
-- The fix is per-row tz attribution:
--
-- - New rows: writer captures `User.timezone` at write time, stores
-- it on the row, and computes `date` using that zone.
-- - Legacy rows: `tz IS NULL` is interpreted as "Europe/Berlin"
-- read-side. The historical bucketing stays consistent with the
-- numbers users have already seen.
--
-- Forward-only, additive, idempotent. No backfill is required because
-- the read-path treats `tz IS NULL` as Europe/Berlin (the value those
-- rows would carry if backfilled). Rollback is a manual DROP COLUMN.
ALTER TABLE "mood_entries"
ADD COLUMN IF NOT EXISTS "tz" VARCHAR(64);
@@ -0,0 +1,24 @@
-- v1.4.25 W6c — per-user Doctor-Report section toggles.
--
-- The doctor-report dialog used to print every available data type
-- whether the user wanted it or not. Marc's directive 2026-05-14: users
-- decide which sections appear in their PDF, and the choice persists so
-- a follow-up export starts from the same picks.
--
-- Shape:
-- { "bp": boolean,
-- "weight": boolean,
-- "pulse": boolean,
-- "bmi": boolean,
-- "mood": boolean, -- privacy-sensitive; default OFF
-- "compliance": boolean,
-- "sleep": boolean }
--
-- Null = "use defaults": every section ON except mood. The privacy
-- default for mood is intentional — mental-health data should be opt-in,
-- not opt-out, even within a single user's own surface.
--
-- Forward-only, additive, idempotent. No backfill: a NULL row maps to
-- the documented defaults at read time.
ALTER TABLE "users"
ADD COLUMN IF NOT EXISTS "doctor_report_prefs_json" JSONB;
@@ -0,0 +1,127 @@
-- v1.4.25 W4d — GLP-1 full integration (research §5).
--
-- Adds the foundation for first-class GLP-1 receptor agonist support
-- (Mounjaro, Ozempic, Wegovy, Zepbound, Trulicity, Saxenda, Rybelsus,
-- compounded semaglutide/tirzepatide). Holistic landing — schema +
-- snapshot + Coach guardrails + UI variants — happens together so the
-- feature surfaces all at once instead of trickling in across releases.
--
-- Design principle: every change is additive. Existing medications keep
-- working untouched. The new columns default to NULL / GENERIC so the
-- previous read paths read the same shape they did before the migration.
--
-- Shapes:
-- - MedicationCategory enum (GENERIC default; GLP1 turns on the
-- specialist code paths). Future categories — INSULIN, BIOLOGIC,
-- FERTILITY — drop into this enum.
-- - Medication.treatment_class column with GENERIC default. The
-- existing `medication_categories` side-table (BLOOD_PRESSURE /
-- VITAMIN / ...) tracks the clinical taxonomy and stays put — it
-- is a different concept (clinical category) and the UI keeps
-- reading it under the existing `category` slot. The new column
-- models "medication kind that needs special handling" so the
-- GLP-1 surfaces (card variant, dashboard tile, Coach snapshot)
-- have a single boolean-ish discriminator.
-- - Medication.doses_per_unit — nullable integer; only meaningful for
-- pen / vial meds (Mounjaro KwikPen = 4 doses, Ozempic 0.25/0.5 mg
-- = 4 doses, Wegovy single-dose pen = 1 dose, compounded vials
-- vary). NULL = inventory tracking is off for this medication.
-- - MedicationDoseChange — append-only titration history. The
-- current dose is "latest row by effective_from". Existing
-- Medication.dose remains the convenience pointer; this table is
-- the history of record.
-- - InjectionSite enum (8 zones — front-of-body view: 4 abdomen
-- quadrants, 2 thighs, 2 upper arms). The body-map picker maps each
-- zone to a clickable region.
-- - MedicationIntakeEvent.injection_site — nullable; only populated
-- for GLP-1 intake events. Existing rows stay NULL and read
-- untouched.
-- - MedicationInventoryEvent — append-only inventory log. Positive
-- delta = stock added (purchase), negative = consumed (one per
-- intake event when doses_per_unit is set). Reason is a free-text
-- audit slot ("purchased", "consumed", "expired", "damaged").
--
-- Forward-only, additive, idempotent. No backfill: every new column
-- carries a sensible NULL/default, and the read paths handle the
-- pre-migration shape verbatim.
-- 1. MedicationCategory enum.
DO $$ BEGIN
CREATE TYPE "medication_category" AS ENUM ('GENERIC', 'GLP1');
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
-- 2. Medication.treatment_class + Medication.doses_per_unit columns.
ALTER TABLE "medications"
ADD COLUMN IF NOT EXISTS "treatment_class" "medication_category" NOT NULL DEFAULT 'GENERIC';
ALTER TABLE "medications"
ADD COLUMN IF NOT EXISTS "doses_per_unit" INTEGER;
CREATE INDEX IF NOT EXISTS "medications_treatment_class_idx" ON "medications" ("treatment_class");
-- 3. InjectionSite enum + MedicationIntakeEvent.injection_site column.
DO $$ BEGIN
CREATE TYPE "injection_site" AS ENUM (
'ABDOMEN_LEFT',
'ABDOMEN_RIGHT',
'ABDOMEN_UPPER_LEFT',
'ABDOMEN_UPPER_RIGHT',
'THIGH_LEFT',
'THIGH_RIGHT',
'UPPER_ARM_LEFT',
'UPPER_ARM_RIGHT'
);
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
ALTER TABLE "medication_intake_events"
ADD COLUMN IF NOT EXISTS "injection_site" "injection_site";
-- 4. MedicationDoseChange — titration history.
CREATE TABLE IF NOT EXISTS "medication_dose_changes" (
"id" TEXT NOT NULL,
"medication_id" TEXT NOT NULL,
"effective_from" TIMESTAMP(3) NOT NULL,
"dose_value" DOUBLE PRECISION NOT NULL,
"dose_unit" TEXT NOT NULL,
"note" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "medication_dose_changes_pkey" PRIMARY KEY ("id")
);
DO $$ BEGIN
ALTER TABLE "medication_dose_changes"
ADD CONSTRAINT "medication_dose_changes_medication_id_fkey"
FOREIGN KEY ("medication_id") REFERENCES "medications"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
CREATE INDEX IF NOT EXISTS "medication_dose_changes_medication_id_effective_from_idx"
ON "medication_dose_changes" ("medication_id", "effective_from");
-- 5. MedicationInventoryEvent — append-only inventory ledger.
CREATE TABLE IF NOT EXISTS "medication_inventory_events" (
"id" TEXT NOT NULL,
"medication_id" TEXT NOT NULL,
"delta" INTEGER NOT NULL,
"reason" TEXT NOT NULL,
"occurred_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "medication_inventory_events_pkey" PRIMARY KEY ("id")
);
DO $$ BEGIN
ALTER TABLE "medication_inventory_events"
ADD CONSTRAINT "medication_inventory_events_medication_id_fkey"
FOREIGN KEY ("medication_id") REFERENCES "medications"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
CREATE INDEX IF NOT EXISTS "medication_inventory_events_medication_id_occurred_at_idx"
ON "medication_inventory_events" ("medication_id", "occurred_at");
@@ -0,0 +1,24 @@
-- v1.4.25 W4e — medication_schedules @map to snake_case (cosmetic +
-- convention).
--
-- Prior to this migration `medication_schedules.windowStart` and
-- `medication_schedules.windowEnd` were the only columns on the model
-- that still used the camelCase identifier from the original
-- 0001_init.sql — every other column on the table (medication_id,
-- days_of_week) already follows the snake_case convention enforced
-- everywhere else in the schema. The drift was harmless (Prisma's
-- generated client uses the TypeScript-side `windowStart` /
-- `windowEnd` names regardless of the SQL identifier), but the
-- inconsistency tripped reviewers and made `grep window_start
-- prisma/migrations/` return zero rows.
--
-- The rename is purely a rename — the data does not move, no indexes
-- change, no foreign keys are affected. We use IF EXISTS so a
-- replayed migration on a fresh-from-schema DB (Prisma's `db push`
-- against a brand-new local) doesn't blow up trying to rename a
-- column that the schema-pushed shape already named snake_case.
--
-- Forward-only; no DOWN migration.
ALTER TABLE "medication_schedules" RENAME COLUMN "windowStart" TO "window_start";
ALTER TABLE "medication_schedules" RENAME COLUMN "windowEnd" TO "window_end";
@@ -0,0 +1,25 @@
-- v1.4.25 W5e — cross-source dedup architecture (foundation).
--
-- Adds a nullable JSON column on `users` that records per-metric-class
-- source priority. Shape matches `src/lib/validations/source-priority.ts`:
-- { "steps": ["APPLE_HEALTH", "WITHINGS", "MANUAL"],
-- "weight": ["WITHINGS", "APPLE_HEALTH", "MANUAL"],
-- ... }
-- NULL = the user has never adjusted the defaults; the analytics
-- aggregator reads `DEFAULT_SOURCE_PRIORITY` from validation code.
--
-- Why a single Json column instead of a side-table:
-- - One row per user per metric-class would mean ~15 rows per user
-- for a setting most users never touch. The Json blob keeps the
-- read-path one column lookup with no JOIN.
-- - Schema evolution is additive — adding a new metric class
-- (Apple Health workouts in v1.5, for instance) requires no
-- migration: the Zod schema gains a key, defaults carry the
-- existing priority list, and rows with the old shape continue
-- to parse with the new key falling back to its default.
--
-- Forward-only, additive. No backfill needed: existing rows keep
-- NULL and read code falls through to the documented defaults.
ALTER TABLE "users"
ADD COLUMN IF NOT EXISTS "source_priority_json" JSONB;
@@ -0,0 +1,25 @@
-- v1.4.25 W5d — Withings full coverage. Adds seven new
-- MeasurementType enum values so the Withings ingest path can land
-- body composition (Body+, Body Cardio, Body Comp, Body Scan),
-- skin temperature (ScanWatch dermal reading — DISTINCT from core
-- body temperature; sharing the bucket would corrupt analytics
-- because surface temps run ~32 °C and core ~37 °C), pulse-wave
-- velocity + vascular age (Body Cardio / Body Scan exclusives), and
-- visceral fat (Body Comp / Body Scan rating).
--
-- See `.planning/research/withings-api-coverage.md` §3 for the gap
-- scoring + the rationale of which meastypes ship in v1.4.25 vs
-- defer to v1.5.
--
-- Additive only, forward-only — every new enum value is unconditional
-- and no existing row needs to be backfilled. The Withings client
-- starts emitting these values once `src/lib/withings/client.ts`
-- gains the meastype → enum mapping (separate commit).
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'FAT_FREE_MASS';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'FAT_MASS';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'MUSCLE_MASS';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'SKIN_TEMPERATURE';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'PULSE_WAVE_VELOCITY';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'VASCULAR_AGE';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'VISCERAL_FAT';
@@ -0,0 +1,20 @@
-- v1.4.25 W5d — Withings OAuth scope tracking.
--
-- Adds a nullable `scope` column to `withings_connections` so the
-- ingest path + the Settings UI can tell which OAuth permissions a
-- given connection holds. Legacy v1.4.24 connections sit on
-- `user.metrics` only; v1.4.25 starts requesting
-- `user.metrics,user.activity` for new connections so the activity /
-- sleep endpoints unlock.
--
-- The Settings → Integrations card surfaces a reconnect banner for
-- legacy connections (`scope IS NULL` OR scope NOT LIKE
-- '%user.activity%') so the user can re-auth and gain step / active
-- energy / distance ingest.
--
-- Forward-only, additive. NULL is the documented "legacy connection"
-- sentinel; existing rows stay NULL and continue to read every
-- `user.metrics`-gated endpoint exactly as before.
ALTER TABLE "withings_connections"
ADD COLUMN IF NOT EXISTS "scope" TEXT;
@@ -0,0 +1,13 @@
-- v1.4.25 W8c — nullable device_type column on measurements.
--
-- Two-axis source-priority picker (src/lib/analytics/source-priority.ts)
-- reads this column to break ties when more than one device contributes
-- the same source's metric (e.g. Apple Watch + iPhone both stream
-- HealthKit steps via APPLE_HEALTH). NULL columns map to "unknown" in
-- the picker, so legacy rows continue to work without a backfill.
--
-- Canonical values documented in src/lib/validations/source-priority.ts
-- under `deviceTypeEnum`: watch | band | ring | phone | scale | other |
-- unknown. Stored as free text to avoid coordinated enum bumps across
-- the iOS client and server every time a new device class arrives.
ALTER TABLE "measurements" ADD COLUMN "device_type" TEXT;
@@ -0,0 +1,30 @@
-- v1.4.25 W8d — Apple Health server-contract prep. Three new
-- MeasurementType enum values close the iOS-17/18 HK coverage gap
-- before the v1.5 iOS-Swift session:
-- * AUDIO_EXPOSURE_ENV — HK `environmentalAudioExposure`
-- (ambient noise; dBA SPL). Watch + iPhone microphone samples.
-- * AUDIO_EXPOSURE_HEADPHONE — HK `headphoneAudioExposure`
-- (AirPods listening-volume sampling; dBA SPL).
-- * TIME_IN_DAYLIGHT — HK `timeInDaylight` (iOS 17+;
-- minutes/day). Mood + sleep correlate.
--
-- The previous task brief listed a fourth value, `WORKOUT_ROUTE`. It
-- has been dropped: workouts are first-class entities with their own
-- `Workout` table (Migration 0053) and the GPS route geometry lives
-- in `WorkoutRoute`. Apple HealthKit also separates `HKWorkout` from
-- `HKQuantitySample`. Carrying a sentinel enum value on the
-- Measurement table when no real Measurement row will ever be of
-- that type would be a dead slot that confuses every downstream
-- code path (analytics summariser, doctor-PDF allow-list, chart
-- registry). Forward-additive — a future analytics rollup row can
-- still be carried on a fresh enum value if the use case ever
-- materialises.
--
-- Additive only, forward-only — every new enum value is unconditional
-- and no existing row needs to be backfilled. The Apple Health
-- mapping (`src/lib/measurements/apple-health-mapping.ts`) gains the
-- corresponding HK identifier rows in the same release.
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'AUDIO_EXPOSURE_ENV';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'AUDIO_EXPOSURE_HEADPHONE';
ALTER TYPE "measurement_type" ADD VALUE IF NOT EXISTS 'TIME_IN_DAYLIGHT';
@@ -0,0 +1,69 @@
-- v1.4.25 W8d — Workout + WorkoutRoute schema.
--
-- Locks the workout-ingest contract before the v1.5 iOS-Swift session
-- so the iOS DTO can be generated against the table layout from day
-- one. v1.4.25 ships no UI surface for workouts beyond the VO2-max
-- tile (Migration 0052 + W8d.5); the ingest endpoint + chart row
-- land in a later release.
--
-- Shape rationale (see .planning/research/w8d-implementation-outline.md
-- §4):
-- * HKWorkout-aligned typed columns for every metric the analytics
-- / doctor-PDF / Coach evidence pipeline reads on the hot path.
-- * `metadata` JSONB blob for the long-tail (HK metadata key/value
-- pairs, Withings hr_zone_0..3, device bundle id) — keeps the
-- table thin while preserving the source representation.
-- * `sport_type` as TEXT (not a Postgres enum) — Apple alone has
-- 70+ HKWorkoutActivityType values; managing them as a Postgres
-- enum would force a migration for every new sport. The Zod
-- boundary in src/lib/validations/* keeps the surface tight.
-- * Dedup on (user_id, source, external_id) — Postgres treats NULL
-- external_id as distinct so manual entries never collide.
--
-- Route geometry uses GeoJSON LineString stored as JSONB rather than
-- Postgres `point[]` or PostGIS `geometry`. v1.4.20 set the same
-- precedent for correlations: no extension dependency on every
-- self-hosted Postgres install. JSONB also matches the GPX-import
-- target shape and Leaflet / MapLibre consume it directly.
CREATE TABLE "workouts" (
"id" TEXT PRIMARY KEY,
"user_id" TEXT NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
"sport_type" TEXT NOT NULL,
"started_at" TIMESTAMP(3) NOT NULL,
"ended_at" TIMESTAMP(3) NOT NULL,
"duration_sec" INTEGER NOT NULL,
"total_energy_kcal" DOUBLE PRECISION,
"total_distance_m" DOUBLE PRECISION,
"avg_heart_rate" INTEGER,
"max_heart_rate" INTEGER,
"min_heart_rate" INTEGER,
"step_count" INTEGER,
"elevation_m" DOUBLE PRECISION,
"pause_duration_sec" INTEGER,
"source" "measurement_source" NOT NULL DEFAULT 'MANUAL',
"external_id" TEXT,
"external_source_version" TEXT,
"metadata" JSONB,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL
);
CREATE UNIQUE INDEX "workouts_user_source_external_key"
ON "workouts" ("user_id", "source", "external_id");
CREATE INDEX "workouts_user_started_idx"
ON "workouts" ("user_id", "started_at");
CREATE INDEX "workouts_user_sport_started_idx"
ON "workouts" ("user_id", "sport_type", "started_at");
CREATE TABLE "workout_routes" (
"id" TEXT PRIMARY KEY,
"workout_id" TEXT NOT NULL UNIQUE REFERENCES "workouts"("id") ON DELETE CASCADE,
-- GeoJSON LineString: { type: "LineString", coordinates: [[lon, lat, alt?], ...] }
"geometry" JSONB NOT NULL,
-- Per-sample ISO timestamps + optional speeds / HR, one entry per
-- coordinate in `geometry`. NULL when the source only ships static
-- GPX (e.g. Withings).
"sample_timestamps" JSONB,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
@@ -0,0 +1,50 @@
-- v1.4.25 W8d — PersonalRecord schema (no detection worker yet).
--
-- Schema lands now so the v1.5 iOS-Swift app can build its query path
-- against a real GET /api/personal-records route from day one. The
-- worker that populates the rows (sweep on insert / nightly job) is
-- explicitly out of v1.4.25 scope — see the deferred section in the
-- W8d phase report. v1.4.25 ships the bare list endpoint that returns
-- whatever rows the DB carries (initially empty for every user).
--
-- Direction enum (MAX | MIN) is stored on the row rather than derived
-- at read time so the future worker doesn't re-resolve a per-metric
-- lookup on every query. Some metric types deliberately carry NULL
-- direction in the helper (BP, glucose, weight, ambiguous-direction
-- metrics) — those never produce a PersonalRecord row at all, so the
-- column stays NOT NULL for the metrics where a record is actually
-- defined.
--
-- Composite uniqueness on (userId, metricType, metricSlot, achievedAt)
-- ensures the detection worker is idempotent — re-running it never
-- inserts a duplicate. A multi-source tie (e.g. iPhone + Apple Watch
-- both report 12_348 steps for the same day) is broken by including
-- `source` so each provenance retains its row; the display layer
-- runs the existing pickCanonicalSourceRows() helper to surface one.
CREATE TYPE "personal_record_direction" AS ENUM ('MAX', 'MIN');
CREATE TABLE "personal_records" (
"id" TEXT PRIMARY KEY,
"user_id" TEXT NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
"metric_type" "measurement_type" NOT NULL,
-- Sport-specific slot for workout-driven PRs (e.g. "running_5km_time").
-- NULL for measurement-driven PRs that don't need a sport dimension.
"metric_slot" TEXT,
"direction" "personal_record_direction" NOT NULL,
"value" DOUBLE PRECISION NOT NULL,
"unit" TEXT NOT NULL,
"achieved_at" TIMESTAMP(3) NOT NULL,
-- FK to the Measurement row that achieved the record. SET NULL on
-- delete so a PR survives the deletion of the originating
-- measurement (the PR is the historical fact, not a derived view).
"source_measurement_id" TEXT REFERENCES "measurements"("id") ON DELETE SET NULL,
"source" "measurement_source" NOT NULL DEFAULT 'MANUAL',
"external_id" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE UNIQUE INDEX "personal_records_dedup_key"
ON "personal_records" ("user_id", "metric_type", "metric_slot", "achieved_at");
CREATE INDEX "personal_records_user_metric_idx"
ON "personal_records" ("user_id", "metric_type", "value");
@@ -0,0 +1,35 @@
-- v1.4.25 W17b/c — extend the measurement dedup composite with sleep_stage.
--
-- The Withings Sleep v2 sync writes one Measurement row per stage segment
-- (AWAKE | LIGHT/CORE | DEEP | REM) for the same night. Every segment
-- shares (user_id, type=SLEEP_DURATION, measured_at, source=WITHINGS) —
-- only the per-stage label differentiates them. The legacy composite
-- (user_id, type, measured_at, source) collapses them onto a single row;
-- including sleep_stage in the unique key keeps every stage distinct
-- while preserving idempotency on a re-sync.
--
-- Postgres NULL semantics: a unique index treats two NULL entries as
-- DISTINCT by default, which would re-break dedup for every non-sleep
-- row (where sleep_stage IS NULL). PG15+ ships `NULLS NOT DISTINCT` as
-- a native unique-index option that flips that behaviour — two rows
-- with NULL sleep_stage now collide just like any other duplicate. The
-- application stack runs Postgres 16 (docker-compose pins
-- postgres:16-alpine), so the syntax is available everywhere HealthLog
-- deploys.
--
-- Prisma 7 still defaults to the NULLS-DISTINCT shape when it
-- regenerates the index, so this migration is hand-written. Future
-- `prisma migrate dev --create-only` runs that touch this index need to
-- preserve the `NULLS NOT DISTINCT` clause manually.
-- Drop the legacy NULLS-DISTINCT composite. The index name is the
-- Prisma 0001_init default — verified via grep on the migrations tree.
DROP INDEX IF EXISTS "measurements_user_id_type_measured_at_source_key";
-- Recreate with sleep_stage as the fifth axis and NULLS NOT DISTINCT
-- so non-sleep rows (sleep_stage IS NULL) continue to dedup on the
-- first four columns alone — same effective semantics as before for
-- every meastype that is not SLEEP_DURATION.
CREATE UNIQUE INDEX "measurements_user_id_type_measured_at_source_sleep_stage_key"
ON "measurements" ("user_id", "type", "measured_at", "source", "sleep_stage")
NULLS NOT DISTINCT;
@@ -0,0 +1,72 @@
-- v1.4.25 W19b — MedicationInventoryItem (pen / vial entity).
--
-- The existing MedicationInventoryEvent ledger (W4d) tracks running
-- stock as a stream of ±delta rows; this new model tracks the
-- *individual* pen / vial entities so the UI can show "Pen #2 of 3 —
-- 12 days left in the 30-day in-use window" rather than just an
-- aggregate count. Both surfaces coexist: the ledger is the
-- consumption stream, this model is the physical-supply inventory.
--
-- Why a dedicated entity per pen / vial:
-- - EMA EPAR §6.3 sets a 30-day in-use clock per opened pen
-- (Mounjaro KwikPen, Saxenda, Trulicity), 56 days for Ozempic.
-- The clock starts at first-use, not at purchase — so we have to
-- persist the per-pen `firstUseAt` somewhere.
-- - A pen also carries its own `printedExpiry` (the date stamped
-- on the carton), which can pre-empt the 30-day clock if the
-- printed expiry lands earlier.
-- - Dose-depletion math is per-pen (Mounjaro KwikPen = 4 doses,
-- Trulicity = 1, Byetta = 60) and needs a `dosesRemaining`
-- counter independent of the aggregate ledger.
--
-- State machine (see `src/lib/medications/inventory/state-machine.ts`):
-- ACTIVE → refrigerated, unopened (default after purchase)
-- IN_USE → opened, 30-day clock counting down from firstUseAt
-- EXPIRED → past 30-day in-use window OR past printedExpiry
-- USED_UP → all doses consumed
--
-- Composite index (user_id, medication_id, state) for the hot read
-- path: "show me my active inventory for this medication". The state
-- column is the variable axis — the UI filters on ACTIVE | IN_USE for
-- the live tile and on EXPIRED | USED_UP for the history collapsed
-- list — so it goes last in the composite for index-prefix selectivity.
CREATE TYPE "medication_inventory_state" AS ENUM (
'ACTIVE',
'IN_USE',
'EXPIRED',
'USED_UP'
);
CREATE TABLE "medication_inventory_items" (
"id" TEXT PRIMARY KEY,
"user_id" TEXT NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
"medication_id" TEXT NOT NULL REFERENCES "medications"("id") ON DELETE CASCADE,
"state" "medication_inventory_state" NOT NULL DEFAULT 'ACTIVE',
"doses_total" INTEGER NOT NULL,
"doses_remaining" INTEGER NOT NULL,
-- NULL until the pen is first opened. Sets the 30-day in-use clock.
"first_use_at" TIMESTAMP(3),
-- Computed = MIN(first_use_at + 30 days, printed_expiry). Persisted
-- rather than derived so a DB-side index / sort by expiry is cheap.
"expires_at" TIMESTAMP(3),
-- The printed carton expiry date the user enters on creation.
"printed_expiry" TIMESTAMP(3),
"purchased_at" TIMESTAMP(3),
-- Free-text note ("Apotheke Müller, 2025-10-12"). Hard-capped to
-- 200 chars at the application layer (see Zod schema); the DB
-- column is unbounded TEXT for consistency with the other note
-- columns on this schema (MedicationDoseChange.note, etc.).
"notes" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX "medication_inventory_items_user_med_state_idx"
ON "medication_inventory_items" ("user_id", "medication_id", "state");
-- A separate index on (user_id, expires_at) supports the daily
-- expire-stale background job — it scans IN_USE rows by expiry-asc
-- and the (user, expires_at) prefix makes that O(log n) per user.
CREATE INDEX "medication_inventory_items_user_expires_idx"
ON "medication_inventory_items" ("user_id", "expires_at");
@@ -0,0 +1,28 @@
-- v1.4.25 W14b — onboarding wizard resume-state.
--
-- Adds `onboarding_step` to the `users` table so the rebuilt multi-step
-- wizard at `/onboarding/[step]` can resume the user at the highest
-- step they reached. Without this column, closing the tab mid-flow
-- wipes progress and forces users back to step 0.
--
-- Step encoding (mirrors `src/components/onboarding/OnboardingShell.tsx`
-- and `src/app/onboarding/[step]/page.tsx`):
-- 0 = welcome (carousel / value-prop intro)
-- 1 = goals ("what do you want to track?")
-- 2 = source ("connect a source" — Withings / Apple Health / manual)
-- 3 = baseline (first measurement / sync confirmation)
-- 4 = done (success screen; same write that flips
-- `onboarding_completed_at` from NULL to NOW())
--
-- Existing rows are backfilled to 0 by PostgreSQL's fast-path
-- `ADD COLUMN ... DEFAULT` (PG11+), which materialises the default
-- without rewriting the table — every pre-W14b user lands at step 0
-- in O(1) time. The column ships nullable purely so the DDL stays
-- additive on every replica; Migration 0060 follows up by flipping
-- it to NOT NULL once the deploy has rolled.
--
-- The `IF NOT EXISTS` guards make the migration idempotent — if the
-- column landed via a prior dev-DB hand-edit, the migration still
-- runs cleanly to completion.
ALTER TABLE "users"
ADD COLUMN IF NOT EXISTS "onboarding_step" INTEGER DEFAULT 0;
@@ -0,0 +1,35 @@
-- v1.4.25 W19c — Research Mode acknowledgment fields.
--
-- Adds three columns to the `users` table that together gate the
-- opt-in GLP-1 PK research-view chart behind an undismissable
-- MDR-disclaimer dialog (research §2.3 + §11). The chart never
-- renders unless `research_mode_enabled = true`, and the dialog
-- only flips that flag after the user explicitly acknowledges the
-- disclaimer copy at a specific version.
--
-- research_mode_enabled — master on/off switch.
-- Default `false` keeps the
-- chart hidden for every
-- existing user.
-- research_mode_acknowledged_at — timestamp of the most
-- recent acknowledgment.
-- NULL when the user has
-- never acknowledged.
-- research_mode_acknowledged_version — string identifier of the
-- disclaimer copy version
-- the user acknowledged
-- (e.g. "2026-05-14.1"). The
-- Settings UI re-prompts when
-- the version drifts ahead
-- of the persisted value, so
-- copy updates cannot quietly
-- keep the chart visible.
--
-- The `IF NOT EXISTS` guards make the migration idempotent — if any
-- column landed via a prior dev-DB hand-edit, the migration still
-- runs cleanly to completion (mirrors the 0057 onboarding-step
-- migration's posture).
ALTER TABLE "users"
ADD COLUMN IF NOT EXISTS "research_mode_enabled" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS "research_mode_acknowledged_at" TIMESTAMP(3),
ADD COLUMN IF NOT EXISTS "research_mode_acknowledged_version" TEXT;
@@ -0,0 +1,79 @@
-- v1.4.25 W19d — MedicationSideEffect logbook.
--
-- 21-entry × 5-category structured side-effect taxonomy derived from
-- EMA EPAR §4.8 ("Undesirable effects") clustered into the five
-- surfaces the HealthLog UI renders. 1-5 Likert severity (finer
-- granularity than the EMA 3-level reporting convention; the UI maps
-- each integer to a translated semantic label).
--
-- Daily capture, not per-shot — delayed-onset symptoms (nausea on
-- day 4 post-tirzepatide is common) keep their actual onset time.
-- The Coach reads these against MedicationDoseChange +
-- MedicationIntakeEvent to surface patterns without making a clinical
-- claim.
--
-- Composite index (user_id, medication_id, occurred_at) is the
-- dominant read path: "last N entries for this medication on the
-- detail page". A second per-user (user_id, occurred_at) index serves
-- the Coach snapshot aggregation, which correlates across medications.
--
-- Severity is bounded with a CHECK constraint at the DB level —
-- defence in depth against client-side Zod drift. Notes are unbounded
-- TEXT, application-layer capped to 280 chars in the Zod schema.
CREATE TYPE "medication_side_effect_category" AS ENUM (
'GI',
'METABOLIC',
'INJECTION_SITE',
'COGNITIVE',
'GLP1_SPECIFIC'
);
CREATE TYPE "medication_side_effect_entry" AS ENUM (
-- GI (5)
'NAUSEA',
'VOMITING',
'DIARRHEA',
'CONSTIPATION',
'ABDOMINAL_PAIN',
-- Metabolic (4)
'HYPOGLYCEMIA_SYMPTOMS',
'DEHYDRATION',
'ANOREXIA',
'ELECTROLYTE_FATIGUE',
-- Injection-site (4)
'INJECTION_REDNESS',
'INJECTION_SWELLING',
'INJECTION_BRUISING',
'INJECTION_INDURATION',
-- Cognitive (4)
'BRAIN_FOG',
'DIZZINESS',
'LOW_MOOD',
'LOW_ENERGY',
-- GLP-1 specific (4)
'EARLY_SATIETY',
'GASTROPARESIS_LIKE',
'DYSGEUSIA',
'GALLBLADDER_DISCOMFORT'
);
CREATE TABLE "medication_side_effects" (
"id" TEXT PRIMARY KEY,
"user_id" TEXT NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
"medication_id" TEXT NOT NULL REFERENCES "medications"("id") ON DELETE CASCADE,
"occurred_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"category" "medication_side_effect_category" NOT NULL,
"entry" "medication_side_effect_entry" NOT NULL,
"severity" INTEGER NOT NULL,
"notes" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "medication_side_effects_severity_range_chk"
CHECK ("severity" >= 1 AND "severity" <= 5)
);
CREATE INDEX "medication_side_effects_user_med_occurred_idx"
ON "medication_side_effects" ("user_id", "medication_id", "occurred_at");
CREATE INDEX "medication_side_effects_user_occurred_idx"
ON "medication_side_effects" ("user_id", "occurred_at");
@@ -0,0 +1,25 @@
-- v1.4.25 W21 Fix-O — Backfill `onboarding_step` and flip column to NOT NULL.
--
-- Migration 0057 shipped `onboarding_step INTEGER DEFAULT 0` — nullable on
-- purpose so the additive DDL didn't risk a long table-rewrite during the
-- W14b deploy. The wizard mount code (`src/app/onboarding/page.tsx`) treats
-- `null` as `0`, the POST route (`src/app/api/onboarding/step/route.ts`)
-- widens its conditional-update WHERE to `OR onboardingStep IS NULL` when
-- the caller is at step 0 — all defensive against the tri-state surface.
--
-- This migration closes that tri-state: every legacy pre-W14b row that
-- still carries a NULL is backfilled to 0 (the same value the read-path
-- already substitutes), then the column is flipped to NOT NULL. New
-- inserts continue to land at the DEFAULT 0 — schema.prisma now mirrors
-- the DB shape: `onboardingStep Int @default(0)` without the `?`.
--
-- Idempotent — re-running on a database that's already been flipped is a
-- no-op for the UPDATE (no rows match) and the ALTER COLUMN tolerates
-- SET NOT NULL on an already-NOT NULL column.
UPDATE "users"
SET "onboarding_step" = 0
WHERE "onboarding_step" IS NULL;
ALTER TABLE "users"
ALTER COLUMN "onboarding_step" SET NOT NULL;
+760 -207
View File
File diff suppressed because it is too large. Load diff