mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
Five layers, because the defect had five places to hide. The catalogue guard checks what the compiler cannot state: every leaf resolves a label a human can read, every group resolves one, the fenced tier stays last, and the shipped template intersects the fence at nothing. The selection guard pins the three minting functions against each other. A stored blob this build cannot read resolves to the empty selection, never to a default set — that is what makes the revoked legacy links revocable rather than silently re-scoped. A request naming an id the server does not know is refused by name rather than dropped, because dropping it would narrow a scope the caller did express. The egress guard freezes the set of aggregator callers with the source of each one's selection written down. The required brand-typed parameter already stops a new path compiling without an answer; this stops one being added without a human writing the answer down, which is the moment a reviewer asks the question. The behavioural sweep aggregates every leaf in and out against a fixture that carries a row for each, and asserts the payload differs. It is parametrised over the catalogue, so a leaf added later is covered the day it is added. Its positive control asserts the all-on payload is genuinely populated first, so a "no difference" result means the gate is inert and not that the account is empty. Beside it: an unmapped measurement type is excluded rather than passed through, no table behind an unchosen leaf is queried at all, and an empty selection produces an empty record. The artefact layer runs the real route and reads what comes out — the FHIR bundle, the PDF text and the zip's contents — with a positive control beside every exclusion. Mutation-checked: making the gate admit everything reddens the sweep for every leaf; passing an unmapped type through reddens the fail-closed case; dropping the mood query's condition reddens the zero-read case; returning the BMI unconditionally reddens the sweep naming BODY_MASS_INDEX; adding a fenced leaf to the template reddens the purity guard; removing the panel's seeding block reddens the first-run and repeat-run cases; dropping the insurance refusal reddens the share-link case; adding a caller outside the frozen list reddens the egress guard naming the file. The panel suite grew past the practice name it was written for and is renamed for what it now covers: the three states, the fenced tier having no group control, and the scope line naming its sensitive inclusions. Integration coverage moves to the leaf model, including the case this release exists for: an account with data in every domain and a caller that named nothing gets an empty record. The OpenAPI contract catches up with the routes — the required selection, the refused keys, the share summary's new fields, the moved `Patient/$everything`, the Coverage search and the five typed reads.
277 lines
9.1 KiB
TypeScript
277 lines
9.1 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
|
|
vi.mock("@/lib/modules/gate", () => ({
|
|
isModuleEnabled: vi.fn(async () => true),
|
|
}));
|
|
vi.mock("@/lib/db", () => ({
|
|
prisma: {
|
|
user: { findUnique: vi.fn() },
|
|
medication: { findMany: vi.fn() },
|
|
},
|
|
}));
|
|
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
|
vi.mock("@/lib/doctor-report-data", () => ({
|
|
collectDoctorReportData: vi.fn(),
|
|
}));
|
|
vi.mock("@/lib/ai/coach/tools/inventory", () => ({
|
|
buildCoachDataInventory: vi.fn(),
|
|
}));
|
|
// v1.30 (G5/C4) — `measurements-inventory` appends the metric-status-only
|
|
// discovery rows; stub the engine so this file never reaches a real DB read.
|
|
vi.mock("@/lib/mcp/rich-reads", () => ({
|
|
metricStatusDiscoveryRows: vi.fn(async () => []),
|
|
}));
|
|
|
|
import { MCP_RESOURCES, MCP_RESOURCE_URIS } from "../resources";
|
|
import { prisma } from "@/lib/db";
|
|
import { collectDoctorReportData } from "@/lib/doctor-report-data";
|
|
import { buildCoachDataInventory } from "@/lib/ai/coach/tools/inventory";
|
|
import { metricStatusDiscoveryRows } from "@/lib/mcp/rich-reads";
|
|
import type { McpAuthContext } from "../auth";
|
|
|
|
const CTX: McpAuthContext = {
|
|
userId: "user-1",
|
|
tokenId: "token-1",
|
|
scopes: ["health:read"],
|
|
binding: "user-1:token-1",
|
|
canRead: true,
|
|
canWrite: false,
|
|
};
|
|
|
|
function resource(uri: string) {
|
|
const def = MCP_RESOURCES.find((r) => r.uri === uri);
|
|
if (!def) throw new Error(`resource ${uri} not registered`);
|
|
return def;
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.resetAllMocks();
|
|
});
|
|
|
|
describe("MCP resource surface", () => {
|
|
it("registers the fixed resources, none admin", () => {
|
|
expect([...MCP_RESOURCE_URIS].sort()).toEqual([
|
|
"healthlog://labs/catalogue",
|
|
"healthlog://measurements/inventory",
|
|
"healthlog://medications",
|
|
"healthlog://profile",
|
|
"healthlog://report/doctor-visit",
|
|
]);
|
|
for (const uri of MCP_RESOURCE_URIS) {
|
|
expect(uri).not.toMatch(/admin/i);
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("healthlog://profile", () => {
|
|
it("returns minimised, health-relevant profile data and omits identifiers", async () => {
|
|
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
|
heightCm: 180,
|
|
dateOfBirth: new Date("1990-01-01T00:00:00Z"),
|
|
gender: "MALE",
|
|
timezone: "Europe/Berlin",
|
|
unitPreference: "metric",
|
|
glucoseUnit: "mmol/L",
|
|
} as never);
|
|
|
|
const result = (await resource("healthlog://profile").read(CTX)) as Record<
|
|
string,
|
|
unknown
|
|
>;
|
|
|
|
// userId is narrowed from the session, never a caller argument.
|
|
expect(prisma.user.findUnique).toHaveBeenCalledWith(
|
|
expect.objectContaining({ where: { id: "user-1" } }),
|
|
);
|
|
expect(result.present).toBe(true);
|
|
expect(result.heightCm).toBe(180);
|
|
expect(typeof result.ageYears).toBe("number");
|
|
expect(result.glucoseUnit).toBe("mmol/L");
|
|
// No direct identifiers leak to the assistant.
|
|
expect(Object.keys(result)).not.toContain("email");
|
|
expect(Object.keys(result)).not.toContain("username");
|
|
expect(Object.keys(result)).not.toContain("role");
|
|
});
|
|
|
|
it("returns { present: false } when the user row is missing", async () => {
|
|
vi.mocked(prisma.user.findUnique).mockResolvedValue(null as never);
|
|
const result = (await resource("healthlog://profile").read(CTX)) as {
|
|
present: boolean;
|
|
};
|
|
expect(result.present).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("healthlog://medications", () => {
|
|
it("lists medications + schedules scoped to the session user", async () => {
|
|
vi.mocked(prisma.medication.findMany).mockResolvedValue([
|
|
{
|
|
name: "Med A",
|
|
dose: "10mg",
|
|
treatmentClass: "GENERIC",
|
|
asNeeded: false,
|
|
pausedAt: null,
|
|
startsOn: null,
|
|
endsOn: null,
|
|
schedules: [
|
|
{
|
|
label: "Morning",
|
|
dose: null,
|
|
windowStart: "08:00",
|
|
windowEnd: "10:00",
|
|
timesOfDay: ["08:00"],
|
|
daysOfWeek: null,
|
|
rrule: null,
|
|
rollingIntervalDays: null,
|
|
scheduleType: "SCHEDULED",
|
|
},
|
|
],
|
|
},
|
|
] as never);
|
|
|
|
const result = (await resource("healthlog://medications").read(
|
|
CTX,
|
|
)) as Record<string, unknown>;
|
|
|
|
expect(prisma.medication.findMany).toHaveBeenCalledWith(
|
|
expect.objectContaining({ where: { userId: "user-1" } }),
|
|
);
|
|
expect(result.present).toBe(true);
|
|
expect(result.count).toBe(1);
|
|
expect(Array.isArray(result.medications)).toBe(true);
|
|
});
|
|
|
|
it("returns { present: false } when no medications are tracked", async () => {
|
|
vi.mocked(prisma.medication.findMany).mockResolvedValue([] as never);
|
|
const result = (await resource("healthlog://medications").read(CTX)) as {
|
|
present: boolean;
|
|
count: number;
|
|
};
|
|
expect(result.present).toBe(false);
|
|
expect(result.count).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe("healthlog://measurements/inventory", () => {
|
|
it("merges the Coach inventory with the metric-status-only discovery rows (G5/C4)", async () => {
|
|
vi.mocked(buildCoachDataInventory).mockResolvedValue({
|
|
entries: [
|
|
{
|
|
tool: "get_metric_series",
|
|
metric: "weight",
|
|
domain: "weight",
|
|
present: true,
|
|
count: 5,
|
|
},
|
|
],
|
|
restMode: false,
|
|
cycleEnabled: false,
|
|
window: "last30days",
|
|
probeScope: { sources: [] },
|
|
} as never);
|
|
vi.mocked(metricStatusDiscoveryRows).mockResolvedValue([
|
|
{
|
|
tool: "compare_metric",
|
|
domain: "Wrist temperature",
|
|
present: false,
|
|
metric: "WRIST_TEMPERATURE",
|
|
},
|
|
] as never);
|
|
|
|
const result = (await resource("healthlog://measurements/inventory").read(
|
|
CTX,
|
|
)) as { present: boolean; metrics: Array<Record<string, unknown>> };
|
|
|
|
expect(metricStatusDiscoveryRows).toHaveBeenCalledWith("user-1");
|
|
expect(result.present).toBe(true);
|
|
expect(result.metrics).toHaveLength(2);
|
|
expect(
|
|
result.metrics.find((m) => m.metric === "WRIST_TEMPERATURE"),
|
|
).toMatchObject({ present: false });
|
|
});
|
|
});
|
|
|
|
describe("healthlog://report/doctor-visit", () => {
|
|
// The resource now reuses the SHARED summariser (doctor-visit-summary.ts), so
|
|
// it grounds the identical rich superset the doctor_visit_summary prompt does
|
|
// — mood, glucose panel, wellness composites, and illness episodes no longer
|
|
// drop out of the resource.
|
|
it("grounds the rich superset like the prompt when the data is present", async () => {
|
|
vi.mocked(collectDoctorReportData).mockResolvedValue({
|
|
period: {
|
|
days: 90,
|
|
since: "2026-03-29T00:00:00.000Z",
|
|
start: "2026-03-29T00:00:00.000Z",
|
|
end: "2026-06-27T00:00:00.000Z",
|
|
},
|
|
patient: {
|
|
username: "tester",
|
|
fullName: "A Person",
|
|
dateOfBirth: "1990-01-01",
|
|
gender: "female",
|
|
heightCm: 170,
|
|
},
|
|
stats: { WEIGHT: { avg: 80, min: 79, max: 82, count: 30, latest: 80 } },
|
|
glucoseClinical: { stillLearning: false, timeInRange: 70 },
|
|
bmi: 24,
|
|
compliance: { Ramipril: { total: 90, taken: 86, skipped: 0, missed: 4 } },
|
|
medications: [{ name: "Ramipril", dose: "5 mg", schedules: [] }],
|
|
mood: { avg: 3.5, min: 2, max: 5, count: 12 },
|
|
wellnessScores: [{ type: "RECOVERY", latest: 70, avg: 65 }],
|
|
illnessEpisodes: [
|
|
{
|
|
label: "Cold",
|
|
type: "ILLNESS",
|
|
lifecycle: "resolved",
|
|
onsetAt: "2026-05-01",
|
|
resolvedAt: "2026-05-08",
|
|
},
|
|
],
|
|
} as never);
|
|
|
|
const result = (await resource("healthlog://report/doctor-visit").read(
|
|
CTX,
|
|
)) as Record<string, unknown>;
|
|
|
|
// Third argument: the owner's SAVED selection, replayed. This surface
|
|
// cannot ask a human, so it never invents a scope.
|
|
expect(collectDoctorReportData).toHaveBeenCalledWith(
|
|
"user-1",
|
|
expect.objectContaining({ days: 90 }),
|
|
expect.objectContaining({ version: 2 }),
|
|
);
|
|
expect(result.present).toBe(true);
|
|
expect(result).toHaveProperty("vitals");
|
|
expect(result).toHaveProperty("mood");
|
|
expect(result).toHaveProperty("glucosePanel");
|
|
expect(result).toHaveProperty("wellnessScores");
|
|
expect(result).toHaveProperty("illnessEpisodes");
|
|
// Patient name never leaks.
|
|
const patient = result.patient as Record<string, unknown>;
|
|
expect(patient).not.toHaveProperty("fullName");
|
|
expect(patient).not.toHaveProperty("username");
|
|
});
|
|
|
|
it("omits absent sections honestly (no zero-fill)", async () => {
|
|
vi.mocked(collectDoctorReportData).mockResolvedValue({
|
|
period: { days: 90, since: "", start: "", end: "" },
|
|
patient: { dateOfBirth: "1990-01-01", gender: "female", heightCm: 170 },
|
|
stats: {},
|
|
glucoseClinical: { stillLearning: true },
|
|
bmi: null,
|
|
compliance: {},
|
|
medications: [],
|
|
mood: null,
|
|
} as never);
|
|
|
|
const result = (await resource("healthlog://report/doctor-visit").read(
|
|
CTX,
|
|
)) as Record<string, unknown>;
|
|
expect(result.present).toBe(true);
|
|
expect(result).not.toHaveProperty("mood");
|
|
expect(result).not.toHaveProperty("glucosePanel");
|
|
expect(result).not.toHaveProperty("wellnessScores");
|
|
expect(result).not.toHaveProperty("illnessEpisodes");
|
|
});
|
|
});
|