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

@@ -0,0 +1,115 @@
/**
* The published `WellnessScoreValue` schema against the value the engine
* actually returns.
*
* `GET /api/insights/derived` types its `value` as an open record — one
* envelope carries eighteen differently-shaped metrics, so no single `$ref`
* fits — which meant every metric's payload shape was undocumented and a
* client had to inspect a live response to learn what was in it. The three
* wellness scores are modelled now, published through the forced-components
* slot, and this holds the published shape to the runtime one: a field added
* to the engine and not to the schema, or the reverse, fails here rather than
* shipping as a spec that describes a payload nobody sends.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
measurement: { findMany: vi.fn() },
strainTrimpCache: { findUnique: vi.fn().mockResolvedValue(null) },
user: { findUnique: vi.fn().mockResolvedValue({ timezone: "UTC" }) },
},
}));
vi.mock("@/lib/insights/derived/readiness", () => ({
computeReadiness: vi.fn(),
}));
import { prisma } from "@/lib/db";
import { computeReadiness } from "@/lib/insights/derived/readiness";
import { computeWellnessScore } from "@/lib/insights/derived/wellness-scores";
import { wellnessScoreValue } from "@/lib/openapi/routes/insights/schemas";
import { openApiComponents } from "@/lib/openapi/routes";
const findMany = prisma.measurement.findMany as ReturnType<typeof vi.fn>;
const NOW = new Date("2026-06-02T08:00:00Z");
const PROFILE = { ageYears: 40, sex: "MALE" as const };
beforeEach(() => {
vi.mocked(computeReadiness).mockResolvedValue({
status: "ok",
value: {
score: 74,
band: "green",
components: [
{ key: "rhr", value: 90, weight: 0.5 },
{ key: "hrv", value: null, weight: 0 },
],
},
} as never);
});
describe("published WellnessScoreValue", () => {
it("is registered as a component even though nothing $refs it", () => {
expect(openApiComponents.schemas).toHaveProperty("WellnessScoreValue");
expect(openApiComponents.schemas?.WellnessScoreValue).toBe(
wellnessScoreValue,
);
});
it("accepts the recovery value the engine emits, field for field", async () => {
findMany.mockResolvedValue([
{
value: 72.4,
measuredAt: new Date("2026-06-01T12:00:00Z"),
source: "COMPUTED",
},
{
value: 60,
measuredAt: new Date("2026-05-31T12:00:00Z"),
source: "COMPUTED",
},
]);
const derived = await computeWellnessScore(
"RECOVERY_SCORE",
"u1",
PROFILE,
{ now: NOW },
);
expect(derived.status).toBe("ok");
if (derived.status !== "ok") return;
const parsed = wellnessScoreValue.safeParse(derived.value);
expect(parsed.error?.issues ?? []).toEqual([]);
expect(parsed.success).toBe(true);
// Not just "parses" — the published field list and the emitted one are the
// same set. A permissive schema would pass the parse above while quietly
// omitting a field, which is the failure this whole change is about.
expect(Object.keys(wellnessScoreValue.shape).sort()).toEqual(
Object.keys(derived.value as unknown as Record<string, unknown>).sort(),
);
});
it("accepts the strain value, whose anchor the other two never carry", async () => {
findMany.mockResolvedValue([
{
value: 55,
measuredAt: new Date("2026-06-01T12:00:00Z"),
source: "COMPUTED",
},
]);
vi.mocked(prisma.strainTrimpCache.findUnique).mockResolvedValue({
anchor: "personal",
} as never);
const derived = await computeWellnessScore("STRAIN_SCORE", "u1", PROFILE, {
now: NOW,
});
expect(derived.status).toBe("ok");
if (derived.status !== "ok") return;
const parsed = wellnessScoreValue.safeParse(derived.value);
expect(parsed.error?.issues ?? []).toEqual([]);
expect(Object.keys(wellnessScoreValue.shape).sort()).toEqual(
Object.keys(derived.value as unknown as Record<string, unknown>).sort(),
);
});
});