Merge remote-tracking branch 'origin/release/v1.46.0' into fix/v146-security

# Conflicts:
#	src/lib/ai/coach/labs-snapshot.ts
#	src/lib/ai/coach/snapshot.ts
This commit is contained in:
Marc-André Bombeck committed 2026-10-25 14:05:23 +01:00
commit 21aa791c3a
54 files changed
+544 -338

No files matched your search

+42 -1
View File
@@ -27,7 +27,8 @@ import {
summariseTitle,
} from "../persistence";
import { encryptToBytes } from "../bytes-codec";
import type { CoachProvenance } from "../types";
import { MAX_TURN_STEPS } from "../activity/contract";
import type { CoachProvenance, CoachStep } from "../types";
describe("summariseTitle", () => {
it("returns the input unchanged when below 80 chars", () => {
@@ -212,6 +213,46 @@ describe("appendMessage — provenance round-trip", () => {
expect(out.metricSource).toEqual(envelope);
});
it("restores every step the turn may record, and none past the cap", async () => {
const step = (n: number): CoachStep => ({
id: `s${n}`,
tool: "get_metric_series",
labelKey: "coach.step.readWindow",
label: "Read the series",
domain: "bp",
window: "last30days",
status: "done",
count: n,
});
const recorded = Array.from({ length: MAX_TURN_STEPS }, (_, i) =>
step(i + 1),
);
stubEchoCreate();
const full = await appendMessage({
conversationId: "conv_1",
role: "assistant",
content: "A long answer.",
metricSource: { windows: [], metrics: [], steps: recorded },
});
expect(full.metricSource?.steps).toEqual(recorded);
// A stored blob longer than the cap is cut at the cap, not before it.
stubEchoCreate(
JSON.stringify({
windows: [],
metrics: [],
steps: [...recorded, step(MAX_TURN_STEPS + 1)],
}),
);
const over = await appendMessage({
conversationId: "conv_1",
role: "assistant",
content: "An over-long blob.",
metricSource: { windows: [], metrics: [] },
});
expect(over.metricSource?.steps).toEqual(recorded);
});
it("tolerates a legacy blob without the new fields (no throw, fields absent)", async () => {
// A pre-feature row: only the original windows/metrics envelope on disk.
stubEchoCreate(
+7
View File
@@ -41,6 +41,13 @@ export const ACTIVITY_TEXT_MAX_CHARS = 400;
/** `a1`..`a99`: the 100th entry of a turn is not recorded. */
export const ACTIVITY_MAX_ENTRIES = 99;
/**
* `s1`..`s64`: the live steps of one turn (four per round of the longest
* turn). Later tool calls still run but show no step. The turn records up to
* this many and a reload restores up to this many, from this one constant.
*/
export const MAX_TURN_STEPS = 64;
export interface ActivityStart {
phase: CoachActivityPhase;
round: number;
+4 -1
View File
@@ -51,7 +51,10 @@
* and no lab row is read, so neither the Coach prompt nor its `get_labs` tool
* sees a value. It used to ride regardless, a decision from before Labs could
* be switched off; the data routes (`/api/labs`) stay ungated, because a
* module decides what a model is given, not what the owner can read.
* module decides what a model is given, not what the owner can read. With the
* module on, the block is `null` only when no reading falls inside the
* lookback limit (the whole record when there is none), or, for a named read,
* when no marker matches the analyte.
*/
import { sameLabUnit } from "@/lib/labs/unit-normalise";
import {
+7 -8
View File
@@ -28,7 +28,11 @@ import {
coachStopSchema,
coachTrailSchema,
} from "./stream-events";
import { ACTIVITY_MAX_ENTRIES, TRAIL_MAX_BYTES } from "./activity/contract";
import {
ACTIVITY_MAX_ENTRIES,
MAX_TURN_STEPS,
TRAIL_MAX_BYTES,
} from "./activity/contract";
import { commitTurnWrites } from "./memory/turn-writes";
import { COACH_CONVERSATION_TITLE_MAX } from "./types";
import { isRedundantViewChip } from "./follow-ups/view-chip";
@@ -56,7 +60,6 @@ import type {
CoachResultEntry,
CoachResultMeta,
CoachResultTable,
CoachStep,
CoachStepDomain,
CoachSuggestion,
CoachTrail,
@@ -225,11 +228,6 @@ function restoreOne<T>(raw: unknown, schema: z.ZodType<T>): T | undefined {
return parsed.success ? parsed.data : undefined;
}
/** The live steps a turn persisted (at most 48 per turn since v1.41). */
function restoreSteps(raw: unknown): CoachStep[] | undefined {
return restoreEach(raw, coachStepSchema, 48);
}
/** The method line; dropped whole when it does not parse. */
function restoreMethod(raw: unknown): CoachMethod | undefined {
const parsed = coachMethodSchema.safeParse(raw);
@@ -341,7 +339,8 @@ function provenanceFromJson(raw: string | null): CoachProvenance | null {
const toolCalls = restoreToolCalls(parsed.toolCalls);
// v1.39.4 — the dialog fields: steps, method, table metadata, chips, the
// clarification choices, and the forced-answer marker.
const steps = restoreSteps(parsed.steps);
// Up to the same cap the turn records steps under.
const steps = restoreEach(parsed.steps, coachStepSchema, MAX_TURN_STEPS);
const method = restoreMethod(parsed.method);
const results = restoreResultMetas(parsed.results);
// A reply stored before view chips were withheld for a table the answer
+3 -2
View File
@@ -667,8 +667,9 @@ async function buildCoachSnapshotImpl(
// v1.18.11 (#65) — lab-result context. Like illness it is CONTEXT, not a
// scope-gated metric: attached without a `registerBlock` so the budget
// degrader never sheds it. The helper is module-gated internally: with the
// labs module off it reads nothing and answers null. The block carries the most-recent resolved reading per biomarker (last 12 months,
// capped) so the Coach can answer "what was my LDL" without re-deriving.
// labs module off it reads nothing and answers null. The block carries the
// latest resolved reading per biomarker (whole record or the lookback limit,
// capped) so the Coach can answer "what was my LDL".
const labsBlockPromise = buildLabsSnapshotBlock(userId, now, reach);
// v1.38 — doctor-visit context. Like illness/labs it is attempted always (a
@@ -34,7 +34,8 @@ import {
} from "@/lib/ai/coach/tools/definitions";
import type { CoachToolResult } from "@/lib/ai/coach/tools/run/types";
import { MAX_TURN_STEPS, snapshotStep, toStep } from "../steps";
import { MAX_TURN_STEPS } from "@/lib/ai/coach/activity/contract";
import { snapshotStep, toStep } from "../steps";
const SOURCES = coachScopeSourceSchema.options;
const WINDOWS = coachScopeWindowSchema.options;
+1 -7
View File
@@ -38,13 +38,7 @@ import {
} from "@/lib/ai/coach/tools/definitions";
import { isTurnResultRef } from "@/lib/ai/coach/results/refs";
import { COMPARE_SERIES_TOOL_NAME } from "@/lib/ai/coach/tools/compare-series";
/**
* At most this many steps per turn; later calls run but show no step.
* v1.41 — four per round of the longest turn: 48 for twelve rounds, 64 since
* v1.41.2 raised the cap to sixteen.
*/
export const MAX_TURN_STEPS = 64;
import { MAX_TURN_STEPS } from "@/lib/ai/coach/activity/contract";
const SCOPE_SOURCES: ReadonlySet<string> = new Set(
coachScopeSourceSchema.options,
@@ -2,8 +2,8 @@
* Doc ↔ code parity guard for the Google Health operator runbook.
*
* The setup-guide link on the Settings card sends a mid-setup user to
* `docs.healthlog.dev/integrations/google-health`, rendered from
* `docs/integrations/google-health.md`. If the client ever requests a scope the
* `docs.healthlog.dev/guides/connect-google-health/`; the operator runbook in
* this repository is `docs/integrations/google-health.md`. If the client ever requests a scope the
* runbook doesn't list, or the walkthrough regresses back to a wrong provider
* (the file was once a Fitbit-Web-API walkthrough), a self-hoster follows a
* broken recipe and the OAuth consent screen rejects the connection.
@@ -20,7 +20,7 @@ import { describe, expect, it } from "vitest";
import { GOOGLE_HEALTH_CORE_SCOPES } from "@/lib/google-health/oauth";
import {
INTEGRATION_DOCS_BASE,
DOCS_GUIDES_BASE,
integrationDocsHref,
} from "@/components/settings/integrations/setup-guide-link";
@@ -70,7 +70,7 @@ describe("google-health setup runbook parity", () => {
// The literal argument also compile-checks that "google-health" is a member
// of the IntegrationDocsProvider union.
expect(integrationDocsHref("google-health")).toBe(
`${INTEGRATION_DOCS_BASE}/google-health`,
`${DOCS_GUIDES_BASE}/connect-google-health/`,
);
});
});
@@ -411,6 +411,74 @@
"grounding": {
"type": "string"
},
"searchedWindow": {
"type": "string"
},
"available": {
"type": "object",
"properties": {
"count": {
"type": "number"
},
"firstDate": {
"type": "string"
},
"lastDate": {
"type": "string"
},
"series": {
"type": "array",
"items": {
"type": "object",
"properties": {
"series": {
"type": "string"
},
"unit": {
"type": [
"string",
"null"
]
},
"count": {
"type": "number"
},
"mean": {
"type": "number"
},
"min": {
"type": "number"
},
"max": {
"type": "number"
}
},
"required": [
"series",
"unit",
"count",
"mean",
"min",
"max"
],
"additionalProperties": false
}
},
"reachableWithWindow": {
"type": [
"string",
"null"
]
}
},
"required": [
"count",
"firstDate",
"lastDate",
"reachableWithWindow"
],
"additionalProperties": false
},
"analyte": {
"type": "string"
},
+46
View File
@@ -540,6 +540,52 @@ describe("get_illness_recovery — condition body site", () => {
});
describe("get_labs", () => {
it.each([{}, { analyte: "LDL" }])(
"declares empty-read availability for ordinary and filtered reads: %j",
async (args) => {
const { z } = await import("zod/v4");
const empty = {
present: false,
reason: "out_of_window",
searchedWindow: "lastYear",
available: {
count: 2,
firstDate: "2020-01-01",
lastDate: "2020-01-02",
reachableWithWindow: null,
},
};
vi.mocked(executeCoachTool).mockResolvedValue(empty);
const def = tool("get_labs");
const result = await def.run(CTX, args);
expect(executeCoachTool).toHaveBeenCalledWith({
userId: CTX.userId,
name: "get_labs",
rawArguments: JSON.stringify(args),
});
expect(z.object(def.outputShape!).strict().parse(result)).toEqual(empty);
},
);
it("keeps output validation closed and availability typed", async () => {
const { z } = await import("zod/v4");
const schema = z.object(tool("get_labs").outputShape!).strict();
expect(z.toJSONSchema(schema).additionalProperties).toBe(false);
expect(schema.safeParse({ present: false, unexpected: true }).success).toBe(
false,
);
expect(
schema.safeParse({ present: false, searchedWindow: 7 }).success,
).toBe(false);
expect(
schema.safeParse({ present: false, available: { count: "2" } }).success,
).toBe(false);
expect(schema.parse({ present: false, reason: "no_data" })).toEqual({
present: false,
reason: "no_data",
});
});
it("forwards the optional analyte filter and returns readings with units + bands", async () => {
vi.mocked(executeCoachTool).mockResolvedValue({
present: true,
+3 -5
View File
@@ -5,16 +5,14 @@ import { resolveMarkerForRead } from "@/lib/labs/biomarker-resolve";
import { getLabHistory, LAB_HISTORY_MAX_LIMIT } from "@/lib/mcp/rich-reads";
import { decodeOffsetCursor } from "@/lib/mcp/pagination";
import type { McpAuthContext } from "../auth";
import { coachReadOutput } from "./output-shapes";
import { runCoachTool, whenModuleOn } from "./shared";
import { READ_ONLY_ANNOTATIONS, type McpToolDefinition } from "./types";
/** Output schema for `get_labs` — latest-per-biomarker OR a paginated history. */
const getLabsOutput: z.ZodRawShape = {
present: z.boolean(),
reason: z.string().optional(),
// Latest-mode payload (the Coach labs section, carried opaque).
data: z.unknown().optional(),
grounding: z.string().optional(),
// Latest-mode payload, including typed empty-read availability metadata.
...coachReadOutput,
// History-mode payload (per-analyte trajectory + pagination).
analyte: z.string().optional(),
readings: z
+7 -5
View File
@@ -75,10 +75,12 @@ const healthKitEntry = z
"One resolved HealthKit metric mapping (defaults merged with the user's stored overrides).",
});
// The health-shaped fields that predate `health` (v1.42.4). They stay on the
// wire through v1.43 so App 1.2.0 keeps decoding, are marked deprecated in the
// document, and go in v1.44.
const LEGACY_HEALTH_FIELD = "Deprecated: removed in v1.44, read `health`.";
// The health-shaped fields that predate `health`. They are marked deprecated
// in the document and stay on the wire: native builds from before `health`
// still decode them, the current one falls back to them only against a server
// that sends no `health`, and the web card's copied diagnostics read the
// failure streak. No removal release is set.
const LEGACY_HEALTH_FIELD = "Deprecated, still served: read `health`.";
function legacy(text?: string): { deprecated: true; description: string } {
return {
@@ -1184,7 +1186,7 @@ const integrationEnvelopeEntry = z
health: connectionHealth
.nullable()
.describe(
"The unified connection state, null when the provider is not connected (and for Fitbit once `retirement.ended`). It supersedes `state`, `lastError`, `consecutiveFailuresByKind`, `syncHealth`, `tokenExpired`, `needsReauth`, `hasActivityScope`, `planUnavailable` and `scopeReconnect` on this entry; those nine are deprecated and removed in v1.44.",
"The unified connection state, null when the provider is not connected (and for Fitbit once `retirement.ended`). It supersedes `state`, `lastError`, `consecutiveFailuresByKind`, `syncHealth`, `tokenExpired`, `needsReauth`, `hasActivityScope`, `planUnavailable` and `scopeReconnect` on this entry; those nine are deprecated and still served for clients that predate `health`.",
),
})
.meta({