Files
HealthLog/src/lib/insights/__tests__/status-summary-screen.test.ts
T
aucun6352 f7cc47850a fix(i18n): make the Korean locale actually work end to end
Registering `ko` in the `Locale` union left seven locale-keyed tables
without an entry, so the build could not type-check and the safety
screens, the citation-coverage grader and the reference-range parser
read nothing at all for a Korean reader.

Three failures were not missing keys but wrong assumptions:

- The shared fold decomposes with NFD and strips U+0300-U+036F. Latin
  accents become plain letters, but Hangul decomposes into jamo, which
  are not in that range and survived — so folded Korean text was a jamo
  sequence no precomposed table entry could ever match. It recomposes to
  NFC now; every Latin, Polish and German fold is byte-identical.
- `normaliseLabKey` kept `[a-z0-9]`, which reduced every Korean analyte
  name to the empty string, so the derived index held none of them and a
  Korean cholesterol result reached a FHIR export uncoded.
- The reference-range parser had the hyphen and the dashes but not the
  tilde a Korean lab actually prints (`3.5~5.0`).

The Korean safety banks carry no `\b` next to a Hangul token — `\b` is
an ASCII `\w` boundary and Hangul is not `\w`, so `/\b증량/` matches
nothing — and the clause order is the mirror of the Latin banks, since
Korean closes with the verb. The dose patterns require a target-marking
particle for the same reason the Latin banks require "to"/"by": without
it the permitted restatement "7.5mg을 복용 중이고, 체중은 내려가고
있어요" tripped the lowering pattern.

The Coach and Insights prompts route `ko` down the reviewed English body
plus a Korean reply directive; there is no `safety-contracts.ko.yaml`, so
the native builder has no Korean ground rules to compose from.
2026-08-26 20:00:44 +09:00

132 lines
5.5 KiB
TypeScript

