diff --git a/.omo/evidence/the-commons-hollow/task-32-the-commons-hollow-incomplete.json b/.omo/evidence/the-commons-hollow/task-32-the-commons-hollow-incomplete.json new file mode 100644 index 0000000..6ceef47 --- /dev/null +++ b/.omo/evidence/the-commons-hollow/task-32-the-commons-hollow-incomplete.json @@ -0,0 +1,44 @@ +{ + "todo": 32, + "scenario": "failure", + "description": "An incomplete exam (diarrhoea assessed but the skin-pinch field left unanswered) through the real src/lib/healthpost.ts classifyExam() engine (no mocks). Per plan todo 32's hard constraint, a required exam field missing for the branch being assessed must be rejected back with a clear prompt naming the missing field, never silently classified or defaulted.", + "command": "npx vitest run src/lib/healthpost.test.ts -t \"incomplete exam\"", + "vitestResult": { + "numPassedTests": 3, + "numFailedTests": 0, + "success": true + }, + "input": { + "ageMonths": 18, + "dangerSigns": { + "unableToDrinkOrBreastfeed": false, + "vomitsEverything": false, + "hasHadConvulsions": false, + "lethargicOrUnconscious": false + }, + "hasCoughOrDifficultBreathing": false, + "hasDiarrhea": true, + "diarrhea": { + "durationDays": 3, + "bloodInStool": false, + "restlessOrIrritable": false, + "sunkenEyes": false, + "ableToDrink": "normal", + "skinPinch": null + } + }, + "actualThrown": { + "name": "MissingExamFieldError", + "message": "Cannot classify: missing required exam field(s): diarrhea.skinPinch. Ask for these before continuing - an incomplete exam must never be guessed or defaulted.", + "missingFields": ["diarrhea.skinPinch"] + }, + "verifiedBehavior": "classifyExam() throws MissingExamFieldError naming the exact missing field (diarrhea.skinPinch) instead of returning any classification - no NO DEHYDRATION / SOME DEHYDRATION / SEVERE DEHYDRATION guess is produced for this incomplete input. Confirmed by a second, independent test vector with a missing cough.breathsPerMinute field and by an out-of-supported-age-range vector (ageMonths=1), both of which also throw rather than classify (see src/lib/healthpost.test.ts, describe block \"WHO-IMCI QA - failure path: incomplete exam\").", + "fullHealthpostSuite": { + "command": "npx vitest run src/lib/healthpost.test.ts", + "testFiles": 1, + "tests": 16, + "numPassedTests": 16, + "numFailedTests": 0, + "success": true + } +} diff --git a/.omo/evidence/the-commons-hollow/task-32-the-commons-hollow.json b/.omo/evidence/the-commons-hollow/task-32-the-commons-hollow.json new file mode 100644 index 0000000..5258445 --- /dev/null +++ b/.omo/evidence/the-commons-hollow/task-32-the-commons-hollow.json @@ -0,0 +1,55 @@ +{ + "todo": 32, + "scenario": "happy", + "description": "A documented 'urgent' WHO-IMCI test vector (10-month-old, cough/difficult breathing with stridor in a calm child, 55 breaths/min) through the real src/lib/healthpost.ts classifyExam() engine (no mocks). Per the published chart booklet, stridor in a calm child alone forces SEVERE PNEUMONIA OR VERY SEVERE DISEASE regardless of the fast-breathing count, so the classification matches exactly.", + "command": "npx vitest run src/lib/healthpost.test.ts -t \"documented urgent test vector\"", + "vitestResult": { + "numPassedTests": 1, + "numFailedTests": 0, + "success": true + }, + "input": { + "ageMonths": 10, + "dangerSigns": { + "unableToDrinkOrBreastfeed": false, + "vomitsEverything": false, + "hasHadConvulsions": false, + "lethargicOrUnconscious": false + }, + "hasCoughOrDifficultBreathing": true, + "cough": { "breathsPerMinute": 55, "chestIndrawing": false, "stridorWhenCalm": true }, + "hasDiarrhea": false + }, + "actualOutput": { + "ageMonths": 10, + "dangerSigns": [], + "classifications": [ + { + "domain": "coughOrDifficultBreathing", + "label": "SEVERE PNEUMONIA OR VERY SEVERE DISEASE", + "urgency": "urgent_referral", + "signsPresent": ["stridor in a calm child"] + } + ], + "overallUrgency": "urgent_referral", + "overallLabel": "SEVERE PNEUMONIA OR VERY SEVERE DISEASE" + }, + "reference": "WHO IMCI Chart Booklet / In-Service Training Module 1 (\"Assess and Classify the Sick Child Age 2 Months up to 5 Years\"): \"A child with cough or difficult breathing and with any of the following signs -- any general danger sign, chest indrawing or stridor in a calm child -- is classified as having SEVERE PNEUMONIA OR VERY SEVERE DISEASE.\" https://iris.who.int/bitstreams/56fc3687-9cf7-4a73-8274-372111fe91c4/download", + "fullHealthpostSuite": { + "command": "npx vitest run src/lib/healthpost.test.ts", + "testFiles": 1, + "tests": 16, + "numPassedTests": 16, + "numFailedTests": 0, + "success": true + }, + "fullRepoSuite": { + "command": "npx vitest run", + "testFiles": 36, + "tests": 185, + "numPassedTests": 184, + "numFailedTests": 1, + "buildExitCode": 0, + "note": "The one repo-wide failure is the pre-existing, unrelated src/AppRoutes.test.tsx fake-indexeddb ConstraintError flake already documented in .omo/evidence/the-commons-hollow/task-20-the-commons-hollow.json; all 16 new healthpost tests passed and the repo-wide count grew from 169 (pre-todo-32) to 185." + } +} diff --git a/src/lib/healthpost.test.ts b/src/lib/healthpost.test.ts new file mode 100644 index 0000000..6941f62 --- /dev/null +++ b/src/lib/healthpost.test.ts @@ -0,0 +1,306 @@ +import { describe, expect, it } from "vitest"; +import { + AgeOutOfSupportedRangeError, + MissingExamFieldError, + classifyExam, + type ExamInput, +} from "./healthpost"; + +// Base exam with every domain "normal"/absent, used as a starting point +// that individual test vectors override field-by-field. This keeps each +// vector's diff from the documented WHO-IMCI chart signs explicit. +function baseExam(overrides: Partial = {}): ExamInput { + return { + ageMonths: 18, + dangerSigns: { + unableToDrinkOrBreastfeed: false, + vomitsEverything: false, + hasHadConvulsions: false, + lethargicOrUnconscious: false, + }, + hasCoughOrDifficultBreathing: false, + hasDiarrhea: false, + ...overrides, + }; +} + +describe("WHO-IMCI danger-sign test vector (chart booklet: CHECK FOR GENERAL DANGER SIGNS)", () => { + it("classifies a convulsing, lethargic child as VERY SEVERE DISEASE / urgent referral with no other complaint", () => { + const result = classifyExam( + baseExam({ + dangerSigns: { + unableToDrinkOrBreastfeed: false, + vomitsEverything: false, + hasHadConvulsions: true, + lethargicOrUnconscious: true, + }, + }), + ); + expect(result.overallUrgency).toBe("urgent_referral"); + expect(result.classifications).toContainEqual( + expect.objectContaining({ domain: "generalDangerSigns", label: "VERY SEVERE DISEASE" }), + ); + expect(result.dangerSigns).toEqual(["convulsions", "lethargic or unconscious"]); + }); +}); + +describe("WHO-IMCI cough/pneumonia test vectors (chart booklet: ASSESS, CLASSIFY COUGH OR DIFFICULT BREATHING)", () => { + it("classifies chest indrawing with no danger sign as SEVERE PNEUMONIA OR VERY SEVERE DISEASE / urgent referral", () => { + const result = classifyExam( + baseExam({ + hasCoughOrDifficultBreathing: true, + cough: { breathsPerMinute: 35, chestIndrawing: true, stridorWhenCalm: false }, + }), + ); + const cough = result.classifications.find((c) => c.domain === "coughOrDifficultBreathing"); + expect(cough).toEqual( + expect.objectContaining({ + label: "SEVERE PNEUMONIA OR VERY SEVERE DISEASE", + urgency: "urgent_referral", + }), + ); + expect(result.overallUrgency).toBe("urgent_referral"); + }); + + it("classifies 52 breaths/min at 8 months (>= 50/min cutoff for age < 12 months) as PNEUMONIA / needs treatment", () => { + const result = classifyExam( + baseExam({ + ageMonths: 8, + hasCoughOrDifficultBreathing: true, + cough: { breathsPerMinute: 52, chestIndrawing: false, stridorWhenCalm: false }, + }), + ); + const cough = result.classifications.find((c) => c.domain === "coughOrDifficultBreathing"); + expect(cough).toEqual(expect.objectContaining({ label: "PNEUMONIA", urgency: "needs_treatment" })); + }); + + it("classifies 45 breaths/min at 8 months as NOT fast (below the 50/min cutoff for age < 12 months)", () => { + const result = classifyExam( + baseExam({ + ageMonths: 8, + hasCoughOrDifficultBreathing: true, + cough: { breathsPerMinute: 45, chestIndrawing: false, stridorWhenCalm: false }, + }), + ); + const cough = result.classifications.find((c) => c.domain === "coughOrDifficultBreathing"); + expect(cough).toEqual( + expect.objectContaining({ label: "NO PNEUMONIA: COUGH OR COLD", urgency: "home_care" }), + ); + }); + + it("classifies 42 breaths/min at 24 months (>= 40/min cutoff for age 12-59 months) as PNEUMONIA", () => { + const result = classifyExam( + baseExam({ + ageMonths: 24, + hasCoughOrDifficultBreathing: true, + cough: { breathsPerMinute: 42, chestIndrawing: false, stridorWhenCalm: false }, + }), + ); + const cough = result.classifications.find((c) => c.domain === "coughOrDifficultBreathing"); + expect(cough).toEqual(expect.objectContaining({ label: "PNEUMONIA", urgency: "needs_treatment" })); + }); + + it("classifies 35 breaths/min at 24 months (below the 40/min cutoff) as NO PNEUMONIA: COUGH OR COLD", () => { + const result = classifyExam( + baseExam({ + ageMonths: 24, + hasCoughOrDifficultBreathing: true, + cough: { breathsPerMinute: 35, chestIndrawing: false, stridorWhenCalm: false }, + }), + ); + const cough = result.classifications.find((c) => c.domain === "coughOrDifficultBreathing"); + expect(cough).toEqual( + expect.objectContaining({ label: "NO PNEUMONIA: COUGH OR COLD", urgency: "home_care" }), + ); + }); +}); + +describe("WHO-IMCI diarrhoea/dehydration test vectors (chart booklet: CLASSIFY DIARRHOEA -> DEHYDRATION)", () => { + it("classifies lethargic + sunken eyes + drinking poorly + very slow skin pinch as SEVERE DEHYDRATION / urgent referral", () => { + const result = classifyExam( + baseExam({ + dangerSigns: { + unableToDrinkOrBreastfeed: false, + vomitsEverything: false, + hasHadConvulsions: false, + lethargicOrUnconscious: true, + }, + hasDiarrhea: true, + diarrhea: { + durationDays: 3, + bloodInStool: false, + restlessOrIrritable: false, + sunkenEyes: true, + ableToDrink: "notAbleOrDrinkingPoorly", + skinPinch: "verySlow", + }, + }), + ); + const dehydration = result.classifications.find((c) => c.domain === "dehydration"); + expect(dehydration).toEqual( + expect.objectContaining({ label: "SEVERE DEHYDRATION", urgency: "urgent_referral" }), + ); + expect(result.overallUrgency).toBe("urgent_referral"); + }); + + it("classifies restless/irritable + drinks eagerly/thirsty (2 of the 'some' signs) as SOME DEHYDRATION / needs treatment", () => { + const result = classifyExam( + baseExam({ + hasDiarrhea: true, + diarrhea: { + durationDays: 3, + bloodInStool: false, + restlessOrIrritable: true, + sunkenEyes: false, + ableToDrink: "eagerThirsty", + skinPinch: "immediate", + }, + }), + ); + const dehydration = result.classifications.find((c) => c.domain === "dehydration"); + expect(dehydration).toEqual( + expect.objectContaining({ label: "SOME DEHYDRATION", urgency: "needs_treatment" }), + ); + }); + + it("classifies only one dehydration sign present (sunken eyes alone) as NO DEHYDRATION / home care", () => { + const result = classifyExam( + baseExam({ + hasDiarrhea: true, + diarrhea: { + durationDays: 3, + bloodInStool: false, + restlessOrIrritable: false, + sunkenEyes: true, + ableToDrink: "normal", + skinPinch: "immediate", + }, + }), + ); + const dehydration = result.classifications.find((c) => c.domain === "dehydration"); + expect(dehydration).toEqual( + expect.objectContaining({ label: "NO DEHYDRATION", urgency: "home_care" }), + ); + }); + + it("classifies 20 days of diarrhoea with dehydration as SEVERE PERSISTENT DIARRHOEA, alongside the dehydration row", () => { + const result = classifyExam( + baseExam({ + hasDiarrhea: true, + diarrhea: { + durationDays: 20, + bloodInStool: false, + restlessOrIrritable: true, + sunkenEyes: true, + ableToDrink: "normal", + skinPinch: "immediate", + }, + }), + ); + expect(result.classifications).toContainEqual( + expect.objectContaining({ label: "SOME DEHYDRATION", urgency: "needs_treatment" }), + ); + expect(result.classifications).toContainEqual( + expect.objectContaining({ label: "SEVERE PERSISTENT DIARRHOEA", urgency: "urgent_referral" }), + ); + expect(result.overallUrgency).toBe("urgent_referral"); + }); + + it("classifies 20 days of diarrhoea with no dehydration as PERSISTENT DIARRHOEA / needs treatment", () => { + const result = classifyExam( + baseExam({ + hasDiarrhea: true, + diarrhea: { + durationDays: 20, + bloodInStool: false, + restlessOrIrritable: false, + sunkenEyes: false, + ableToDrink: "normal", + skinPinch: "immediate", + }, + }), + ); + expect(result.classifications).toContainEqual( + expect.objectContaining({ label: "NO DEHYDRATION", urgency: "home_care" }), + ); + expect(result.classifications).toContainEqual( + expect.objectContaining({ label: "PERSISTENT DIARRHOEA", urgency: "needs_treatment" }), + ); + }); + + it("classifies blood in the stool as DYSENTERY alongside the independent dehydration row", () => { + const result = classifyExam( + baseExam({ + hasDiarrhea: true, + diarrhea: { + durationDays: 2, + bloodInStool: true, + restlessOrIrritable: false, + sunkenEyes: false, + ableToDrink: "normal", + skinPinch: "immediate", + }, + }), + ); + expect(result.classifications).toContainEqual( + expect.objectContaining({ domain: "dysentery", label: "DYSENTERY", urgency: "needs_treatment" }), + ); + }); +}); + +describe("WHO-IMCI QA - happy path: a documented urgent test vector", () => { + it("classifies stridor in a calm child with fast breathing as urgent overall", () => { + const result = classifyExam( + baseExam({ + ageMonths: 10, + hasCoughOrDifficultBreathing: true, + cough: { breathsPerMinute: 55, chestIndrawing: false, stridorWhenCalm: true }, + }), + ); + expect(result.overallUrgency).toBe("urgent_referral"); + expect(result.overallLabel).toBe("SEVERE PNEUMONIA OR VERY SEVERE DISEASE"); + }); +}); + +describe("WHO-IMCI QA - failure path: incomplete exam", () => { + it("rejects a cough exam missing breathsPerMinute instead of guessing a classification", () => { + expect(() => + classifyExam( + baseExam({ + hasCoughOrDifficultBreathing: true, + cough: { + breathsPerMinute: undefined as unknown as number, + chestIndrawing: false, + stridorWhenCalm: false, + }, + }), + ), + ).toThrow(MissingExamFieldError); + }); + + it("names the exact missing field in the thrown error", () => { + try { + classifyExam( + baseExam({ + hasDiarrhea: true, + diarrhea: { + durationDays: 3, + bloodInStool: false, + restlessOrIrritable: false, + sunkenEyes: false, + ableToDrink: "normal", + skinPinch: undefined as unknown as "immediate", + }, + }), + ); + expect.unreachable("classifyExam should have thrown MissingExamFieldError"); + } catch (error) { + expect(error).toBeInstanceOf(MissingExamFieldError); + expect((error as MissingExamFieldError).missingFields).toEqual(["diarrhea.skinPinch"]); + } + }); + + it("rejects an age outside the 2-59 month chart range instead of guessing", () => { + expect(() => classifyExam(baseExam({ ageMonths: 1 }))).toThrow(AgeOutOfSupportedRangeError); + }); +}); diff --git a/src/lib/healthpost.ts b/src/lib/healthpost.ts new file mode 100644 index 0000000..8d2197d --- /dev/null +++ b/src/lib/healthpost.ts @@ -0,0 +1,428 @@ +/** + * Health Post: WHO-IMCI triage decision engine (plan todo 32). + * + * This encodes the REAL, published WHO Integrated Management of Childhood + * Illness (IMCI) decision tree for a child age 2 months up to 5 years, as + * plain deterministic JS rule logic - no model, no heuristic scoring, no + * fabricated thresholds. Every cutoff and sign below is taken directly + * from the WHO IMCI chart booklet and its companion in-service training + * module: + * - WHO IMCI Chart Booklet: + * https://cdn.who.int/media/docs/default-source/mca-documents/child/imci-integrated-management-of-childhood-illness/imci-in-service-training/imci-chart-booklet.pdf + * - WHO IMCI In-Service Training Module 1, "Assess and Classify the Sick + * Child Age 2 Months up to 5 Years": + * https://cdn.who.int/media/docs/default-source/mca-documents/child/imci-integrated-management-of-childhood-illness/imci-in-service-training/imci-in_servicetraining_module_01.pdf + * + * Decision tree implemented here (the four classification tables the + * chart booklet lists under CHECK FOR GENERAL DANGER SIGNS, ASSESS COUGH + * OR DIFFICULT BREATHING, and ASSESS DIARRHOEA -> DEHYDRATION / + * PERSISTENT DIARRHOEA / DYSENTERY): + * + * 1. General danger signs (ask: unable to drink/breastfeed? vomits + * everything? has had convulsions? look: lethargic or unconscious?). + * ANY one present means VERY SEVERE DISEASE - urgent referral - + * regardless of any other finding. + * 2. Cough or difficult breathing: any general danger sign, OR chest + * indrawing, OR stridor in a calm child -> SEVERE PNEUMONIA OR VERY + * SEVERE DISEASE (urgent referral). Otherwise fast breathing (>=50 + * breaths/min for age 2-<12 months, >=40 breaths/min for age 12-59 + * months) -> PNEUMONIA (needs treatment). Otherwise -> NO PNEUMONIA: + * COUGH OR COLD (home care). + * 3. Diarrhoea -> dehydration: two or more of {lethargic or + * unconscious, sunken eyes, not able to drink or drinking poorly, + * skin pinch goes back very slowly} -> SEVERE DEHYDRATION (urgent + * referral). Otherwise two or more of {restless/irritable, sunken + * eyes, drinks eagerly/thirsty, skin pinch goes back slowly} -> SOME + * DEHYDRATION (needs treatment). Otherwise -> NO DEHYDRATION (home + * care). "Sunken eyes" legitimately counts toward either column at + * once, exactly as the published two-column chart allows. + * 4. Diarrhoea -> persistent diarrhoea (duration >= 14 days) and + * dysentery (blood in the stool) are independent classification + * rows per the same chart and are evaluated alongside dehydration, + * not instead of it. + * + * "Lethargic or unconscious" is one physical sign checked once during the + * general danger-sign assessment; it is reused (never re-asked) by the + * dehydration table below, matching how a single real exam is actually + * conducted. + * + * Hard constraint (plan todo 32): an incomplete exam - a required field + * missing for the branch actually being assessed - is NEVER silently + * classified or defaulted. `classifyExam` throws `MissingExamFieldError` + * naming exactly which field(s) are missing so the caller can prompt the + * user for them. An age outside the 2-59 month range this chart covers + * throws `AgeOutOfSupportedRangeError` rather than guessing against the + * wrong protocol (ages under 2 months use WHO's separate young-infant + * chart, not implemented here). + */ + +export type Urgency = "urgent_referral" | "needs_treatment" | "home_care"; + +/** Ask/look general danger-sign checks, done once for every child in this age range. */ +export interface DangerSignsInput { + unableToDrinkOrBreastfeed: boolean; + vomitsEverything: boolean; + hasHadConvulsions: boolean; + lethargicOrUnconscious: boolean; +} + +/** Required only when `hasCoughOrDifficultBreathing` is true. */ +export interface CoughExamInput { + breathsPerMinute: number; + chestIndrawing: boolean; + stridorWhenCalm: boolean; +} + +/** Required only when `hasDiarrhea` is true. `restlessOrIrritable` and the + * shared `lethargicOrUnconscious` danger sign are mutually describing the + * same child's condition, exactly as the chart's single "condition" look + * feeds both the general danger-sign check and the dehydration table. */ +export interface DiarrheaExamInput { + durationDays: number; + bloodInStool: boolean; + restlessOrIrritable: boolean; + sunkenEyes: boolean; + ableToDrink: "normal" | "eagerThirsty" | "notAbleOrDrinkingPoorly"; + skinPinch: "immediate" | "slow" | "verySlow"; +} + +export interface ExamInput { + /** Whole months, 2-59 inclusive (this chart's supported range: 2 months up to 5 years). */ + ageMonths: number; + dangerSigns: DangerSignsInput; + hasCoughOrDifficultBreathing: boolean; + cough?: CoughExamInput; + hasDiarrhea: boolean; + diarrhea?: DiarrheaExamInput; +} + +export type ClassificationDomain = + | "generalDangerSigns" + | "coughOrDifficultBreathing" + | "dehydration" + | "persistentDiarrhea" + | "dysentery"; + +export interface DomainClassification { + domain: ClassificationDomain; + label: string; + urgency: Urgency; + /** The specific signs that drove this classification, for an honest, auditable result. */ + signsPresent: string[]; +} + +export interface TriageResult { + ageMonths: number; + dangerSigns: string[]; + classifications: DomainClassification[]; + overallUrgency: Urgency; + overallLabel: string; +} + +/** + * Thrown instead of guessing when a field required for the branch being + * assessed is missing. Lists every missing field in one pass so the + * caller can prompt for all of them at once rather than one at a time. + */ +export class MissingExamFieldError extends Error { + readonly missingFields: string[]; + + constructor(missingFields: string[]) { + super( + `Cannot classify: missing required exam field(s): ${missingFields.join(", ")}. ` + + "Ask for these before continuing - an incomplete exam must never be guessed or defaulted.", + ); + this.name = "MissingExamFieldError"; + this.missingFields = missingFields; + } +} + +/** Thrown for an age this chart does not cover, rather than classifying against the wrong protocol. */ +export class AgeOutOfSupportedRangeError extends Error { + constructor(ageMonths: number) { + super( + `Cannot classify: this engine supports ages 2-59 months (2 months up to 5 years) per the ` + + `published WHO-IMCI chart; received ageMonths=${ageMonths}. Ages under 2 months need WHO's ` + + "separate young-infant protocol - do not guess against this chart.", + ); + this.name = "AgeOutOfSupportedRangeError"; + } +} + +function isMissing(value: unknown): boolean { + return value === undefined || value === null; +} + +function validateExam(input: ExamInput): void { + const missing: string[] = []; + + if (isMissing(input.ageMonths)) missing.push("ageMonths"); + + if (!input.dangerSigns) { + missing.push( + "dangerSigns.unableToDrinkOrBreastfeed", + "dangerSigns.vomitsEverything", + "dangerSigns.hasHadConvulsions", + "dangerSigns.lethargicOrUnconscious", + ); + } else { + if (isMissing(input.dangerSigns.unableToDrinkOrBreastfeed)) + missing.push("dangerSigns.unableToDrinkOrBreastfeed"); + if (isMissing(input.dangerSigns.vomitsEverything)) + missing.push("dangerSigns.vomitsEverything"); + if (isMissing(input.dangerSigns.hasHadConvulsions)) + missing.push("dangerSigns.hasHadConvulsions"); + if (isMissing(input.dangerSigns.lethargicOrUnconscious)) + missing.push("dangerSigns.lethargicOrUnconscious"); + } + + if (isMissing(input.hasCoughOrDifficultBreathing)) { + missing.push("hasCoughOrDifficultBreathing"); + } else if (input.hasCoughOrDifficultBreathing) { + if (!input.cough) { + missing.push("cough.breathsPerMinute", "cough.chestIndrawing", "cough.stridorWhenCalm"); + } else { + if (isMissing(input.cough.breathsPerMinute)) missing.push("cough.breathsPerMinute"); + if (isMissing(input.cough.chestIndrawing)) missing.push("cough.chestIndrawing"); + if (isMissing(input.cough.stridorWhenCalm)) missing.push("cough.stridorWhenCalm"); + } + } + + if (isMissing(input.hasDiarrhea)) { + missing.push("hasDiarrhea"); + } else if (input.hasDiarrhea) { + if (!input.diarrhea) { + missing.push( + "diarrhea.durationDays", + "diarrhea.bloodInStool", + "diarrhea.restlessOrIrritable", + "diarrhea.sunkenEyes", + "diarrhea.ableToDrink", + "diarrhea.skinPinch", + ); + } else { + if (isMissing(input.diarrhea.durationDays)) missing.push("diarrhea.durationDays"); + if (isMissing(input.diarrhea.bloodInStool)) missing.push("diarrhea.bloodInStool"); + if (isMissing(input.diarrhea.restlessOrIrritable)) + missing.push("diarrhea.restlessOrIrritable"); + if (isMissing(input.diarrhea.sunkenEyes)) missing.push("diarrhea.sunkenEyes"); + if (isMissing(input.diarrhea.ableToDrink)) missing.push("diarrhea.ableToDrink"); + if (isMissing(input.diarrhea.skinPinch)) missing.push("diarrhea.skinPinch"); + } + } + + if (missing.length > 0) { + throw new MissingExamFieldError(missing); + } + + if (!Number.isInteger(input.ageMonths) || input.ageMonths < 2 || input.ageMonths > 59) { + throw new AgeOutOfSupportedRangeError(input.ageMonths); + } +} + +/** Fast-breathing cutoff per the chart's two age bands. */ +function fastBreathingThreshold(ageMonths: number): number { + return ageMonths < 12 ? 50 : 40; +} + +function triggeredDangerSigns(d: DangerSignsInput): string[] { + const signs: string[] = []; + if (d.unableToDrinkOrBreastfeed) signs.push("unable to drink or breastfeed"); + if (d.vomitsEverything) signs.push("vomits everything"); + if (d.hasHadConvulsions) signs.push("convulsions"); + if (d.lethargicOrUnconscious) signs.push("lethargic or unconscious"); + return signs; +} + +function classifyCough( + cough: CoughExamInput, + ageMonths: number, + dangerSigns: string[], +): DomainClassification { + const threshold = fastBreathingThreshold(ageMonths); + const fastBreathing = cough.breathsPerMinute >= threshold; + + if (dangerSigns.length > 0 || cough.chestIndrawing || cough.stridorWhenCalm) { + const signsPresent = [ + ...dangerSigns.map((s) => `general danger sign: ${s}`), + ...(cough.chestIndrawing ? ["chest indrawing"] : []), + ...(cough.stridorWhenCalm ? ["stridor in a calm child"] : []), + ]; + return { + domain: "coughOrDifficultBreathing", + label: "SEVERE PNEUMONIA OR VERY SEVERE DISEASE", + urgency: "urgent_referral", + signsPresent, + }; + } + + if (fastBreathing) { + return { + domain: "coughOrDifficultBreathing", + label: "PNEUMONIA", + urgency: "needs_treatment", + signsPresent: [ + `fast breathing (${cough.breathsPerMinute}/min >= ${threshold}/min threshold for this age)`, + ], + }; + } + + return { + domain: "coughOrDifficultBreathing", + label: "NO PNEUMONIA: COUGH OR COLD", + urgency: "home_care", + signsPresent: [], + }; +} + +function classifyDehydration( + diarrhea: DiarrheaExamInput, + lethargicOrUnconscious: boolean, +): DomainClassification { + const severeSigns: string[] = []; + if (lethargicOrUnconscious) severeSigns.push("lethargic or unconscious"); + if (diarrhea.sunkenEyes) severeSigns.push("sunken eyes"); + if (diarrhea.ableToDrink === "notAbleOrDrinkingPoorly") + severeSigns.push("not able to drink or drinking poorly"); + if (diarrhea.skinPinch === "verySlow") severeSigns.push("skin pinch goes back very slowly"); + + if (severeSigns.length >= 2) { + return { + domain: "dehydration", + label: "SEVERE DEHYDRATION", + urgency: "urgent_referral", + signsPresent: severeSigns, + }; + } + + const someSigns: string[] = []; + if (diarrhea.restlessOrIrritable) someSigns.push("restless, irritable"); + if (diarrhea.sunkenEyes) someSigns.push("sunken eyes"); + if (diarrhea.ableToDrink === "eagerThirsty") someSigns.push("drinks eagerly, thirsty"); + if (diarrhea.skinPinch === "slow") someSigns.push("skin pinch goes back slowly"); + + if (someSigns.length >= 2) { + return { + domain: "dehydration", + label: "SOME DEHYDRATION", + urgency: "needs_treatment", + signsPresent: someSigns, + }; + } + + return { + domain: "dehydration", + label: "NO DEHYDRATION", + urgency: "home_care", + signsPresent: [], + }; +} + +function classifyPersistentDiarrhea( + durationDays: number, + dehydrationUrgency: Urgency, +): DomainClassification | null { + if (durationDays < 14) return null; + const hasDehydration = dehydrationUrgency !== "home_care"; + if (hasDehydration) { + return { + domain: "persistentDiarrhea", + label: "SEVERE PERSISTENT DIARRHOEA", + urgency: "urgent_referral", + signsPresent: [`diarrhoea for ${durationDays} days (>= 14)`, "dehydration present"], + }; + } + return { + domain: "persistentDiarrhea", + label: "PERSISTENT DIARRHOEA", + urgency: "needs_treatment", + signsPresent: [`diarrhoea for ${durationDays} days (>= 14)`], + }; +} + +function classifyDysentery(bloodInStool: boolean): DomainClassification | null { + if (!bloodInStool) return null; + return { + domain: "dysentery", + label: "DYSENTERY", + urgency: "needs_treatment", + signsPresent: ["blood in the stool"], + }; +} + +const URGENCY_RANK: Record = { + urgent_referral: 3, + needs_treatment: 2, + home_care: 1, +}; + +function pickOverall(classifications: DomainClassification[]): { + overallUrgency: Urgency; + overallLabel: string; +} { + if (classifications.length === 0) { + return { + overallUrgency: "home_care", + overallLabel: "NO DANGER SIGNS, COUGH, OR DIARRHOEA ASSESSED", + }; + } + const maxRank = Math.max(...classifications.map((c) => URGENCY_RANK[c.urgency])); + const overallUrgency = (Object.keys(URGENCY_RANK) as Urgency[]).find( + (u) => URGENCY_RANK[u] === maxRank, + ) as Urgency; + const overallLabel = classifications + .filter((c) => URGENCY_RANK[c.urgency] === maxRank) + .map((c) => c.label) + .join("; "); + return { overallUrgency, overallLabel }; +} + +/** + * Classifies one completed exam against the published WHO-IMCI decision + * tree. Throws `MissingExamFieldError` for any required field missing + * from the branch actually being assessed, and `AgeOutOfSupportedRangeError` + * for an age outside 2-59 months - never guesses or defaults either way. + */ +export function classifyExam(input: ExamInput): TriageResult { + validateExam(input); + + const dangerSigns = triggeredDangerSigns(input.dangerSigns); + const classifications: DomainClassification[] = []; + + if (dangerSigns.length > 0) { + classifications.push({ + domain: "generalDangerSigns", + label: "VERY SEVERE DISEASE", + urgency: "urgent_referral", + signsPresent: dangerSigns, + }); + } + + if (input.hasCoughOrDifficultBreathing) { + // Validated above: input.cough is present whenever hasCoughOrDifficultBreathing is true. + classifications.push(classifyCough(input.cough as CoughExamInput, input.ageMonths, dangerSigns)); + } + + if (input.hasDiarrhea) { + // Validated above: input.diarrhea is present whenever hasDiarrhea is true. + const diarrhea = input.diarrhea as DiarrheaExamInput; + const dehydration = classifyDehydration(diarrhea, input.dangerSigns.lethargicOrUnconscious); + classifications.push(dehydration); + + const persistent = classifyPersistentDiarrhea(diarrhea.durationDays, dehydration.urgency); + if (persistent) classifications.push(persistent); + + const dysentery = classifyDysentery(diarrhea.bloodInStool); + if (dysentery) classifications.push(dysentery); + } + + const { overallUrgency, overallLabel } = pickOverall(classifications); + + return { + ageMonths: input.ageMonths, + dangerSigns, + classifications, + overallUrgency, + overallLabel, + }; +}