fix(release): harden v1.31 arrival contracts

This commit is contained in:
Marc-André Bombeck committed 2026-07-20 00:40:20 +02:00
1 parent 44add3bc1e
commit 4591899657
98 files changed
+5560 -1600

No files matched your search

@@ -27,6 +27,7 @@ vi.mock("@/lib/api-handler", () => ({
}));
vi.mock("@/lib/modules/gate", () => ({
requireModuleEnabled: vi.fn(async () => ({ enabled: true })),
isModuleEnabled: vi.fn(async () => true),
}));
vi.mock("@/lib/feature-flags", () => ({
requireAssistantSurface: vi.fn(async () => undefined),
@@ -41,6 +42,25 @@ vi.mock("@/lib/db", () => ({
prisma: {
user: { findUnique: vi.fn(async () => ({ coachPrefsJson: null })) },
coachConversation: { findFirst: vi.fn(async () => ({ id: "c1" })) },
workout: {
findFirst: vi.fn(async () => ({
sportType: "running",
source: "APPLE_HEALTH",
startedAt: new Date("2026-07-01T06:00:00Z"),
endedAt: new Date("2026-07-01T06:40:00Z"),
durationSec: 2400,
totalEnergyKcal: 410,
totalDistanceM: 7200,
avgHeartRate: 148,
maxHeartRate: 171,
minHeartRate: 96,
stepCount: 6800,
elevationM: 62,
pauseDurationSec: 0,
metadata: null,
samples: null,
})),
},
},
}));
@@ -136,6 +156,17 @@ vi.mock("@/lib/ai/coach/snapshot", () => ({
referenceGrounding: "REFERENCE RANGES",
})),
}));
vi.mock("@/lib/workouts/hr-series", () => ({
buildWorkoutHrSeries: vi.fn(async () => null),
}));
vi.mock("@/lib/workouts/zones", () => ({
computeZones: vi.fn(() => null),
hrMaxFromAge: vi.fn(() => 185),
parseWhoopZoneDurations: vi.fn(() => null),
}));
vi.mock("@/lib/workouts/sport-context", () => ({
buildSportContext: vi.fn(async () => null),
}));
// Tool-module surface — stub the inventory + loop so we assert routing only.
const {
@@ -258,6 +289,23 @@ describe("coach chat — tool-mode routing (F1)", () => {
expect(userContent).not.toContain(SNAPSHOT_JSON);
});
it("pins selected-workout evidence into the tool-mode prompt", async () => {
resolveProviderChain.mockResolvedValue([
{ providerType: "anthropic", instance: {} },
]);
await postAndDrain({
message: "Why was that hard?",
workoutId: "workout-1",
});
const args = (runCoachToolLoop.mock.calls[0] as unknown[])[0] as {
messages: Array<{ content: string }>;
};
expect(args.messages[0].content).toContain("SELECTED WORKOUT DATA");
expect(args.messages[0].content).toContain("thisWorkout");
expect(args.messages[0].content).toContain("2400");
});
it("reserves the multi-round budget in tool mode", async () => {
resolveProviderChain.mockResolvedValue([
{ providerType: "anthropic", instance: {} },
@@ -37,8 +37,12 @@ vi.mock("@/lib/api-handler", () => ({
},
}));
const { isModuleEnabled } = vi.hoisted(() => ({
isModuleEnabled: vi.fn(async () => true),
}));
vi.mock("@/lib/modules/gate", () => ({
requireModuleEnabled: vi.fn(async () => ({ enabled: true })),
isModuleEnabled,
}));
vi.mock("@/lib/feature-flags", () => ({
requireAssistantSurface: vi.fn(async () => undefined),
@@ -281,9 +285,19 @@ beforeEach(() => {
},
workingProvider: { providerType: "admin-openai" },
});
isModuleEnabled.mockResolvedValue(true);
});
describe("coach chat — workout scope, first turn", () => {
it("does not read workout evidence when the workouts module is disabled", async () => {
isModuleEnabled.mockResolvedValueOnce(false);
withPriorTurns(0);
await postAndDrain({ message: "Why was that hard?", workoutId: "w1" });
expect(workoutFindFirst).not.toHaveBeenCalled();
expect(lastUserPrompt()).not.toContain("thisWorkout");
});
it("pins the workout's own numbers as a snapshot section", async () => {
withPriorTurns(0);
await postAndDrain({ message: "Why was that hard?", workoutId: "w1" });
+31 -17
View File
@@ -37,7 +37,7 @@ import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { checkRateLimit } from "@/lib/rate-limit";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { isModuleEnabled, requireModuleEnabled } from "@/lib/modules/gate";
import { resolveServerLocale } from "@/lib/i18n/server-locale";
import { getServerTranslator } from "@/lib/i18n/server-translator";
@@ -547,18 +547,13 @@ async function handleChatRequest(request: NextRequest): Promise<Response> {
priorTurns.length >= TURN_CAP && priorTurns.length <= TURN_CAP + 1;
const includeFullSnapshot = isFirstTurn || historyElisionCrossing;
// v1.31.0 — a conversation launched from one workout pins ONE additional,
// bounded evidence section onto its snapshot.
//
// SNAPSHOT-ONCE. The read is gated on `isFirstTurn`, so it happens exactly
// once per conversation no matter how long the thread grows. The block then
// rides the same `includeFullSnapshot` prefix every other section does — the
// model composes its first reply against it, and that reply stays in the
// transcript on every later turn, so the figures remain in context without
// being re-paid for. Per-turn work is therefore CONSTANT in conversation
// length, which is the whole point of the ~99 % token cut.
// A workout launch is an optional narrowing of Coach, not permission to
// bypass the workouts module. Disabled modules contribute no read and no
// provider payload; the generic conversation still proceeds.
const workoutsEnabled =
!workoutId || (await isModuleEnabled(userId, "workouts"));
const workoutEvidence =
isFirstTurn && workoutId
isFirstTurn && workoutId && workoutsEnabled
? await buildWorkoutEvidenceSection(userId, workoutId)
: null;
if (workoutId) {
@@ -769,15 +764,22 @@ Reply now as the assistant, in ${LANGUAGE_NAMES[locale]}.`;
// equivalent of that narrowing). Empty string on a generic open.
const focusHint = renderFocusHint(effectiveScope?.sources);
const focusBlock = focusHint ? `${focusHint}\n\n` : "";
const workoutDataBlock =
workoutEvidence === null
? ""
: `SELECTED WORKOUT DATA
${fenceHealthData(JSON.stringify({ thisWorkout: workoutEvidence }))}
`;
const messages: AiMessage[] = [
{
role: "user",
content: `${focusBlock}${renderDataInventory(inventory)}${guidedBlock}
content: `${focusBlock}${workoutDataBlock}${renderDataInventory(inventory)}${guidedBlock}
CONVERSATION
${transcript}
Reply now as the assistant, in ${LANGUAGE_NAMES[locale]}. Fetch any figures you cite with the tools first.`,
Reply now as the assistant, in ${LANGUAGE_NAMES[locale]}. The selected-workout block is already authoritative; fetch any other figures you cite with the tools first.`,
},
];
const loop = await runCoachToolLoop({
@@ -803,7 +805,10 @@ Reply now as the assistant, in ${LANGUAGE_NAMES[locale]}. Fetch any figures you
result = loop.result;
workingProviderType = loop.workingProviderType;
toolTrace = loop.toolTrace;
toolResultPayloads = (loop.toolResults ?? []).map((r) => r.data);
toolResultPayloads = [
...(workoutEvidence === null ? [] : [workoutEvidence]),
...(loop.toolResults ?? []).map((r) => r.data),
];
totalTokensSpent = loop.totalTokens;
cachedTokensSpent = loop.cachedTokens;
} else {
@@ -852,7 +857,10 @@ Reply now as the assistant, in ${LANGUAGE_NAMES[locale]}. Fetch any figures you
// grade. When figures WERE delivered, the authoritative set is the
// structured snapshot record (incl. the correlations block).
if (includeFullSnapshot) {
noToolsSnapshotPayloads = [snapshot.sections];
noToolsSnapshotPayloads = [
snapshot.sections,
...(workoutEvidence === null ? [] : [workoutEvidence]),
];
}
}
} catch (err) {
@@ -1656,7 +1664,11 @@ async function buildWorkoutEvidenceSection(
const profile = await prisma.user.findUnique({
where: { id: userId },
select: { sourcePriorityJson: true, dateOfBirth: true },
select: {
sourcePriorityJson: true,
dateOfBirth: true,
timezone: true,
},
});
// The SAME series the detail route serves as `hrSeries` — one builder,
@@ -1680,12 +1692,14 @@ async function buildWorkoutEvidenceSection(
userId,
row.sportType,
profile?.sourcePriorityJson ?? null,
workoutId,
);
return buildWorkoutEvidence({
sportType: row.sportType,
source: row.source,
startedAt: row.startedAt,
timezone: profile?.timezone ?? "Europe/Berlin",
durationSec: row.durationSec,
totalEnergyKcal: row.totalEnergyKcal,
totalDistanceM: row.totalDistanceM,