feat(insights): view ECG recordings

ECG recordings synced from a compatible watch were stored encrypted but
shown nowhere. They now have a surface in Insights: a list of recordings,
each opening the full single-lead waveform on a familiar ECG grid, with the
date, duration, average heart rate, and the result the device recorded.

The read routes narrow ownership in the query and decrypt the waveform
through the existing fail-closed codec; the overview is min/max-decimated so
the R-wave peaks survive the reduction, with a raw path for a calibrated
view. The result shown is the recording device's own classification,
attributed to the device — HealthLog does not read or interpret the trace
and produces no verdict of its own. A permanent note states this, and a
non-normal result carries a line to discuss the recording with a clinician.
This commit is contained in:
Marc-André Bombeck committed 2026-07-16 09:55:35 +02:00
1 parent 7a0a271c70
commit 49ed0f41df
28 files changed
+2124 -4

No files matched your search

+60
View File
@@ -4,9 +4,11 @@
* Schema declarations live in `./schemas`; this module is the path orchestrator.
*/
import type { ZodOpenApiObject } from "zod-openapi";
import { z } from "zod/v4";
import {
consentRequiredResponse,
dataEnvelope,
errorEnvelope,
moduleDisabledResponse,
stdResponses,
} from "../shared";
@@ -31,6 +33,9 @@ import {
insightsPregenerateRequest,
insightsPregenerateResponse,
dashboardSnapshotResponse,
ecgListResponse,
ecgDetailQuery,
ecgDetailResponse,
} from "./schemas";
export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
@@ -429,6 +434,61 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/insights/ecg": {
get: {
tags: ["Insights"],
summary: "ECG recording list (metadata only)",
description:
"v1.28.50 — the authenticated user's ECG recordings as a cheap, index-covered metadata list (recorded time, duration, sampling rate, sample count, average heart rate, lead, and the DEVICE's own rhythm classification). NEVER decrypts or returns the waveform — the per-recording strip is fetched on demand from GET /api/insights/ecg/{id}. Reflects only the recording device's certified on-device classification, verbatim; HealthLog never re-classifies an ECG or produces a diagnosis. Data-availability-gated: an empty account returns `hasRecordings: false`. Module-gated on `insights` and the operator `insightStatus` assistant surface; no LLM call. Auth via cookie or Bearer.",
responses: {
"200": {
description: "The ECG recording list (possibly empty).",
content: {
"application/json": {
schema: dataEnvelope(ecgListResponse, "EcgListResponseEnvelope"),
},
},
},
...moduleDisabledResponse,
...stdResponses,
},
},
},
"/api/insights/ecg/{id}": {
get: {
tags: ["Insights"],
summary: "One ECG recording with waveform",
description:
"v1.28.50 — one recording's decrypted waveform plus metadata and the DEVICE's verbatim classification. Ownership is narrowed in the query where (`{ id, userId }`) so a cross-user read is structurally impossible; a foreign or unknown id 404s (existence sealed). The waveform is AES-256-GCM at rest, decrypted through the fail-closed codec. By default the ~9000-sample strip is min/max-decimated to ~2500 display points so R-wave peaks survive; `?full=1` returns the raw array. HealthLog does not interpret the trace, measure intervals, annotate beats, or emit a verdict of its own. Module-gated on `insights` and the operator `insightStatus` assistant surface; no LLM call. `no-store`. Auth via cookie or Bearer.",
requestParams: {
path: z.object({
id: z.string().describe("The ECG recording id (cuid)."),
}),
query: ecgDetailQuery,
},
responses: {
"200": {
description:
"The recording's waveform + metadata + device classification.",
content: {
"application/json": {
schema: dataEnvelope(
ecgDetailResponse,
"EcgDetailResponseEnvelope",
),
},
},
},
"404": {
description:
"No ECG recording with that id for the authenticated user (existence sealed — a foreign id is indistinguishable from a missing one).",
content: { "application/json": { schema: errorEnvelope } },
},
...moduleDisabledResponse,
...stdResponses,
},
},
},
"/api/insights/correlations": {
get: {
tags: ["Insights"],
+132
View File
@@ -1003,3 +1003,135 @@ const insightCard = z
export const insightsCardsResponse = z
.array(insightCard)
.meta({ id: "InsightsCardsResponse" });
// v1.28.50 — ECG recording surface. The device's own AFib verdict, verbatim.
// Only three RhythmClassification values occur for an ECG strip; the field is
// nullable when the source omitted a classification.
const ecgClassification = z
.enum(["IRREGULAR", "NOT_DETECTED", "INCONCLUSIVE"])
.nullable()
.describe(
"The RECORDING DEVICE's own rhythm classification, surfaced verbatim: IRREGULAR (device flagged possible atrial fibrillation), NOT_DETECTED (algorithm ran, nothing flagged), INCONCLUSIVE (poor signal / out-of-range HR). Null when the source reported none. HealthLog never re-classifies an ECG — this is the device's certified on-device result, not a HealthLog verdict.",
);
const ecgRecordingListItem = z
.object({
id: z.string().describe("Recording id (cuid)."),
recordedAt: z.iso
.datetime({ offset: true })
.describe("On-device recording time (the display timestamp)."),
durationSeconds: z
.number()
.nullable()
.describe(
"`sampleCount / samplingFrequency` in seconds; null when the source omitted the sampling frequency.",
),
samplingFrequency: z
.number()
.int()
.describe(
"Signal sampling rate in Hz (Withings ScanWatch = 300); 0 when the source omitted it.",
),
sampleCount: z
.number()
.int()
.describe("Number of samples in the (encrypted) waveform array."),
averageHeartRate: z
.number()
.int()
.nullable()
.describe(
"Source-reported average heart rate (BPM) for the strip, when present.",
),
lead: z
.string()
.nullable()
.describe(
"Recording lead label when the source reports it; null for the single-lead ScanWatch (Lead I).",
),
classification: ecgClassification,
source: z
.string()
.describe("Measurement source that wrote the recording (e.g. WITHINGS)."),
hasWaveform: z
.boolean()
.describe(
"True when a waveform is stored (`sampleCount > 0`); false for a verdict-only fallback event with no signal to fetch.",
),
})
.meta({ id: "EcgRecordingListItem" });
export const ecgListResponse = z
.object({
recordings: z
.array(ecgRecordingListItem)
.describe("The user's ECG recordings, newest first (capped at 200)."),
hasRecordings: z
.boolean()
.describe(
"False for an account with no recordings — the client un-mounts the whole ECG surface (data-availability floor).",
),
})
.meta({
id: "EcgListResponse",
description:
"Metadata-only ECG recording list. Never carries the waveform — the per-recording strip is fetched on demand from GET /api/insights/ecg/{id}. Read-only; no LLM call. Reflects only the device's own classification, never a HealthLog interpretation.",
});
export const ecgDetailQuery = z
.object({
full: z
.literal("1")
.optional()
.describe(
"`1` returns the RAW, un-decimated sample array (the true-calibration 25 mm/s · 10 mm/mV zoom view). Omitted returns the min/max-decimated ~2500-point fit-to-width overview (`decimated: true`).",
),
})
.meta({ id: "EcgDetailQuery" });
export const ecgDetailResponse = z
.object({
recordedAt: z.iso
.datetime({ offset: true })
.describe("On-device recording time (the display timestamp)."),
durationSeconds: z
.number()
.nullable()
.describe(
"Strip duration in seconds; null when the sampling frequency was 0.",
),
samplingFrequency: z
.number()
.int()
.describe("Signal sampling rate in Hz (300 for a ScanWatch)."),
averageHeartRate: z
.number()
.int()
.nullable()
.describe(
"Source-reported average heart rate (BPM) for the strip, when present.",
),
lead: z
.string()
.nullable()
.describe(
"Recording lead label when reported; null for the single-lead ScanWatch (Lead I).",
),
classification: ecgClassification,
source: z.string().describe("Measurement source that wrote the recording."),
samples: z
.array(z.number())
.describe(
"Micro-volt waveform samples. Min/max-decimated to ~2500 points by default so R-wave peaks survive the fit-to-width compression; the raw array when `?full=1`. The x-position of each sample is implied by its index (an overview trace, not a calibrated-time axis) unless `decimated` is false.",
),
decimated: z
.boolean()
.describe(
"True when `samples` was min/max-decimated for display; false when the raw array is returned (`?full=1`, or a strip already at or below the display budget).",
),
})
.meta({
id: "EcgDetailResponse",
description:
"One ECG recording's decrypted waveform plus metadata and the DEVICE's verbatim classification. Ownership is narrowed in the query where — a foreign / unknown id 404s. The waveform is AES-256-GCM at rest, decrypted through the fail-closed codec. HealthLog does not interpret the trace, measure intervals, annotate beats, or emit a verdict of its own. no-store.",
});