mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 08:02:12 +00:00
Bucket D phase 1 of the v1.4.3 polish pass — the AI insights felt
"static" because (a) findings repeated phrasing with no concrete
numbers and (b) the inline-chart machinery existed but was prompted
permissively, so the model rarely used it.
Two concrete moves, scoped to ship in this hotfix:
1. **`metric:MOOD` is now an allowlisted chart token.** Renderer in
`<InsightAdvisorCard>` branches on `tokenKind(token)` — measurement
tokens still mount `<HealthChart>`, but `metric:MOOD` mounts the
dedicated, self-fetching `<MoodChart>` instead. The mood timeline
was previously the most under-served by the AI prose because it
couldn't be charted inline; now the model can illustrate adherence-
risk and mood-drift findings with the same chart users see on the
/mood page. Drift test was updated in lockstep — the v1.4.2 guard
that asserted MOOD was excluded now asserts it's present, plus a
new guard asserts COMPLIANCE is still excluded (no self-fetching
wrapper exists yet for `<ComplianceLineChart>`; ship that in v1.5).
2. **Prompt grew an EVIDENCE CONTRACT and a forbidden-phrase list.**
The base system prompt (DE + EN both) now requires every
`findings[]` entry to put a concrete number from the snapshot in
`value` ("138/85 mmHg", "+0.4 mmol/L vs. 30d-avg") instead of
adjective prose ("slightly elevated"). Findings without a snapshot
anchor MUST be omitted — variable cardinality 0..8 explicitly
stated, sorted by salience, NO padding. The forbidden-phrase list
blocks generic boilerplate that signals ungrounded output: "achte
auf ausreichend Schlaf", "drink enough water", "regular exercise",
"consult your doctor" (except in the disclaimer field which exists
precisely for that line). The chart-token instruction flipped from
passive ("Du DARFST") to active ("Bevorzuge Tokens immer dann,
wenn …") with three explicit triggers — temporal claims, threshold
references, window comparisons — that reliably surface chart-worthy
findings.
Carved out of v1.4.3 for v1.5: telescoping multi-resolution payload
(14d daily + 10w weekly + 21mo monthly + yearly summary per QA
research 1) and the evidence-ref output schema extension (QA 2).
Both touch the prompt's input shape and would change every cache
key + token bill — they want their own phase.
Tests + typecheck green (671/671 — one new chart-tokens drift
guard).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
81 lines
3.1 KiB
TypeScript
81 lines
3.1 KiB
TypeScript
/**
|
|
* Chart-include tokens for AI insight prose.
|
|
*
|
|
* The LLM can embed one of the literal strings below inside `summary` or
|
|
* `findings[].label` to inline-render the matching chart underneath the
|
|
* paragraph. Every token the model emits is matched against this allowlist
|
|
* — anything else (typos, hallucinations, attempts to inject other strings)
|
|
* is silently dropped before it ever reaches the renderer.
|
|
*
|
|
* Render path: prose → parseChartTokens(prose) → matching chart component
|
|
* per token. The visible prose is run through stripChartTokens so the
|
|
* literal token string never surfaces in the UI.
|
|
*/
|
|
// v1.4.3: allowlist extended with `metric:MOOD` so the AI can illustrate
|
|
// findings about mood drift inline. <MoodChart> is self-fetching, so the
|
|
// renderer just mounts it.
|
|
//
|
|
// `metric:COMPLIANCE` was prepared but pulled before ship — the existing
|
|
// <ComplianceLineChart> takes pre-aggregated daily data via props and
|
|
// has no self-fetching wrapper, so wiring it inline would silently
|
|
// render an empty chart. Land it in v1.5 once a self-fetching wrapper
|
|
// exists.
|
|
export const ALLOWED_CHART_TOKENS = [
|
|
"metric:WEIGHT",
|
|
"metric:BLOOD_PRESSURE_SYS",
|
|
"metric:BLOOD_PRESSURE_DIA",
|
|
"metric:PULSE",
|
|
"metric:BODY_FAT",
|
|
"metric:SLEEP_DURATION",
|
|
"metric:ACTIVITY_STEPS",
|
|
"metric:BLOOD_GLUCOSE",
|
|
"metric:TOTAL_BODY_WATER",
|
|
"metric:BONE_MASS",
|
|
"metric:OXYGEN_SATURATION",
|
|
"metric:MOOD",
|
|
] as const;
|
|
|
|
export type ChartToken = (typeof ALLOWED_CHART_TOKENS)[number];
|
|
|
|
const ALLOWED_SET = new Set<string>(ALLOWED_CHART_TOKENS);
|
|
|
|
// Greedy `[A-Z_]+` match. Uppercase letters and underscores only — anything
|
|
// else (apostrophes, spaces, lowercase, digits) terminates the token, so
|
|
// trailing junk like `metric:WEIGHT' onclick='alert(1)'` cleaves cleanly
|
|
// into the safe metric and an inert text remainder.
|
|
const TOKEN_REGEX = /metric:[A-Z_]+/g;
|
|
|
|
/**
|
|
* Find every well-formed chart token in `text` and return only those that
|
|
* are in the allowlist. Hallucinated tokens (e.g. `metric:NUKE`) are
|
|
* silently dropped.
|
|
*/
|
|
export function parseChartTokens(text: string): ChartToken[] {
|
|
const matches: string[] = text.match(TOKEN_REGEX) ?? [];
|
|
return matches.filter((m): m is ChartToken => ALLOWED_SET.has(m));
|
|
}
|
|
|
|
/** Strip the chart tokens out of the visible insight text. */
|
|
export function stripChartTokens(text: string): string {
|
|
return text
|
|
.replace(TOKEN_REGEX, "")
|
|
.replace(/\s{2,}/g, " ")
|
|
.trim();
|
|
}
|
|
|
|
/** Map a chart token to the metric param the underlying chart component
|
|
* expects. For MeasurementType-backed tokens this is a real enum value
|
|
* (`WEIGHT`, `PULSE`, …); for `MOOD` and `COMPLIANCE` it's a synthetic
|
|
* identifier the renderer routes to a dedicated chart component. */
|
|
export function tokenToMetric(token: ChartToken): string {
|
|
return token.slice("metric:".length);
|
|
}
|
|
|
|
/** Token kinds the renderer needs to distinguish. MeasurementType tokens
|
|
* feed `<HealthChart>`; `metric:MOOD` mounts the dedicated, self-fetching
|
|
* `<MoodChart>` instead. */
|
|
export function tokenKind(token: ChartToken): "measurement" | "mood" {
|
|
if (token === "metric:MOOD") return "mood";
|
|
return "measurement";
|
|
}
|