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

+118 -4
View File
@@ -10416,7 +10416,9 @@ paths:
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.
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.
parameters:
- in: query
name: metric
@@ -10478,6 +10480,30 @@ paths:
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.
- in: query
name: windowDays
schema:
description: "Trailing window the metric summarises, in days (1–90). 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."
type: integer
minimum: 1
maximum: 90
description: "Trailing window the metric summarises, in days (1–90). 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."
responses:
"200":
description: The flat derived-metric value (ok or insufficient).
@@ -51988,9 +52014,14 @@ components:
type: string
additionalProperties: {}
- type: "null"
description: 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'.
description: 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:
$ref: "#/components/schemas/DerivedCoverage"
confidence:
@@ -68041,6 +68072,89 @@ components:
group at that index, un-placed tags follow in their home category. Display-only — placements referencing
hidden/archived/unknown keys are silently dropped at read time. Both fields optional: PUT merges
preserve-when-absent."
WellnessScoreValue:
type: object
properties:
score:
type: integer
minimum: -9007199254740991
maximum: 9007199254740991
description: The latest persisted 0–100 score.
band:
type: string
enum:
- green
- yellow
- red
description: "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:
anyOf:
- type: integer
minimum: -9007199254740991
maximum: 9007199254740991
- type: "null"
description: Score minus the mean of the earlier days in the window; null when the window holds only one day.
daysInWindow:
type: integer
minimum: -9007199254740991
maximum: 9007199254740991
description: 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:
type: string
format: date-time
pattern: ^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|([+-](?:[01]\d|2[0-3]):[0-5]\d)))$
description: "`measuredAt` of the latest score."
series:
type: array
items:
type: number
description: "Trailing scores, oldest → newest, capped at 30 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:
description: 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.
anyOf:
- type: string
enum:
- personal
- population
- type: "null"
components:
description: 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.
anyOf:
- type: array
items:
type: object
properties:
key:
type: string
description: Contributor id, e.g. rhr / hrv / sleep.
value:
anyOf:
- type: number
- type: "null"
description: 0–100 sub-score, null when the input was missing.
weight:
type: number
description: Effective weight after redistributing missing inputs.
required:
- key
- value
- weight
additionalProperties: false
- type: "null"
required:
- score
- band
- trendDelta
- daysInWindow
- asOf
- series
additionalProperties: false
parameters:
AccountSelector:
name: X-HealthLog-Account