feat(insights): let a caller choose the derived-metric window

`GET /api/insights/derived` accepts `windowDays`, bounded to 1..90, and
threads it to the dispatcher. Omitting it changes nothing: every engine
keeps its own default, so a caller that asks for nothing reads exactly
what it read before.

Ninety is where the tier this route promises runs out. The rollup router
opens its WEEK floor at 91 days, and the baseline engines cannot compose
a spread from WEEK buckets, so a 91-day request falls through to a raw
`measurement.findMany` with no row cap — for a densely sampled type that
is a full history scan, and the analytics-read budget allows 120 of them
a minute per account. The trailing `series` is capped at 30 points
regardless, so past the ceiling a wider window would only broaden the
mean behind the value. Out of range is a 422 rather than a clamp.

An unhonoured window is visible rather than silent. `provenance.windowDays`
is the window the engine actually used and `coverage.historyDays` the days
that actually backed it, so a three-week record answering a thirty-day
request reports both numbers instead of implying coverage it does not
have. `HEALTH_SCORE` composes fixed per-pillar windows and reports the
widest; a new suite freezes that it is the only metric that does, so an
arm added later cannot quietly drop the parameter.

Recovery keeps its canonical resolution under the wider window. A worn
band stamps the wake morning and the computed proxy the night before, and
only `resolveCanonicalRecovery` pairs them; a test seeds forty such
nights, asks for sixty days, and holds the answer to forty nights with a
flat trend — a bypass leaves eighty rows and a false climb.

Contract: model `WellnessScoreValue` field for field and publish it. The
envelope's `value` has to stay an open record because one route serves
eighteen differently-shaped metrics, so nothing can `$ref` the shape and
it went out undocumented — `series`, `daysInWindow` and `asOf` were on
the wire with no way to find them short of inspecting a live response. It
is registered in the forced-components slot instead, held against the
runtime interface by a test, and the fields it does not cover are named
in the schema comment so the remaining gap is known rather than invisible.
This commit is contained in:
Marc-André Bombeck committed 2026-08-24 02:00:55 +02:00
1 parent d290422923
commit d7d8e437ee
11 files changed
+659 -9

No files matched your search

