feat(illness): correlation + recovery-gap engine

Add the retrospective correlation engine for illness episodes: a pre-onset
anomaly scan (deviation in robust SDs from the user's own median±MAD
baseline), the nadir / what-dropped across the active span, and the
recovery-gap (physiological return-to-baseline vs the felt-better marker).
CHRONIC_ONGOING is excluded from the gap. Every derived number is gated by
the shared coverage/confidence model — a thin signal asserts nothing rather
than showing a wrong figure.

The baseline window ends strictly before the pre-onset lookback, so an
episode's own days can never contaminate the baseline it is measured against.
Reads are DAY-native (rollup tier with a live-SQL fallback), reusing the
baseline engine's read path so the rollup-vs-live parity carries over.

Surfaces:
- GET /api/illness/episodes/{id}/correlation — per-episode findings (gated
  Derived wire shape; red-flag escalation for sustained low SpO2 / fever).
- GET /api/illness/insights — cross-episode retrospective ("sick N times ·
  typical recovery gap X days"), with the typical-gap withheld below the
  min-sample floor. Retrospective only — never a predictor or diagnoser.

Reliability battery: golden-fixture recovery-gap math, rollup-vs-live parity,
baseline-contamination guard, thin-data / coverage-gate, red-flag escalation.
Born-gated + owner-scoped; server-authoritative DTO (iOS renders). i18n ×6.
This commit is contained in:
Marc-André Bombeck committed 2026-06-16 22:16:19 +02:00
1 parent a7b2b61b99
commit 745fa28c8b
16 files changed
+1737

No files matched your search

@@ -0,0 +1,87 @@
/**
* `GET /api/illness/episodes/{id}/correlation` — the retrospective correlation
* findings for one episode: the pre-onset anomaly scan ("how did it announce
* itself"), the nadir / what-dropped, and the recovery-gap (physiological
* return-to-baseline vs the felt-better marker).
*
* Server-authoritative + coverage-gated: the response is a `Derived<T>` flat
* wire shape (`status: "ok" | "insufficient"`). When the signal is thin the
* engine returns `insufficient` with coverage + a reason — the surface renders
* "we're still learning", never a fabricated number. The findings are derived
* from the user's OWN baseline (median ± MAD), never a population constant, and
* the baseline window is contamination-guarded (ends before the pre-onset
* lookback). Retrospective ONLY — never a predictor or diagnoser. Born-gated +
* owner-scoped.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { apiSuccess, apiError } from "@/lib/api-response";
import { requireIllnessEnabled } from "@/lib/illness/gate";
import { computeEpisodeCorrelation } from "@/lib/illness/correlation-read";
import { DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
type RouteParams = { params: Promise<{ id: string }> };
export const GET = apiHandler(
async (_request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const gate = await requireIllnessEnabled(user.id);
if (!gate.enabled) return gate.response;
const { id } = await params;
const episode = await prisma.illnessEpisode.findUnique({
where: { id },
select: {
id: true,
userId: true,
deletedAt: true,
onsetAt: true,
resolvedAt: true,
lifecycle: true,
},
});
if (!episode || episode.userId !== user.id || episode.deletedAt !== null) {
return apiError("Episode not found", 404);
}
const tz = user.timezone ?? DEFAULT_TIMEZONE;
const derived = await computeEpisodeCorrelation(
user.id,
{
id: episode.id,
onsetAt: episode.onsetAt,
resolvedAt: episode.resolvedAt,
lifecycle: episode.lifecycle,
},
tz,
);
annotate({
action: {
name: "illness.correlation.read",
entity_type: "illness_episode",
entity_id: id,
},
meta: {
status: derived.status,
recovery_gap_days:
derived.status === "ok" ? derived.value.recoveryGapDays : null,
red_flags: derived.status === "ok" ? derived.value.redFlags.length : 0,
},
});
return apiSuccess({
episodeId: id,
status: derived.status,
value: derived.status === "ok" ? derived.value : null,
coverage: derived.coverage,
confidence: derived.status === "ok" ? derived.confidence : null,
provenance: derived.provenance,
reason: derived.status === "insufficient" ? derived.reason : null,
});
},
);