fix(insights): wire grip / pain / waist / waist-to-height across web and MCP

Grip strength, pain (0–10 NRS), waist circumference, and waist-to-height
existed in the measurement enum, signal registry, and FHIR export but had
no web entry, no detail page, single non-sex-aware bands, and a split-brain
MCP exposure. This closes those gaps.

Web capture: the four signals join the manual measurement form, so a
web-only self-hoster can log them (the iOS client and the measurements API
already could).

Detail pages: flip detailPage on for the four signals and mount each on the
shared HealthKit metric template (chart, stat strip, Coach-read strip,
assessment card) via routed sub-pages and tab-strip pills, the same detail
spine every other metric carries.

Sex-aware bands: grip strength (EWGSOP2 men 27 / women 16 kg) and waist
(WHO men 94 / women 80 cm) now classify by the profile sex through the
age/sex norm resolver the assessment already threads; the resolver also
returns a sex-specific, age-independent band when no date of birth is set.
Fix the waist-to-height boundary so the NICE >= 0.5 rule is correct (the
last in-range value is 0.49).

MCP single source of truth: decouple the registry mcp facet from the Coach
snapshot — a signal can be MCP-readable without being on the Coach surface.
Mark the four physical signals mcp:true, derive the MCP rich-reads clinical
set from the registry flag instead of a duplicate allowlist, and relax the
invariant to coachSnapshot implies mcp (not the reverse). PHQ-9 / GAD-7 and
the environmental signals stay mcp:false and unreachable. compare_metric and
detect_changepoints now advertise clinical-signal support to match
get_metric_baseline.
This commit is contained in:
Marc-André Bombeck committed 2026-06-28 18:33:53 +02:00
1 parent 4f39058629
commit a69697b50f
25 files changed
+726 -62

No files matched your search