import { describe, it, expect } from "vitest";
import { finalizeStatusSummary } from "@/lib/insights/status-shared";
import { locales } from "@/lib/i18n/config";
/**
* The status-card chokepoint. Before this existed the only transform between a
* provider and a persisted assessment was whitespace normalisation, so a dose
* imperative on the Weight card persisted as the day's cached assessment while
* the identical sentence in the Coach was caught and replaced.
*
* The WITHHOLD policy itself is asserted by the caller's `ok: false` branch —
* here we pin that the chokepoint reports the violation instead of returning
* text, and that clean prose survives byte-for-byte.
*/
const DOSE_VIOLATION: Record<string, string> = {
en: '{"summary":"Consider increasing to 10 mg next week."}',
de: '{"summary":"Erhöhe auf 7,5 mg in der nächsten Woche."}',
fr: '{"summary":"Augmentez votre dose à 2,4 mg la semaine prochaine."}',
es: '{"summary":"Aumente su dosis a 2,4 mg la próxima semana."}',
it: '{"summary":"Aumenti la sua dose a 2,4 mg la prossima settimana."}',
pl: '{"summary":"Proszę zwiększyć dawkę do 2,4 mg w przyszłym tygodniu."}',
ko: '{"summary":"다음 주에 2.4mg으로 늘려 보세요."}',
};
const CAUSAL_VIOLATION: Record<string, string> = {
en: '{"summary":"Your weight fell because you slept more."}',
de: '{"summary":"Dein Gewicht sank wegen des Schlafs."}',
fr: '{"summary":"Votre poids a baissé parce que vous avez mieux dormi."}',
es: '{"summary":"Su peso bajó porque durmió más."}',
it: '{"summary":"Il suo peso è calato perché ha dormito di più."}',
pl: '{"summary":"Waga spadła, ponieważ spał Pan więcej."}',
ko: '{"summary":"수면 때문에 체중이 줄었어요."}',
};
const CLEAN: Record<string, string> = {
en: '{"summary":"Your weight is averaging 82 kg this week, steady against last month."}',
de: '{"summary":"Dein Gewicht liegt diese Woche im Schnitt bei 82 kg, stabil gegenüber dem Vormonat."}',
fr: '{"summary":"Votre poids est en moyenne de 82 kg cette semaine, stable par rapport au mois dernier."}',
es: '{"summary":"Su peso promedia 82 kg esta semana, estable frente al mes pasado."}',
it: '{"summary":"Il suo peso è in media di 82 kg questa settimana, stabile rispetto al mese scorso."}',
pl: '{"summary":"Waga wynosi średnio 82 kg w tym tygodniu, stabilnie wobec zeszłego miesiąca."}',
ko: '{"summary":"이번 주 체중은 평균 82kg으로, 지난달과 비슷해요."}',
};
describe("finalizeStatusSummary — dose prescriptions are withheld", () => {
for (const locale of locales) {
it(`reports a violation instead of text in ${locale}`, () => {
const out = finalizeStatusSummary(DOSE_VIOLATION[locale], locale);
expect(out.ok).toBe(false);
if (!out.ok) expect(out.reason).toBe("dose_prescription");
});
}
});
describe("finalizeStatusSummary — causal claims are withheld", () => {
/**
* Status cards are the `insights` surface GROUND RULE 12 declares, so unlike
* the Coach they DO enforce the no-causation contract.
*/
for (const locale of locales) {
it(`reports a causal claim in ${locale}`, () => {
const out = finalizeStatusSummary(CAUSAL_VIOLATION[locale], locale);
expect(out.ok).toBe(false);
if (!out.ok) expect(out.reason).toBe("causal_claim");
});
}
});
describe("finalizeStatusSummary — clean assessments pass untouched", () => {
for (const locale of locales) {
it(`returns the parsed summary verbatim in ${locale}`, () => {
const out = finalizeStatusSummary(CLEAN[locale], locale);
expect(out.ok).toBe(true);
if (out.ok) {
expect(out.text).toBe(
JSON.parse(CLEAN[locale]).summary as unknown as string,
);
}
});
}
it("still parses a bare-prose reply that ignores the JSON envelope", () => {
const out = finalizeStatusSummary(
"Your resting pulse is averaging 58 bpm, in line with your baseline.",
"en",
);
expect(out.ok).toBe(true);
if (out.ok) expect(out.text).toContain("58 bpm");
});
it("treats an empty completion as empty text, not a violation", () => {
const out = finalizeStatusSummary("", "en");
expect(out.ok).toBe(true);
});
});
/**
* HealthLog#608 — a truncated `{ "summary": "…` (unclosed, no `}`) used to fall
* through the parser and render raw (braces, `"summary"`, quotes, literal `\n`)
* in the resting-pulse Assessment card. It must now resolve to the withhold
* state so the caller serves its deterministic stub, never the raw envelope.
*/
describe("finalizeStatusSummary — malformed structured output is withheld", () => {
const TRUNCATED =
'{ "summary": "Your resting pulse has been running lower than the last check';
it("withholds a truncated envelope instead of surfacing raw JSON", () => {
const out = finalizeStatusSummary(TRUNCATED, "en");
expect(out.ok).toBe(false);
if (!out.ok) expect(out.reason).toBe("unparseable_output");
// Nothing about the raw envelope can leak on the ok:false branch.
if (out.ok) {
expect(out.text).not.toContain('"summary"');
expect(out.text).not.toContain("{");
}
});
it("withholds a summary-less object", () => {
const out = finalizeStatusSummary("{}", "en");
expect(out.ok).toBe(false);
if (!out.ok) expect(out.reason).toBe("unparseable_output");
});
it("still renders a valid object summary", () => {
const out = finalizeStatusSummary('{"summary":"Steady at 58 bpm."}', "en");
expect(out.ok).toBe(true);
if (out.ok) expect(out.text).toBe("Steady at 58 bpm.");
});
});