mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 15:42:24 +00:00
Declare every MCP output field and read live rows in discovery
list_metrics declares availability, the Coach-backed reads declare searchedWindow and available, and get_intraday_pulse declares min and max per bucket. An integration test validates every tool's real output against its advertised schema under a strict 2020-12 validator. The metric-status discovery rows and the search clinical-signal probe filter deletedAt, guarded for every measurement read in the MCP and Coach tool trees.
This commit is contained in:
1 parent
316e52dee3
commit
15b2f6f4de
4 files changed
+668
No files matched your search
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Guard: every measurement read on the MCP surface and in the Coach tools
|
||||
* reads live rows only.
|
||||
*
|
||||
* A deleted measurement is a tombstone (`deletedAt` set), not a missing row.
|
||||
* Two presence probes on the MCP side (`metricStatusDiscoveryRows` and the
|
||||
* `search` clinical-signal probe) grouped by type without `deletedAt: null`:
|
||||
* a type whose readings had all been deleted still counted as present, and
|
||||
* because the live-rows partial index (`measurements_live_covering_idx`,
|
||||
* `WHERE deleted_at IS NULL`) only serves a query that carries the same
|
||||
* predicate, the probe walked every tombstone of the account (about a second
|
||||
* against 23 ms on a large production record).
|
||||
*
|
||||
* The guard reads the source of both trees, finds every
|
||||
* `prisma.measurement.<read>(` call, takes its argument up to the matching
|
||||
* parenthesis, and asserts the argument names `deletedAt`. Unique-key
|
||||
* lookups (`findUnique`) are idempotency checks on a key a tombstone still
|
||||
* holds, and are left out on purpose. Raw SQL against `measurements` must
|
||||
* carry `deleted_at` the same way.
|
||||
*/
|
||||
import { readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { join, relative } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const ROOTS = ["src/lib/mcp", "src/lib/ai/coach/tools"];
|
||||
const READS =
|
||||
/\bprisma\.measurement\.(findMany|findFirst|count|groupBy|aggregate)\s*\(/g;
|
||||
const RAW = /\b(?:FROM|JOIN)\s+"?measurements"?\b/gi;
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
return readdirSync(dir).flatMap((name) => {
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) {
|
||||
return name === "__tests__" ? [] : sourceFiles(path);
|
||||
}
|
||||
return /\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name) ? [path] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** The text from `open` (an opening parenthesis) to its matching close. */
|
||||
function balanced(text: string, open: number): string {
|
||||
let depth = 0;
|
||||
for (let i = open; i < text.length; i += 1) {
|
||||
if (text[i] === "(") depth += 1;
|
||||
else if (text[i] === ")") {
|
||||
depth -= 1;
|
||||
if (depth === 0) return text.slice(open, i + 1);
|
||||
}
|
||||
}
|
||||
return text.slice(open);
|
||||
}
|
||||
|
||||
interface Site {
|
||||
at: string;
|
||||
argument: string;
|
||||
}
|
||||
|
||||
function readSites(): { calls: Site[]; raw: Site[] } {
|
||||
const calls: Site[] = [];
|
||||
const raw: Site[] = [];
|
||||
for (const root of ROOTS) {
|
||||
for (const file of sourceFiles(join(process.cwd(), root))) {
|
||||
const text = readFileSync(file, "utf8");
|
||||
const name = relative(process.cwd(), file);
|
||||
const lineOf = (index: number) => text.slice(0, index).split("\n").length;
|
||||
for (const match of text.matchAll(READS)) {
|
||||
const open = (match.index ?? 0) + match[0].length - 1;
|
||||
calls.push({
|
||||
at: `${name}:${lineOf(match.index ?? 0)}`,
|
||||
argument: balanced(text, open),
|
||||
});
|
||||
}
|
||||
for (const match of text.matchAll(RAW)) {
|
||||
// The statement around it: up to the closing backtick of the
|
||||
// tagged template the query lives in.
|
||||
const start = match.index ?? 0;
|
||||
const end = text.indexOf("`", start);
|
||||
raw.push({
|
||||
at: `${name}:${lineOf(start)}`,
|
||||
argument: text.slice(start, end === -1 ? undefined : end),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return { calls, raw };
|
||||
}
|
||||
|
||||
describe("measurement reads on the MCP surface and in the Coach tools", () => {
|
||||
const { calls, raw } = readSites();
|
||||
|
||||
it("finds the reads it is meant to check", () => {
|
||||
// A matcher that matches nothing proves nothing: the two probes this
|
||||
// guard was written for, the rich-read counts and the availability
|
||||
// probe are all in these trees.
|
||||
expect(calls.length).toBeGreaterThanOrEqual(5);
|
||||
expect(raw.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("filters every Prisma read to live rows", () => {
|
||||
const missing = calls
|
||||
.filter((site) => !/\bdeletedAt\b/.test(site.argument))
|
||||
.map((site) => site.at);
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
|
||||
it("filters every raw read to live rows", () => {
|
||||
const missing = raw
|
||||
.filter((site) => !/\bdeleted_at\b/.test(site.argument))
|
||||
.map((site) => site.at);
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -481,11 +481,16 @@ export async function metricStatusDiscoveryRows(userId: string): Promise<
|
||||
metric: string;
|
||||
}>
|
||||
> {
|
||||
// v1.41.2 — live rows only. Without `deletedAt: null` a type whose rows
|
||||
// were all deleted still counted as present, and the grouped count could
|
||||
// not use the live-rows partial index (`measurements_live_covering_idx`),
|
||||
// so it walked every tombstone on the way.
|
||||
const rows = await prisma.measurement.groupBy({
|
||||
by: ["type"],
|
||||
where: {
|
||||
userId,
|
||||
type: { in: MCP_METRIC_STATUS_DISCOVERY.map((s) => s.measurementType) },
|
||||
deletedAt: null,
|
||||
},
|
||||
_count: { _all: true },
|
||||
});
|
||||
|
||||
@@ -537,11 +537,15 @@ function searchAndFetchTools(): McpToolDefinition[] {
|
||||
...MCP_CLINICAL_SIGNALS,
|
||||
...MCP_METRIC_STATUS_DISCOVERY,
|
||||
];
|
||||
// v1.41.2 — live rows only: a deleted reading is not a signal the
|
||||
// record holds, and the filter lets the probe use the live-rows
|
||||
// partial index instead of walking the tombstones.
|
||||
const discoverablePresent = await prisma.measurement.groupBy({
|
||||
by: ["type"],
|
||||
where: {
|
||||
userId: ctx.userId,
|
||||
type: { in: discoverableSignals.map((s) => s.measurementType) },
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
const presentTypes = new Set(discoverablePresent.map((r) => r.type));
|
||||
@@ -815,6 +819,31 @@ const coachReadOutput: z.ZodRawShape = {
|
||||
reason: z.string().optional(),
|
||||
data: z.unknown().optional(),
|
||||
grounding: z.string().optional(),
|
||||
// v1.41.2 — a miss describes its own scope and, when the record holds rows
|
||||
// the window could not reach, what it holds (`CoachToolResult`). The
|
||||
// executor has returned both since v1.37; undeclared, they made a strict
|
||||
// client refuse every out-of-window read (the #1170 class).
|
||||
searchedWindow: z.string().optional(),
|
||||
available: z
|
||||
.object({
|
||||
count: z.number(),
|
||||
firstDate: z.string(),
|
||||
lastDate: z.string(),
|
||||
series: z
|
||||
.array(
|
||||
z.object({
|
||||
series: z.string(),
|
||||
unit: z.string().nullable(),
|
||||
count: z.number(),
|
||||
mean: z.number(),
|
||||
min: z.number(),
|
||||
max: z.number(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
reachableWithWindow: z.string().nullable(),
|
||||
})
|
||||
.optional(),
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -895,6 +924,20 @@ const listMetricsOutput: z.ZodRawShape = {
|
||||
present: z.boolean(),
|
||||
count: z.number().optional(),
|
||||
metric: z.string().optional(),
|
||||
// #1170 — what the record holds for a domain the window found
|
||||
// nothing in (`InventoryEntry.availability`). The handler always
|
||||
// returned it; the advertised schema did not declare it, and the
|
||||
// output schema closes every object, so a strict client refused the
|
||||
// whole result.
|
||||
availability: z
|
||||
.object({
|
||||
state: z.string(),
|
||||
count: z.number().optional(),
|
||||
firstDate: z.string().optional(),
|
||||
lastDate: z.string().optional(),
|
||||
reachableWithWindow: z.string().nullable(),
|
||||
})
|
||||
.optional(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
@@ -1211,6 +1254,10 @@ const getIntradayPulseOutput: z.ZodRawShape = {
|
||||
startMinute: z.number(),
|
||||
mean: z.number(),
|
||||
count: z.number(),
|
||||
// v1.41.2 — the bucket's low / high where the source carries a
|
||||
// spread (`IntradayHrBucket`); returned since v1.30.7, never declared.
|
||||
min: z.number().optional(),
|
||||
max: z.number().optional(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
|
||||
Reference in new issue
Block a user