marmar-context / web / context / test / personal-factors.test.ts
personal-factors.test.ts
Raw
import { describe, expect, it } from "vitest";
import { parseLine, toInput } from "../server/context";
import { groundedFact } from "../server/guards";
import type { Fact } from "../src/types";

describe("personal factor facts", () => {
  it("parses labelled weight, sex, pregnancy and potassium", () => {
    expect(parseLine("Weight: 46 kg")).toMatchObject({
      kind: "weight",
      label: "46 kg",
      problem: null,
    });
    expect(parseLine("Weight: 101 lb")?.problem).toMatch(/kg/);
    expect(parseLine("Sex: Female")).toMatchObject({ label: "female", problem: null });
    expect(parseLine("Sex: unknown")?.problem).toBeTruthy();
    expect(parseLine("Pregnancy: breastfeeding")?.problem).toBeNull();
    expect(parseLine("Pregnancy: maybe")?.problem).toBeTruthy();
    expect(
      parseLine("Lab: Potassium; value: 5.8; unit: mmol/L; date: 2026-10-20")?.problem
    ).toBeNull();
    expect(
      parseLine("Lab: Potassium; value: 5.8; unit: mEq/L; date: 2026-10-20")?.problem
    ).toMatch(/unit/);
  });

  it("passes them to the engine", () => {
    const facts = [
      "Weight: 46 kg",
      "Sex: female",
      "Pregnancy: pregnant",
    ].map((line, i) => ({
      ...parseLine(line)!,
      id: `s:${i}`,
      sourceId: "s",
      quote: line,
      line: i + 1,
    })) as Fact[];
    const input = toInput(facts);
    expect(input.subject).toMatchObject({ weightKg: 46, sex: "female" });
    expect(input.reproductive).toBe("pregnant");
  });

  it("accepts model facts only when the line states them", () => {
    expect(groundedFact("Weight: 46 kg", "She weighed 46 kg at the visit.")?.problem).toBeNull();
    expect(() => groundedFact("Weight: 46 kg", "She is small and frail.")).toThrow();
    expect(() => groundedFact("Weight: 46 kg", "She weighed 146 kg.")).toThrow();
    expect(groundedFact("Sex: female", "A 78-year-old woman.")?.problem).toBeNull();
    expect(() => groundedFact("Sex: female", "She takes lisinopril.")).toThrow();
    expect(
      groundedFact("Weight: 60 kg", "Her mother weighs 60 kg.")?.problem
    ).toBeTruthy();
    expect(
      groundedFact("Pregnancy: pregnant", "She is possibly pregnant.")?.problem
    ).toBeTruthy();
    expect(groundedFact("Pregnancy: breastfeeding", "She is breastfeeding her son.")).toBeTruthy();
  });
});