+2 -1
View File
@@ -95,7 +95,8 @@ describe("resolveRichMetric", () => {
const whtr = resolveRichMetric("waist-to-height ratio");
expect(whtr?.measurementType).toBe("WAIST_TO_HEIGHT");
expect(whtr?.band).toEqual({ low: 0, high: 0.5 });
// WHtR ≥ 0.5 flags increased risk, so the last in-range value is 0.49.
expect(whtr?.band).toEqual({ low: 0, high: 0.49 });
// The exact registry key resolves too.
expect(resolveRichMetric("GRIP_STRENGTH")?.measurementType).toBe(
+34 -25
View File
@@ -43,7 +43,7 @@ import {
getMetricStatusMeta,
METRIC_STATUS_IDS,
} from "@/lib/insights/metric-status-registry";
import { getSignal } from "@/lib/signals/registry";
import { allSignals, getSignal } from "@/lib/signals/registry";
import { classifyReferenceRange } from "@/lib/labs/reference-range";
import { resolveLabFields } from "@/lib/labs/serialise";
import { sanitizeValueText } from "@/lib/ai/coach/labs-snapshot";
@@ -182,24 +182,21 @@ function fromRegistry(id: string): RichMetric | null {
//
// The v1.25 clinical-signals wave added a set of physical / clinical
// measurements to the signal registry. They sit OFF the Coach snapshot by
// design (`coachSnapshot:false ⇒ surfaces.mcp:false`), so the Coach-driven
// reads (`get_metric_series`, the data inventory) never surface them. The MCP
// layer exposes them here through the rollup-backed rich reads — `compare_metric`,
// `get_metric_baseline`, `detect_changepoints` — and through `search` / `fetch`.
// design (`coachSnapshot:false`), so the Coach-driven reads
// (`get_metric_series`, the data inventory) never surface them — that path
// would report no data for a signal it does not carry. The MCP layer exposes
// them here through the rollup-backed rich reads — `compare_metric`,
// `get_metric_baseline`, `detect_changepoints` — and through `search` /
// `fetch`.
//
// Exposure is an EXPLICIT allowlist owned by this module, not the registry's own
// `surfaces.mcp` flag: the registry keeps these off the Coach surface, while the
// MCP read surface opts them in one signal at a time. The registry remains the
// single source of truth for grounding (the backing `MeasurementType`, unit, and
// population band). Deliberately ABSENT and therefore unreachable over MCP: the
// PHQ-9 / GAD-7 mental-health screeners and every environmental (`ENV_*`) signal
// — they never reach AI / MCP by construction.
export const MCP_CLINICAL_SIGNAL_KEYS = [
"GRIP_STRENGTH",
"PAIN_NRS",
"WAIST_CIRCUMFERENCE",
"WAIST_TO_HEIGHT",
] as const;
// The registry's own `surfaces.mcp` flag is the SINGLE source of truth for
// MCP exposure: a signal surfaces here iff it is a measurement marked
// `mcp:true` while staying off the Coach snapshot (`coachSnapshot:false`).
// The `mcp` and `coachSnapshot` facets are independent — a signal can be
// MCP-readable without being on the Coach surface. Deliberately ABSENT and
// therefore unreachable over MCP: the PHQ-9 / GAD-7 mental-health screeners
// and every environmental (`ENV_*`) signal — they carry `mcp:false` and never
// reach AI / MCP by construction.
/** Build a `RichMetric` from a registry signal key (measurement-kind only). */
function richMetricFromSignal(key: string): RichMetric | null {
@@ -215,11 +212,23 @@ function richMetricFromSignal(key: string): RichMetric | null {
};
}
/** Resolved clinical signals, keyed by their registry key (built once). */
/**
* The MCP-only clinical signals, derived from the registry: every measurement
* signal marked `mcp:true` that stays off the Coach snapshot. This is the one
* place the registry's `surfaces.mcp` flag is consumed for the rich reads —
* no duplicate allowlist to drift against.
*/
const CLINICAL_SIGNAL_BY_KEY = new Map<string, RichMetric>();
for (const key of MCP_CLINICAL_SIGNAL_KEYS) {
const metric = richMetricFromSignal(key);
if (metric) CLINICAL_SIGNAL_BY_KEY.set(key, metric);
for (const sig of allSignals()) {
if (
sig.kind !== "measurement" ||
sig.surfaces.mcp !== true ||
sig.surfaces.coachSnapshot !== false
) {
continue;
}
const metric = richMetricFromSignal(sig.key);
if (metric) CLINICAL_SIGNAL_BY_KEY.set(sig.key, metric);
}
/**
@@ -256,9 +265,9 @@ const CLINICAL_ALIASES: Record<string, string> = {
/**
* Resolve a free-text name to a clinical signal the MCP layer exposes, or
* `null`. Closed by construction to the `MCP_CLINICAL_SIGNAL_KEYS` allowlist, so
* a screener key (PHQ9_SCORE / GAD7_SCORE) or an `ENV_*` key can never resolve
* here even though they exist in the registry.
* `null`. Closed by construction to the registry-derived `mcp:true` measurement
* set, so a screener key (PHQ9_SCORE / GAD7_SCORE) or an `ENV_*` key — all
* `mcp:false` — can never resolve here even though they exist in the registry.
*/
function resolveClinicalSignal(key: string): RichMetric | null {
const aliased = CLINICAL_ALIASES[key];
+2 -2
View File
@@ -889,7 +889,7 @@ export const MCP_TOOLS: McpToolDefinition[] = [
name: "compare_metric",
title: "Compare metrics or windows",
description:
"Compare one metric against another over the same horizon, OR a single metric across two horizons. A horizon is either one of the five fixed trailing windows OR an explicit {from,to} date range (use `range`/`rangeB` for before-vs-after-a-date). Returns each side's rollup statistics (count, mean, min, max) with units and reference bands, plus a delta + percent change when both sides share a unit. Returns { present: false } when a side has no data.",
"Compare one metric against another over the same horizon, OR a single metric across two horizons. A horizon is either one of the five fixed trailing windows OR an explicit {from,to} date range (use `range`/`rangeB` for before-vs-after-a-date). Also resolves the clinical-signal metrics (grip strength, pain 0–10 NRS, waist circumference, waist-to-height ratio). Returns each side's rollup statistics (count, mean, min, max) with units and reference bands, plus a delta + percent change when both sides share a unit. Returns { present: false } when a side has no data.",
inputShape: {
metric: z.string().min(1).max(60),
metricB: z.string().min(1).max(60).optional(),
@@ -931,7 +931,7 @@ export const MCP_TOOLS: McpToolDefinition[] = [
name: "detect_changepoints",
title: "Detect level shifts in a metric",
description:
"Surface points where a metric's level shifted over a trailing window OR an explicit {from,to} date range (e.g. 'when did my weight trend change?'). Runs a conservative changepoint scan over the rollup tier's bucket means and reports each shift's date, direction, and before/after means with units. High firing bar — returns { present: false } when too little data exists or no shift clears the threshold.",
"Surface points where a metric's level shifted over a trailing window OR an explicit {from,to} date range (e.g. 'when did my weight trend change?'). Also resolves the clinical-signal metrics (grip strength, pain 0–10 NRS, waist circumference, waist-to-height ratio). Runs a conservative changepoint scan over the rollup tier's bucket means and reports each shift's date, direction, and before/after means with units. High firing bar — returns { present: false } when too little data exists or no shift clears the threshold.",
inputShape: {
metric: z.string().min(1).max(60),
window: coachScopeWindowSchema.optional(),