+11 -1
View File
@@ -57,7 +57,7 @@ import { encounterPaths } from "./encounters";
import { vaccinationPaths } from "./vaccinations";
import { illnessPaths } from "./illness";
import { importPaths } from "./import";
import { insightsPaths } from "./insights";
import { insightsPaths, wellnessScoreValue } from "./insights";
import { integrationPaths } from "./integrations";
import { insightsSignalPaths } from "./insights-signals";
import { labsPaths } from "./labs";
@@ -200,12 +200,22 @@ export const openApiComponents: NonNullable<ZodOpenApiObject["components"]> = {
// but every actual consumer is a `.extend()` of it (`PutCoachPrefsRequest`,
// `CoachPrefsResponse`) — `.extend()` builds a new object, so the base
// never carries forward to a $ref on its own.
//
// `WellnessScoreValue` is here for a different reason. `GET
// /api/insights/derived` serves eighteen metrics through one envelope, so
// its `value` has to stay an open record — no single `$ref` can describe
// it. That left every metric's payload undocumented, and a client team read
// the DTO and reported two fields as missing that were already on the wire.
// Publishing the shape a `$ref` cannot reach is exactly what this slot is
// for; the `value` description names it as the shape the three score ids
// return.
schemas: {
Medication: medicationResource,
MedicationDoseHistoryImportFatalReason:
medicationDoseHistoryImportFatalReasonEnum,
CoachPrefs: coachPrefsSchema,
MoodTagLayout: moodTagLayout,
WellnessScoreValue: wellnessScoreValue,
},
// v1.36.0 — the per-request account selector, defined in the sharing route
// module so that `src/__tests__/acting-account-boundary-guard.test.ts` keeps
+1
View File
@@ -4,3 +4,4 @@
* Part of the OpenAPI route table; aggregated in `../index.ts`.
*/
export { insightsPaths } from "./paths";
export { wellnessScoreValue } from "./schemas";
+1 -1
View File
@@ -804,7 +804,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
tags: ["Insights"],
summary: "Derived wellness metric (compute-once)",
description:
"v1.10.0 — the compute-once `Derived<T>` value for any registered derived wellness metric (personal typical-range vitals baseline, cardio-fitness band, vascular-age delta, sleep score, readiness, coincident-deviation flag). One generic route over a closed registry enum; an unknown `metric` 422s. Pure compute over the rollup tier with a per-type live fallback on a coverage miss — no LLM call, no narrative, no cache table. Returns the flat `Derived<T>` union so the native client can decode one stable shape and combine values across metrics. Auth via cookie or Bearer.",
"v1.10.0 — the compute-once `Derived<T>` value for any registered derived wellness metric (personal typical-range vitals baseline, cardio-fitness band, vascular-age delta, sleep score, readiness, coincident-deviation flag). One generic route over a closed registry enum; an unknown `metric` 422s. Pure compute over the rollup tier with a per-type live fallback on a coverage miss — no LLM call, no narrative, no cache table. Returns the flat `Derived<T>` union so the native client can decode one stable shape and combine values across metrics. `windowDays` widens or narrows the trailing window a metric summarises; `provenance.windowDays` always reports the window actually used and `coverage.historyDays` the days that actually backed it. Auth via cookie or Bearer.",
requestParams: {
query: derivedMetricQuery,
},
+93 -1
View File
@@ -13,6 +13,10 @@ import {
VITALS_BASELINE_TYPES,
SAME_TIME_BASELINE_TYPES,
} from "@/lib/insights/derived/registry";
import {
DERIVED_MAX_WINDOW_DAYS,
SPARKLINE_MAX_POINTS,
} from "@/lib/insights/derived/types";
import { ANALYTICS_RANGES } from "@/lib/analytics/range-delta";
import { PROVIDER_CHAIN_TYPES } from "@/lib/ai/provider-chain";
import { PERIOD_DAYS } from "@/lib/insights/narrative/period-narrative";
@@ -144,9 +148,97 @@ export const derivedMetricQuery = z
.describe(
"The single measurement type a baseline metric works over. `VITALS_BASELINE` takes one of the eleven vitals (`RESTING_HEART_RATE` through `WEIGHT`; defaults to `RESTING_HEART_RATE`). `SAME_TIME_BASELINE` takes one of the four cumulative day metrics — `ACTIVITY_STEPS`, `ACTIVE_ENERGY_BURNED`, `WALKING_RUNNING_DISTANCE`, `FLIGHTS_CLIMBED`. Ignored by the composite metrics. A type the named metric does not support yields an `insufficient` value rather than a 422, so client metric combinations stay forgiving.",
),
windowDays: z.coerce
.number()
.int()
.min(1)
.max(DERIVED_MAX_WINDOW_DAYS)
.optional()
.describe(
`Trailing window the metric summarises, in days (1–${DERIVED_MAX_WINDOW_DAYS}). Omit it and each metric keeps its own default — 14 days for the wellness-score trend, 30 for the vitals baselines, 90 for BMI, 180 for cardio fitness, 365 for the vascular-age delta. A value outside the range is a 422, never a silent clamp; the ceiling is where the derived tier stops resolving against DAY rollup buckets and would fall back to an uncapped raw read. Always read \`provenance.windowDays\` back: it is the window the engine ACTUALLY used, and \`HEALTH_SCORE\` composes fixed per-pillar windows and reports the widest of them rather than the one you asked for. The window is a request, not a promise about coverage — \`coverage.historyDays\` is how many days of record actually backed the answer, and it is smaller than \`windowDays\` for anyone whose history is shorter than the window. Not accepted on the batch route, which always runs the engine defaults.`,
),
})
.meta({ id: "DerivedMetricQuery" });
/**
* The `RECOVERY_SCORE` / `STRESS_SCORE` / `STRAIN_SCORE` value object.
*
* Modelled here because the free-form `value` record left every derived
* metric's payload shape undocumented, and a client reading the DTO could not
* see that `series`, `daysInWindow` and `asOf` were already on the wire.
*
* Nothing `$ref`s it — `value` has to stay an open record while one route
* serves eighteen differently-shaped value objects — so it is registered in
* the forced-components slot in `../index.ts`, the same slot `Medication` and
* `CoachPrefs` use. Its fields are held against the runtime interface by
* `derived-wellness-value-contract.test.ts`, so the published shape cannot
* drift away from what the engine actually returns.
*
* STILL OPAQUE, and known to be: the value shapes of `VITALS_BASELINE` (prose
* only, in the `value` description), `FITNESS_AGE`, `VASCULAR_AGE_DELTA`,
* `HRV_BALANCE`, `BMI`, `SLEEP_SCORE`, `READINESS`, `COINCIDENT_DEVIATION`,
* `TRAJECTORY`, `SAME_TIME_BASELINE`, `SIX_MINUTE_WALK_BAND`, `HEALTH_SCORE`
* and the three fixed-type baselines. Each is a TypeScript interface next to
* its engine under `src/lib/insights/derived/`; modelling them is a schema per
* engine and belongs in its own change rather than riding along here.
*/
export const wellnessScoreValue = z
.object({
score: z.number().int().describe("The latest persisted 0–100 score."),
band: z
.enum(["green", "yellow", "red"])
.describe(
"Server's verdict on the score. Direction-aware: recovery bands high-is-good, stress and strain invert, so a client must never re-band the number itself.",
),
trendDelta: z
.number()
.int()
.nullable()
.describe(
"Score minus the mean of the earlier days in the window; null when the window holds only one day.",
),
daysInWindow: z
.number()
.int()
.describe(
"Days that actually carried a score inside the window. Compare against `provenance.windowDays` — a shorter record answers a wide request with fewer days, and this is where that shows.",
),
asOf: z.iso
.datetime({ offset: true })
.describe("`measuredAt` of the latest score."),
series: z
.array(z.number())
.describe(
`Trailing scores, oldest → newest, capped at ${SPARKLINE_MAX_POINTS} points however wide the window is. For RECOVERY these are the canonical per-night values: a worn band and the server's own proxy write the same night on different clocks, and the server collapses them to one value per night before this array is built.`,
),
anchor: z
.enum(["personal", "population"])
.nullable()
.optional()
.describe(
"STRAIN only — whether this score was judged against the user's own training history or the cold-start population reference. Null for recovery and stress.",
),
components: z
.array(
z.object({
key: z.string().describe("Contributor id, e.g. rhr / hrv / sleep."),
value: z
.number()
.nullable()
.describe("0–100 sub-score, null when the input was missing."),
weight: z
.number()
.describe("Effective weight after redistributing missing inputs."),
}),
)
.nullable()
.optional()
.describe(
"RECOVERY only, and only when the canonical value is the server's computed proxy — a device-native recovery percentage is not our blend and carries no decomposition.",
),
})
.meta({ id: "WellnessScoreValue" });
export const derivedCoverage = z
.object({
requiredInputs: z
@@ -238,7 +330,7 @@ export const derivedMetricResponse = z
.record(z.string(), z.unknown())
.nullable()
.describe(
"Metric-specific value object when status is 'ok' (e.g. { type, center, low, high, spread, sampleDays, k, series } for VITALS_BASELINE, where `series` is the trailing per-day mean values for the inline sparkline); null when 'insufficient'.",
"Metric-specific value object when status is 'ok'; null when 'insufficient'. The shape is chosen by `metric`, and the record stays open because one route serves eighteen of them. `RECOVERY_SCORE` / `STRESS_SCORE` / `STRAIN_SCORE` return the `WellnessScoreValue` schema — field-by-field in `components.schemas`, including the `series`, `daysInWindow` and `asOf` a client would otherwise have to discover by inspecting a live payload. `VITALS_BASELINE` returns { type, center, low, high, spread, sampleDays, k, series }, where `series` is the trailing per-day means for the inline sparkline. The remaining metrics' value objects are not modelled here yet; their shapes are TypeScript interfaces beside their engines under `src/lib/insights/derived/`.",
),
coverage: derivedCoverage,
confidence: derivedConfidence