fix(insights): correct medication compliance and per-user insight bucketing

A cluster of related correctness gaps in the compliance denominator and the
insight surfaces that read it:

- Paused medications. A doctor-ordered pause flipped `active` off and stamped
  `pausedAt`, but resume nulled `pausedAt`, so the interval was irrecoverable
  and every paused day became a missed dose after resume — collapsing
  adherence across the Health Score, the BP gate, the Coach snapshot and the
  report. Persist pause intervals as durable eras (new `MedicationPauseEra`,
  migration 0211), close the open era on resume, thread the eras through the
  compliance context and drop slots inside a paused interval from the
  denominator. Every compliance call site now fetches and passes the eras.

- Health Score eras. The Health-Score fast path was the only compliance
  caller that skipped the shared schedule select and schedule revisions, so
  after a schedule edit it scored past days against the current schedule
  while every other surface used the historical era. Switch it to the shared
  select and thread revisions (and pause eras) like the canonical path.

- Insight bucketing timezone. The per-metric status series bucketed every
  user in Europe/Berlin, so a near-midnight reading landed in the wrong day
  and the relative-day phrasing was off for non-Berlin self-hosters. Thread
  the resolved user timezone and key off `userDayKey`.

- Correlation significance. User-facing correlations surfaced from five
  paired points with strength read straight off the coefficient. Route them
  through the rigorous engine (at least twenty pairs, Student-t p below 0.05)
  so small-N coincidences no longer render as confident findings.

- Resting-pulse input. The mood-versus-"resting pulse" correlation fed the
  raw PULSE day-mean, which folds in workout HR, under a "Resting pulse"
  label. Feed `resolveRestingPulseSeries` (clean RESTING_HEART_RATE, else a
  daily low-percentile proxy) so the label matches the input.
This commit is contained in:
Marc-André Bombeck committed 2026-06-28 03:28:37 +02:00
1 parent 9e6a58b186
commit a827fe2ca7
33 files changed
+1007 -182

No files matched your search

@@ -0,0 +1,31 @@
-- v1.25 — durable medication pause intervals (H-MED1).
--
-- The `medications.paused_at` column is a single live marker: resume clears
-- it, so the paused window is irrecoverable once the medication resumes.
-- After a resume the compliance denominator spanned created_at..now and every
-- paused day's expected slot collapsed to "missed", deflating adherence.
--
-- `medication_pause_eras` records each pause as its own durable row: a pause
-- stamps an open era (`resumed_at` NULL), resume closes the latest open era
-- (`resumed_at` = now). The compliance engine drops expected dose slots whose
-- anchor falls inside any `[paused_at, resumed_at ?? now)` interval so a
-- resumed medication never counts the paused days as missed. The `paused_at`
-- marker column on `medications` is left intact — current readers depend on it.
CREATE TABLE "medication_pause_eras" (
"id" TEXT NOT NULL,
"medication_id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"paused_at" TIMESTAMPTZ(6) NOT NULL,
"resumed_at" TIMESTAMPTZ(6),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "medication_pause_eras_pkey" PRIMARY KEY ("id")
);
CREATE INDEX "medication_pause_eras_medication_id_idx" ON "medication_pause_eras"("medication_id");
CREATE INDEX "medication_pause_eras_user_id_idx" ON "medication_pause_eras"("user_id");
ALTER TABLE "medication_pause_eras" ADD CONSTRAINT "medication_pause_eras_medication_id_fkey" FOREIGN KEY ("medication_id") REFERENCES "medications"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "medication_pause_eras" ADD CONSTRAINT "medication_pause_eras_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+48 -10
View File
@@ -583,6 +583,7 @@ model User {
measurements Measurement[]
medications Medication[]
intakeEvents MedicationIntakeEvent[]
medicationPauseEras MedicationPauseEra[]
apiTokens ApiToken[]
// v1.24 — MCP remote OAuth 2.1 connections (1:N). Each row is a granted
// authorization for an MCP client, audience-bound to health:read/health:write.
@@ -1947,6 +1948,14 @@ model Medication {
/// ranges into eras so past days read against the schedule that was
/// live THEN, not the current one.
scheduleRevisions MedicationScheduleRevision[]
/// v1.25 — durable pause intervals. A pause stamps an open era
/// (`resumedAt = null`); resume closes the latest open era. The
/// compliance engine drops expected slots whose anchor falls inside a
/// pause interval so a resumed medication never counts the paused days
/// as missed. The `pausedAt` column on this model stays the live
/// single-pause marker the reminder/today surfaces read; the era table
/// is the additive durable record the rate paths need.
pauseEras MedicationPauseEra[]
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -2097,6 +2106,35 @@ model MedicationScheduleRevision {
@@map("medication_schedule_revisions")
}
/// v1.25 — durable medication pause intervals. The `Medication.pausedAt`
/// column is a single live marker that resume clears, so the paused window
/// is irrecoverable once the medication resumes. This table records each
/// pause as its own row: a pause stamps an open era (`resumedAt = null`),
/// resume closes the latest open era (`resumedAt = now`). The compliance
/// engine reads the eras and drops expected dose slots whose anchor falls
/// inside any `[pausedAt, resumedAt ?? now)` interval so a resumed
/// medication never counts the paused days as missed.
model MedicationPauseEra {
id String @id @default(cuid())
medicationId String @map("medication_id")
userId String @map("user_id")
/// Inclusive start of the pause interval (the instant the medication
/// was paused).
pausedAt DateTime @map("paused_at") @db.Timestamptz(6)
/// Exclusive end of the pause interval (the instant the medication was
/// resumed). NULL = still paused; readers treat an open era as running
/// to `now`.
resumedAt DateTime? @map("resumed_at") @db.Timestamptz(6)
createdAt DateTime @default(now()) @map("created_at")
medication Medication @relation(fields: [medicationId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([medicationId])
@@index([userId])
@@map("medication_pause_eras")
}
enum IntakeSource {
WEB
API
@@ -2553,21 +2591,21 @@ model TelegramPromptContext {
// ─── API Tokens (for external ingest) ──────────────────────
model ApiToken {
id String @id @default(cuid())
userId String @map("user_id")
name String
tokenHash String @unique @map("token_hash") // SHA-256 of the token
permissions String[] @default(["medication:ingest"])
lastUsedAt DateTime? @map("last_used_at")
expiresAt DateTime? @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
revoked Boolean @default(false)
id String @id @default(cuid())
userId String @map("user_id")
name String
tokenHash String @unique @map("token_hash") // SHA-256 of the token
permissions String[] @default(["medication:ingest"])
lastUsedAt DateTime? @map("last_used_at")
expiresAt DateTime? @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
revoked Boolean @default(false)
// The MCP OAuth connection this access token belongs to, when it was minted
// through the `/api/mcp/oauth` bridge. Null for manually-minted tokens and
// native-client tokens. Lets a connection revoke kill every access row it
// ever issued (H2), and lets the connector token list exclude the transient
// 60-minute access rows so it does not flood (M2).
mcpConnectionId String? @map("mcp_connection_id")
mcpConnectionId String? @map("mcp_connection_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
mcpConnection McpOAuthConnection? @relation(fields: [mcpConnectionId], references: [id], onDelete: SetNull)