mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
Merge branch 'fix/v1438-api' into release/v1.43.8
This commit is contained in:
commit
4a0db28713
99 files changed
+5219
-1018
No files matched your search
@@ -3,6 +3,7 @@ import {
|
||||
trendSlope,
|
||||
detectAnomalies,
|
||||
summarize,
|
||||
wireSummary,
|
||||
type DataPoint,
|
||||
} from "../trends";
|
||||
|
||||
@@ -166,3 +167,19 @@ describe("summarize", () => {
|
||||
expect(summary.latest).toBe(data[N - 1].value);
|
||||
});
|
||||
});
|
||||
|
||||
describe("wireSummary", () => {
|
||||
it("drops the in-process anomaly count and keeps every published statistic", () => {
|
||||
const data = Array.from({ length: 10 }, (_, i) => ({
|
||||
date: new Date(Date.UTC(2026, 0, i + 1)),
|
||||
value: i === 9 ? 400 : 70 + i,
|
||||
}));
|
||||
const full = summarize(data);
|
||||
expect(full).toHaveProperty("anomalyCount");
|
||||
|
||||
const wire = wireSummary(full);
|
||||
expect(wire).not.toHaveProperty("anomalyCount");
|
||||
const { anomalyCount: _dropped, ...rest } = full;
|
||||
expect(wire).toEqual(rest);
|
||||
});
|
||||
});
|
||||
@@ -74,7 +74,7 @@ import {
|
||||
isHourlyMeanTypeSql,
|
||||
windowMeanSql,
|
||||
} from "@/lib/measurements/day-mean";
|
||||
import type { DataSummary } from "@/lib/analytics/trends";
|
||||
import { wireSummary, type DataSummary } from "@/lib/analytics/trends";
|
||||
import { measurementTypeEnum } from "@/lib/validations/measurement";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { caches, type ServerCache } from "@/lib/cache/server-cache";
|
||||
@@ -491,7 +491,7 @@ async function withSleepNightTotals(
|
||||
// dashboard tile reads slope30); recompute them off the night series is
|
||||
// out of scope here — the per-night `summarize()` already fills slope7 /
|
||||
// slope30 from the night DataPoints, so use them directly.
|
||||
slice.summaries.SLEEP_DURATION = summary;
|
||||
slice.summaries.SLEEP_DURATION = wireSummary(summary);
|
||||
// Additive, observational: the latest night's main session saw two
|
||||
// writer buckets with clearly different asleep totals. Round to whole
|
||||
// minutes, matching the `/api/sleep/night` serialisation.
|
||||
|
||||
@@ -156,6 +156,20 @@ export interface DataSummary {
|
||||
avg30LastYear?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A summary as `/api/analytics` publishes it: without `anomalyCount`.
|
||||
*
|
||||
* The SQL summaries path cannot compute the figure, so the route's published
|
||||
* summary has not carried it since v1.37.19. Two of its summaries are still
|
||||
* built by `summarize()` (the per-night sleep series and the glucose
|
||||
* meal-context split), and both put it back on the wire until they were run
|
||||
* through this.
|
||||
*/
|
||||
export function wireSummary(summary: DataSummary): DataSummary {
|
||||
const { anomalyCount: _inProcessOnly, ...wire } = summary;
|
||||
return wire;
|
||||
}
|
||||
|
||||
export function summarize(data: DataPoint[]): DataSummary {
|
||||
if (data.length === 0) {
|
||||
// Empty series — return null for stats so callers can render an explicit
|
||||
|
||||
@@ -55,6 +55,7 @@ import {
|
||||
attachRecordContextEcho,
|
||||
} from "./sharing/record-session-fence";
|
||||
import { refuseOnKeyMismatch } from "./boot/key-mismatch-refusal";
|
||||
import { meterAccountWrite, type WriteMeterOptions } from "./auth/write-meter";
|
||||
import { acceptIncomingRequestId } from "./http/request-id";
|
||||
import { withErrorEnvelopeDefaults } from "./api-response";
|
||||
import {
|
||||
@@ -545,12 +546,16 @@ export function isScopedCredential(auth: AuthContext): boolean {
|
||||
*/
|
||||
export async function requireAuth(
|
||||
requiredPermission?: string,
|
||||
options?: Pick<WriteMeterOptions, "writeBucket">,
|
||||
): Promise<AuthContext> {
|
||||
const auth = await authenticateCaller(requiredPermission);
|
||||
const carrier = await readActingCarrier(auth);
|
||||
if (carrier.kind !== "none") {
|
||||
throw refuseUndeclaredMode(auth, carrier);
|
||||
}
|
||||
// The shared write ceiling, for every write this resolver admits — see
|
||||
// `meterAccountWrite`.
|
||||
await meterAccountWrite(auth.user.id, options);
|
||||
return auth;
|
||||
}
|
||||
|
||||
@@ -866,6 +871,7 @@ export async function requireActorAuth(): Promise<AuthContext> {
|
||||
auditRefusal(auth, { kind: "header", accountId: header }, "actor_surface");
|
||||
throw new SharingNotPermittedError();
|
||||
}
|
||||
await meterAccountWrite(auth.user.id);
|
||||
return auth;
|
||||
}
|
||||
|
||||
@@ -913,6 +919,13 @@ export interface RecordAuthOptions {
|
||||
* above `"read"`.
|
||||
*/
|
||||
readonly readOverPost?: true;
|
||||
/**
|
||||
* This route meters its writes with a dedicated bucket instead of the shared
|
||||
* per-account one (`meterAccountWrite`). Frozen per route, with the reason,
|
||||
* by `write-rate-limit-guard.test.ts`, which also requires the route to call
|
||||
* its own limiter.
|
||||
*/
|
||||
readonly writeBucket?: "own";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -966,6 +979,13 @@ export async function requireRecordAuth(
|
||||
// fence reads, so the invariant is "before the carrier", not "before the
|
||||
// first database await".
|
||||
await assertRecordSessionFence(auth);
|
||||
// The shared write ceiling, charged to the ACTING account before any grant
|
||||
// is read, so a refused write counts like an admitted one — see
|
||||
// `meterAccountWrite`.
|
||||
await meterAccountWrite(auth.user.id, {
|
||||
readOverPost: options?.readOverPost,
|
||||
writeBucket: options?.writeBucket,
|
||||
});
|
||||
const carrier = await readActingCarrier(auth);
|
||||
|
||||
// A narrow, single-purpose Bearer never acts on another record.
|
||||
@@ -1063,6 +1083,7 @@ export async function requireGuardianAuth(): Promise<RecordAuthContext> {
|
||||
// a context that has since moved must be refused before the marker is read,
|
||||
// not after.
|
||||
await assertRecordSessionFence(auth);
|
||||
await meterAccountWrite(auth.user.id);
|
||||
const carrier = await readActingCarrier(auth);
|
||||
|
||||
if (carrier.kind === "none") {
|
||||
@@ -1207,6 +1228,7 @@ export async function requireAdmin(): Promise<AuthContext> {
|
||||
if (sessionData.user.role !== "ADMIN") {
|
||||
throw new HttpError(403, "Admin access required", AUTH_ERROR_CODES.admin);
|
||||
}
|
||||
await meterAccountWrite(sessionData.user.id);
|
||||
return { ...sessionData, authMethod: "cookie" };
|
||||
}
|
||||
|
||||
@@ -1233,6 +1255,7 @@ export async function requireCookieAuth(): Promise<AuthContext> {
|
||||
auth_method: "session",
|
||||
});
|
||||
}
|
||||
await meterAccountWrite(sessionData.user.id);
|
||||
return { ...sessionData, authMethod: "cookie" };
|
||||
}
|
||||
|
||||
@@ -1343,6 +1366,8 @@ export async function requireFreshMfa(
|
||||
});
|
||||
}
|
||||
|
||||
await meterAccountWrite(sessionData.user.id);
|
||||
|
||||
// The account must hold a credential that can stamp `mfaVerifiedAt` in the
|
||||
// first place. Without one a step-up-gated action is unreachable by design
|
||||
// rather than merely refused, so the refusal is named differently
|
||||
@@ -1661,6 +1686,7 @@ export async function requireBearerAuth(): Promise<BearerAuthContext> {
|
||||
}
|
||||
const raw = authHeader.slice(7);
|
||||
const auth = await authenticateBearer(raw, undefined);
|
||||
await meterAccountWrite(auth.user.id);
|
||||
return {
|
||||
...auth,
|
||||
apiTokenId: auth.session.id,
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// The unit setup stubs the meter for every route test; this file is where the
|
||||
// real one is pinned.
|
||||
vi.mock("@/lib/auth/write-meter", async (importOriginal) =>
|
||||
importOriginal<typeof import("@/lib/auth/write-meter")>(),
|
||||
);
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
event: null as null | { getHttpMethod: () => string | undefined },
|
||||
allowed: true,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
getEvent: () => state.event,
|
||||
annotate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkRecordWriteRateLimit: vi.fn(async () => ({
|
||||
allowed: state.allowed,
|
||||
limit: 300,
|
||||
remaining: state.allowed ? 299 : 0,
|
||||
resetAt: Date.now() + 60_000,
|
||||
})),
|
||||
}));
|
||||
|
||||
import {
|
||||
meterAccountWrite,
|
||||
RECORD_WRITE_RATE_LIMITED_CODE,
|
||||
} from "../write-meter";
|
||||
import { checkRecordWriteRateLimit } from "@/lib/rate-limit";
|
||||
import { HttpError } from "@/lib/api-errors";
|
||||
|
||||
function request(method: string | undefined) {
|
||||
state.event = { getHttpMethod: () => method };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(checkRecordWriteRateLimit).mockClear();
|
||||
state.allowed = true;
|
||||
state.event = null;
|
||||
});
|
||||
|
||||
describe("meterAccountWrite", () => {
|
||||
it.each(["POST", "PUT", "PATCH", "DELETE", "patch"])(
|
||||
"charges the acting account for a %s",
|
||||
async (method) => {
|
||||
request(method);
|
||||
await meterAccountWrite("account-1");
|
||||
expect(checkRecordWriteRateLimit).toHaveBeenCalledWith("account-1");
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["GET", "HEAD", "OPTIONS"])("leaves a %s alone", async (method) => {
|
||||
request(method);
|
||||
await meterAccountWrite("account-1");
|
||||
expect(checkRecordWriteRateLimit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("charges nothing outside a request", async () => {
|
||||
await meterAccountWrite("account-1");
|
||||
expect(checkRecordWriteRateLimit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("charges one request once, however many resolvers it passes", async () => {
|
||||
request("POST");
|
||||
await meterAccountWrite("account-1");
|
||||
await meterAccountWrite("account-1");
|
||||
expect(checkRecordWriteRateLimit).toHaveBeenCalledTimes(1);
|
||||
|
||||
request("POST");
|
||||
await meterAccountWrite("account-1");
|
||||
expect(checkRecordWriteRateLimit).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("leaves a read-over-POST alone, and only the POST", async () => {
|
||||
request("POST");
|
||||
await meterAccountWrite("account-1", { readOverPost: true });
|
||||
expect(checkRecordWriteRateLimit).not.toHaveBeenCalled();
|
||||
request("DELETE");
|
||||
await meterAccountWrite("account-1", { readOverPost: true });
|
||||
expect(checkRecordWriteRateLimit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("leaves a route with its own bucket alone", async () => {
|
||||
request("POST");
|
||||
await meterAccountWrite("account-1", { writeBucket: "own" });
|
||||
expect(checkRecordWriteRateLimit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses a spent bucket with 429 and the published code", async () => {
|
||||
state.allowed = false;
|
||||
request("PATCH");
|
||||
const refusal = await meterAccountWrite("account-1").catch((e) => e);
|
||||
expect(refusal).toBeInstanceOf(HttpError);
|
||||
expect((refusal as HttpError).statusCode).toBe(429);
|
||||
expect((refusal as HttpError).errorCode).toBe(
|
||||
RECORD_WRITE_RATE_LIMITED_CODE,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* The shared per-account write ceiling, applied where the caller is resolved.
|
||||
*
|
||||
* `checkRecordWriteRateLimit` (300 writes a minute per acting account) used to
|
||||
* be called by hand in a dozen create routes, and the other mutating routes
|
||||
* had no ceiling at all: of 364 mutating handlers, 169 met no limiter, every
|
||||
* PATCH and DELETE on an `[id]` among them. A positive list of routes that
|
||||
* remember to call it can only fall behind the routes that exist, so the
|
||||
* ceiling now sits on the path every authenticated write already takes: the
|
||||
* identity resolvers in `src/lib/api-handler.ts` call {@link meterAccountWrite}
|
||||
* once the caller is known, and it charges the bucket for any request whose
|
||||
* method writes.
|
||||
*
|
||||
* What it does not do:
|
||||
*
|
||||
* - charge a read. GET, HEAD and OPTIONS pass untouched, and so does a POST a
|
||||
* route declared `readOverPost` (a search whose query must not stand in a
|
||||
* URL).
|
||||
* - charge one request twice. A route that resolves the caller through two
|
||||
* helpers (step-up on top of a session) is charged once.
|
||||
* - meter a route that declared its own bucket. The bulk ingest endpoints
|
||||
* the native client syncs through have dedicated ceilings sized for that
|
||||
* volume; charging the shared bucket as well would let a large HealthKit
|
||||
* backfill lock the person out of logging a single dose by hand. Declaring
|
||||
* `writeBucket: "own"` is frozen per route by
|
||||
* `src/__tests__/write-rate-limit-guard.test.ts`, which also requires the
|
||||
* route to call its own limiter.
|
||||
*
|
||||
* The bucket is keyed on the ACTING account, the precedent from the delegable
|
||||
* medication routes: a delegate spends their own allowance rather than the
|
||||
* record owner's, and cannot collect a fresh one by switching records. A
|
||||
* refused request is counted too, since the charge happens before the body is
|
||||
* read.
|
||||
*/
|
||||
import { HttpError } from "@/lib/api-errors";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { checkRecordWriteRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
/** The code a refusal by the shared write bucket carries. */
|
||||
export const RECORD_WRITE_RATE_LIMITED_CODE = "record_write.rate_limited";
|
||||
|
||||
const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
||||
|
||||
/** Requests already charged, so a second resolver in one request is free. */
|
||||
const charged = new WeakSet<object>();
|
||||
|
||||
export interface WriteMeterOptions {
|
||||
/** The route answers this POST without writing (see `readOverPost`). */
|
||||
readOverPost?: true;
|
||||
/**
|
||||
* The route meters its writes with a dedicated bucket instead of the shared
|
||||
* one. Reviewed per route by the write rate-limit guard.
|
||||
*/
|
||||
writeBucket?: "own";
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge the acting account's shared write bucket for this request, or refuse
|
||||
* it with 429 when the bucket is spent.
|
||||
*
|
||||
* Outside a request (no wide event, so no method) there is nothing to charge.
|
||||
*/
|
||||
export async function meterAccountWrite(
|
||||
accountId: string,
|
||||
options: WriteMeterOptions = {},
|
||||
): Promise<void> {
|
||||
const evt = getEvent();
|
||||
if (!evt) return;
|
||||
const method = (evt.getHttpMethod() ?? "").toUpperCase();
|
||||
if (!WRITE_METHODS.has(method)) return;
|
||||
if (options.readOverPost === true && method === "POST") return;
|
||||
if (options.writeBucket === "own") {
|
||||
annotate({ meta: { write_bucket: "own" } });
|
||||
return;
|
||||
}
|
||||
if (charged.has(evt)) return;
|
||||
charged.add(evt);
|
||||
|
||||
const rl = await checkRecordWriteRateLimit(accountId);
|
||||
if (!rl.allowed) {
|
||||
annotate({ meta: { record_write_rate_limited: true } });
|
||||
throw new HttpError(
|
||||
429,
|
||||
"Too many writes, try again later",
|
||||
RECORD_WRITE_RATE_LIMITED_CODE,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,25 @@
|
||||
* no rollup, no sync, no FHIR, no insights. Charts read entries LIVE.
|
||||
*/
|
||||
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { readNote } from "@/lib/crypto/note-cipher";
|
||||
|
||||
/**
|
||||
* The joins behind a published custom-metric row: its newest live entry and
|
||||
* its live entry count. Every read that answers with the row — the
|
||||
* catalogue, the single metric, the edit echo — includes these, so `latest`
|
||||
* and `entryCount` cannot be present on one and missing on another.
|
||||
*/
|
||||
export const CUSTOM_METRIC_LATEST_INCLUDE = {
|
||||
entries: {
|
||||
where: { deletedAt: null },
|
||||
orderBy: { measuredAt: "desc" },
|
||||
take: 1,
|
||||
select: { value: true, unit: true, measuredAt: true },
|
||||
},
|
||||
_count: { select: { entries: { where: { deletedAt: null } } } },
|
||||
} satisfies Prisma.CustomMetricInclude;
|
||||
|
||||
/** A custom-metric catalog row as the API serialises it. */
|
||||
export interface CustomMetricRow {
|
||||
id: string;
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { buildOpenApiDocument } from "@/lib/openapi/registry";
|
||||
|
||||
import { clientBuildOf, deprecated, DEPRECATIONS } from "../deprecation";
|
||||
|
||||
beforeEach(() => vi.mocked(annotate).mockClear());
|
||||
|
||||
function request(userAgent?: string): Request {
|
||||
return new Request("http://localhost/api/feature-flags", {
|
||||
headers: userAgent ? { "user-agent": userAgent } : {},
|
||||
});
|
||||
}
|
||||
|
||||
describe("deprecated()", () => {
|
||||
it("dates the deprecation and the sunset, and names the successor", () => {
|
||||
const res = deprecated(
|
||||
new Response(null, { headers: { Link: '</a>; rel="next"' } }),
|
||||
"/api/feature-flags",
|
||||
request(),
|
||||
);
|
||||
const notice = DEPRECATIONS["/api/feature-flags"];
|
||||
expect(res.headers.get("Deprecation")).toBe(
|
||||
`@${Date.parse(`${notice.since}T00:00:00Z`) / 1000}`,
|
||||
);
|
||||
expect(new Date(res.headers.get("Sunset")!).toISOString()).toBe(
|
||||
`${notice.sunset}T00:00:00.000Z`,
|
||||
);
|
||||
// A Link the route already set survives beside the successor.
|
||||
expect(res.headers.get("Link")).toBe(
|
||||
'</a>; rel="next", </api/auth/me>; rel="successor-version"',
|
||||
);
|
||||
});
|
||||
|
||||
it("logs which client build still asked", () => {
|
||||
deprecated(
|
||||
new Response(null),
|
||||
"/api/feature-flags",
|
||||
request("HealthLog-iOS/1.2.0 (dev.healthlog.app)"),
|
||||
);
|
||||
expect(annotate).toHaveBeenCalledWith({
|
||||
meta: {
|
||||
deprecated_route: "/api/feature-flags",
|
||||
deprecation_sunset: DEPRECATIONS["/api/feature-flags"].sunset,
|
||||
client_build: "ios/1.2.0",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("sunsets every notice after it was deprecated", () => {
|
||||
for (const notice of Object.values(DEPRECATIONS)) {
|
||||
expect(Date.parse(notice.sunset)).toBeGreaterThan(
|
||||
Date.parse(notice.since),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("clientBuildOf", () => {
|
||||
it("reads the native build, a browser, anything else, and nothing", () => {
|
||||
expect(clientBuildOf("HealthLog-iOS/1.3.0 (dev.healthlog.app)")).toBe(
|
||||
"ios/1.3.0",
|
||||
);
|
||||
expect(
|
||||
clientBuildOf("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"),
|
||||
).toBe("web");
|
||||
expect(clientBuildOf("curl/8.4.0")).toBe("other");
|
||||
expect(clientBuildOf(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("each deprecation is published and applied", () => {
|
||||
const doc = buildOpenApiDocument() as unknown as {
|
||||
paths: Record<string, Record<string, { deprecated?: boolean }>>;
|
||||
};
|
||||
|
||||
it.each(Object.keys(DEPRECATIONS))(
|
||||
"%s is deprecated in the contract and answers through the helper",
|
||||
(route) => {
|
||||
const ops = Object.values(doc.paths[route] ?? {});
|
||||
expect(ops.length).toBeGreaterThan(0);
|
||||
expect(ops.every((op) => op.deprecated === true)).toBe(true);
|
||||
const src = readFileSync(
|
||||
join(process.cwd(), "src/app", route, "route.ts"),
|
||||
"utf8",
|
||||
);
|
||||
expect(src).toContain(`deprecated(response, "${route}", request)`);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { combinedCap, listPage, parseListQuery } from "../list-query";
|
||||
|
||||
describe("listPage", () => {
|
||||
it("asks for one row past the limit and reports a cut only when that row exists", async () => {
|
||||
const read = vi.fn(async (take: number) =>
|
||||
Array.from({ length: Math.min(take, 5) }, (_, i) => i),
|
||||
);
|
||||
|
||||
const cut = await listPage(3, read);
|
||||
expect(read).toHaveBeenLastCalledWith(4);
|
||||
expect(cut.rows).toEqual([0, 1, 2]);
|
||||
expect(cut.cap).toEqual({ truncated: true, limit: 3 });
|
||||
|
||||
// Exactly full is complete: five rows, a limit of five.
|
||||
const full = await listPage(5, read);
|
||||
expect(full.rows).toHaveLength(5);
|
||||
expect(full.cap).toEqual({ truncated: false, limit: 5 });
|
||||
|
||||
const short = await listPage(9, read);
|
||||
expect(short.rows).toHaveLength(5);
|
||||
expect(short.cap.truncated).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("combinedCap", () => {
|
||||
it("is truncated when any list was cut", () => {
|
||||
expect(
|
||||
combinedCap(
|
||||
{ truncated: false, limit: 50 },
|
||||
{ truncated: true, limit: 50 },
|
||||
),
|
||||
).toEqual({ truncated: true, limit: 50 });
|
||||
expect(
|
||||
combinedCap(
|
||||
{ truncated: false, limit: 50 },
|
||||
{ truncated: false, limit: 50 },
|
||||
).truncated,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseListQuery", () => {
|
||||
const options = { defaultLimit: 50, maxLimit: 200, offset: true };
|
||||
|
||||
it("applies the default and reads both fields", () => {
|
||||
expect(parseListQuery(new URLSearchParams(), options).data).toEqual({
|
||||
limit: 50,
|
||||
offset: 0,
|
||||
});
|
||||
expect(
|
||||
parseListQuery(new URLSearchParams("limit=10&offset=20"), options).data,
|
||||
).toEqual({ limit: 10, offset: 20 });
|
||||
});
|
||||
|
||||
it("refuses a limit past the ceiling and a negative offset, both at once", () => {
|
||||
const parsed = parseListQuery(
|
||||
new URLSearchParams("limit=500&offset=-1"),
|
||||
options,
|
||||
);
|
||||
expect(parsed.success).toBe(false);
|
||||
expect(parsed.error?.issues.map((i) => i.path[0]).sort()).toEqual([
|
||||
"limit",
|
||||
"offset",
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores offset on a route that does not page", () => {
|
||||
expect(
|
||||
parseListQuery(new URLSearchParams("offset=20"), {
|
||||
defaultLimit: 50,
|
||||
maxLimit: 200,
|
||||
}).data,
|
||||
).toEqual({ limit: 50, offset: 0 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* How a deprecated route says so: on the wire, and in the operator's log.
|
||||
*
|
||||
* `/api/feature-flags` was marked deprecated with a bare `Deprecation: true`
|
||||
* and no date at all: a client could learn that the route was going, never
|
||||
* when, and the operator could not tell which builds still called it, so the
|
||||
* removal criterion ("the first release after the native build that reads
|
||||
* `ai` ships") could not be checked against anything. A deprecation is now one
|
||||
* reviewed notice per route, applied with {@link deprecated}:
|
||||
*
|
||||
* - `Deprecation: @<unix seconds>` — when it was deprecated (RFC 9745);
|
||||
* - `Sunset: <HTTP-date>` — from when the route may stop answering
|
||||
* (RFC 8594);
|
||||
* - `Link: <successor>; rel="successor-version"` — where to go instead;
|
||||
* - a wide-event annotation naming the route's notice and the calling
|
||||
* client build, read off the `User-Agent`, so the log answers "who still
|
||||
* calls this" before the sunset arrives.
|
||||
*
|
||||
* The notices live in {@link DEPRECATIONS}, so the dates are in one place and
|
||||
* `deprecation.test.ts` holds each route that applies one to the OpenAPI
|
||||
* `deprecated` flag.
|
||||
*/
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { dayKeyAsUtcMidnight } from "@/lib/tz/date-only";
|
||||
|
||||
export interface DeprecationNotice {
|
||||
/** The day the route was deprecated, `YYYY-MM-DD` (UTC). */
|
||||
since: string;
|
||||
/** The first day the route may stop answering, `YYYY-MM-DD` (UTC). */
|
||||
sunset: string;
|
||||
/** The path that replaces it, when there is one. */
|
||||
successor?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every route that answers as deprecated, with its dates.
|
||||
*
|
||||
* `/api/feature-flags`: deprecated in v1.39.0 (2026-09-24), when `ai` on
|
||||
* `GET /api/auth/me` replaced it. The shipped native build still reads it, so
|
||||
* the sunset leaves two native release cycles.
|
||||
*/
|
||||
export const DEPRECATIONS = {
|
||||
"/api/feature-flags": {
|
||||
since: "2026-09-24",
|
||||
sunset: "2027-03-31",
|
||||
successor: "/api/auth/me",
|
||||
},
|
||||
} as const satisfies Record<string, DeprecationNotice>;
|
||||
|
||||
export type DeprecatedRoute = keyof typeof DEPRECATIONS;
|
||||
|
||||
/**
|
||||
* A notice day as the instant the header states. Both headers carry instants,
|
||||
* and a deprecation published for every client has no one person's day to
|
||||
* start from, so the day is read as UTC midnight: the label form.
|
||||
*/
|
||||
function utcDay(day: string): Date {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) {
|
||||
throw new Error(`Deprecation date must be YYYY-MM-DD, got "${day}"`);
|
||||
}
|
||||
return dayKeyAsUtcMidnight(day);
|
||||
}
|
||||
|
||||
/**
|
||||
* The calling client, coarsely: `ios/<version>` for the native app (its
|
||||
* `User-Agent` is `HealthLog-iOS/<version> (<bundle id>)`), `web` for a
|
||||
* browser, `other` for anything else, null with no header.
|
||||
*/
|
||||
export function clientBuildOf(userAgent: string | null): string | null {
|
||||
if (!userAgent) return null;
|
||||
const ios = /^HealthLog-iOS\/([0-9][0-9A-Za-z.+-]{0,31})/.exec(userAgent);
|
||||
if (ios) return `ios/${ios[1]}`;
|
||||
if (/^Mozilla\//.test(userAgent)) return "web";
|
||||
return "other";
|
||||
}
|
||||
|
||||
/** Mark a response as coming from a deprecated route, and log who asked. */
|
||||
export function deprecated<R extends Response>(
|
||||
response: R,
|
||||
route: DeprecatedRoute,
|
||||
request: Request,
|
||||
): R {
|
||||
const notice: DeprecationNotice = DEPRECATIONS[route];
|
||||
const since = utcDay(notice.since);
|
||||
const sunset = utcDay(notice.sunset);
|
||||
response.headers.set("Deprecation", `@${Math.floor(since.getTime() / 1000)}`);
|
||||
response.headers.set("Sunset", sunset.toUTCString());
|
||||
if (notice.successor) {
|
||||
response.headers.append(
|
||||
"Link",
|
||||
`<${notice.successor}>; rel="successor-version"`,
|
||||
);
|
||||
}
|
||||
annotate({
|
||||
meta: {
|
||||
deprecated_route: route,
|
||||
deprecation_sunset: notice.sunset,
|
||||
client_build: clientBuildOf(request.headers.get("user-agent")),
|
||||
},
|
||||
});
|
||||
return response;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* The `limit` and `offset` query fields of a paged list, safe for any bundle.
|
||||
*
|
||||
* Kept apart from `./list-query.ts` (which reaches the response envelope) so a
|
||||
* request schema in `src/lib/validations/` can use them without pulling server
|
||||
* code into a client that imports the same schema.
|
||||
*/
|
||||
import { z } from "zod";
|
||||
|
||||
/** The `limit` field, for a route whose query schema has other fields too. */
|
||||
export function listLimitField({
|
||||
defaultLimit,
|
||||
maxLimit,
|
||||
}: {
|
||||
defaultLimit: number;
|
||||
maxLimit: number;
|
||||
}) {
|
||||
return z.coerce.number().int().min(1).max(maxLimit).default(defaultLimit);
|
||||
}
|
||||
|
||||
/** The `offset` field, for a route whose query schema has other fields too. */
|
||||
export function listOffsetField() {
|
||||
return z.coerce.number().int().min(0).max(100_000).default(0);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* One way to read a page of a list, and one way to say whether it was cut.
|
||||
*
|
||||
* The list routes had grown five answers to "is there more": `meta.truncated`
|
||||
* from `src/lib/api/list-cap.ts`, a `hasMore` computed as `rows.length ===
|
||||
* limit` (true on a list that is exactly full, so a client asks for a page
|
||||
* that does not exist), a `total` from a second count query, a sync cursor,
|
||||
* and nothing at all. This module is where a capped or paged list gets its
|
||||
* page, so the signal is computed the same way everywhere:
|
||||
*
|
||||
* - {@link parseListQuery} reads `limit` (and `offset`, where the route
|
||||
* pages) with the route's own default and ceiling;
|
||||
* - {@link listPage} runs the read for one row past the limit and cuts it
|
||||
* back, so `cap.truncated` is exact: true only when a row past the page
|
||||
* exists.
|
||||
*
|
||||
* The cap is the one in `list-cap.ts` — this module adds no second signal.
|
||||
* A route answers with `apiListSuccess(data, cap)` (the envelope's `meta`),
|
||||
* or, where a route already published a `hasMore` in its body, derives that
|
||||
* field from `cap.truncated`.
|
||||
*
|
||||
* Every read through here must have a total order: the `orderBy` ends in the
|
||||
* row id, so a page boundary between two rows that share a timestamp does not
|
||||
* repeat one of them on the next page or drop it. `list-page-guard.test.ts`
|
||||
* holds every capped list to this module and to that tiebreaker.
|
||||
*/
|
||||
import { z } from "zod";
|
||||
|
||||
import { capRows, overfetch, type ListCap } from "@/lib/api/list-cap";
|
||||
|
||||
import { listLimitField, listOffsetField } from "./list-query-fields";
|
||||
|
||||
export interface ListQueryOptions {
|
||||
/** The limit when the request names none. */
|
||||
defaultLimit: number;
|
||||
/** The largest limit a request may ask for. */
|
||||
maxLimit: number;
|
||||
/** Whether the route pages with `offset`. */
|
||||
offset?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read `limit` (and `offset`) from a request's query string.
|
||||
*
|
||||
* Returns the Zod result, so the route answers a bad value with the same
|
||||
* multi-issue 422 it gives every other field.
|
||||
*/
|
||||
export function parseListQuery(
|
||||
params: URLSearchParams,
|
||||
options: ListQueryOptions,
|
||||
) {
|
||||
const schema = z.object({
|
||||
limit: listLimitField(options),
|
||||
offset: options.offset ? listOffsetField() : z.literal(0).default(0),
|
||||
});
|
||||
return schema.safeParse({
|
||||
limit: params.get("limit") ?? undefined,
|
||||
offset: options.offset ? (params.get("offset") ?? undefined) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a list read for one page and say whether rows past it exist.
|
||||
*
|
||||
* `read` receives the `take` to pass to Prisma (one past `limit`); the rows
|
||||
* come back cut to `limit` with the exact cap beside them.
|
||||
*/
|
||||
export async function listPage<T>(
|
||||
limit: number,
|
||||
read: (take: number) => Promise<readonly T[]>,
|
||||
): Promise<{ rows: T[]; cap: ListCap }> {
|
||||
return capRows(await read(overfetch(limit)), limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* The cap of a response that carries several capped lists at once (the
|
||||
* encounters' upcoming and past arms, the grants given and received): more
|
||||
* rows exist when any one of them was cut.
|
||||
*/
|
||||
export function combinedCap(...caps: ListCap[]): ListCap {
|
||||
return {
|
||||
truncated: caps.some((cap) => cap.truncated),
|
||||
limit: Math.max(...caps.map((cap) => cap.limit)),
|
||||
};
|
||||
}
|
||||
@@ -53,6 +53,7 @@ import { MCP_TOOLS } from "../tools";
|
||||
import { buildCoachDataInventory } from "@/lib/ai/coach/tools/inventory";
|
||||
import { executeCoachTool } from "@/lib/ai/coach/tools/executor";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { loadRecordCandidates } from "@/lib/mcp/record-search";
|
||||
import {
|
||||
USER_TEXT_FENCE_START,
|
||||
USER_TEXT_FENCE_END,
|
||||
@@ -134,6 +135,37 @@ describe("search", () => {
|
||||
expect(result.results.map((r) => r.id)).toContain("lab:LDL");
|
||||
expect(result.results.some((r) => r.id.startsWith("med:"))).toBe(false);
|
||||
});
|
||||
it("says the search was assembled from a cut read, on every page", async () => {
|
||||
vi.mocked(buildCoachDataInventory).mockResolvedValue({
|
||||
entries: [],
|
||||
window: "90d",
|
||||
restMode: false,
|
||||
cycleEnabled: false,
|
||||
} as never);
|
||||
vi.mocked(prisma.medication.findMany).mockResolvedValue([]);
|
||||
vi.mocked(prisma.labResult.findMany).mockResolvedValue([]);
|
||||
vi.mocked(loadRecordCandidates).mockImplementationOnce(
|
||||
async (_userId, _query, _origin, options) => {
|
||||
options?.onTruncated?.("visit");
|
||||
return [];
|
||||
},
|
||||
);
|
||||
|
||||
const cut = (await tool("search").run(CTX, { query: "cardio" })) as {
|
||||
truncated: boolean;
|
||||
truncatedSources?: string[];
|
||||
};
|
||||
expect(cut.truncated).toBe(true);
|
||||
expect(cut.truncatedSources).toEqual(["visit"]);
|
||||
|
||||
const whole = (await tool("search").run(CTX, { query: "cardio" })) as {
|
||||
truncated: boolean;
|
||||
truncatedSources?: string[];
|
||||
};
|
||||
expect(whole.truncated).toBe(false);
|
||||
expect(whole).not.toHaveProperty("truncatedSources");
|
||||
});
|
||||
|
||||
it("keeps distinct lab analytes stable across cursor pages", async () => {
|
||||
vi.mocked(buildCoachDataInventory).mockResolvedValue({
|
||||
entries: [],
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* A tool that throws answers with a fixed sentence and a code, never with the
|
||||
* exception's own text.
|
||||
*
|
||||
* Without the wrap the SDK hands the model `error.message`, which for a
|
||||
* database failure is Prisma's prose: the query, the columns, sometimes a value
|
||||
* from the record. The detail belongs in the operator's log.
|
||||
*/
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const event = vi.hoisted(() => ({
|
||||
setError: vi.fn(),
|
||||
getRequestId: () => "req-123",
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
ecgRecording: {
|
||||
findMany: vi.fn(async () => {
|
||||
throw new Error(
|
||||
"Invalid `prisma.ecgRecording.findMany()` invocation: column ecg_recordings.waveform_encrypted does not exist (value: 4711)",
|
||||
);
|
||||
}),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
getEvent: () => event,
|
||||
}));
|
||||
|
||||
process.env.APP_URL = "http://localhost";
|
||||
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
import { createMcpServer } from "../server";
|
||||
import { MCP_TOOL_FAILED } from "../tool-failure";
|
||||
import type { McpAuthContext } from "../auth";
|
||||
|
||||
const ctx: McpAuthContext = {
|
||||
userId: "u-1",
|
||||
tokenId: "t-1",
|
||||
scopes: ["health:read"],
|
||||
binding: "u-1:t-1",
|
||||
canRead: true,
|
||||
canWrite: false,
|
||||
};
|
||||
|
||||
describe("a failing tool", () => {
|
||||
it("tells the model a fixed sentence, a code and the request id, and logs the cause", async () => {
|
||||
const server = createMcpServer(ctx);
|
||||
const client = new Client({ name: "failure-test", version: "1.0.0" });
|
||||
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
|
||||
await Promise.all([server.connect(serverSide), client.connect(clientSide)]);
|
||||
|
||||
const result = (await client.callTool({
|
||||
name: "get_ecg_recordings",
|
||||
arguments: {},
|
||||
})) as { isError?: boolean; content: Array<{ text: string }> };
|
||||
await client.close();
|
||||
await server.close();
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
const text = result.content.map((c) => c.text).join("\n");
|
||||
expect(text).not.toMatch(/prisma|invocation|column|waveform|4711/i);
|
||||
const body = JSON.parse(text) as {
|
||||
error: { code: string; message: string; requestId?: string };
|
||||
};
|
||||
expect(body.error.code).toBe(MCP_TOOL_FAILED);
|
||||
expect(body.error.requestId).toBe("req-123");
|
||||
expect(body.error.message).toContain("get_ecg_recordings");
|
||||
|
||||
// The cause went to the event, which redacts it on the way to the log.
|
||||
expect(event.setError).toHaveBeenCalledWith(expect.any(Error));
|
||||
expect((event.setError.mock.calls[0][0] as Error).message).toContain(
|
||||
"findMany",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1110,12 +1110,48 @@ describe("get_visits", () => {
|
||||
};
|
||||
expect(arg.where.userId).toBe("user-1");
|
||||
expect(arg.where.deletedAt).toBeNull();
|
||||
expect(arg.take).toBe(50);
|
||||
// One past the cap of 50: the extra row only says whether more exist.
|
||||
expect(arg.take).toBe(51);
|
||||
// The window arg narrows the range; the injected userId body field is
|
||||
// ignored entirely.
|
||||
expect(arg.where.occurredAt).toBeDefined();
|
||||
});
|
||||
|
||||
it("says when the visit list was cut at its cap, and only then", async () => {
|
||||
const visit = (n: number) => ({
|
||||
id: `enc-${n}`,
|
||||
occurredAt: new Date(Date.UTC(2026, 0, 1) - n * 86_400_000),
|
||||
status: "DONE",
|
||||
kind: "ROUTINE",
|
||||
reasonEncrypted: null,
|
||||
outcomeEncrypted: null,
|
||||
bodySiteEncrypted: null,
|
||||
laterality: null,
|
||||
practitioner: null,
|
||||
});
|
||||
vi.mocked(prisma.encounter.findMany).mockResolvedValueOnce(
|
||||
Array.from({ length: 51 }, (_, n) => visit(n)) as never,
|
||||
);
|
||||
const cut = (await tool("get_visits").run(CTX, {})) as {
|
||||
visits: unknown[];
|
||||
truncated: boolean;
|
||||
limit: number;
|
||||
};
|
||||
expect(cut.visits).toHaveLength(50);
|
||||
expect(cut).toMatchObject({ truncated: true, limit: 50 });
|
||||
|
||||
// Exactly full is the whole list.
|
||||
vi.mocked(prisma.encounter.findMany).mockResolvedValueOnce(
|
||||
Array.from({ length: 50 }, (_, n) => visit(n)) as never,
|
||||
);
|
||||
const full = (await tool("get_visits").run(CTX, {})) as {
|
||||
visits: unknown[];
|
||||
truncated: boolean;
|
||||
};
|
||||
expect(full.visits).toHaveLength(50);
|
||||
expect(full.truncated).toBe(false);
|
||||
});
|
||||
|
||||
it("narrows to one practitioner by a case-insensitive name substring", async () => {
|
||||
vi.mocked(prisma.encounter.findMany).mockResolvedValue([] as never);
|
||||
await tool("get_visits").run(CTX, { practitioner: "herz" });
|
||||
@@ -1535,6 +1571,49 @@ describe("get_intraday_pulse — v1.30 coverage review (G2)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("get_ecg_recordings — the list says when it was cut", () => {
|
||||
const row = (n: number) => ({
|
||||
id: `ecg-${n}`,
|
||||
recordedAt: new Date(Date.UTC(2026, 6, 1) - n * 3_600_000),
|
||||
durationSeconds: 30,
|
||||
samplingFrequency: 512,
|
||||
sampleCount: 15360,
|
||||
averageHeartRate: 70,
|
||||
lead: "LEAD_I",
|
||||
rhythmClassification: "NOT_DETECTED",
|
||||
source: "APPLE_HEALTH",
|
||||
});
|
||||
|
||||
it("reads one past the cap and reports the cut exactly", async () => {
|
||||
vi.mocked(prisma.ecgRecording.findMany).mockResolvedValueOnce(
|
||||
Array.from({ length: 201 }, (_, n) => row(n)) as never,
|
||||
);
|
||||
const cut = (await tool("get_ecg_recordings").run(CTX, {})) as {
|
||||
recordings: unknown[];
|
||||
truncated: boolean;
|
||||
limit: number;
|
||||
};
|
||||
const call = vi
|
||||
.mocked(prisma.ecgRecording.findMany)
|
||||
.mock.calls.at(-1)![0] as {
|
||||
take: number;
|
||||
orderBy: unknown;
|
||||
};
|
||||
expect(call.take).toBe(201);
|
||||
expect(call.orderBy).toEqual([{ recordedAt: "desc" }, { id: "desc" }]);
|
||||
expect(cut.recordings).toHaveLength(200);
|
||||
expect(cut).toMatchObject({ truncated: true, limit: 200 });
|
||||
|
||||
vi.mocked(prisma.ecgRecording.findMany).mockResolvedValueOnce(
|
||||
Array.from({ length: 200 }, (_, n) => row(n)) as never,
|
||||
);
|
||||
const full = (await tool("get_ecg_recordings").run(CTX, {})) as {
|
||||
truncated: boolean;
|
||||
};
|
||||
expect(full.truncated).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("get_ecg_recordings — v1.30 coverage review (G3)", () => {
|
||||
it("returns metadata-only recordings with the device classification verbatim", async () => {
|
||||
vi.mocked(prisma.ecgRecording.findMany).mockResolvedValue([
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* A capped MCP read, and the fields that tell the model it was cut.
|
||||
*
|
||||
* Several tools stopped at their own ceiling and said nothing: the ECG list at
|
||||
* 200, the visit history at 50, the booked appointments at 25, the record
|
||||
* search at a per-kind scan. A model handed the 50 newest visits reads the
|
||||
* fiftieth as the oldest there is and answers "your first cardiology visit was
|
||||
* in 2024" from a list that simply ended there.
|
||||
*
|
||||
* Same semantics as the REST list cap (`src/lib/api/list-cap.ts`), through the
|
||||
* same helper: the read asks for one row past the limit, and `truncated` is
|
||||
* true only when that row exists. A tool spreads {@link capFields} into its
|
||||
* result and {@link cappedOutput} into its output shape.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { listPage } from "@/lib/http/list-query";
|
||||
import type { ListCap } from "@/lib/api/list-cap-shape";
|
||||
|
||||
/** Run a capped read: the rows within `limit`, and whether more exist. */
|
||||
export function capped<T>(
|
||||
limit: number,
|
||||
read: (take: number) => Promise<readonly T[]>,
|
||||
): Promise<{ rows: T[]; cap: ListCap }> {
|
||||
return listPage(limit, read);
|
||||
}
|
||||
|
||||
/** The cap as tool-result fields. */
|
||||
export function capFields(cap: ListCap): { truncated: boolean; limit: number } {
|
||||
return { truncated: cap.truncated, limit: cap.limit };
|
||||
}
|
||||
|
||||
/**
|
||||
* The output-shape fields for a capped list. Optional, because a grounded
|
||||
* `{ present: false }` miss carries no list to have cut.
|
||||
*/
|
||||
export const cappedOutput = {
|
||||
truncated: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"True when more records exist than this result lists: the list was cut at `limit`. Do not treat the last record listed as the oldest or the only one; say the list is partial.",
|
||||
),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.optional()
|
||||
.describe("The most records this result could list."),
|
||||
};
|
||||
@@ -27,6 +27,7 @@ import { MCP_RESOURCES, MCP_RESOURCE_TEMPLATES } from "./resources";
|
||||
import { MCP_PROMPTS } from "./prompts";
|
||||
import { resolveBaseOrigin } from "./oauth/config";
|
||||
import { advertiseToolSchemasAs2020 } from "./schema-dialect";
|
||||
import { toolFailure } from "./tool-failure";
|
||||
|
||||
export const MCP_SERVER_NAME = "healthlog";
|
||||
export const MCP_SERVER_VERSION = "1.0.0";
|
||||
@@ -102,7 +103,12 @@ export function createMcpServer(ctx: McpAuthContext): McpServer {
|
||||
...(tool.outputShape ? { outputSchema: tool.outputShape } : {}),
|
||||
},
|
||||
async (args: Record<string, unknown>) => {
|
||||
const result = await tool.run(ctx, args ?? {});
|
||||
let result: unknown;
|
||||
try {
|
||||
result = await tool.run(ctx, args ?? {});
|
||||
} catch (error) {
|
||||
return toolFailure(tool.name, error);
|
||||
}
|
||||
const content = [
|
||||
{ type: "text" as const, text: JSON.stringify(result) },
|
||||
];
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* What a model is told when a tool fails, and what the operator is told.
|
||||
*
|
||||
* A tool that threw was answered by the MCP SDK with the exception's own
|
||||
* message as the result text, so a database failure reached the model, and
|
||||
* through it the person's chat, as Prisma's prose: the query shape, the
|
||||
* column names, sometimes a value from the record. That text is for the
|
||||
* operator. The model gets a fixed sentence it can relay, a stable code to
|
||||
* branch on, and the request id that finds the event in the log; the
|
||||
* exception goes to the wide event, through the same redaction every other
|
||||
* error takes.
|
||||
*/
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
|
||||
/** The code a failed tool call carries in its MCP result (not an HTTP `meta.errorCode`). */
|
||||
export const MCP_TOOL_FAILED = "mcp.tool.failed";
|
||||
|
||||
export function toolFailure(
|
||||
toolName: string,
|
||||
error: unknown,
|
||||
): {
|
||||
isError: true;
|
||||
content: Array<{ type: "text"; text: string }>;
|
||||
} {
|
||||
const evt = getEvent();
|
||||
const requestId = evt?.getRequestId() ?? null;
|
||||
if (evt) {
|
||||
evt.setError(error);
|
||||
annotate({
|
||||
action: { name: "mcp.tool.failed" },
|
||||
meta: { tool: toolName },
|
||||
});
|
||||
} else {
|
||||
// The stdio entrypoint runs outside a request, and stderr is its log.
|
||||
console.error(`HealthLog MCP: tool ${toolName} failed`, error);
|
||||
}
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({
|
||||
error: {
|
||||
code: MCP_TOOL_FAILED,
|
||||
message: `The ${toolName} tool could not complete this request. Try again later; if it keeps failing, the operator can find the failure by its request id.`,
|
||||
...(requestId ? { requestId } : {}),
|
||||
},
|
||||
}),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
+131
-72
@@ -70,6 +70,7 @@ import {
|
||||
import { loadIntradayPulse } from "@/lib/analytics/intraday-pulse-io";
|
||||
import { DEFAULT_TIMEZONE, userDayKey } from "@/lib/tz/format";
|
||||
import { encodeOffsetCursor, decodeOffsetCursor } from "@/lib/mcp/pagination";
|
||||
import { capFields, capped, cappedOutput } from "@/lib/mcp/capped";
|
||||
import { loadAutoTakeRollingAnchors } from "@/lib/medications/auto-take";
|
||||
import {
|
||||
computeDisplayDue,
|
||||
@@ -477,6 +478,15 @@ function searchAndFetchTools(): McpToolDefinition[] {
|
||||
}),
|
||||
),
|
||||
nextCursor: z.string().optional(),
|
||||
truncated: cappedOutput.truncated.describe(
|
||||
"True when a source this search reads stopped at its scan ceiling, so older records of that kind were not searched and no cursor reaches them. An empty or short result is then not proof that nothing matches; narrow the query or use the kind's own tool.",
|
||||
),
|
||||
truncatedSources: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe(
|
||||
"Which sources were cut: medication, lab, visit, condition, document, vaccination.",
|
||||
),
|
||||
},
|
||||
async run(ctx, args) {
|
||||
const rawQuery =
|
||||
@@ -526,12 +536,21 @@ function searchAndFetchTools(): McpToolDefinition[] {
|
||||
isModuleEnabled(ctx.userId, "labs"),
|
||||
]);
|
||||
|
||||
// Sources whose read stopped at its ceiling, so the result can say it
|
||||
// was assembled from part of the record instead of reading as all of
|
||||
// it.
|
||||
const truncatedSources: string[] = [];
|
||||
const meds = medicationsOn
|
||||
? await prisma.medication.findMany({
|
||||
where: { userId: ctx.userId },
|
||||
select: { id: true, name: true, dose: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: SEARCH_RESULT_SCAN_CAP,
|
||||
? await capped(SEARCH_RESULT_SCAN_CAP, (take) =>
|
||||
prisma.medication.findMany({
|
||||
where: { userId: ctx.userId },
|
||||
select: { id: true, name: true, dose: true },
|
||||
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
||||
take,
|
||||
}),
|
||||
).then(({ rows, cap }) => {
|
||||
if (cap.truncated) truncatedSources.push("medication");
|
||||
return rows;
|
||||
})
|
||||
: [];
|
||||
for (const med of meds) {
|
||||
@@ -549,12 +568,18 @@ function searchAndFetchTools(): McpToolDefinition[] {
|
||||
}
|
||||
|
||||
const labs = labsOn
|
||||
? await prisma.labResult.findMany({
|
||||
where: { userId: ctx.userId, deletedAt: null },
|
||||
select: { analyte: true },
|
||||
distinct: ["analyte"],
|
||||
orderBy: { analyte: "asc" },
|
||||
take: SEARCH_RESULT_SCAN_CAP,
|
||||
? await capped(SEARCH_RESULT_SCAN_CAP, (take) =>
|
||||
prisma.labResult.findMany({
|
||||
where: { userId: ctx.userId, deletedAt: null },
|
||||
select: { analyte: true },
|
||||
distinct: ["analyte"],
|
||||
// One row per analyte, so the analyte alone is a total order.
|
||||
orderBy: { analyte: "asc" },
|
||||
take,
|
||||
}),
|
||||
).then(({ rows, cap }) => {
|
||||
if (cap.truncated) truncatedSources.push("lab");
|
||||
return rows;
|
||||
})
|
||||
: [];
|
||||
for (const lab of labs) {
|
||||
@@ -636,7 +661,9 @@ function searchAndFetchTools(): McpToolDefinition[] {
|
||||
// v1.39.3 — visits (procedures included), conditions, documents and
|
||||
// vaccinations, each behind its own module switch.
|
||||
candidates.push(
|
||||
...(await loadRecordCandidates(ctx.userId, rawQuery, origin)),
|
||||
...(await loadRecordCandidates(ctx.userId, rawQuery, origin, {
|
||||
onTruncated: (kind) => truncatedSources.push(kind),
|
||||
})),
|
||||
);
|
||||
|
||||
const results = rankCandidates(candidates, rawQuery).map(
|
||||
@@ -658,6 +685,12 @@ function searchAndFetchTools(): McpToolDefinition[] {
|
||||
...(hasMore
|
||||
? { nextCursor: encodeOffsetCursor(offset + SEARCH_PAGE_SIZE) }
|
||||
: {}),
|
||||
// Every page says so, not only the last: the cut is in what was
|
||||
// searched, which no cursor reaches past.
|
||||
truncated: truncatedSources.length > 0,
|
||||
...(truncatedSources.length > 0
|
||||
? { truncatedSources: [...new Set(truncatedSources)].sort() }
|
||||
: {}),
|
||||
};
|
||||
},
|
||||
},
|
||||
@@ -1356,6 +1389,12 @@ const getPreventiveCareOutput: z.ZodRawShape = {
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
appointmentsTruncated: cappedOutput.truncated.describe(
|
||||
"True when more booked appointments exist than `appointments` lists: the list was cut at `appointmentsLimit`, soonest first. Say the list is partial.",
|
||||
),
|
||||
appointmentsLimit: cappedOutput.limit.describe(
|
||||
"The most appointments this result could list.",
|
||||
),
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1392,6 +1431,7 @@ const getVisitsOutput: z.ZodRawShape = {
|
||||
// "module_disabled" when the illness module is off and the condition
|
||||
// labels are withheld rather than absent (v1.39.3).
|
||||
conditionsReason: z.string().optional(),
|
||||
...cappedOutput,
|
||||
};
|
||||
|
||||
/** Default trailing window for `get_visits` when the caller names none. */
|
||||
@@ -1529,6 +1569,7 @@ const getEcgRecordingsOutput: z.ZodRawShape = {
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
...cappedOutput,
|
||||
};
|
||||
|
||||
/** `get_labs` behind its module gate: latest-per-biomarker or a history page. */
|
||||
@@ -2182,21 +2223,25 @@ export const MCP_TOOLS: McpToolDefinition[] = [
|
||||
// Upcoming appointments ride alongside the Vorsorge due-list, read from
|
||||
// `Encounter` (a booked visit in the future). They are a NAMED field on
|
||||
// this result, not a second tool, so "what is coming up" is one answer.
|
||||
const appointmentRows = await prisma.encounter.findMany({
|
||||
where: {
|
||||
userId: ctx.userId,
|
||||
deletedAt: null,
|
||||
status: "PLANNED",
|
||||
occurredAt: { gt: now },
|
||||
},
|
||||
orderBy: { occurredAt: "asc" },
|
||||
take: MAX_APPOINTMENTS,
|
||||
include: {
|
||||
practitioner: {
|
||||
select: { name: true, specialty: true, deletedAt: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
const { rows: appointmentRows, cap: appointmentCap } = await capped(
|
||||
MAX_APPOINTMENTS,
|
||||
(take) =>
|
||||
prisma.encounter.findMany({
|
||||
where: {
|
||||
userId: ctx.userId,
|
||||
deletedAt: null,
|
||||
status: "PLANNED",
|
||||
occurredAt: { gt: now },
|
||||
},
|
||||
orderBy: [{ occurredAt: "asc" }, { id: "asc" }],
|
||||
take,
|
||||
include: {
|
||||
practitioner: {
|
||||
select: { name: true, specialty: true, deletedAt: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const appointments = appointmentRows.map((r) => {
|
||||
const reason = decryptVisitText(r.reasonEncrypted);
|
||||
// A practitioner the person deleted is no longer named.
|
||||
@@ -2288,7 +2333,15 @@ export const MCP_TOOLS: McpToolDefinition[] = [
|
||||
return {
|
||||
present: true,
|
||||
...(checkups.length > 0 ? { checkups } : {}),
|
||||
...(appointments.length > 0 ? { appointments } : {}),
|
||||
...(appointments.length > 0
|
||||
? {
|
||||
appointments,
|
||||
// The cap describes the appointments only; the checkups are
|
||||
// read whole.
|
||||
appointmentsTruncated: appointmentCap.truncated,
|
||||
appointmentsLimit: appointmentCap.limit,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
},
|
||||
},
|
||||
@@ -2394,25 +2447,27 @@ export const MCP_TOOLS: McpToolDefinition[] = [
|
||||
async run(ctx) {
|
||||
// Device data, served whatever the AI switches or the AI analysis
|
||||
// opt-out say, like `GET /api/insights/ecg`.
|
||||
const rows = await prisma.ecgRecording.findMany({
|
||||
where: { userId: ctx.userId },
|
||||
// Everything EXCEPT `waveformEncrypted` — mirrors `GET
|
||||
// /api/insights/ecg`'s own select exactly; no decrypt ever happens
|
||||
// on this path.
|
||||
select: {
|
||||
id: true,
|
||||
recordedAt: true,
|
||||
durationSeconds: true,
|
||||
samplingFrequency: true,
|
||||
sampleCount: true,
|
||||
averageHeartRate: true,
|
||||
lead: true,
|
||||
rhythmClassification: true,
|
||||
source: true,
|
||||
},
|
||||
orderBy: { recordedAt: "desc" },
|
||||
take: MAX_ECG_RECORDINGS,
|
||||
});
|
||||
const { rows, cap } = await capped(MAX_ECG_RECORDINGS, (take) =>
|
||||
prisma.ecgRecording.findMany({
|
||||
where: { userId: ctx.userId },
|
||||
// Everything EXCEPT `waveformEncrypted` — mirrors `GET
|
||||
// /api/insights/ecg`'s own select exactly; no decrypt ever happens
|
||||
// on this path.
|
||||
select: {
|
||||
id: true,
|
||||
recordedAt: true,
|
||||
durationSeconds: true,
|
||||
samplingFrequency: true,
|
||||
sampleCount: true,
|
||||
averageHeartRate: true,
|
||||
lead: true,
|
||||
rhythmClassification: true,
|
||||
source: true,
|
||||
},
|
||||
orderBy: [{ recordedAt: "desc" }, { id: "desc" }],
|
||||
take,
|
||||
}),
|
||||
);
|
||||
|
||||
if (rows.length === 0) {
|
||||
annotate({
|
||||
@@ -2444,6 +2499,7 @@ export const MCP_TOOLS: McpToolDefinition[] = [
|
||||
present: true,
|
||||
classificationSource: "device" as const,
|
||||
recordings,
|
||||
...capFields(cap),
|
||||
};
|
||||
},
|
||||
},
|
||||
@@ -2498,33 +2554,35 @@ export const MCP_TOOLS: McpToolDefinition[] = [
|
||||
const cutoff = months === null ? null : new Date(now);
|
||||
cutoff?.setMonth(cutoff.getMonth() - (months ?? 0));
|
||||
|
||||
const rows = await prisma.encounter.findMany({
|
||||
// `userId` is the resolved session's, never an argument — a visit
|
||||
// belonging to another account is unreachable by construction.
|
||||
where: {
|
||||
userId: ctx.userId,
|
||||
deletedAt: null,
|
||||
occurredAt: { ...(cutoff ? { gte: cutoff } : {}), lte: now },
|
||||
...(kind ? { kind } : {}),
|
||||
...(practitioner
|
||||
? {
|
||||
practitioner: {
|
||||
is: {
|
||||
name: { contains: practitioner, mode: "insensitive" },
|
||||
deletedAt: null,
|
||||
const { rows, cap } = await capped(MAX_VISITS, (take) =>
|
||||
prisma.encounter.findMany({
|
||||
// `userId` is the resolved session's, never an argument — a visit
|
||||
// belonging to another account is unreachable by construction.
|
||||
where: {
|
||||
userId: ctx.userId,
|
||||
deletedAt: null,
|
||||
occurredAt: { ...(cutoff ? { gte: cutoff } : {}), lte: now },
|
||||
...(kind ? { kind } : {}),
|
||||
...(practitioner
|
||||
? {
|
||||
practitioner: {
|
||||
is: {
|
||||
name: { contains: practitioner, mode: "insensitive" },
|
||||
deletedAt: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
orderBy: { occurredAt: "desc" },
|
||||
take: MAX_VISITS,
|
||||
include: {
|
||||
practitioner: {
|
||||
select: { name: true, specialty: true, deletedAt: true },
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
orderBy: [{ occurredAt: "desc" }, { id: "desc" }],
|
||||
take,
|
||||
include: {
|
||||
practitioner: {
|
||||
select: { name: true, specialty: true, deletedAt: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Absence is explicit. An empty list is { present: false } — "you have
|
||||
// never recorded a visit" — NEVER { present: true, visits: [] }, which
|
||||
@@ -2590,6 +2648,7 @@ export const MCP_TOOLS: McpToolDefinition[] = [
|
||||
present: true,
|
||||
windowMonths: months,
|
||||
visits,
|
||||
...capFields(cap),
|
||||
...(illnessOn ? {} : { conditionsReason: "module_disabled" }),
|
||||
};
|
||||
},
|
||||
|
||||
+63
-41
@@ -5,6 +5,7 @@
|
||||
* client `queryFn` gets from the wire. Ciphertext never leaves this module:
|
||||
* the note is decrypted onto `note` and the context rides `contextForWire`.
|
||||
*/
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { shapeMoodNote } from "@/lib/crypto/note-cipher";
|
||||
import { shapeLevelA } from "@/lib/mood/level-a";
|
||||
@@ -30,6 +31,66 @@ function parseTags(tags: string | null): string[] {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a read of one entry joins: the structured-tag links with their rating
|
||||
* and kind, and the day context.
|
||||
*
|
||||
* v1.8.5 — the link keys pre-populate the taxonomy picker; v1.12.0 — the
|
||||
* per-link `rating` + tag `kind` split binary tags from rated factors on
|
||||
* hydrate; v1.38 — the day context, sparse by design: most rows carry none
|
||||
* and the join costs nothing on those.
|
||||
*/
|
||||
export const MOOD_ENTRY_WIRE_INCLUDE = {
|
||||
tagLinks: {
|
||||
select: {
|
||||
rating: true,
|
||||
moodTag: { select: { key: true, kind: true } },
|
||||
},
|
||||
},
|
||||
context: true,
|
||||
} satisfies Prisma.MoodEntryInclude;
|
||||
|
||||
type MoodEntryWithWireJoins = Prisma.MoodEntryGetPayload<{
|
||||
include: typeof MOOD_ENTRY_WIRE_INCLUDE;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* The one wire shape of a mood entry, for the list and the single-entry
|
||||
* read alike, so an entry opened on its own carries the same fields as the
|
||||
* same entry in the list.
|
||||
*/
|
||||
export function toMoodEntryWire({
|
||||
tagLinks,
|
||||
context,
|
||||
...e
|
||||
}: MoodEntryWithWireJoins) {
|
||||
return {
|
||||
// v1.23 — decrypt `noteEncrypted` onto `note`, strip the ciphertext.
|
||||
// v1.37 — the five level-A values under the keys the create path takes,
|
||||
// so the edit form reads back what it wrote instead of mapping column
|
||||
// names to wire names by hand. The column spelling is stripped, not
|
||||
// joined: one number under two names is a choice nobody made.
|
||||
...shapeLevelA(shapeMoodNote(e)),
|
||||
tags: parseTags(e.tags),
|
||||
// v1.8.5 — flat list of binary structured-tag keys attached to the
|
||||
// entry (rated factors are surfaced separately below).
|
||||
tagKeys: tagLinks
|
||||
.filter((link) => link.moodTag.kind !== "RATED")
|
||||
.map((link) => link.moodTag.key),
|
||||
// v1.12.0 — rated factors with their per-entry score, so the edit
|
||||
// form re-renders the sliders without a refetch.
|
||||
ratedFactors: tagLinks
|
||||
.filter((link) => link.moodTag.kind === "RATED" && link.rating !== null)
|
||||
.map((link) => ({
|
||||
key: link.moodTag.key,
|
||||
rating: link.rating as number,
|
||||
})),
|
||||
// v1.38 — the day context, or null. The ciphertext never leaves the
|
||||
// server: `contextForWire` reads the note and drops the column.
|
||||
context: context ? contextForWire(context) : null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listMoodEntriesPage(
|
||||
userId: string,
|
||||
params: MoodEntryListParams,
|
||||
@@ -59,51 +120,12 @@ export async function listMoodEntriesPage(
|
||||
orderBy: { [sortBy]: sortDir },
|
||||
take: limit,
|
||||
skip: offset,
|
||||
// v1.8.5 — include the structured-tag link keys so the edit form
|
||||
// can pre-populate the taxonomy picker.
|
||||
// v1.12.0 — also carry the per-link `rating` + the tag `kind` so
|
||||
// the client can split binary tags from rated factors on hydrate.
|
||||
include: {
|
||||
tagLinks: {
|
||||
select: {
|
||||
rating: true,
|
||||
moodTag: { select: { key: true, kind: true } },
|
||||
},
|
||||
},
|
||||
// v1.38 — the day context, so the edit dialog can pre-populate the
|
||||
// sections without a second round trip per row. Sparse by design: most
|
||||
// rows carry none and the join costs nothing on those.
|
||||
context: true,
|
||||
},
|
||||
include: MOOD_ENTRY_WIRE_INCLUDE,
|
||||
}),
|
||||
prisma.moodEntry.count({ where }),
|
||||
]);
|
||||
|
||||
const entriesWithParsedTags = entries.map(({ tagLinks, context, ...e }) => ({
|
||||
// v1.23 — decrypt `noteEncrypted` onto `note`, strip the ciphertext.
|
||||
// v1.37 — the five level-A values under the keys the create path takes,
|
||||
// so the edit form reads back what it wrote instead of mapping column
|
||||
// names to wire names by hand. The column spelling is stripped, not
|
||||
// joined: one number under two names is a choice nobody made.
|
||||
...shapeLevelA(shapeMoodNote(e)),
|
||||
tags: parseTags(e.tags),
|
||||
// v1.8.5 — flat list of binary structured-tag keys attached to the
|
||||
// entry (rated factors are surfaced separately below).
|
||||
tagKeys: tagLinks
|
||||
.filter((link) => link.moodTag.kind !== "RATED")
|
||||
.map((link) => link.moodTag.key),
|
||||
// v1.12.0 — rated factors with their per-entry score, so the edit
|
||||
// form re-renders the sliders without a refetch.
|
||||
ratedFactors: tagLinks
|
||||
.filter((link) => link.moodTag.kind === "RATED" && link.rating !== null)
|
||||
.map((link) => ({
|
||||
key: link.moodTag.key,
|
||||
rating: link.rating as number,
|
||||
})),
|
||||
// v1.38 — the day context, or null. The ciphertext never leaves the
|
||||
// server: `contextForWire` reads the note and drops the column.
|
||||
context: context ? contextForWire(context) : null,
|
||||
}));
|
||||
const entriesWithParsedTags = entries.map(toMoodEntryWire);
|
||||
|
||||
return {
|
||||
entries: entriesWithParsedTags,
|
||||
|
||||
@@ -392,6 +392,7 @@ export const ERROR_CODE_CATALOGUE: Readonly<Record<string, readonly string[]>> =
|
||||
],
|
||||
route: ["route.retired"],
|
||||
search: ["search.invalid"],
|
||||
security_activity: ["security_activity.invalid"],
|
||||
"share-link": [
|
||||
"share-link.document.decryptFailed",
|
||||
"share-link.document.notFound",
|
||||
|
||||
@@ -1708,7 +1708,7 @@ export const authPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Auth"],
|
||||
summary: "List recent account-security activity",
|
||||
description:
|
||||
"v1.23 — the SHARED security-activity feed: the caller's recent auth + export + deletion audit events with timestamp, resolved location, and a host-masked IP. `limit` query param caps at 100 (default 50). Reuses the AuditLog store; no event detail bodies are surfaced.",
|
||||
"v1.23 — the SHARED security-activity feed: the caller's recent auth + export + deletion audit events with timestamp, resolved location, and a host-masked IP. `limit` is 1-100 (default 50); a value outside that is a 422 naming it. Reuses the AuditLog store; no event detail bodies are surfaced.",
|
||||
requestParams: {
|
||||
query: z.object({
|
||||
limit: z.coerce
|
||||
@@ -1717,7 +1717,9 @@ export const authPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
.min(1)
|
||||
.max(100)
|
||||
.optional()
|
||||
.describe("Page size; defaults to 50, clamped to 100."),
|
||||
.describe(
|
||||
"Page size, 1-100; defaults to 50. Out of range is a 422.",
|
||||
),
|
||||
}),
|
||||
},
|
||||
responses: {
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
errorEnvelope,
|
||||
idempotencyKeyParameter,
|
||||
idempotentWrite,
|
||||
listEnvelope,
|
||||
recordRefusal,
|
||||
recordWriteRateLimitResponse,
|
||||
stdResponses,
|
||||
@@ -346,7 +347,7 @@ export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Records"],
|
||||
summary: "List visits",
|
||||
description:
|
||||
"Returns the caller's live visits, split into `upcoming` and `past`. Bounded and windowed; soft-deleted visits are excluded.",
|
||||
"Returns the caller's live visits, split into `upcoming` (soonest first) and `past` (newest first). `limit` and `offset` apply to each list; `meta.truncated` is true when either list has rows past this page, so a client reads the next `offset` until it is false. Soft-deleted visits are excluded.",
|
||||
requestParams: { query: listEncountersQuery },
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
@@ -354,7 +355,7 @@ export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
description: "The caller's visits.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(encounterList, "ListEncountersEnvelope"),
|
||||
schema: listEnvelope(encounterList, "ListEncountersEnvelope"),
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -612,7 +613,7 @@ export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Records"],
|
||||
summary: "List practitioners",
|
||||
description:
|
||||
"Returns the caller's address book, name-ordered, with an optional case-insensitive name search.",
|
||||
"Returns the caller's address book, name-ordered, with an optional case-insensitive search over name, practice and specialty. Paged with `limit` and `offset`; `meta.truncated` says whether another page exists.",
|
||||
requestParams: { query: listPractitionersQuery },
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
@@ -620,7 +621,7 @@ export const encounterPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
description: "The caller's address book.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
schema: listEnvelope(
|
||||
z.array(practitioner),
|
||||
"ListPractitionersEnvelope",
|
||||
),
|
||||
|
||||
@@ -32,45 +32,6 @@ import { isoDateTime } from "@/lib/validations/datetime";
|
||||
/** The retrospective periods the narrative route accepts, read off the engine. */
|
||||
const NARRATIVE_PERIOD_VALUES = Object.keys(PERIOD_DAYS);
|
||||
|
||||
export const insightsComprehensiveResponse = z
|
||||
.object({
|
||||
summary: z.string(),
|
||||
recommendations: z.array(z.record(z.string(), z.unknown())),
|
||||
citations: z.array(z.record(z.string(), z.unknown())),
|
||||
warnings: z.array(z.record(z.string(), z.unknown())),
|
||||
dailyBriefing: z.record(z.string(), z.unknown()).nullable().optional(),
|
||||
trendAnnotations: z.record(z.string(), z.unknown()).nullable().optional(),
|
||||
storyboardAnnotations: z
|
||||
.array(z.record(z.string(), z.unknown()))
|
||||
.optional(),
|
||||
metricSource: z.record(z.string(), z.unknown()).optional(),
|
||||
revalidating: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"True when the body is served from last-good cache (stale-while-revalidate) while a fresh aggregation runs in the background. The client keeps polling on `revalidating` (bounded) so the open page converges on the fresh body.",
|
||||
),
|
||||
hasProvider: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"Whether a configured AI provider exists for the record: provider presence and nothing else. False never means the operator switched AI off or consent is missing; `ai` says that.",
|
||||
),
|
||||
ai: z
|
||||
.object({
|
||||
briefing: aiCapabilityState,
|
||||
statusText: aiCapabilityState,
|
||||
})
|
||||
.describe(
|
||||
"Whether the AI parts that decorate the overview can be shown: the daily briefing and the per-metric status notes. Resolved per request, never cached with the body. The overview itself is computed data and loads whatever these say.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "InsightsComprehensiveResponse",
|
||||
description:
|
||||
"The Insights overview's computed read. No provider is called on this path; every figure is computed from the record.",
|
||||
});
|
||||
|
||||
// v1.8.7.1 — generic per-HealthKit-metric assessment. The query enum is
|
||||
// derived from the same registry the route validates against, so the
|
||||
// spec, the route, and the cache scope cannot drift. The seven
|
||||
@@ -1999,6 +1960,166 @@ export const dataSummary = z
|
||||
"Per-measurement-type summary. Every statistic is null on an empty series rather than 0, so a client never charts a zero it was never given. `anomalyCount` and `slope90` were computed here historically and left this wire in v1.37.19 — they are not fields of this shape.",
|
||||
});
|
||||
|
||||
/**
|
||||
* A summary the overview computes in-process. The same statistics as the
|
||||
* analytics summary, plus the count of readings the outlier rule flags, which
|
||||
* only the in-process path can produce. Declared here rather than derived from
|
||||
* either `DataSummary` copy so its trend component cannot collide with theirs.
|
||||
*/
|
||||
const comprehensiveTrend = z.object({
|
||||
slope: z.number().describe("Least-squares slope in units per day."),
|
||||
direction: z.enum(["up", "down", "stable"]),
|
||||
confidence: z.number().describe("R² of the fit, 0..1."),
|
||||
});
|
||||
|
||||
const comprehensiveSummary = z
|
||||
.object({
|
||||
count: z.number().int(),
|
||||
latest: z.number().nullable(),
|
||||
min: z.number().nullable(),
|
||||
max: z.number().nullable(),
|
||||
mean: z.number().nullable(),
|
||||
median: z.number().nullable(),
|
||||
avg7: z.number().nullable(),
|
||||
avg30: z.number().nullable(),
|
||||
slope7: comprehensiveTrend.nullable(),
|
||||
slope30: comprehensiveTrend.nullable(),
|
||||
anomalyCount: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.describe("Readings in the series the outlier rule flags."),
|
||||
avg30LastMonth: z.number().nullable().optional(),
|
||||
avg30LastYear: z.number().nullable().optional(),
|
||||
})
|
||||
.meta({ id: "ComprehensiveMetricSummary" });
|
||||
|
||||
const correlationStat = z
|
||||
.object({
|
||||
r: z.number(),
|
||||
strength: z
|
||||
.enum(["stark", "moderat", "schwach", "keine"])
|
||||
.describe(
|
||||
"Strength bucket. The tokens are GERMAN on the wire; treat them as opaque identifiers and localise client-side.",
|
||||
),
|
||||
n: z.number().int(),
|
||||
})
|
||||
.meta({
|
||||
id: "CorrelationStat",
|
||||
description:
|
||||
"A significant Pearson correlation (n >= 20, p < 0.05). The field holding it is null when the pairing is not significant.",
|
||||
});
|
||||
|
||||
const classification = z.object({
|
||||
category: z.string(),
|
||||
color: z.string().describe("A CSS colour token for the web client."),
|
||||
severity: z.enum(["normal", "elevated", "warning", "danger"]),
|
||||
});
|
||||
|
||||
export const insightsComprehensiveResponse = z
|
||||
.object({
|
||||
summaries: z
|
||||
.record(z.string(), comprehensiveSummary)
|
||||
.describe(
|
||||
"Keyed by `MeasurementType`. Only types with readings in the last 90 days are present.",
|
||||
),
|
||||
bmi: z.number().nullable(),
|
||||
bmiClassification: classification.nullable(),
|
||||
bpClassification: classification.nullable(),
|
||||
bpPctInTarget: z
|
||||
.number()
|
||||
.nullable()
|
||||
.describe(
|
||||
"Share of blood-pressure readings inside the target band, 0-100.",
|
||||
),
|
||||
bpTargets: z
|
||||
.object({
|
||||
sysLow: z.number(),
|
||||
sysHigh: z.number(),
|
||||
diaLow: z.number(),
|
||||
diaHigh: z.number(),
|
||||
})
|
||||
.nullable()
|
||||
.describe("Age-banded targets; null without a date of birth."),
|
||||
weightBpCorrelation: correlationStat.nullable(),
|
||||
scatterData: z
|
||||
.array(z.object({ weight: z.number(), sysBP: z.number() }))
|
||||
.describe("Weight against systolic pressure, paired by day."),
|
||||
bpMedicationCorrelation: correlationStat
|
||||
.extend({ medicationCount: z.number().int() })
|
||||
.nullable(),
|
||||
bpMedicationScatterData: z.array(
|
||||
z.object({ continuityPct: z.number(), sysBP: z.number() }),
|
||||
),
|
||||
moodSummary: comprehensiveSummary.nullable(),
|
||||
moodBpCorrelation: correlationStat.nullable(),
|
||||
moodBpScatterData: z.array(
|
||||
z.object({ mood: z.number(), sysBP: z.number() }),
|
||||
),
|
||||
moodWeightCorrelation: correlationStat.nullable(),
|
||||
moodWeightScatterData: z.array(
|
||||
z.object({ mood: z.number(), weight: z.number() }),
|
||||
),
|
||||
moodPulseCorrelation: correlationStat.nullable(),
|
||||
moodPulseScatterData: z.array(
|
||||
z.object({ mood: z.number(), pulse: z.number() }),
|
||||
),
|
||||
medications: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
dose: z.string(),
|
||||
category: z.string(),
|
||||
categoryLabel: z
|
||||
.string()
|
||||
.nullable()
|
||||
.describe(
|
||||
"The label of a custom category; null for a built-in one.",
|
||||
),
|
||||
compliance7: z.number().describe("Percent, 0-100."),
|
||||
compliance30: z.number().describe("Percent, 0-100."),
|
||||
streak: z.number().int(),
|
||||
taken7: z.number().int(),
|
||||
skipped7: z.number().int(),
|
||||
missed7: z.number().int(),
|
||||
}),
|
||||
)
|
||||
.describe("Cadence-aware compliance per active medication."),
|
||||
alerts: z.array(
|
||||
z.object({
|
||||
level: z.enum(["success", "info", "warning", "danger"]),
|
||||
title: z.string(),
|
||||
message: z.string(),
|
||||
}),
|
||||
),
|
||||
hasProvider: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"Whether a configured AI provider exists for the record: provider presence and nothing else. False never means the operator switched AI off or consent is missing; `ai` says that.",
|
||||
),
|
||||
dataSpanDays: z.number().int().nonnegative(),
|
||||
totalMeasurements: z.number().int().nonnegative(),
|
||||
revalidating: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"True when the body is served from last-good cache (stale-while-revalidate) while a fresh aggregation runs in the background. The client keeps polling on `revalidating` (bounded) so the open page converges on the fresh body.",
|
||||
),
|
||||
ai: z
|
||||
.object({
|
||||
briefing: aiCapabilityState,
|
||||
statusText: aiCapabilityState,
|
||||
})
|
||||
.describe(
|
||||
"Whether the AI parts that decorate the overview can be shown: the daily briefing and the per-metric status notes. Resolved per request, never cached with the body. The overview itself is computed data and loads whatever these say.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "InsightsComprehensiveResponse",
|
||||
description:
|
||||
"The Insights overview's computed read. No provider is called on this path; every figure is computed from the record. The model-written briefing is not part of it; it is read from `GET /api/insights/generate`.",
|
||||
});
|
||||
|
||||
const lastSeenSlot = z
|
||||
.object({
|
||||
lastSeenAt: isoDateTime(),
|
||||
|
||||
@@ -290,6 +290,13 @@ export const measurementResource = z
|
||||
.optional()
|
||||
.describe("External-system dedup key; null for manual entries."),
|
||||
externalSourceVersion: z.string().nullable().optional(),
|
||||
aggregationProvenance: z
|
||||
.string()
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"Authority of an aggregate stored under a `stats:` identity: `HEALTHKIT_STATISTICS`, `EXPORT_XML_SOURCE_MAX` or `LEGACY_UNKNOWN`. Null on an ordinary sample row. Decode unknown values leniently.",
|
||||
),
|
||||
glucoseContext: z
|
||||
.string()
|
||||
.nullable()
|
||||
@@ -450,7 +457,11 @@ const sleepSessionResource = z.object({
|
||||
.describe(
|
||||
"True when the source has no per-stage onset timestamps and the server synthesised a contiguous timeline in a fixed physiological order (WHOOP). The client renders the hypnogram but labels it an approximate layout and never recomputes. False for real-series sources (Apple Health / Withings / Fitbit).",
|
||||
),
|
||||
stages: z.record(sleepStageEnum, z.number().int().nonnegative()),
|
||||
stages: z
|
||||
.partialRecord(sleepStageEnum, z.number().int().nonnegative())
|
||||
.describe(
|
||||
"Minutes per stage. Only the stages the night recorded are present; an absent stage is not zero minutes, it was not measured.",
|
||||
),
|
||||
segments: z.array(sleepSegmentResource),
|
||||
sourceDiscrepancy: z
|
||||
.object({
|
||||
@@ -757,8 +768,10 @@ const seriesBatchRowSchema = z.object({
|
||||
const seriesBatchResponse = z
|
||||
.object({
|
||||
series: z
|
||||
.record(measurementTypeEnum, z.array(seriesBatchRowSchema))
|
||||
.describe("Per-type daily series, keyed by MeasurementType."),
|
||||
.partialRecord(measurementTypeEnum, z.array(seriesBatchRowSchema))
|
||||
.describe(
|
||||
"Per-type daily series, keyed by MeasurementType. Only the requested types are present.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "MeasurementsSeriesBatchResponse",
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
MEDICATION_CATEGORY_VALUES,
|
||||
MEDICATION_CONTAINER_TYPE_VALUES,
|
||||
MEDICATION_TREATMENT_CLASS_VALUES,
|
||||
doseWindowEntrySchema,
|
||||
injectionSiteEnum,
|
||||
} from "@/lib/validations/medication";
|
||||
import { medicationExtractionSchema } from "@/lib/ai/coach/medication-extract-prompt";
|
||||
import {
|
||||
@@ -223,6 +225,13 @@ export const medicationScheduleResource = z
|
||||
.describe(
|
||||
'v1.7.0 cyclic "off" weeks. Only meaningful when `scheduleType` is CYCLIC; null otherwise.',
|
||||
),
|
||||
doseWindows: z
|
||||
.array(doseWindowEntrySchema)
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"Per-dose on-time windows as stored. Null when every dose time keeps the default derivation.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "MedicationSchedule",
|
||||
@@ -233,9 +242,54 @@ export const medicationScheduleResource = z
|
||||
export const medicationResource = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
userId: z.string().optional().describe("The record the row belongs to."),
|
||||
name: z.string(),
|
||||
dose: z.string(),
|
||||
treatmentClass: medicationTreatmentClassEnum,
|
||||
deliveryForm: z
|
||||
.enum(["ORAL", "INJECTION", "OTHER"])
|
||||
.optional()
|
||||
.describe(
|
||||
"How the medication is taken. A one-time injection is `oneShot` with `INJECTION`.",
|
||||
),
|
||||
trackInjectionSites: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"Whether intakes record an injection site. Only offered for `INJECTION`.",
|
||||
),
|
||||
allowedInjectionSites: z
|
||||
.array(injectionSiteEnum)
|
||||
.optional()
|
||||
.describe("The sites the rotation offers; empty means every site."),
|
||||
externalSource: z
|
||||
.literal("APPLE_HEALTH")
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"v1.32.25 — provenance of the medication. `APPLE_HEALTH` marks the row a read-only mirror of the iOS 26+ HealthKit Medications sync; NULL is a native HealthLog medication.",
|
||||
),
|
||||
externalId: z
|
||||
.string()
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"The source's own identifier for a mirrored medication, paired with `externalSource`; null for a native one.",
|
||||
),
|
||||
lowStockNotifiedAt: isoDateTime()
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"When the low-stock alert last fired for this medication; null when it has not since the stock was last topped up. Server-written.",
|
||||
),
|
||||
lowStockNotifiedThresholdDays: z
|
||||
.number()
|
||||
.int()
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"The runway threshold, in days, that alert fired at. Server-written.",
|
||||
),
|
||||
dosesPerUnit: z
|
||||
.number()
|
||||
.int()
|
||||
@@ -371,6 +425,12 @@ export const medicationListEntry = medicationResource
|
||||
// even though the shared base leaves them optional for the write paths.
|
||||
nextDueAt: isoDateTime().nullable(),
|
||||
nextDueOverdue: z.boolean(),
|
||||
nextDueScheduleId: z
|
||||
.string()
|
||||
.nullable()
|
||||
.describe(
|
||||
"The schedule `nextDueAt` belongs to; null when nothing is due.",
|
||||
),
|
||||
remindersActive: z
|
||||
.boolean()
|
||||
.describe(
|
||||
|
||||
@@ -394,7 +394,7 @@ export const metaPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
summary: "The operator's assistant switches (deprecated)",
|
||||
deprecated: true,
|
||||
description:
|
||||
'Deprecated: read `ai` on GET /api/auth/me instead, which resolves each AI capability for the record from the switches, the record\'s modules, the provider, consent and who is asking. This route projects the operator switches alone and is removed in the first release after the native build that reads `ai` ships. Responses carry `Deprecation: true` and `Link: </api/auth/me>; rel="successor-version"`. The master is applied server-side, so every sub-switch is already false when it is off.\n\n' +
|
||||
'Deprecated: read `ai` on GET /api/auth/me instead, which resolves each AI capability for the record from the switches, the record\'s modules, the provider, consent and who is asking. This route projects the operator switches alone and is removed in the first release after the native build that reads `ai` ships. Responses carry `Deprecation` (the date it was deprecated, as `@<unix seconds>`), `Sunset` (the first day it may stop answering) and `Link: </api/auth/me>; rel="successor-version"`. The master is applied server-side, so every sub-switch is already false when it is off.\n\n' +
|
||||
"An ACTOR surface: it answers about the deployment, not about a record, so it keeps answering while the caller is acting on somebody else's — the Coach launcher and the assistant chrome are gated on it, and a refusal here would delete a piece of the shell rather than a piece of the data. A request that attaches the per-request account selector (the `AccountSelector` header parameter) is refused with 403 `sharing.not_permitted` rather than quietly answered.\n\n" +
|
||||
"Served with `Cache-Control: private, max-age=60`: an operator's toggle propagates within a minute, and the flag read stays off the hot mount path in the meantime.",
|
||||
responses: {
|
||||
@@ -408,6 +408,23 @@ export const metaPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
),
|
||||
},
|
||||
},
|
||||
headers: {
|
||||
Deprecation: {
|
||||
description:
|
||||
"When this route was deprecated, as an RFC 9745 date: `@` and Unix seconds.",
|
||||
schema: { type: "string" as const, pattern: "^@[0-9]+$" },
|
||||
},
|
||||
Sunset: {
|
||||
description:
|
||||
"The first day this route may stop answering (RFC 8594 HTTP-date).",
|
||||
schema: { type: "string" as const },
|
||||
},
|
||||
Link: {
|
||||
description:
|
||||
'The successor, as `</api/auth/me>; rel="successor-version"`.',
|
||||
schema: { type: "string" as const },
|
||||
},
|
||||
},
|
||||
},
|
||||
"403": {
|
||||
description:
|
||||
|
||||
@@ -1192,6 +1192,12 @@ const moodAggregatesResponse = z
|
||||
.array(z.object({ x: z.number(), y: z.number() }))
|
||||
.describe("Mood (x) versus metric (y), paired by day."),
|
||||
n: z.number().int().describe("Paired-day count."),
|
||||
suppressed: z
|
||||
.enum(["insufficientPairs", "notSignificant"])
|
||||
.optional()
|
||||
.describe(
|
||||
"Why `result` is null: too few paired days, or a pairing that did not reach significance. Absent when `result` is set.",
|
||||
),
|
||||
}),
|
||||
)
|
||||
.describe(
|
||||
|
||||
@@ -383,6 +383,18 @@ const notificationPrefsResolved = z
|
||||
nudgeFrequency: z
|
||||
.enum(["weekly", "biweekly"])
|
||||
.describe("Nudge frequency cap: one per 7 or per 14 days."),
|
||||
nudgeAiComposed: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"Opt-in for model-written nudge copy. Off by default; the deterministic template is always the fallback.",
|
||||
),
|
||||
}),
|
||||
measurementReminder: z.object({
|
||||
clientManaged: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"True when the iOS app owns local check-up reminders; the server-side measurement-reminder APNs send is then suppressed. Default false.",
|
||||
),
|
||||
}),
|
||||
content: z.object({
|
||||
detail: z
|
||||
|
||||
@@ -128,7 +128,10 @@ const profileSettings = z
|
||||
gender: z.enum(["MALE", "FEMALE", "OTHER"]).nullable(),
|
||||
locale: z.enum(["de", "en", "es", "fr", "it", "pl", "ko", "nl"]).nullable(),
|
||||
timezone: z.string(),
|
||||
unitPreference: z.enum(["metric", "imperial"]),
|
||||
unitPreference: z
|
||||
.enum(["metric", "imperial"])
|
||||
.nullable()
|
||||
.describe("Null when the record never chose one: metric applies."),
|
||||
timeFormat: z.enum(["AUTO", "H12", "H24"]),
|
||||
dateFormat: z.enum(["AUTO", "DMY", "MDY", "YMD"]),
|
||||
})
|
||||
|
||||
@@ -356,10 +356,12 @@ export const stdResponses = {
|
||||
*
|
||||
* The batch endpoints have been capped at 60 calls a minute since they were
|
||||
* written and the per-record siblings were not capped at all, which is exactly
|
||||
* backwards: the batch endpoint is the one a well-behaved client uses. The
|
||||
* eleven single-record creates now share one generous per-account bucket, and
|
||||
* this is the response that names it — a client that meets a ceiling should be
|
||||
* able to read which one it met without a bug report.
|
||||
* backwards: the batch endpoint is the one a well-behaved client uses. Every
|
||||
* authenticated write now shares one generous per-account bucket, charged where
|
||||
* the caller is resolved (`src/lib/auth/write-meter.ts`), and this is the
|
||||
* response that names it on the single-record creates that publish it — a
|
||||
* client that meets a ceiling should be able to read which one it met without
|
||||
* a bug report.
|
||||
*
|
||||
* Spread AFTER `...stdResponses` so it replaces the generic 429 on those
|
||||
* operations. The headers block is the one the standard 429 already declares.
|
||||
@@ -371,7 +373,7 @@ export const stdResponses = {
|
||||
export const recordWriteRateLimitResponse = {
|
||||
"429": {
|
||||
description:
|
||||
"Rate limit exceeded. This route shares one per-account bucket with the other single-record writes — `record-write:<accountId>`, 300 requests per 60 seconds — keyed on the ACTING account, so a delegate burns their own allowance rather than the record owner's. Nothing was written. `meta.errorCode` is `record_write.rate_limited`, which is what tells this refusal apart from a route's own narrower bucket when both can answer 429. The `Retry-After`, `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` headers describe that bucket; back off on `Retry-After` rather than guessing. Every request counts against the bucket, refused ones included: the check runs before the body is read, so a client looping on a 422 spends the same allowance as one that writes rows. A client with more than a handful of rows to send should use the batch endpoint for its domain instead of looping this one.",
|
||||
"Rate limit exceeded. This route shares one per-account bucket with every other authenticated write — `record-write:<accountId>`, 300 requests per 60 seconds — keyed on the ACTING account, so a delegate burns their own allowance rather than the record owner's. Only the bulk ingest endpoints, which meter themselves with a dedicated bucket, stay outside it. Nothing was written. `meta.errorCode` is `record_write.rate_limited`, which is what tells this refusal apart from a route's own narrower bucket when both can answer 429. The `Retry-After`, `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` headers describe that bucket; back off on `Retry-After` rather than guessing. Every request counts against the bucket, refused ones included: the check runs before the body is read, so a client looping on a 422 spends the same allowance as one that writes rows. A client with more than a handful of rows to send should use the batch endpoint for its domain instead of looping this one.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
headers: stdResponses["429"].headers,
|
||||
},
|
||||
|
||||
@@ -119,7 +119,7 @@ const symptomEventList = z
|
||||
.meta({
|
||||
id: "SymptomEventList",
|
||||
description:
|
||||
"A page of occurrences, newest first. `hasMore` is true when the page is full; page on with `to` set to the oldest `occurredAt` seen.",
|
||||
"A page of occurrences, newest first. `hasMore` is true exactly when an occurrence past this page exists; page on with `to` set to the oldest `occurredAt` seen.",
|
||||
});
|
||||
|
||||
const deletedResponse = z
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
recordRefusal,
|
||||
recordWriteRateLimitResponse,
|
||||
stdResponses,
|
||||
listEnvelope,
|
||||
} from "./shared";
|
||||
import { isoDateTime } from "@/lib/validations/datetime";
|
||||
|
||||
@@ -413,7 +414,7 @@ export const vaccinationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Records"],
|
||||
summary: "List vaccinations",
|
||||
description:
|
||||
"Returns the caller's live doses, newest first, each with its series resolved per component antigen. Soft-deleted doses are excluded.",
|
||||
"Returns the caller's live doses, newest first, each with its series resolved per component antigen over the whole record, never over the page. Paged with `limit` (default 300) and `offset`; `meta.truncated` says whether another page exists. Soft-deleted doses are excluded.",
|
||||
requestParams: { query: listVaccinationsQuery },
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
@@ -421,7 +422,7 @@ export const vaccinationPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
description: "The caller's immunization history.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(vaccinationList, "ListVaccinationsEnvelope"),
|
||||
schema: listEnvelope(vaccinationList, "ListVaccinationsEnvelope"),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
+9
-11
@@ -136,25 +136,23 @@ export async function checkEnvironmentBackfillRateLimit(
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared per-account ceiling for the single-record writes.
|
||||
* Shared per-account ceiling for every authenticated write.
|
||||
*
|
||||
* The batch endpoints have been capped at 60 calls a minute since they were
|
||||
* written; the per-record siblings a naive or older client loops over were not
|
||||
* capped at all, which is backwards — the batch endpoint is the one a
|
||||
* well-behaved client uses. This is the floor under the other direction:
|
||||
* `POST /api/measurements`, `/api/mood-entries`, both medication-intake writes,
|
||||
* `/api/labs`, a custom-metric entry, a cycle day-log, a vaccination, an
|
||||
* allergy, a biomarker and an encounter.
|
||||
* well-behaved client uses. This was first the floor under a dozen creates,
|
||||
* called by hand; it is now charged where the caller is resolved
|
||||
* (`meterAccountWrite`, `src/lib/auth/write-meter.ts`), so every POST, PUT,
|
||||
* PATCH and DELETE an authenticated caller sends counts against it, except on
|
||||
* the bulk ingest routes that meter themselves.
|
||||
*
|
||||
* One shared bucket, not one per route, for the reason
|
||||
* `checkAnalyticsReadRateLimit` gives: a loop that rotates across ten creates
|
||||
* `checkAnalyticsReadRateLimit` gives: a loop that rotates across ten routes
|
||||
* should still meet a cap. Three hundred a minute is five writes a second
|
||||
* sustained for a full minute — no hand-driven session and no sync burst
|
||||
* reaches it. Ten of the eleven are wrapped in `withIdempotency`, so an honest
|
||||
* retry storm is deduplicated before it is counted; `POST
|
||||
* /api/medications/intake` is not, because it updates a named `intakeId`
|
||||
* rather than creating a row, so a replay writes the status that is already
|
||||
* there. It exists to cut off the pathological loop, not to shape traffic.
|
||||
* reaches it. It exists to cut off the pathological loop, not to shape
|
||||
* traffic.
|
||||
*
|
||||
* A refused request is counted too: the check runs before the body is read,
|
||||
* so a client looping on a 422 spends its allowance without writing a row.
|
||||
|
||||
@@ -983,7 +983,20 @@ async function endGrant(
|
||||
(current.expiresAt === null || current.expiresAt > new Date());
|
||||
|
||||
if (!actorOwnsGrant || !isActiveManagedGuardian) return end();
|
||||
return reduceManagedProfileGuardian(db, current.grantorId, end);
|
||||
// `current` was read before the record lock. A concurrent change that holds
|
||||
// the lock first (the Guardian's account deletion ends this grant) commits
|
||||
// in between, and counting under the lock would then refuse with "add
|
||||
// another Guardian" for a grant that is no longer active, instead of saying
|
||||
// it has already ended. So the grant is re-read under the lock; only a grant
|
||||
// still live there is a Guardian whose removal the count has to allow.
|
||||
return withManagedProfileLock(db, current.grantorId, async () => {
|
||||
const live = await db.accountGrant.findFirst({
|
||||
where: { id: grantId, revokedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!live) return end();
|
||||
return reduceManagedProfileGuardian(db, current.grantorId, end);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { listOffsetField } from "@/lib/http/list-query-fields";
|
||||
|
||||
export const practitionerCreateSchema = z
|
||||
.object({
|
||||
name: z.string().min(1).max(160),
|
||||
@@ -50,6 +52,11 @@ export const practitionerListQuerySchema = z
|
||||
.object({
|
||||
q: z.string().min(1).max(160).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(200).optional(),
|
||||
offset: listOffsetField()
|
||||
.optional()
|
||||
.describe(
|
||||
"Rows to skip, for reading the address book page by page; `meta.truncated` says whether another page exists.",
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
* moment the catalogue is authoritative, because the picker produced it.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
import { listOffsetField } from "@/lib/http/list-query-fields";
|
||||
|
||||
import {
|
||||
ANTIGEN_SLUGS,
|
||||
@@ -195,6 +196,11 @@ export const vaccinationListQuerySchema = z
|
||||
from: isoDateTime().optional(),
|
||||
to: isoDateTime().optional(),
|
||||
limit: z.coerce.number().int().min(1).max(500).optional(),
|
||||
offset: listOffsetField()
|
||||
.optional()
|
||||
.describe(
|
||||
"Doses to skip, for reading the log page by page; `meta.truncated` says whether another page exists.",
|
||||
),
|
||||
})
|
||||
.strict()
|
||||
.refine((q) => !(q.from && q.to) || q.from <= q.to, {
|
||||
|
||||
Reference in new issue
Block a user