feat(ai): serve Insights and Coach data whatever AI says

Data never depends on AI. The Insights data reads no longer ask an AI
switch or the `insights` module (now only the AI analysis opt-out): ECG
list, detail and upload, rhythm events, derived scores, rule cards,
correlations and patterns, the baseline strip, health status, intraday
pulse, and the Today digest with its dismiss. Breathing screening moves
to the sleep module and lab changes to the labs module. Stored Coach
facts, conversations, message ratings and the seen stamp stay readable
and erasable while the Coach is unavailable. Cards now say
`provider: "rules"`.

Reads that mix data with model text answer 200, null the model text
and publish an `ai` state from the capability resolver, without warming
anything: comprehensive (`ai.briefing`, `ai.statusText`, `hasProvider`
from the presence probe), the derived assessment override, the period
narrative, nudge status, the seeded opener, about-me questions, the
workout paragraph, the pregenerate warm (`queued: false`), the Today
digest (lead, reaction line, check-in) and the dashboard briefing,
which is now applied per read after the snapshot cache. Hiding the
Coach no longer hides the briefing.

`insights/generate` GET and POST ask the `briefing` capability and
`insights/chat` POST the `coach` capability, with the typed refusal
envelope; a missing provider keeps the chat's `coach.provider.none`
frame and adds `reason`. The /coach page, the MCP ECG and intraday
tools and `aiAvailable` on the provider route follow the same answer.

An inventory of AI and data routes replaces the Coach gate inventory:
every route that asks a capability names it, and no data route asks.

Refs #975
This commit is contained in:
Marc-André Bombeck committed 2026-09-24 09:19:36 +02:00
1 parent f434ba7d29
commit 3309ac177c
104 files changed
+3299 -1636

No files matched your search

@@ -0,0 +1,149 @@
/**
* AI capability route inventory, across the whole API tree.
*
* Proves, from source text, the route half of "data never depends on AI":
*
* 1. Every `route.ts` under `src/app/api` that asks an AI capability
* (`requireAiCapability` / `getAiCapability`) is on `AI_ROUTES`, which
* names the capability and whether it refuses (`action`) or answers 200
* with the model text nulled (`mixed`).
* 2. Each `AI_ROUTES` entry asks exactly the capabilities it declares, by
* literal key; an `action` route calls `requireAiCapability`, a `mixed`
* read never does (a mixed read never refuses for an AI reason).
* 3. Every `DATA_ROUTES` entry asks neither gate, nor the retired
* `requireAssistantSurface`.
* 4. The matchers find what they judge: non-zero counts, and a call split
* across lines still matches.
*
* What it does NOT prove: that a gate sits before the work it guards, or that
* a mixed read really nulls the text. The route tests and the integration
* files (`tests/integration/ai-optional-*.test.ts`) prove behaviour; this
* proves no route escapes classification and no data route grows a gate.
*
* Mutation checks (each turned this file red by name): adding
* `await requireAiCapability("statusText")` to `insights/ecg/route.ts`;
* removing the capability call from `insights/chat/route.ts`; swapping
* `getAiCapability` for `requireAiCapability` in `insights/narrative`;
* breaking the call matcher.
*/
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative, resolve } from "node:path";
import { describe, expect, it } from "vitest";
import { AI_CAPABILITY_KEYS } from "@/lib/ai/capabilities/types";
import { AI_ROUTES, DATA_ROUTES } from "./ai-route-inventory";
const repoRoot = resolve(__dirname, "..", "..", "..", "..");
/** Comment lines out, so prose naming a gate is not read as a call. */
function code(path: string): string {
return readFileSync(resolve(repoRoot, path), "utf8")
.split("\n")
.filter((line) => !/^\s*(\*|\/\/|\/\*)/.test(line))
.join("\n");
}
/** Whitespace-tolerant: a call split across lines still matches. */
const GATE_CALL = /\b(requireAiCapability|getAiCapability)\s*\(\s*"(\w+)"/g;
const ANY_GATE = /\b(?:requireAiCapability|getAiCapability)\s*\(/;
const REQUIRE_GATE = /\brequireAiCapability\s*\(/;
const RETIRED_GATE = /\brequireAssistantSurface\s*\(/;
function gateCalls(text: string): Array<{ fn: string; key: string }> {
return [...text.matchAll(GATE_CALL)].map((m) => ({ fn: m[1], key: m[2] }));
}
function routeFiles(): string[] {
const root = resolve(repoRoot, "src/app/api");
const hits: string[] = [];
function walk(dir: string): void {
for (const entry of readdirSync(dir)) {
const full = join(dir, entry);
if (statSync(full).isDirectory()) {
if (entry === "__tests__" || entry === "node_modules") continue;
walk(full);
} else if (entry === "route.ts") {
hits.push(relative(repoRoot, full).split(/[\\/]/).join("/"));
}
}
}
walk(root);
return hits.sort();
}
const ROUTES = routeFiles();
describe("AI capability route inventory", () => {
it("the matcher reads a call split across lines", () => {
const split = 'await requireAiCapability(\n "coach",\n );';
expect(gateCalls(split)).toEqual([
{ fn: "requireAiCapability", key: "coach" },
]);
expect(ANY_GATE.test("getAiCapability (\n")).toBe(true);
});
it("finds the routes it is meant to judge", () => {
expect(ROUTES.length).toBeGreaterThan(100);
const asking = ROUTES.filter((path) => ANY_GATE.test(code(path)));
// A matcher that stopped matching would agree with an empty world.
expect(asking.length).toBeGreaterThan(0);
expect(asking.length).toBe(Object.keys(AI_ROUTES).length);
expect(Object.keys(DATA_ROUTES).length).toBeGreaterThan(0);
});
it("every route that asks an AI capability is on AI_ROUTES", () => {
const unlisted = ROUTES.filter(
(path) => ANY_GATE.test(code(path)) && !(path in AI_ROUTES),
);
expect(
unlisted,
"these routes ask an AI capability but are not on AI_ROUTES — add them with their capability, or remove the gate from a data route",
).toEqual([]);
});
describe.each(Object.entries(AI_ROUTES))("%s", (path, entry) => {
it("exists and asks exactly the capabilities it declares", () => {
expect(ROUTES, `${path} no longer exists`).toContain(path);
const calls = gateCalls(code(path));
expect(calls.length, `${path} asks no capability`).toBeGreaterThan(0);
for (const { key } of calls) {
expect(AI_CAPABILITY_KEYS as readonly string[]).toContain(key);
}
expect([...new Set(calls.map((c) => c.key))].sort()).toEqual(
[...entry.capabilities].sort(),
);
});
it(`is ${entry.kind === "action" ? "an action that refuses" : "a mixed read that never refuses"}`, () => {
const refuses = REQUIRE_GATE.test(code(path));
expect(
refuses,
entry.kind === "action"
? `${path} is an action but never calls requireAiCapability`
: `${path} is a mixed read but calls requireAiCapability — a mixed read answers 200 and nulls the model text`,
).toBe(entry.kind === "action");
});
});
it("no data route asks an AI capability or the retired gate", () => {
const offenders = Object.keys(DATA_ROUTES).filter((path) => {
const text = code(path);
return ANY_GATE.test(text) || RETIRED_GATE.test(text);
});
expect(
offenders,
"data routes never depend on AI: remove the gate, or move the route to AI_ROUTES if it now serves model text",
).toEqual([]);
});
it("no data route is stale or listed twice", () => {
const missing = Object.keys(DATA_ROUTES).filter(
(path) => !ROUTES.includes(path),
);
expect(missing, "DATA_ROUTES names files that do not exist").toEqual([]);
const both = Object.keys(DATA_ROUTES).filter((path) => path in AI_ROUTES);
expect(both).toEqual([]);
});
});
+191
View File
@@ -0,0 +1,191 @@
/**
* The AI route inventory: which API routes ask an AI capability, and which
* are data and must never ask.
*
* The rule it pins (the AI-optional design): data never depends on AI. A
* route that serves measurements, device records, computed scores,
* statistics or template sentences imports no AI gate and is never refused
* because a switch is off, a provider is missing, consent is absent or the
* person opted out of AI analysis. A route that calls a model, or serves text
* a model wrote, names its capability:
*
* - `action` routes call `requireAiCapability(key)` and refuse with the
* capability envelope;
* - `mixed` reads call `getAiCapability(key)`, answer 200, null the model
* text and say why in `ai`. They never refuse for an AI reason, so they
* never call `requireAiCapability`.
*
* Read by two guards: `ai-capability-route-inventory.test.ts` (the whole API
* tree) and `insights/__tests__/coach-route-gate-inventory.test.ts` (every
* route in the trees where AI routes live is classified). Not a test file, so
* importing it registers nothing.
*/
import type { AiCapabilityKey } from "@/lib/ai/capabilities/types";
export interface AiRouteEntry {
kind: "action" | "mixed";
capabilities: readonly AiCapabilityKey[];
why: string;
}
export const AI_ROUTES: Readonly<Record<string, AiRouteEntry>> = {
"src/app/api/insights/chat/route.ts": {
kind: "action",
capabilities: ["coach"],
why: "POST streams a Coach reply from a model. The history GET in the same file asks nothing.",
},
"src/app/api/insights/generate/route.ts": {
kind: "action",
capabilities: ["briefing"],
why: "POST generates the briefing; GET is a pure AI read (the payload is the model text and nothing else), so both refuse.",
},
"src/app/api/insights/comprehensive/route.ts": {
kind: "mixed",
capabilities: ["briefing", "statusText"],
why: "Computed overview data; the `ai` block says whether the briefing and status notes around it can be shown.",
},
"src/app/api/insights/derived/route.ts": {
kind: "mixed",
capabilities: ["statusText"],
why: "Computed score; only the model-written assessment override follows the capability.",
},
"src/app/api/insights/narrative/route.ts": {
kind: "mixed",
capabilities: ["periodNarrative"],
why: "A deterministic narrative is data; a model-written one is served only while the capability is available.",
},
"src/app/api/insights/pregenerate/route.ts": {
kind: "mixed",
capabilities: ["briefing", "statusText"],
why: "Enqueue-only warm that returns no model text: `queued: false` when neither half can run.",
},
"src/app/api/insights/coach/nudge-status/route.ts": {
kind: "mixed",
capabilities: ["coach"],
why: "The unread signal of a Coach that is unavailable is the quiet empty shape, never a refusal.",
},
"src/app/api/insights/coach/seeded-question/route.ts": {
kind: "mixed",
capabilities: ["coach"],
why: "The opener exists only to open the Coach: `signal: null` while it is unavailable.",
},
"src/app/api/coach/about-me/route.ts": {
kind: "mixed",
capabilities: ["aboutMeQuestions"],
why: "The profile is data; only model-written follow-up questions follow the capability.",
},
"src/app/api/workouts/[id]/route.ts": {
kind: "mixed",
capabilities: ["workoutInsights"],
why: "The workout is data; only the stored Activity Insight paragraph follows the capability.",
},
};
/**
* Routes that are data and must never import an AI gate. Every entry is a
* claim the guard checks against the file.
*/
export const DATA_ROUTES: Readonly<Record<string, string>> = {
// The design's list of formerly AI-gated data reads and writes.
"src/app/api/insights/derived/batch/route.ts":
"Deterministic scores and assessments for the whole grid.",
"src/app/api/insights/ecg/route.ts":
"Device recordings, list and live ingest: an upload is never refused because AI is off.",
"src/app/api/insights/ecg/[id]/route.ts": "One device recording's waveform.",
"src/app/api/insights/rhythm-events/route.ts":
"The device's own flagged events, verbatim.",
"src/app/api/insights/cards/route.ts":
"Rule alerts from the threshold engine; `provider` is `rules`.",
"src/app/api/insights/correlations/route.ts":
"Statistics; the retired Correlations switch gated no model output.",
"src/app/api/insights/coach-read/route.ts":
"Baseline placement and the strongest association, both computed.",
"src/app/api/insights/coach/seen/route.ts":
"A timestamp on the caller's own row.",
"src/app/api/insights/coach/facts/route.ts":
"Stored Coach facts: readable and erasable while the Coach is unavailable.",
"src/app/api/insights/coach/facts/[id]/route.ts": "Erasing one stored fact.",
"src/app/api/insights/chat/[id]/route.ts":
"One stored conversation: read, rename, delete.",
"src/app/api/insights/chat/messages/[id]/feedback/route.ts":
"A rating on a message that already exists.",
"src/app/api/insights/breathing-screening/route.ts":
"Device breathing data, owned by the sleep module.",
"src/app/api/insights/labs-changes/route.ts":
"Lab deltas, owned by the labs module.",
"src/app/api/insights/health-status/route.ts":
"Baseline drift, computed over core vitals.",
"src/app/api/insights/pulse/intraday/route.ts":
"The day's pulse shape, a core vital.",
"src/app/api/insights/patterns/route.ts": "Stored correlation statistics.",
"src/app/api/insights/patterns/[id]/route.ts":
"Dismissing a stored correlation.",
"src/app/api/daily/digest/route.ts":
"The Today digest is data; its AI parts are masked by the loader through the capability resolver, never refused.",
"src/app/api/daily/digest/dismiss/route.ts": "Dismissing a Today rail item.",
"src/app/api/dashboard/snapshot/route.ts":
"The dashboard is data; the briefing inside it is masked per read by the snapshot loader, never refused.",
// Configuration and other non-AI routes in the insights tree.
"src/app/api/insights/feedback/route.ts":
"Feedback on a recommendation that already exists.",
"src/app/api/insights/glp1-plateau/route.ts":
"A deterministic plateau detector over weight and dose history.",
"src/app/api/insights/glp1-timeline/route.ts":
"A merge of medication events.",
"src/app/api/insights/layout/route.ts": "The person's tile layout.",
"src/app/api/insights/provider-chain/route.ts":
"AI configuration: editable while AI is unavailable, so it can be set up.",
"src/app/api/insights/settings/route.ts":
"AI configuration: editable while AI is unavailable, so it can be set up.",
"src/app/api/insights/targets/route.ts": "Threshold reference values.",
// The Coach tree's own data: gated on the `coach` module, never on AI.
"src/app/api/coach/about-me/adopt/route.ts":
"Folds a typed answer into the stored profile; no model call.",
"src/app/api/coach/about-me/questions/route.ts":
"Reads or dismisses stored questions; no model call.",
"src/app/api/coach/plans/route.ts": "Stored Coach plans.",
"src/app/api/coach/plans/[id]/route.ts": "One stored Coach plan.",
"src/app/api/coach/reminders/route.ts": "Stored Coach reminders.",
"src/app/api/coach/reminders/[id]/route.ts": "One stored Coach reminder.",
"src/app/api/coach/reminder-suggestions/route.ts":
"Deterministic reminder suggestions.",
"src/app/api/coach/suggested-actions/route.ts":
"Confirms a proposed action from a closed allowlist; no model call.",
};
/**
* Routes in the AI trees whose AI gating another change owns. Each still has
* to be classified; the entry names who moves it. An entry that starts
* calling a capability gate fails the guard until it moves to `AI_ROUTES`.
*/
export const PENDING_ROUTES: Readonly<Record<string, string>> = {
"src/app/api/insights/chat/fenced/route.ts":
"Document chat inside a conversation: moves to `coach` and `documentAi` with the document-extraction routes.",
"src/app/api/insights/chat/[id]/attachments/route.ts":
"Attaching a document to a conversation: moves to `coach` and `documentAi` with the document-extraction routes.",
"src/app/api/insights/chat/[id]/attachments/[documentId]/route.ts":
"Detaching a document: removal of one's own data, stays ungated once the document routes move.",
"src/app/api/insights/biomarker-assessment/route.ts":
"Status family: moves to `statusText` (200 with null text) in its own change.",
"src/app/api/insights/blood-pressure-status/route.ts":
"Status family: moves to `statusText` in its own change.",
"src/app/api/insights/bmi-status/route.ts":
"Status family: moves to `statusText` in its own change.",
"src/app/api/insights/medication-compliance-status/route.ts":
"Status family: moves to `statusText` in its own change.",
"src/app/api/insights/metric-status/route.ts":
"Status family: moves to `statusText` in its own change.",
"src/app/api/insights/mood-status/route.ts":
"Status family: moves to `statusText` in its own change.",
"src/app/api/insights/pulse-status/route.ts":
"Status family: moves to `statusText` in its own change.",
"src/app/api/insights/weight-status/route.ts":
"Status family: moves to `statusText` in its own change.",
};
/** The trees in which every route has to be classified above. */
export const AI_ROUTE_TREES = [
"src/app/api/insights",
"src/app/api/coach",
"src/app/api/daily",
] as const;
@@ -32,11 +32,19 @@ import { MODULE_KEYS, type ModuleKey } from "@/lib/modules/registry";
* `delegatesTo`):
* - cycle → `requireCycleEnabled(...)` (the cycle gate the
* `cycle` ModuleKey delegates to).
* - coach → `requireAssistantSurface("coach")` (the assistant
* master flag + per-user opt-out the `coach` ModuleKey
* delegates to). Covered in depth by the sibling
* `coach-route-gate-inventory.test.ts`; listed here so
* coach-bearing routes are not flagged as ungated.
* - an AI capability → `requireAiCapability(key)` /
* `getAiCapability(key)`. A capability resolves its owning
* modules and the AI opt-out (the `coach` module and
* `disableCoach` for the Coach, the `insights` module for
* every other capability), so an AI route that names one is
* gated on those modules. Covered in depth by
* `ai-capability-route-inventory.test.ts`. The `insights`
* module is the AI analysis opt-out and gates only AI parts;
* the data routes that happen to live under
* `/api/insights` are EXEMPT below.
* - coach → `requireAssistantSurface("coach")`, the retired gate,
* still recognised for the one route outside these trees
* that has not moved to its capability yet.
*
* 3. EXEMPT — an explicit, COMMENTED allowlist of routes that serve a
* toggleable domain but are deliberately NOT gated, each with the
@@ -147,9 +155,10 @@ const MODULE_ROUTE_TREES_BY_KEY: Readonly<
// counted as directly gated here, and the sibling
// `coach-route-gate-inventory.test.ts` covers the surface in depth.
coach: ["src/app/api/coach"],
// v1.18.0 (B2) — the AI-narrative insights tree, plus v1.28's unified
// daily-digest read (`GET /api/daily/digest`), which is the AI-narrative
// daily layer and gates on `insights` directly.
// The `insights` module is the AI analysis opt-out. It owns no data route:
// the AI routes under these trees name a capability that folds it in, and
// the data routes that live here (ECG, scores, statistics, the Today
// digest) are EXEMPT below because a computation never depends on AI.
insights: ["src/app/api/insights", "src/app/api/daily"],
// v1.18.1 (D3) — medications graduated from CORE to a toggleable module.
// SURFACE-gated (nav entry, dashboard widget, the dedicated Medikamente
@@ -299,12 +308,39 @@ const EXEMPT_ROUTES: ReadonlyArray<string> = [
// ── INFRA / UI-ONLY ───────────────────────────────────────────────
// Static FHIR CapabilityStatement — server metadata, no user data.
"src/app/api/fhir/metadata/route.ts",
// ── DATA (insights tree) ──────────────────────────────────────────
// The `insights` module is the AI analysis opt-out, so it gates AI parts
// only, through the capability. These routes serve or accept data that no
// model wrote: device recordings and events, computed scores, statistics,
// rule alerts, the person's stored Coach data and the Today digest. Turning
// AI analysis off must leave every one of them working.
"src/app/api/insights/ecg/route.ts",
"src/app/api/insights/ecg/[id]/route.ts",
"src/app/api/insights/rhythm-events/route.ts",
"src/app/api/insights/derived/batch/route.ts",
"src/app/api/insights/cards/route.ts",
"src/app/api/insights/correlations/route.ts",
"src/app/api/insights/coach-read/route.ts",
"src/app/api/insights/health-status/route.ts",
"src/app/api/insights/pulse/intraday/route.ts",
"src/app/api/insights/patterns/route.ts",
"src/app/api/insights/patterns/[id]/route.ts",
// Stored Coach data: viewing and erasing it never depends on the Coach
// being available (the GDPR reason), and a timestamp on one's own row is
// data too.
"src/app/api/insights/coach/seen/route.ts",
"src/app/api/insights/coach/facts/route.ts",
"src/app/api/insights/coach/facts/[id]/route.ts",
"src/app/api/insights/chat/[id]/route.ts",
"src/app/api/insights/chat/messages/[id]/feedback/route.ts",
// The Today digest and its dismiss: data, with the AI parts masked by the
// loader through the capability resolver.
"src/app/api/daily/digest/route.ts",
"src/app/api/daily/digest/dismiss/route.ts",
// ── INFRA / CONFIG (insights) ─────────────────────────────────────
// v1.18.0 (B2) — the insights tree's non-narrative routes. The
// `insights` module gates the AI-narrative SURFACES (status cards,
// correlations, derived scores, period narrative, the rhythm-event
// timeline); these six carry no narrative payload, so gating them would
// only break configuration / settings reads while the module is off.
// The insights tree's configuration routes carry no narrative payload,
// so gating them would only break configuration / settings reads while
// the module is off.
//
// AI provider + privacy settings and the read-only chain summary — pure
// configuration of the assistant, surfaced under Settings → AI, not an
@@ -386,6 +422,9 @@ const EXEMPT_ROUTES: ReadonlyArray<string> = [
const MODULE_GATE_NEEDLE = "requireModuleEnabled(";
const CYCLE_GATE_NEEDLE = "requireCycleEnabled(";
const COACH_GATE_NEEDLE = 'requireAssistantSurface("coach")';
// An AI capability resolves its owning modules and the AI opt-out, so a route
// that names one is gated on them.
const AI_CAPABILITY_GATE = /\b(?:requireAiCapability|getAiCapability)\s*\(/;
// v1.18.1 — the illness journal's thin gate wrapper. `requireIllnessEnabled`
// delegates to `requireModuleEnabled(userId, "illness")` and re-stamps the
// illness-specific errorCode, exactly mirroring how `cycle` delegates to
@@ -467,6 +506,15 @@ function fileHasCall(text: string, needle: string): boolean {
});
}
/** True when a non-comment line calls an AI capability gate. */
function fileHasCapabilityGate(text: string): boolean {
return text.split("\n").some((line) => {
const trimmed = line.trim();
if (trimmed.startsWith("//") || trimmed.startsWith("*")) return false;
return AI_CAPABILITY_GATE.test(line);
});
}
/**
* Extract the module key from a `requireModuleEnabled(user.id, "<key>")`
* call. Returns the literal key, or null when the key is computed (the
@@ -633,6 +681,7 @@ describe("module API route gate inventory", () => {
if (fileHasCall(text, CYCLE_GATE_NEEDLE)) continue;
if (fileHasCall(text, COACH_GATE_NEEDLE)) continue;
if (fileHasCall(text, ILLNESS_GATE_NEEDLE)) continue;
if (fileHasCapabilityGate(text)) continue;
if (exempt.has(path)) continue;
@@ -753,7 +802,8 @@ describe("module API route gate inventory", () => {
fileHasCall(text, MODULE_GATE_NEEDLE) ||
fileHasCall(text, CYCLE_GATE_NEEDLE) ||
fileHasCall(text, COACH_GATE_NEEDLE) ||
fileHasCall(text, ILLNESS_GATE_NEEDLE)
fileHasCall(text, ILLNESS_GATE_NEEDLE) ||
fileHasCapabilityGate(text)
) {
stillGated.push(path);
}
@@ -108,7 +108,10 @@ vi.mock("@/lib/ai/coach/self-context-questions", () => ({
questions: [],
source: "none",
})),
buildFallbackQuestions: vi.fn(() => ["deterministic hint"]),
}));
// The follow-up questions are the route's one AI part: `aboutMeQuestions`.
vi.mock("@/lib/ai/capabilities/gate", () => ({ getAiCapability: vi.fn() }));
import { GET, PUT } from "../route";
import {
@@ -118,6 +121,12 @@ import {
} from "@/lib/ai/coach/about-me";
import { deriveClarifyingQuestions } from "@/lib/ai/coach/self-context-questions";
import { auditLog } from "@/lib/auth/audit";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import { buildFallbackQuestions } from "@/lib/ai/coach/self-context-questions";
import {
AI_AVAILABLE,
aiUnavailable,
} from "@/__tests__/helpers/ai-capability-fixtures";
type Envelope = {
data: unknown;
@@ -151,6 +160,7 @@ function putReq(
describe("about-me module gate", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getAiCapability).mockResolvedValue(AI_AVAILABLE);
profileFindUnique.mockResolvedValue({
updatedAt: new Date(0),
aiIncludedSections: ["ABOUT_ME"],
@@ -284,6 +294,7 @@ describe("about-me module gate", () => {
},
"en",
["ABOUT_ME"],
{ aiAvailable: true },
);
expect(setPendingQuestionsForUser).toHaveBeenCalledWith(
"u1",
@@ -292,6 +303,71 @@ describe("about-me module gate", () => {
);
});
it("derives without the model while aboutMeQuestions is unavailable", async () => {
setGates(true, false);
vi.mocked(getAiCapability).mockResolvedValue(
aiUnavailable("operator_disabled"),
);
vi.mocked(getSelfContextForUser).mockResolvedValueOnce({
aboutMe: "I run daily",
conditions: null,
allergies: null,
coachFocus: null,
});
const res = await put(putReq({ aiIncludedSections: ["ABOUT_ME"] }));
expect(res.status).toBe(200);
expect(getAiCapability).toHaveBeenCalledWith("aboutMeQuestions");
expect(vi.mocked(deriveClarifyingQuestions).mock.calls[0]?.[4]).toEqual({
aiAvailable: false,
});
expect((res.data as { ai: unknown }).ai).toEqual(
aiUnavailable("operator_disabled"),
);
});
it("GET swaps an outstanding (possibly model-written) set for the deterministic hints while unavailable", async () => {
setGates(true, false);
vi.mocked(getAiCapability).mockResolvedValue(aiUnavailable("no_provider"));
vi.mocked(getPendingQuestionsForUser).mockResolvedValueOnce([
"a question a model may have written",
]);
const res = await get();
expect(res.status).toBe(200);
const data = res.data as { pendingQuestions: string[]; ai: unknown };
expect(data.pendingQuestions).toEqual(["deterministic hint"]);
expect(data.ai).toEqual(aiUnavailable("no_provider"));
});
it("GET keeps an answered (empty) set empty while unavailable", async () => {
setGates(true, false);
vi.mocked(getAiCapability).mockResolvedValue(aiUnavailable("no_provider"));
vi.mocked(getPendingQuestionsForUser).mockResolvedValueOnce([]);
const res = await get();
expect(
(res.data as { pendingQuestions: string[] }).pendingQuestions,
).toEqual([]);
expect(buildFallbackQuestions).not.toHaveBeenCalled();
});
it("GET serves the stored set while available", async () => {
setGates(true, false);
vi.mocked(getPendingQuestionsForUser).mockResolvedValueOnce([
"stored question",
]);
const res = await get();
expect(
(res.data as { pendingQuestions: string[] }).pendingQuestions,
).toEqual(["stored question"]);
});
it("clears pending questions when inclusion removes every text field", async () => {
setGates(true, false);
profileFindUnique.mockResolvedValue({
+33 -5
View File
@@ -19,6 +19,13 @@
* text child only — no markdown library exists in the tree and none
* may be added (XSS posture, see the contributor notes).
*
* The follow-up questions are the one AI part. Model-written questions are
* derived and served only while the `aboutMeQuestions` capability is
* available; otherwise the deterministic completion hints stand in, no
* provider is called, and the `ai` field says why. Stored questions cannot be
* told apart by origin, so while the capability is unavailable an outstanding
* set is replaced on read by the deterministic hints for the same profile.
*
* Ownership: the user id always comes from `requireAuth()`; the body
* carries only the text. Audit rows never contain the text itself —
* only per-field lengths — because it is free-form health prose.
@@ -44,7 +51,11 @@ import {
filterSelfContextForAi,
setPendingQuestionsForUser,
} from "@/lib/ai/coach/about-me";
import { deriveClarifyingQuestions } from "@/lib/ai/coach/self-context-questions";
import {
buildFallbackQuestions,
deriveClarifyingQuestions,
} from "@/lib/ai/coach/self-context-questions";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import { requireModuleEnabled } from "@/lib/modules/gate";
import {
ABOUT_ME_FIELD_MAX_CHARS,
@@ -79,7 +90,7 @@ export const GET = apiHandler(async () => {
const gate = await requireSelfContextConsumer(user.id);
if (!gate.enabled) return gate.response;
const [ctx, pendingQuestions, row] = await Promise.all([
const [ctx, storedQuestions, row, ai] = await Promise.all([
getSelfContextForUser(user.id),
gate.coachEnabled
? getPendingQuestionsForUser(user.id)
@@ -88,7 +99,22 @@ export const GET = apiHandler(async () => {
where: { userId: user.id },
select: { updatedAt: true, aiIncludedSections: true },
}),
getAiCapability("aboutMeQuestions"),
]);
const aiIncludedSections =
(row?.aiIncludedSections as HealthProfileAiSection[] | undefined) ??
DEFAULT_HEALTH_PROFILE_AI_SECTIONS;
// A stored set may be model-written. While the capability is unavailable
// an outstanding set is swapped for the deterministic hints; an answered
// (empty) set stays empty.
const pendingQuestions =
ai.available || storedQuestions.length === 0
? storedQuestions
: buildFallbackQuestions(
filterSelfContextForAi(ctx, aiIncludedSections),
user.locale,
aiIncludedSections,
);
annotate({
action: { name: "coach.about_me.get" },
@@ -107,12 +133,11 @@ export const GET = apiHandler(async () => {
allergies: ctx.allergies,
coachFocus: ctx.coachFocus,
pendingQuestions,
aiIncludedSections:
(row?.aiIncludedSections as HealthProfileAiSection[] | undefined) ??
DEFAULT_HEALTH_PROFILE_AI_SECTIONS,
aiIncludedSections,
updatedAt: row?.updatedAt?.toISOString() ?? null,
maxChars: ABOUT_ME_MAX_CHARS,
fieldMaxChars: ABOUT_ME_FIELD_MAX_CHARS,
ai,
});
});
@@ -325,6 +350,7 @@ export const PUT = apiHandler(async (req: Request) => {
ctx.allergies === null &&
ctx.coachFocus === null;
const ai = await getAiCapability("aboutMeQuestions");
let pendingQuestions: string[] = [];
let questionsToPersist: string[] | null | undefined;
let questionsSource: "ai" | "fallback" | "none" = "none";
@@ -342,6 +368,7 @@ export const PUT = apiHandler(async (req: Request) => {
aiContext,
user.locale,
aiIncludedSections,
{ aiAvailable: ai.available },
);
pendingQuestions = derived.questions;
questionsSource = derived.source;
@@ -404,6 +431,7 @@ export const PUT = apiHandler(async (req: Request) => {
updatedAt: updatedAtIso,
maxChars: ABOUT_ME_MAX_CHARS,
fieldMaxChars: ABOUT_ME_FIELD_MAX_CHARS,
ai,
});
});
@@ -8,9 +8,9 @@ import { SCORE_VERSION } from "@/lib/analytics/score/types";
/**
* `GET /api/daily/digest` — the P3 read seam.
*
* Under test: cookie/Bearer auth narrows the user, the `insights` module gate
* returns a 403 `module.disabled` envelope when off (even for a valid
* session), and the happy path returns the `DailyDigest` DTO shape. The digest
* Under test: cookie/Bearer auth narrows the user, the `insights` module (the
* AI analysis opt-out) no longer refuses the digest, and the happy path
* returns the `DailyDigest` DTO shape. The digest
* itself is composed by `loadDailyDigest`, mocked here — the route must reach
* no provider (there is nothing AI-shaped in this module graph).
*/
@@ -44,6 +44,7 @@ import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { loadDailyDigest } from "@/lib/daily/load-digest";
import { DIGEST_AI_AVAILABLE } from "@/__tests__/helpers/ai-capability-fixtures";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
@@ -57,6 +58,7 @@ const SESSION_OK = {
const DIGEST: DailyDigest = {
generatedAt: "2026-07-16T09:00:00.000Z",
ai: DIGEST_AI_AVAILABLE,
phase: "final",
sleepPending: false,
score: {
@@ -95,7 +97,7 @@ describe("GET /api/daily/digest", () => {
expect(vi.mocked(loadDailyDigest)).not.toHaveBeenCalled();
});
it("returns the 403 module.disabled envelope when insights is off", async () => {
it("serves the digest with the insights module (the AI analysis opt-out) off", async () => {
vi.mocked(requireModuleEnabled).mockResolvedValue({
enabled: false,
response: apiError('Module "insights" is not enabled', 403, {
@@ -104,18 +106,9 @@ describe("GET /api/daily/digest", () => {
}),
});
const res = await callGet(makeReq());
expect(res.status).toBe(403);
const body = await res.json();
expect(body.meta?.errorCode).toBe("module.disabled");
expect(vi.mocked(loadDailyDigest)).not.toHaveBeenCalled();
});
it("gates on the insights module key", async () => {
await callGet(makeReq());
expect(vi.mocked(requireModuleEnabled)).toHaveBeenCalledWith(
"user-1",
"insights",
);
expect(res.status).toBe(200);
expect(vi.mocked(requireModuleEnabled)).not.toHaveBeenCalled();
expect(vi.mocked(loadDailyDigest)).toHaveBeenCalled();
});
it("returns 200 with the DailyDigest DTO on the happy path", async () => {
@@ -1,8 +1,8 @@
/**
* `POST /api/daily/digest/dismiss` — the Today rail dismiss surface.
*
* Under test: cookie/Bearer auth narrows the user, the `insights` module gate
* returns a 403 `module.disabled` envelope when off, an `itemKey` that isn't
* Under test: cookie/Bearer auth narrows the user, the `insights` module (the
* AI analysis opt-out) no longer refuses a dismissal, an `itemKey` that isn't
* namespaced under a dismissible kind 422s BEFORE any DB write, and the happy
* path upserts the `DismissedPriorityItem` row scoped to the caller.
*/
@@ -98,7 +98,7 @@ describe("POST /api/daily/digest/dismiss", () => {
expect(prisma.dismissedPriorityItem.upsert).not.toHaveBeenCalled();
});
it("returns the 403 module.disabled envelope when insights is off", async () => {
it("accepts a dismissal with the insights module (the AI analysis opt-out) off", async () => {
vi.mocked(requireModuleEnabled).mockResolvedValue({
enabled: false,
response: apiError('Module "insights" is not enabled', 403, {
@@ -109,8 +109,9 @@ describe("POST /api/daily/digest/dismiss", () => {
const res = await callPost(
makeReq({ itemKey: "milestone:record_first:WEIGHT:2026-07-16" }),
);
expect(res.status).toBe(403);
expect(prisma.dismissedPriorityItem.upsert).not.toHaveBeenCalled();
expect(res.status).toBe(200);
expect(requireModuleEnabled).not.toHaveBeenCalled();
expect(prisma.dismissedPriorityItem.upsert).toHaveBeenCalled();
});
it("422s an itemKey that isn't namespaced under a dismissible kind — an actionable item can never be dismissed", async () => {
+2 -6
View File
@@ -12,8 +12,8 @@
* an upsert, so a repeat dismiss of the same instance is a no-op rather than
* a conflict. `userId` is narrowed from `requireAuth()` only; the body never
* carries one. Cookie OR Bearer, mirroring the digest GET route's own auth
* policy, and gated on the same `insights` module (the daily rail's host
* surface).
* policy. Like the digest GET it carries no module gate: the rail is data,
* and the `insights` module is the AI analysis opt-out.
*/
import type { NextRequest } from "next/server";
@@ -28,7 +28,6 @@ import { annotate } from "@/lib/logging/context";
import { prisma } from "@/lib/db";
import { invalidateUserHealthScore } from "@/lib/cache/invalidate";
import { isScoreNoticeItemKey } from "@/lib/daily/priority-item";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { dismissPriorityItemSchema } from "@/lib/validations/daily";
@@ -40,9 +39,6 @@ const DISMISS_WINDOW_MS = 60_000;
export const POST = apiHandler(async (req: NextRequest) => {
const { user } = await requireAuth();
const gate = await requireModuleEnabled(user.id, "insights");
if (!gate.enabled) return gate.response;
const rl = await checkRateLimit(
`daily-digest-dismiss:${user.id}`,
DISMISS_RATE_LIMIT,
+8 -10
View File
@@ -10,14 +10,15 @@
* provider call is reachable from this path, and nothing warms on mount.
*
* Cookie OR Bearer auth via `requireAuth()`; `userId` is narrowed from the
* resolved session — never a body field. Gated on the `insights` module (the
* daily digest is the AI-narrative daily layer); a disabled account gets the
* standard 403 `module.disabled` envelope even over a Bearer token. The rail's
* data-tile inputs inherit their own module gates via the snapshot builder.
* resolved session — never a body field. No module gate and no AI gate: the
* digest is data (score, doses, syncs, checkups, the day's markers). Its AI
* parts, the briefing lead, the reaction line and the Coach check-in, are
* served only while their capabilities are available, and the `ai` block says
* which. The rail's data-tile inputs inherit their own module gates via the
* snapshot builder.
*/
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { NO_STORE_BUT_BFCACHE } from "@/lib/http/cache-headers";
import { loadDailyDigest } from "@/lib/daily/load-digest";
@@ -27,13 +28,10 @@ export const GET = apiHandler(async () => {
// The record's Today hero. Same family as the dashboard snapshot and
// admitted on the same argument: an aggregate over the record's own data,
// assembled from already-cached values with no provider on the path. The
// module gate below now runs against the RECORD, which is the behaviour that
// matters — a delegate gets the hero only where the owner switched insights
// on, never where the delegate did. Re-examine with the snapshot when
// AI parts resolve against the RECORD, so a delegate sees the owner's
// capabilities, never their own. Re-examine with the snapshot when
// per-module scope lands; a digest is a summary of several modules at once.
const { user } = await requireRecordAuth("read", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
const digest = await loadDailyDigest(user);
@@ -38,9 +38,19 @@ vi.mock("next/headers", () => ({
}));
const buildDashboardSnapshot = vi.fn();
vi.mock("@/lib/dashboard/snapshot", () => ({
vi.mock("@/lib/dashboard/snapshot", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/dashboard/snapshot")>()),
buildDashboardSnapshot: (...a: unknown[]) => buildDashboardSnapshot(...a),
}));
// The per-read briefing capability; its own behaviour is pinned in
// `snapshot-read-briefing-capability.test.ts`.
vi.mock("@/lib/ai/capabilities/record", () => ({
aiCapabilityForRecord: async () => ({
available: true,
reason: null,
onDeviceAllowed: true,
}),
}));
import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
@@ -1,254 +1,119 @@
import { readdirSync, readFileSync, statSync } from "node:fs";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative, resolve } from "node:path";
import { describe, expect, it } from "vitest";
/**
* v1.4.38 W-C M6 — Coach API route gate inventory.
*
* The web surfaces are protected by the `flags.coach` short-circuit in
* every Coach-bearing component (see
* `src/lib/feature-flags/__tests__/coach-cascade.test.tsx`). The
* server-side mirror is `requireAssistantSurface("coach")` in every
* Coach-only route handler. Without a discovery test, a future
* contributor who lands a new `/api/insights/<foo>/route.ts` whose body
* touches the Coach stack would have to remember the gate by hand — a
* silent miss leaks the surface even when the operator turned the
* Coach matrix off.
*
* The walk below scans every `route.ts` under `src/app/api/insights/`
* and groups each handler into one of three buckets:
*
* 1. Coach-gated — file imports + invokes
* `requireAssistantSurface("coach")`.
* 2. Other-gated — file invokes `requireAssistantSurface()` with a
* different surface (`insightStatus`,
* `correlations`, `briefing`).
* 3. Allowlisted — non-Coach Insights routes that don't gate on
* the matrix at all (provider chain, settings,
* targets, glp1-timeline, feedback). Allowlist
* lives alongside the test for easy review.
*
* Anything that doesn't fit one of the three buckets is an orphan and
* fails the test by name so the fix is one search-and-add.
*/
const NON_COACH_GATED_ROUTES: ReadonlyArray<string> = [
// Non-Coach assistant surfaces — gated on a sibling sub-flag.
// Per-biomarker assessment. Gated on the same `insightStatus` sub-flag as
// the metric-status + specialised status routes (no Coach prose).
"src/app/api/insights/biomarker-assessment/route.ts",
"src/app/api/insights/blood-pressure-status/route.ts",
"src/app/api/insights/bmi-status/route.ts",
"src/app/api/insights/cards/route.ts",
"src/app/api/insights/medication-compliance-status/route.ts",
// v1.8.7.1 — generic per-HealthKit-metric assessment. Gated on the
// same `insightStatus` sub-flag as the seven specialised status routes.
"src/app/api/insights/metric-status/route.ts",
"src/app/api/insights/mood-status/route.ts",
// v1.11.0 — period-narrative read route. Gates on the same `insightStatus`
// sub-flag as the assessment routes (no Coach prose).
"src/app/api/insights/narrative/route.ts",
// v1.9.0 — on-demand full assessment warm. Warms the same assessment
// cards the status routes serve, so it gates on `insightStatus`, not
// `coach`: a user with assessments enabled but Coach disabled can warm.
"src/app/api/insights/pregenerate/route.ts",
"src/app/api/insights/pulse-status/route.ts",
"src/app/api/insights/weight-status/route.ts",
];
const NOT_COACH_OWNED_ROUTES: ReadonlyArray<string> = [
// Settings + chain inventory — surface-agnostic infra reads. The
// settings UI itself is server-rendered and the chain page hides
// when no provider is configured; neither one carries assistant
// prose. Disabling Coach must not break these reads — the user can
// still inspect and reconfigure the chain that gets re-enabled.
"src/app/api/insights/provider-chain/route.ts",
// Correlation statistics: computed, never written by a model. The switch
// that used to gate them was retired because it stopped no AI work.
"src/app/api/insights/correlations/route.ts",
"src/app/api/insights/settings/route.ts",
// Read-only data feeds — `/targets` is a non-assistant Zielwerte
// page driven by classifications, not LLM prose; the GLP-1 timeline
// is the same data the medication page paints whether the assistant
// is on or off. Recommendation feedback (`/feedback`) records a
// thumbs-up/-down on a NON-Coach recommendation row that was
// produced before the operator flipped the flag; gating it would
// mean the operator's mid-flight toggle erases the user's
// ability to dispose of stale recommendations.
"src/app/api/insights/feedback/route.ts",
"src/app/api/insights/glp1-timeline/route.ts",
// Deterministic GLP-1 plateau detector read (no assistant prose) — same
// medications-domain posture as glp1-timeline directly above.
"src/app/api/insights/glp1-plateau/route.ts",
// v1.5.5 — per-user tile layout for the `/insights` surface. The
// endpoint persists tile visibility + ordering only; it carries no
// assistant prose and is the mirror of `/api/dashboard/widgets`,
// which also sits outside the Coach gate. Disabling Coach must not
// wedge the user's ability to reorder the insights tile strip.
"src/app/api/insights/layout/route.ts",
"src/app/api/insights/targets/route.ts",
// v1.25 — read-only awareness cards for the overview. Each is pure compute
// over the rollup / lab tier (baseline-drift, sleep-breathing screening,
// last-panel lab deltas) and carries no assistant prose; they gate on the
// `insights` module, not on the Coach surface. Disabling Coach must not
// wedge these factual reads.
"src/app/api/insights/health-status/route.ts",
"src/app/api/insights/breathing-screening/route.ts",
"src/app/api/insights/labs-changes/route.ts",
// S11 — the intraday pulse / tension read. Deterministic compute over the
// day's raw PULSE / steps / workouts (10-minute mean shape + the cautious
// elevated-at-rest window); it carries no assistant prose and gates on the
// `insights` module, not the Coach surface. Same posture as health-status /
// labs-changes directly above — disabling Coach must not wedge this read.
"src/app/api/insights/pulse/intraday/route.ts",
// Persisted correlation decisions are deterministic Insights data. They
// gate on the Insights module and remain usable when Coach is disabled.
"src/app/api/insights/patterns/route.ts",
"src/app/api/insights/patterns/[id]/route.ts",
// v1.29.x (S7) — the FENCED multi-document coach chat + its attach/detach
// mutations. These live under /insights/chat for URL grouping but are
// DOCUMENT-surface routes: they gate on the `inboundDocuments` module
// (`requireModuleEnabled`), NOT on the Coach assistant surface — parity with
// the document-sheet chat (`/api/documents/inbound/[id]/chat`, outside this
// scan). The security boundary here is the fence (no tools, no snapshot),
// not the Coach gate; disabling Coach must not wedge a fenced document chat
// any more than it wedges the document sheet. See the S7 design §3.2 step 1.
"src/app/api/insights/chat/fenced/route.ts",
"src/app/api/insights/chat/[id]/attachments/route.ts",
"src/app/api/insights/chat/[id]/attachments/[documentId]/route.ts",
// Deterministic reads behind the Insights overview: the comprehensive
// overview query, the derived-metric tiles, the ECG list, strip and live
// ingest, and the device-flagged rhythm events. None of them carries
// assistant prose or calls a provider; they gate on the `insights` module
// only. Switching the assistant off, the master or a sub-flag, must not
// refuse them, or the overview fails to load.
"src/app/api/insights/comprehensive/route.ts",
"src/app/api/insights/derived/route.ts",
"src/app/api/insights/derived/batch/route.ts",
"src/app/api/insights/ecg/route.ts",
"src/app/api/insights/ecg/[id]/route.ts",
"src/app/api/insights/rhythm-events/route.ts",
];
const COACH_GATE_NEEDLE = 'requireAssistantSurface("coach")';
const ANY_GATE_NEEDLE = "requireAssistantSurface(";
import {
AI_ROUTES,
AI_ROUTE_TREES,
DATA_ROUTES,
PENDING_ROUTES,
} from "../../__tests__/ai-route-inventory";
/**
* Return true when the file contains the needle on a line that is NOT
* a pure comment. A documentation comment that mentions the gate
* (`// requireAssistantSurface("coach") protects this surface`) must
* not satisfy the gate-presence check — otherwise a contributor who
* deletes the actual call but leaves the docstring would slip through.
* Every route in the trees where AI routes live is classified.
*
* This file used to sort the `/api/insights` routes into "Coach-gated",
* "other-gated" and "not Coach-owned" by the operator switch each one read.
* That sorting encoded the defect the AI-optional design removes: ECG uploads,
* rhythm events, scores and correlation statistics sat behind AI switches, so
* turning AI off took data down with it. The rule now is the capability rule:
*
* - a data route asks no AI capability and is never refused for an AI
* reason;
* - an AI route names its capability (`requireAiCapability` for an action,
* `getAiCapability` for a mixed read).
*
* The lists live in `src/app/api/__tests__/ai-route-inventory.ts`; the whole
* API tree is checked against them by `ai-capability-route-inventory.test.ts`.
* This file walks the insights, Coach and daily trees and fails by name on any
* route that none of the lists classifies, so a new route there has to decide
* which kind it is. `PENDING_ROUTES` names the few whose AI gating another
* change owns; an entry there that starts asking a capability fails until it
* moves to `AI_ROUTES`.
*
* Mutation checks: deleting `insights/ecg/route.ts` from `DATA_ROUTES` fails
* the orphan test by name; adding `getAiCapability("coach")` to a pending
* route fails the pending test; pointing the walk at an empty tree fails the
* count.
*/
function fileHasGateCall(text: string, needle: string): boolean {
return text.split("\n").some((line) => {
if (!line.includes(needle)) return false;
const trimmed = line.trim();
if (trimmed.startsWith("//")) return false;
if (trimmed.startsWith("*")) return false;
return true;
});
}
/**
* Walk every `route.ts` under `src/app/api/insights/` (including
* dynamic segments under `[id]`). Returns POSIX-style paths relative
* to the repo root.
*/
function findInsightsRouteFiles(): string[] {
// __dirname here is `src/app/api/insights/__tests__/`, so the
// insights root is one directory up.
const insightsRoot = resolve(__dirname, "..");
const repoRoot = resolve(insightsRoot, "..", "..", "..", "..");
const repoRoot = resolve(__dirname, "..", "..", "..", "..", "..");
function routeFiles(tree: string): string[] {
const hits: string[] = [];
function walk(dir: string): void {
const entries = readdirSync(dir);
for (const entry of entries) {
for (const entry of readdirSync(dir)) {
const full = join(dir, entry);
const stat = statSync(full);
if (stat.isDirectory()) {
if (entry === "__tests__") continue;
if (entry === "node_modules") continue;
if (statSync(full).isDirectory()) {
if (entry === "__tests__" || entry === "node_modules") continue;
walk(full);
continue;
} else if (entry === "route.ts") {
hits.push(relative(repoRoot, full).split(/[\\/]/).join("/"));
}
if (entry !== "route.ts") continue;
hits.push(relative(repoRoot, full).split(/[\\/]/).join("/"));
}
}
walk(insightsRoot);
return hits.sort();
walk(resolve(repoRoot, tree));
return hits;
}
describe("Coach API route gate inventory", () => {
it("every Coach-bearing insights route imports requireAssistantSurface('coach')", () => {
const repoRoot = resolve(__dirname, "..", "..", "..", "..", "..");
const routes = findInsightsRouteFiles();
expect(routes.length).toBeGreaterThan(0);
const ROUTES = AI_ROUTE_TREES.flatMap(routeFiles).sort();
const allowlistOther = new Set(NON_COACH_GATED_ROUTES);
const allowlistNone = new Set(NOT_COACH_OWNED_ROUTES);
const ANY_GATE = /\b(?:requireAiCapability|getAiCapability)\s*\(/;
const orphans: Array<{ path: string; reason: string }> = [];
function code(path: string): string {
return readFileSync(resolve(repoRoot, path), "utf8")
.split("\n")
.filter((line) => !/^\s*(\*|\/\/|\/\*)/.test(line))
.join("\n");
}
for (const path of routes) {
const full = resolve(repoRoot, path);
const text = readFileSync(full, "utf8");
const hasCoachGate = fileHasGateCall(text, COACH_GATE_NEEDLE);
const hasAnyGate = fileHasGateCall(text, ANY_GATE_NEEDLE);
if (hasCoachGate) continue;
if (allowlistOther.has(path)) {
// Sanity — the file should still gate on SOME assistant
// surface. A stale entry on this allowlist is misleading
// documentation; flip the failure mode so the orphan is
// reported with the right diagnosis.
if (!hasAnyGate) {
orphans.push({
path,
reason:
"listed in NON_COACH_GATED_ROUTES but has no requireAssistantSurface() call at all",
});
}
continue;
}
if (allowlistNone.has(path)) continue;
orphans.push({
path,
reason: `missing requireAssistantSurface("coach"); add the gate or move the route onto an allowlist (NON_COACH_GATED_ROUTES / NOT_COACH_OWNED_ROUTES)`,
});
describe("insights, Coach and daily route classification", () => {
it("walks trees that exist and finds routes in them", () => {
for (const tree of AI_ROUTE_TREES) {
expect(existsSync(resolve(repoRoot, tree)), tree).toBe(true);
}
expect(ROUTES.length).toBeGreaterThan(40);
});
it("classifies every route as AI, data or pending", () => {
const orphans = ROUTES.filter(
(path) =>
!(path in AI_ROUTES) &&
!(path in DATA_ROUTES) &&
!(path in PENDING_ROUTES),
);
expect(
orphans,
[
"Coach API route gate inventory found unaccounted-for handler(s):",
...orphans.map((o) => ` - ${o.path}: ${o.reason}`),
"Unclassified routes. Decide what each one is and add it to",
"src/app/api/__tests__/ai-route-inventory.ts:",
" AI_ROUTES — it calls a model or serves model text (name the capability);",
" DATA_ROUTES — it serves or accepts data and must never ask AI.",
].join("\n"),
).toEqual([]);
});
it("allowlists do not reference deleted route files", () => {
const known = new Set(findInsightsRouteFiles());
const stale = [...NON_COACH_GATED_ROUTES, ...NOT_COACH_OWNED_ROUTES].filter(
(path) => !known.has(path),
it("classifies no route twice", () => {
const lists = [AI_ROUTES, DATA_ROUTES, PENDING_ROUTES].map((list) =>
Object.keys(list),
);
const seen = new Map<string, number>();
for (const list of lists) {
for (const path of list) seen.set(path, (seen.get(path) ?? 0) + 1);
}
expect([...seen].filter(([, n]) => n > 1).map(([path]) => path)).toEqual(
[],
);
});
expect(
stale,
[
"Allowlist entries point to files that no longer exist —",
"delete the stale entries from",
"`src/app/api/insights/__tests__/coach-route-gate-inventory.test.ts`:",
...stale.map((p) => ` - ${p}`),
].join("\n"),
).toEqual([]);
it("keeps PENDING_ROUTES honest: existing files, none of them asking yet", () => {
for (const path of Object.keys(PENDING_ROUTES)) {
expect(ROUTES, `${path} no longer exists`).toContain(path);
expect(
ANY_GATE.test(code(path)),
`${path} now asks an AI capability — move it to AI_ROUTES`,
).toBe(false);
}
});
});
@@ -10,7 +10,7 @@
* classification). SCREENING SIGNAL ONLY — never a HealthLog diagnosis; the
* card states this explicitly.
*
* Mirrors `/api/insights/derived`: `apiHandler`, `requireAuth`, the `insights`
* Mirrors `/api/insights/derived`: `apiHandler`, `requireAuth`, the `sleep`
* module gate, the shared analytics-read budget. `userId` is narrowed from the
* session.
*/
@@ -31,7 +31,10 @@ export const GET = apiHandler(async () => {
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
// The screening belongs to sleep: with the sleep module off it hides like
// every other sleep surface. Not an AI read, so the `insights` module (the
// AI analysis opt-out) does not gate it.
const m = await requireModuleEnabled(user.id, "sleep");
if (!m.enabled) return m.response;
const rl = await checkAnalyticsReadRateLimit(user.id);
@@ -7,9 +7,8 @@ vi.mock("@/lib/db", () => ({
measurement: { findMany: vi.fn() },
medication: { findMany: vi.fn() },
medicationIntakeEvent: { findMany: vi.fn() },
// v1.4.31 — gated on `assistant.insightStatus`; null row falls
// back to the all-on default so existing assertions ride
// through unchanged.
// The operator switches are read by nothing on this route any more; the
// mock stays so a test can prove a switch-off changes nothing.
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
// v1.28 perf — PULSE now reads through the DAY-rollup read-swap
// (`probeRollupCoverage` + `readDayMeanSeries`). An empty coverage
@@ -20,10 +19,8 @@ vi.mock("@/lib/db", () => ({
},
}));
// v1.18.0 — the route now resolves the `insights` module gate after
// `requireAuth()`. Mock it default-enabled so the existing assertions
// (data shape + assistant-flag gating) ride through; the dedicated
// off → 403 coverage lives in the route-gate inventory test.
// The route no longer asks the `insights` module (the AI analysis opt-out);
// the mock stays so a test can prove it is never consulted.
vi.mock("@/lib/modules/gate", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/modules/gate")>()),
requireModuleEnabled: vi.fn().mockResolvedValue({ enabled: true }),
@@ -72,7 +69,6 @@ beforeEach(() => {
vi.mocked(prisma.user.findUnique).mockResolvedValue({
heightCm: null,
dateOfBirth: null,
aiProvider: null,
} as never);
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue(null as never);
// v1.28 perf — empty coverage probe routes PULSE through the
@@ -86,33 +82,29 @@ function makeReq(): NextRequest {
return new NextRequest("http://localhost/api/insights/cards");
}
describe("GET /api/insights/cards — assistant-flag gate", () => {
it("returns 403 + errorCode when insightStatus is disabled", async () => {
describe("GET /api/insights/cards — rule alerts are data", () => {
it("answers 200 with every AI switch off", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.appSettings.findUnique).mockResolvedValueOnce({
assistantEnabled: true,
assistantCoachEnabled: true,
assistantBriefingEnabled: true,
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue({
assistantEnabled: false,
assistantCoachEnabled: false,
assistantBriefingEnabled: false,
assistantInsightStatusEnabled: false,
assistantDocumentAiEnabled: true,
assistantDocumentAiEnabled: false,
} as never);
const res = await callGet(makeReq());
expect(res.status).toBe(403);
const body = (await res.json()) as { meta?: { errorCode?: string } };
expect(body.meta?.errorCode).toBe("assistant.disabled.insightStatus");
expect(res.status).toBe(200);
});
it("returns 403 when the master flag is off", async () => {
it("answers 200 with the AI analysis opt-out on, without asking the module", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.appSettings.findUnique).mockResolvedValueOnce({
assistantEnabled: false,
assistantCoachEnabled: true,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: true,
assistantDocumentAiEnabled: true,
vi.mocked(requireModuleEnabled).mockResolvedValue({
enabled: false,
response: new Response(null, { status: 403 }),
} as never);
const res = await callGet(makeReq());
expect(res.status).toBe(403);
expect(res.status).toBe(200);
expect(requireModuleEnabled).not.toHaveBeenCalled();
});
});
@@ -157,19 +149,23 @@ describe("GET /api/insights/cards", () => {
vi.mocked(prisma.measurement.findMany).mockResolvedValue(
measurements as never,
);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
heightCm: null,
dateOfBirth: null,
aiProvider: "ANTHROPIC",
} as never);
const res = await callGet(makeReq());
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: Array<{ severity: string; provider: string; title: string }>;
data: Array<{
severity: string;
provider: string;
title: string;
summary: string | null;
}>;
};
expect(body.data.length).toBeGreaterThan(0);
expect(body.data[0].provider).toBe("anthropic");
// The threshold engine wrote these, never a model: the provider says so
// and no card ever carries null text (a native decoder needs both).
for (const card of body.data) {
expect(card.provider).toBe("rules");
expect(typeof card.summary).toBe("string");
}
expect(body.data.some((c) => c.severity === "alert")).toBe(true);
});
+9 -10
View File
@@ -5,10 +5,14 @@
* shared `generateAlerts()` rule engine, then re-shapes each `HealthAlert`
* to the iOS Insight model (id, title, summary, severity, recommendations,
* provider).
*
* Every card is a rule alert: deterministic text from the threshold engine,
* never model output. So the route carries no AI gate and no `insights`
* module gate (the AI analysis opt-out), `summary` is never null, and
* `provider` is `"rules"`. It used to echo the account's chosen AI provider
* (or `"claude"`), which claimed a model wrote text that none did.
*/
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { prisma } from "@/lib/db";
@@ -68,12 +72,6 @@ export const GET = apiHandler(async () => {
// v1.37.0 — MANAGE-level read: computed over the whole record, with no
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// v1.4.31 — the iOS cards adapter feeds the same per-metric
// insight surfaces the web `<InsightStatusCard>` mounts on each
// /insights/<metric> sub-page. Both share the operator gate.
await requireAssistantSurface("insightStatus");
annotate({ action: { name: "insights.cards" } });
const NINETY_DAY_WINDOW = 90;
@@ -83,7 +81,7 @@ export const GET = apiHandler(async () => {
await Promise.all([
prisma.user.findUnique({
where: { id: user.id },
select: { heightCm: true, dateOfBirth: true, aiProvider: true },
select: { heightCm: true, dateOfBirth: true },
}),
// WEIGHT + BP are manual entries (low volume, and BP needs exact-
// timestamp pairing below for `bpPctInTarget`), so a bounded raw read
@@ -257,7 +255,8 @@ export const GET = apiHandler(async () => {
medications: medicationCompliance,
});
const provider = dbUser?.aiProvider?.toLowerCase() ?? "claude";
// The rule engine wrote these, not a model.
const provider = "rules";
const generatedAt = new Date().toISOString();
const cards: InsightCard[] = alerts.map((alert, idx) => ({
+5 -10
View File
@@ -21,7 +21,6 @@ import {
safeJson,
} from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { auditLog } from "@/lib/auth/audit";
import { COACH_CONVERSATION_TITLE_MAX } from "@/lib/ai/coach/types";
@@ -43,10 +42,9 @@ const renameConversationSchema = z
export const GET = apiHandler(async (_request: NextRequest, ctx: RouteCtx) => {
const auth = await requireAuth();
// v1.4.38 W-C M6 — operator can hide the Coach surface app-wide;
// the conversation reader is part of the Coach stack (encrypted
// assistant prose), so a disabled surface must 403 here too.
await requireAssistantSurface("coach");
// Never AI-gated: a stored conversation is the person's own data. Reading,
// renaming and deleting it keep working while the Coach is unavailable for
// any reason, so a thread can always be reviewed and erased.
const { id } = await ctx.params;
if (!id) return apiError("coach.conversation.notFound", 404);
@@ -74,7 +72,6 @@ export const GET = apiHandler(async (_request: NextRequest, ctx: RouteCtx) => {
export const PATCH = apiHandler(async (request: NextRequest, ctx: RouteCtx) => {
const auth = await requireAuth();
await requireAssistantSurface("coach");
const { id } = await ctx.params;
if (!id) return apiError("coach.conversation.notFound", 404);
@@ -114,10 +111,8 @@ export const PATCH = apiHandler(async (request: NextRequest, ctx: RouteCtx) => {
export const DELETE = apiHandler(
async (_request: NextRequest, ctx: RouteCtx) => {
const auth = await requireAuth();
// v1.4.38 W-C M6 — same gate as GET; a disabled Coach surface
// means the user can't reach the conversation list anyway, so the
// delete affordance must stay behind the same kill-switch.
await requireAssistantSurface("coach");
// Not AI-gated, like GET: deleting one's own thread never waits on the
// Coach being available.
const { id } = await ctx.params;
if (!id) return apiError("coach.conversation.notFound", 404);
@@ -26,11 +26,14 @@ 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),
vi.mock("@/lib/ai/capabilities/gate", () => ({
requireAiCapability: vi.fn(async () => ({
available: true,
reason: null,
onDeviceAllowed: true,
})),
}));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number) => ({ data: null, error, status }),
@@ -0,0 +1,224 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { AiUnavailableError } from "@/lib/ai/capabilities/refusal";
/**
* The Coach chat POST (SSE) asks for the `coach` AI capability right after
* auth, before the body is parsed or anything else runs. The capability folds
* in what the Coach module gate, the operator switch and the `disableCoach`
* opt-out used to answer separately, plus provider presence and consent.
*
* - Unavailable for any reason but a missing provider: the capability
* envelope is thrown (apiHandler renders it) and nothing else runs.
* - `no_provider`: the existing `coach.provider.none` SSE frame, now with
* `reason`, because the streaming clients already read that frame.
*
* The conversation-list GET is the person's stored data: it never asks.
*/
vi.mock("@/lib/api-handler", () => ({
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
requireAuth: vi.fn(async () => ({ user: { id: "u1", locale: "en" } })),
HttpError: class HttpError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
},
}));
const { requireAiCapability } = vi.hoisted(() => ({
requireAiCapability: vi.fn(),
}));
vi.mock("@/lib/ai/capabilities/gate", () => ({ requireAiCapability }));
vi.mock("@/lib/modules/gate", () => ({
isModuleEnabled: vi.fn(async () => true),
MODULE_DISABLED_ERROR_CODE: "module.disabled",
}));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number, meta?: unknown) => ({
data: null,
error,
status,
meta,
}),
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
apiValidationError: (error: string, _issues: unknown, status: number) =>
new Response(JSON.stringify({ data: null, error }), { status }),
sanitiseZodIssues: () => [],
}));
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
vi.mock("@/lib/db", () => ({ prisma: {} }));
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn() }));
vi.mock("@/lib/i18n/server-locale", () => ({
resolveServerLocale: vi.fn(async () => "en"),
}));
vi.mock("@/lib/ai/provider-runner", () => ({
AllProvidersFailedError: class extends Error {},
runRawCompletionWithFallback: vi.fn(),
}));
vi.mock("@/lib/ai/provider", () => ({
resolveProviderChain: vi.fn(),
resolveProvider: vi.fn(),
}));
vi.mock("@/lib/ai/consent-guard", () => ({ assertConsentForChain: vi.fn() }));
vi.mock("@/lib/ai/prompts/insight-generator", () => ({ PROMPT_VERSION: "x" }));
vi.mock("@/lib/ai/coach/types", () => ({
coachChatRequestSchema: {
safeParse: () => ({ success: false, error: { issues: [] } }),
},
}));
// v1.20.0 (F1) — the route statically imports the tool barrel; this suite
// never reaches tool code (it asserts the 403 module-gate short-circuit), so a
// thin stub keeps the import graph satisfied without pulling the real schemas.
vi.mock("@/lib/ai/coach/tools", () => ({
COACH_TOOL_DEFS: [],
MAX_ROUNDS: 3,
buildCoachDataInventory: vi.fn(),
renderDataInventory: vi.fn(),
renderFocusHint: vi.fn(() => ""),
buildToolModeAddendum: vi.fn(),
runCoachToolLoop: vi.fn(),
}));
vi.mock("@/lib/ai/coach/persistence", () => ({
appendMessage: vi.fn(),
createConversation: vi.fn(),
fetchConversationWithMessages: vi.fn(),
listConversations: vi.fn(async () => ({
conversations: [],
nextCursor: null,
})),
}));
vi.mock("@/lib/ai/coach/coach-memory-shared", () => ({
enqueueCoachMemoryRefresh: vi.fn(),
}));
vi.mock("@/lib/ai/coach/facts", () => ({ storeDeterministicFacts: vi.fn() }));
vi.mock("@/lib/ai/coach/budget", () => ({
buildDateKey: vi.fn(),
reserveBudget: vi.fn(async () => ({
allowed: true,
reserved: 0,
totalAfter: 0,
})),
reconcileSpend: vi.fn(),
resolveDailyCap: vi.fn(() => 200_000),
resolveDailyCapFor: vi.fn(() => 200_000),
resolveCostOwner: vi.fn(() => "operator" as const),
}));
vi.mock("@/lib/ai/coach/refusal", () => ({ detectRefusal: vi.fn() }));
vi.mock("@/lib/ai/coach/system-prompt", () => ({
getCoachSystemPrompt: vi.fn(),
}));
vi.mock("@/lib/ai/coach/about-me", () => ({
getSelfContextTextForUser: vi.fn(),
}));
vi.mock("@/lib/ai/coach/snapshot", () => ({ buildCoachSnapshot: vi.fn() }));
vi.mock("@/lib/ai/coach/keyvalues", () => ({
parseKeyValuesSentinel: vi.fn(),
}));
vi.mock("@/lib/validations/coach-prefs", () => ({ parseCoachPrefs: vi.fn() }));
// Collect the frames a stream would carry, so a refusal frame is observable.
vi.mock("@/lib/sse/create-stream", () => ({
createSseStream: vi.fn(
(start: (c: { enqueue: (chunk: Uint8Array) => void }) => void) => {
const chunks: string[] = [];
start({
enqueue: (chunk) => chunks.push(new TextDecoder().decode(chunk)),
});
return chunks.join("");
},
),
}));
import { POST, GET } from "../route";
type Envelope = { data: unknown; error: string | null; status: number };
const post = POST as unknown as (req: Request) => Promise<Response>;
const get = GET as unknown as (req: Request) => Promise<Envelope>;
function chatPostReq(): Request {
return new Request("http://localhost/api/insights/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "hi" }),
});
}
function listReq(): Request {
return new Request("http://localhost/api/insights/chat", { method: "GET" });
}
describe("coach chat capability gate", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it.each([
["operator_disabled", 403, "assistant.disabled.coach"],
["module_disabled", 403, "module.disabled"],
["user_disabled", 403, "module.disabled"],
["consent_required", 403, "consent.ai.required"],
["not_permitted_for_record", 403, "ai.record.notPermitted"],
["check_failed", 503, "ai.unavailable"],
] as const)(
"POST refuses with the capability envelope for %s",
async (reason, status, errorCode) => {
requireAiCapability.mockRejectedValue(
new AiUnavailableError("coach", reason),
);
const refused = await post(chatPostReq()).catch((err: unknown) => err);
expect(refused).toBeInstanceOf(AiUnavailableError);
const error = refused as AiUnavailableError;
expect(error.status).toBe(status);
expect(error.meta).toMatchObject({
errorCode,
capability: "coach",
reason,
});
expect(requireAiCapability).toHaveBeenCalledWith("coach");
},
);
it("POST keeps the coach.provider.none SSE frame for a missing provider, with the reason", async () => {
requireAiCapability.mockRejectedValue(
new AiUnavailableError("coach", "no_provider"),
);
const res = await post(chatPostReq());
expect(res.status).toBe(200);
const body = await res.text();
expect(body).toContain('"code":"coach.provider.none"');
expect(body).toContain('"reason":"no_provider"');
});
it("POST continues past the gate when the Coach is available", async () => {
requireAiCapability.mockResolvedValue({
available: true,
reason: null,
onDeviceAllowed: true,
});
const res = await post(chatPostReq());
// The stubbed schema refuses the body, so reaching validation proves the
// gate let the request through.
expect(res.status).toBe(422);
});
it("GET never asks for the capability: stored conversations stay readable", async () => {
requireAiCapability.mockRejectedValue(
new AiUnavailableError("coach", "operator_disabled"),
);
const res = await get(listReq());
expect(res.status).toBe(200);
expect(requireAiCapability).not.toHaveBeenCalled();
});
});
@@ -24,10 +24,14 @@ 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),
vi.mock("@/lib/ai/capabilities/gate", () => ({
requireAiCapability: vi.fn(async () => ({
available: true,
reason: null,
onDeviceAllowed: true,
})),
}));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number) => ({ data: null, error, status }),
@@ -37,11 +37,14 @@ 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),
vi.mock("@/lib/ai/capabilities/gate", () => ({
requireAiCapability: vi.fn(async () => ({
available: true,
reason: null,
onDeviceAllowed: true,
})),
}));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number) => ({ data: null, error, status }),
@@ -30,11 +30,14 @@ 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),
vi.mock("@/lib/ai/capabilities/gate", () => ({
requireAiCapability: vi.fn(async () => ({
available: true,
reason: null,
onDeviceAllowed: true,
})),
}));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number) => ({ data: null, error, status }),
@@ -27,11 +27,14 @@ 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),
vi.mock("@/lib/ai/capabilities/gate", () => ({
requireAiCapability: vi.fn(async () => ({
available: true,
reason: null,
onDeviceAllowed: true,
})),
}));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number) => ({ data: null, error, status }),
@@ -22,12 +22,9 @@ vi.mock("@/lib/api-handler", () => ({
},
}));
const { requireModuleEnabled, requireAssistantSurface } = vi.hoisted(() => ({
requireModuleEnabled: vi.fn(async () => ({ enabled: true })),
requireAssistantSurface: vi.fn(async () => undefined),
vi.mock("@/lib/modules/gate", () => ({
isModuleEnabled: vi.fn(async () => true),
}));
vi.mock("@/lib/modules/gate", () => ({ requireModuleEnabled }));
vi.mock("@/lib/feature-flags", () => ({ requireAssistantSurface }));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number, meta?: unknown) => ({
@@ -132,8 +129,6 @@ function listReq(qs = ""): Request {
describe("GET /api/insights/chat — q search param", () => {
beforeEach(() => {
vi.clearAllMocks();
requireModuleEnabled.mockResolvedValue({ enabled: true });
requireAssistantSurface.mockResolvedValue(undefined);
listConversations.mockResolvedValue({
conversations: [],
nextCursor: null,
@@ -1,204 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
/**
* v1.18.0 — the Coach chat POST (SSE) and the conversation-list GET both
* enforce the two-layer module gate (operator availability AND the
* per-user `disableCoach` opt-out) right after auth. A disabled module
* returns the 403 `module.disabled` envelope verbatim before any other
* Coach dependency runs; an enabled module falls through to the existing
* assistant-flag check. The suite pins both branches so a refactor can't
* quietly drop the gate.
*/
vi.mock("@/lib/api-handler", () => ({
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
requireAuth: vi.fn(async () => ({ user: { id: "u1", locale: "en" } })),
HttpError: class HttpError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
},
}));
// The legacy assistant-flag gate the handler reaches AFTER the module
// gate. We throw a sentinel so an enabled module is observable by the
// control reaching this call.
class AssistantSentinel extends Error {}
const { requireModuleEnabled, requireAssistantSurface } = vi.hoisted(() => ({
requireModuleEnabled: vi.fn(),
requireAssistantSurface: vi.fn(),
}));
vi.mock("@/lib/modules/gate", () => ({ requireModuleEnabled }));
vi.mock("@/lib/feature-flags", () => ({ requireAssistantSurface }));
// Everything else the module imports — stubbed harmlessly; none of it is
// reached on the disabled branch, and the enabled branch stops at the
// assistant sentinel above.
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number, meta?: unknown) => ({
data: null,
error,
status,
meta,
}),
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
}));
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
vi.mock("@/lib/db", () => ({ prisma: {} }));
vi.mock("@/lib/rate-limit", () => ({ checkRateLimit: vi.fn() }));
vi.mock("@/lib/i18n/server-locale", () => ({
resolveServerLocale: vi.fn(async () => "en"),
}));
vi.mock("@/lib/ai/provider-runner", () => ({
AllProvidersFailedError: class extends Error {},
runRawCompletionWithFallback: vi.fn(),
}));
vi.mock("@/lib/ai/provider", () => ({
resolveProviderChain: vi.fn(),
resolveProvider: vi.fn(),
}));
vi.mock("@/lib/ai/consent-guard", () => ({ assertConsentForChain: vi.fn() }));
vi.mock("@/lib/ai/prompts/insight-generator", () => ({ PROMPT_VERSION: "x" }));
vi.mock("@/lib/ai/coach/types", () => ({
coachChatRequestSchema: { safeParse: () => ({ success: false }) },
}));
// v1.20.0 (F1) — the route statically imports the tool barrel; this suite
// never reaches tool code (it asserts the 403 module-gate short-circuit), so a
// thin stub keeps the import graph satisfied without pulling the real schemas.
vi.mock("@/lib/ai/coach/tools", () => ({
COACH_TOOL_DEFS: [],
MAX_ROUNDS: 3,
buildCoachDataInventory: vi.fn(),
renderDataInventory: vi.fn(),
renderFocusHint: vi.fn(() => ""),
buildToolModeAddendum: vi.fn(),
runCoachToolLoop: vi.fn(),
}));
vi.mock("@/lib/ai/coach/persistence", () => ({
appendMessage: vi.fn(),
createConversation: vi.fn(),
fetchConversationWithMessages: vi.fn(),
listConversations: vi.fn(async () => ({
conversations: [],
nextCursor: null,
})),
}));
vi.mock("@/lib/ai/coach/coach-memory-shared", () => ({
enqueueCoachMemoryRefresh: vi.fn(),
}));
vi.mock("@/lib/ai/coach/facts", () => ({ storeDeterministicFacts: vi.fn() }));
vi.mock("@/lib/ai/coach/budget", () => ({
buildDateKey: vi.fn(),
reserveBudget: vi.fn(async () => ({
allowed: true,
reserved: 0,
totalAfter: 0,
})),
reconcileSpend: vi.fn(),
resolveDailyCap: vi.fn(() => 200_000),
resolveDailyCapFor: vi.fn(() => 200_000),
resolveCostOwner: vi.fn(() => "operator" as const),
}));
vi.mock("@/lib/ai/coach/refusal", () => ({ detectRefusal: vi.fn() }));
vi.mock("@/lib/ai/coach/system-prompt", () => ({
getCoachSystemPrompt: vi.fn(),
}));
vi.mock("@/lib/ai/coach/about-me", () => ({
getSelfContextTextForUser: vi.fn(),
}));
vi.mock("@/lib/ai/coach/snapshot", () => ({ buildCoachSnapshot: vi.fn() }));
vi.mock("@/lib/ai/coach/keyvalues", () => ({
parseKeyValuesSentinel: vi.fn(),
}));
vi.mock("@/lib/validations/coach-prefs", () => ({ parseCoachPrefs: vi.fn() }));
vi.mock("@/lib/sse/create-stream", () => ({ createSseStream: vi.fn() }));
import { POST, GET } from "../route";
type Envelope = {
data: unknown;
error: string | null;
status: number;
meta?: { errorCode?: string; module?: string };
};
const post = POST as unknown as (req: Request) => Promise<Envelope>;
const get = GET as unknown as (req: Request) => Promise<Envelope>;
const disabledResponse: Envelope = {
data: null,
error: 'Module "coach" is not enabled',
status: 403,
meta: { errorCode: "module.disabled", module: "coach" },
};
function chatPostReq(): Request {
return new Request("http://localhost/api/insights/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: "hi" }),
});
}
function listReq(): Request {
return new Request("http://localhost/api/insights/chat", { method: "GET" });
}
describe("coach chat module gate", () => {
beforeEach(() => {
vi.clearAllMocks();
requireAssistantSurface.mockImplementation(async () => {
throw new AssistantSentinel("reached assistant surface");
});
});
it("POST returns 403 module.disabled when Coach is disabled", async () => {
requireModuleEnabled.mockResolvedValue({
enabled: false,
response: disabledResponse,
});
const res = await post(chatPostReq());
expect(res.status).toBe(403);
expect(res.meta?.errorCode).toBe("module.disabled");
expect(res.meta?.module).toBe("coach");
expect(requireModuleEnabled).toHaveBeenCalledWith("u1", "coach");
// The gate short-circuits before the legacy assistant flag.
expect(requireAssistantSurface).not.toHaveBeenCalled();
});
it("POST falls through to the assistant flag when Coach is enabled", async () => {
requireModuleEnabled.mockResolvedValue({ enabled: true });
await expect(post(chatPostReq())).rejects.toBeInstanceOf(AssistantSentinel);
expect(requireAssistantSurface).toHaveBeenCalledWith("coach");
});
it("GET returns 403 module.disabled when Coach is disabled", async () => {
requireModuleEnabled.mockResolvedValue({
enabled: false,
response: disabledResponse,
});
const res = await get(listReq());
expect(res.status).toBe(403);
expect(res.meta?.errorCode).toBe("module.disabled");
expect(requireModuleEnabled).toHaveBeenCalledWith("u1", "coach");
expect(requireAssistantSurface).not.toHaveBeenCalled();
});
it("GET reaches 200 when Coach is enabled", async () => {
requireModuleEnabled.mockResolvedValue({ enabled: true });
requireAssistantSurface.mockResolvedValue(undefined);
const res = await get(listReq());
expect(res.status).toBe(200);
expect(requireAssistantSurface).toHaveBeenCalledWith("coach");
});
});
@@ -28,10 +28,14 @@ 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),
vi.mock("@/lib/ai/capabilities/gate", () => ({
requireAiCapability: vi.fn(async () => ({
available: true,
reason: null,
onDeviceAllowed: true,
})),
}));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number) => ({ data: null, error, status }),
@@ -26,11 +26,14 @@ 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),
vi.mock("@/lib/ai/capabilities/gate", () => ({
requireAiCapability: vi.fn(async () => ({
available: true,
reason: null,
onDeviceAllowed: true,
})),
}));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number) => ({ data: null, error, status }),
@@ -41,11 +41,14 @@ 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),
vi.mock("@/lib/ai/capabilities/gate", () => ({
requireAiCapability: vi.fn(async () => ({
available: true,
reason: null,
onDeviceAllowed: true,
})),
}));
vi.mock("@/lib/api-response", () => ({
apiError: (error: string, status: number) => ({ data: null, error, status }),
@@ -43,7 +43,6 @@ import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { Prisma } from "@/generated/prisma/client";
import { resolveCoachFeedbackAttribution } from "@/lib/ai/feedback-attribution";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
@@ -60,11 +59,8 @@ interface RouteContext {
async function handlePost(request: NextRequest, ctx: RouteContext) {
const { user } = await requireAuth();
// v1.4.38 W-C M6 — Coach message feedback is a Coach surface
// affordance; gate it on the same operator kill-switch so a
// disabled Coach matrix can't be skirted through the feedback
// endpoint.
await requireAssistantSurface("coach");
// Not AI-gated: a rating on a message that already exists is data about
// the person's own thread and calls no model.
const { id: messageId } = await ctx.params;
// Per-user rate limit — same shape as the recommendation feedback
+61 -20
View File
@@ -7,7 +7,11 @@
* and a closing `done` frame carrying the persisted message ids.
*
* Behaviour:
* 1. requireAuth() — cookie session OR bearer token (iOS app).
* 1. requireAuth() — cookie session OR bearer token (iOS app), then the
* `coach` AI capability (operator switch, the Coach module and the
* `disableCoach` opt-out, provider presence, consent). Refused with the
* capability envelope, except `no_provider`, which keeps its
* `coach.provider.none` SSE frame (now with `reason`).
* 2. Validate body with `coachChatRequestSchema`.
* 3. reserveBudget(resolveDailyCap(chain)) — 429 with
* `coach.budget.exceeded` when the day's token cap for the
@@ -41,8 +45,10 @@ import { redactOptional, redactSecrets } from "@/lib/logging/redact";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { checkRateLimit } from "@/lib/rate-limit";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { isModuleEnabled, requireModuleEnabled } from "@/lib/modules/gate";
import { isModuleEnabled } from "@/lib/modules/gate";
import { requireAiCapability } from "@/lib/ai/capabilities/gate";
import { AiUnavailableError } from "@/lib/ai/capabilities/refusal";
import type { AiUnavailableReason } from "@/lib/ai/capabilities/types";
import { resolveServerLocale } from "@/lib/i18n/server-locale";
import { getServerTranslator } from "@/lib/i18n/server-translator";
@@ -187,16 +193,38 @@ function flushTick(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}
/**
* The `coach` capability gate for a turn. Every unavailable reason throws the
* capability envelope (`assistant.disabled.coach`, `module.disabled`,
* `consent.ai.required`, `ai.record.notPermitted`, `ai.unavailable`), except
* `no_provider`: the streaming clients already read that one as the
* `coach.provider.none` SSE frame, so it keeps that wire and gains `reason`.
* Returns the frame to send, or null when the Coach is available.
*/
async function coachCapabilityRefusal(): Promise<Response | null> {
try {
await requireAiCapability("coach");
return null;
} catch (err) {
if (err instanceof AiUnavailableError && err.reason === "no_provider") {
annotate({ action: { name: "insights.coach.noProvider" } });
return streamProviderError({
code: "coach.provider.none",
reason: "no_provider",
});
}
throw err;
}
}
async function handleChatRequest(request: NextRequest): Promise<Response> {
const auth = await requireAuth();
// v1.18.0 — two-layer module gate (operator availability + per-user
// disableCoach) on top of the legacy assistant flag. 403 module.disabled.
const gate = await requireModuleEnabled(auth.user.id, "coach");
if (!gate.enabled) return gate.response;
// v1.4.31 — operator can disable the Coach surface app-wide.
// Throws AssistantDisabledError → apiHandler returns 403 +
// `errorCode: "assistant.disabled.coach"` per the iOS contract.
await requireAssistantSurface("coach");
// The `coach` capability, right after auth and before the rate limit and
// the body parse. It folds in what the Coach module gate, the operator
// switch and the `disableCoach` opt-out used to answer separately, plus
// provider presence and consent.
const refused = await coachCapabilityRefusal();
if (refused) return refused;
const userId = auth.user.id;
let body: unknown;
@@ -560,7 +588,10 @@ async function handleChatRequest(request: NextRequest): Promise<Response> {
annotate({
action: { name: "insights.coach.noProvider" },
});
return streamProviderError({ code: "coach.provider.none" });
return streamProviderError({
code: "coach.provider.none",
reason: "no_provider",
});
}
chain.push({ providerType: "admin-openai", instance: legacy });
}
@@ -579,6 +610,15 @@ async function handleChatRequest(request: NextRequest): Promise<Response> {
// as before — the snapshot builder stays alive as the no-tools floor.
const toolMode = chain.every((c) => c.instance.supportsTools !== false);
// The last check before the budget reservation and the provider call: the
// `coach` capability again, at the egress site, so the call site names its
// capability whatever happens to the gate at the top. Inside one request
// the capability inputs are memoised, so this answers from the same
// resolution as the top gate; a fresh read at the wire belongs to the
// provider chokepoints, not to this route.
const refusedAtEgress = await coachCapabilityRefusal();
if (refusedAtEgress) return refusedAtEgress;
// v1.18.7 (SENIOR-DEV HIGH) — atomically RESERVE the day's budget before
// the provider call. The reservation increments the day's total by the
// per-call ceiling (`maxTokens`) in one upsert and returns the new total;
@@ -1613,13 +1653,18 @@ async function reportCoachStreamDefect(err: unknown): Promise<void> {
}
}
function streamProviderError(args: { code: string }): Response {
function streamProviderError(args: {
code: string;
/** The capability reason, when the refusal came from one. */
reason?: AiUnavailableReason;
}): Response {
const stream = createSseStream((controller) => {
controller.enqueue(
encodeFrame({
type: "error",
code: args.code,
message: args.code,
...(args.reason ? { reason: args.reason } : {}),
}),
);
});
@@ -1662,13 +1707,9 @@ const LIST_QUERY_MAX_LEN = 200;
*/
export const GET = apiHandler(async (request: NextRequest) => {
const auth = await requireAuth();
// v1.18.0 — same two-layer module gate as the SSE POST.
const gate = await requireModuleEnabled(auth.user.id, "coach");
if (!gate.enabled) return gate.response;
// v1.4.31 — same gate as the SSE POST. Hiding the rail when
// the operator has disabled Coach matches the FAB suppression
// on the client.
await requireAssistantSurface("coach");
// Never AI-gated and never module-gated: the conversation list is the
// person's stored data. It stays readable while the Coach is unavailable
// for any reason, so every thread can be found and deleted.
const url = new URL(request.url);
const cursor = url.searchParams.get("cursor");
const limitRaw = url.searchParams.get("limit");
+6 -10
View File
@@ -11,7 +11,9 @@
* Mirrors the `/api/insights/derived` precedent: `apiHandler` wrapper, Zod
* `safeParse` on the query (unknown `metric` → 422 via `returnAllZodIssues`),
* cookie OR Bearer auth, `userId` narrowed from the session (never a query
* field), insights-module gate, and the shared analytics-read budget.
* field), and the shared analytics-read budget. No AI gate and no module
* gate: both lines are computed, and the `insights` module is the AI analysis
* opt-out.
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
@@ -19,8 +21,6 @@ import { apiError, apiSuccess, returnAllZodIssues } from "@/lib/api-response";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { checkAnalyticsReadRateLimit } from "@/lib/rate-limit";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { measurementTypeEnum } from "@/lib/validations/measurement";
import { buildCoachReadStrip } from "@/lib/insights/derived/coach-read";
import { resolveServerLocale } from "@/lib/i18n/server-locale";
@@ -37,13 +37,9 @@ export const GET = apiHandler(async (request: NextRequest) => {
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// The strip is the ambient Coach presence on the metric page, so it
// gates on the Coach assistant matrix too: an operator who turns the
// Coach off must not see a "Coach read" line linger.
await requireAssistantSurface("coach");
// Pure compute over the baseline and correlation engines. The name is
// historical: no model writes either line, so neither the Coach switch nor
// the AI analysis opt-out refuses it.
// Shared analytics-read budget — generous; caps a runaway navigation loop.
const rl = await checkAnalyticsReadRateLimit(user.id);
@@ -12,8 +12,8 @@
* convention is the idempotent-delete one used elsewhere in the tree
* (a not-found delete is a successful no-op, not a 404).
*
* Coach-gated: same `requireAssistantSurface("coach")` kill-switch as the
* collection route.
* Never AI-gated, like the collection route: deleting a stored fact keeps
* working while the Coach is unavailable.
*/
import type { NextRequest } from "next/server";
@@ -21,7 +21,6 @@ import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { prisma } from "@/lib/db";
import { requireAssistantSurface } from "@/lib/feature-flags";
interface RouteCtx {
params: Promise<{ id: string }>;
@@ -30,7 +29,6 @@ interface RouteCtx {
export const DELETE = apiHandler(
async (_request: NextRequest, ctx: RouteCtx) => {
const { user } = await requireAuth();
await requireAssistantSurface("coach");
const { id } = await ctx.params;
@@ -10,7 +10,8 @@
* returns the count.
* - [id] DELETE soft-deletes the caller's own fact, and a cross-user /
* unknown id is a 0-count no-op that returns `{ deleted: false }`.
* - the `requireAssistantSurface("coach")` gate is present on every verb.
* - no verb asks for the `coach` capability: the facts are the person's
* data, readable and erasable while the Coach is unavailable.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
@@ -28,12 +29,17 @@ vi.mock("@/lib/auth/session", () => ({
getSession: vi.fn(),
}));
// v1.4.31 — `requireAssistantSurface()` gates near the top of each
// handler. Mock the module boundary so flag reads are deterministic; the
// gate-presence assertions below verify the call is actually made.
vi.mock("@/lib/feature-flags", () => ({
requireAssistantSurface: vi.fn(async () => undefined),
AssistantDisabledError: class extends Error {},
// The capability gate answers "unavailable" throughout: every verb must
// still work, and must not even ask.
vi.mock("@/lib/ai/capabilities/gate", () => ({
requireAiCapability: vi.fn(async () => {
throw new Error("the coach capability was consulted");
}),
getAiCapability: vi.fn(async () => ({
available: false,
reason: "operator_disabled",
onDeviceAllowed: false,
})),
}));
// Mock the codec so the test never needs an encryption key. The "row"
@@ -78,7 +84,10 @@ import { GET, DELETE } from "../route";
import { DELETE as DELETE_ONE } from "../[id]/route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { requireAssistantSurface } from "@/lib/feature-flags";
import {
getAiCapability,
requireAiCapability,
} from "@/lib/ai/capabilities/gate";
import { annotate } from "@/lib/logging/context";
const SESSION_OK = {
@@ -111,7 +120,6 @@ function deleteReq(): NextRequest {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(requireAssistantSurface).mockResolvedValue(undefined as never);
});
describe("GET /api/insights/coach/facts", () => {
@@ -223,10 +231,12 @@ describe("GET /api/insights/coach/facts", () => {
});
});
it("invokes the coach assistant-surface gate", async () => {
it("lists facts while the Coach is unavailable, without asking", async () => {
vi.mocked(prisma.coachFact.findMany).mockResolvedValue([] as never);
await callGet();
expect(requireAssistantSurface).toHaveBeenCalledWith("coach");
const res = await callGet();
expect(res.status).toBe(200);
expect(requireAiCapability).not.toHaveBeenCalled();
expect(getAiCapability).not.toHaveBeenCalled();
});
});
@@ -261,12 +271,14 @@ describe("DELETE /api/insights/coach/facts — forget all", () => {
expect(body.data.cleared).toBe(0);
});
it("invokes the coach assistant-surface gate", async () => {
it("forgets everything while the Coach is unavailable, without asking", async () => {
vi.mocked(prisma.coachFact.updateMany).mockResolvedValue({
count: 0,
} as never);
await callDeleteAll();
expect(requireAssistantSurface).toHaveBeenCalledWith("coach");
const res = await callDeleteAll();
expect(res.status).toBe(200);
expect(requireAiCapability).not.toHaveBeenCalled();
expect(getAiCapability).not.toHaveBeenCalled();
});
});
@@ -316,13 +328,15 @@ describe("DELETE /api/insights/coach/facts/[id] — forget one", () => {
expect(arg.where.userId).toBe("user-1");
});
it("invokes the coach assistant-surface gate", async () => {
it("forgets one fact while the Coach is unavailable, without asking", async () => {
vi.mocked(prisma.coachFact.updateMany).mockResolvedValue({
count: 0,
} as never);
await callDeleteOne(deleteReq(), {
const res = await callDeleteOne(deleteReq(), {
params: Promise.resolve({ id: "f1" }),
});
expect(requireAssistantSurface).toHaveBeenCalledWith("coach");
expect(res.status).toBe(200);
expect(requireAiCapability).not.toHaveBeenCalled();
expect(getAiCapability).not.toHaveBeenCalled();
});
});
+4 -6
View File
@@ -14,20 +14,19 @@
* skipped rather than 500ing the whole list — the surface stays available
* for the rows that DO decrypt.
*
* Coach-gated: a fact only exists because the Coach extracted it, so the
* management surface sits behind the same `requireAssistantSurface("coach")`
* kill-switch as the rest of the Coach stack.
* Never AI-gated. The facts are the person's stored data: viewing and
* deleting them keeps working while the Coach is off for any reason (the
* operator's switch, the person's own opt-out, no provider, no consent).
* Erasure that depends on the feature being on is no erasure.
*/
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { prisma } from "@/lib/db";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { decryptFromBytes } from "@/lib/ai/coach/bytes-codec";
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
await requireAssistantSurface("coach");
const rows = await prisma.coachFact.findMany({
where: { userId: user.id, deletedAt: null },
@@ -80,7 +79,6 @@ export const GET = apiHandler(async () => {
export const DELETE = apiHandler(async () => {
const { user } = await requireAuth();
await requireAssistantSurface("coach");
// Soft-delete every active fact — keeps the rows for audit while
// hiding them from injection. `updateMany` scoped to the caller can
@@ -11,19 +11,26 @@
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
const { requireRecordAuth, evaluateContext, readStatus } = vi.hoisted(() => ({
requireRecordAuth: vi.fn(),
evaluateContext: vi.fn(async () => ({ surfaced: 0, errored: 0 })),
readStatus: vi.fn(async () => ({ unread: false, nudgedAt: null })),
}));
const { requireRecordAuth, evaluateContext, readStatus, getAiCapability } =
vi.hoisted(() => ({
requireRecordAuth: vi.fn(),
evaluateContext: vi.fn(async () => ({ surfaced: 0, errored: 0 })),
readStatus: vi.fn(
async (): Promise<{ unread: boolean; nudgedAt: string | null }> => ({
unread: false,
nudgedAt: null,
}),
),
getAiCapability: vi.fn(),
}));
const AVAILABLE = { available: true, reason: null, onDeviceAllowed: true };
vi.mock("@/lib/api-handler", () => ({
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
requireRecordAuth,
}));
vi.mock("@/lib/feature-flags", () => ({
requireAssistantSurface: vi.fn(async () => undefined),
}));
vi.mock("@/lib/ai/capabilities/gate", () => ({ getAiCapability }));
vi.mock("@/lib/ai/coach/nudge-status", () => ({
readCoachNudgeStatus: readStatus,
}));
@@ -40,6 +47,7 @@ import { GET } from "../route";
beforeEach(() => {
vi.clearAllMocks();
readStatus.mockResolvedValue({ unread: false, nudgedAt: null });
getAiCapability.mockResolvedValue(AVAILABLE);
});
describe("nudge-status — NEXT_APP_OPEN hook", () => {
@@ -93,3 +101,51 @@ describe("nudge-status — NEXT_APP_OPEN hook", () => {
}
});
});
describe("nudge-status — the coach capability", () => {
it("adds the resolved state beside the unread signal while available", async () => {
requireRecordAuth.mockResolvedValue({
user: { id: "u1" },
actor: { id: "u1" },
});
readStatus.mockResolvedValue({ unread: true, nudgedAt: "2026-07-18" });
const res = (await (GET as unknown as () => Promise<unknown>)()) as {
data: Record<string, unknown>;
};
expect(getAiCapability).toHaveBeenCalledWith("coach");
expect(res.data).toEqual({
unread: true,
nudgedAt: "2026-07-18",
ai: AVAILABLE,
});
});
it.each(["operator_disabled", "user_disabled", "no_provider"] as const)(
"answers the quiet 200 shape for %s, reading and evaluating nothing",
async (reason) => {
requireRecordAuth.mockResolvedValue({
user: { id: "u1" },
actor: { id: "u1" },
});
const ai = { available: false, reason, onDeviceAllowed: false };
getAiCapability.mockResolvedValue(ai);
const res = (await (GET as unknown as () => Promise<unknown>)()) as {
data: Record<string, unknown>;
error: null;
};
expect(res.error).toBeNull();
expect(res.data).toEqual({
nudgedAt: null,
unread: false,
conversationId: null,
ai,
});
expect(readStatus).not.toHaveBeenCalled();
expect(evaluateContext).not.toHaveBeenCalled();
},
);
});
@@ -21,10 +21,16 @@
* `nudgedAt` carries the newest assistant-message timestamp so the FAB's
* local seen-stamp keys on a stable value (kept for the existing client
* contract).
*
* A mixed read: while the `coach` capability is unavailable (operator switch,
* opt-out, no provider, no consent) the route still answers 200, with the
* quiet shape `{ unread: false, nudgedAt: null, conversationId: null }` and
* an `ai` state saying why. There is no Coach to open, so there is nothing
* unread, and no app-open reminder is evaluated.
*/
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import { readCoachNudgeStatus } from "@/lib/ai/coach/nudge-status";
import { evaluateCoachContextReminders } from "@/lib/ai/coach/context-reminders";
import { prisma } from "@/lib/db";
@@ -46,9 +52,15 @@ export const GET = apiHandler(async () => {
// budget and writes into their conversation, and reading whether the thread
// has something unopened does neither.
const { user, actor } = await requireRecordAuth("read", "record");
// Operator-level flag — an `AppSettings` singleton, unaffected by whose
// record is open.
await requireAssistantSurface("coach");
const ai = await getAiCapability("coach");
if (!ai.available) {
return apiSuccess({
nudgedAt: null,
unread: false,
conversationId: null,
ai,
});
}
// NEXT_APP_OPEN Coach reminders resolve here: this poll mounts with the
// app chrome, which makes it the app-open signal itself. Owner-only — a
@@ -67,7 +79,7 @@ export const GET = apiHandler(async () => {
// Shared with the `/coach` RSC prefetch (`src/app/coach/page.tsx`) so both
// readers compute the unread signal identically.
return apiSuccess(await readCoachNudgeStatus(user.id));
return apiSuccess({ ...(await readCoachNudgeStatus(user.id)), ai });
});
export const dynamic = "force-dynamic";
@@ -12,16 +12,15 @@ const findUniqueMock = vi.fn().mockResolvedValue({ notificationPrefs: null });
vi.mock("@/lib/db", () => ({
prisma: {
user: { findUnique: (...args: unknown[]) => findUniqueMock(...args) },
// No settings row: every assistant switch at its default (on). A switch
// read that fails now fails closed, so the row has to be readable.
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
},
}));
vi.mock("@/lib/modules/gate", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/modules/gate")>()),
requireModuleEnabled: vi.fn().mockResolvedValue({ enabled: true }),
resolveModuleMap: vi.fn().mockResolvedValue({}),
// The `coach` capability decides whether an opener is served at all; pinned
// here so the route test does not depend on the capability loader's reads.
const AVAILABLE = { available: true, reason: null, onDeviceAllowed: true };
const getAiCapability = vi.fn();
vi.mock("@/lib/ai/capabilities/gate", () => ({
getAiCapability: (...args: unknown[]) => getAiCapability(...args),
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
@@ -84,6 +83,7 @@ beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
findUniqueMock.mockResolvedValue({ notificationPrefs: null });
getAiCapability.mockResolvedValue(AVAILABLE);
});
describe("GET /api/insights/coach/seeded-question", () => {
@@ -120,8 +120,25 @@ describe("GET /api/insights/coach/seeded-question", () => {
score: 58,
band: "yellow",
});
expect(getAiCapability).toHaveBeenCalledWith("coach");
expect((body.data as { ai?: unknown }).ai).toEqual(AVAILABLE);
});
it.each(["operator_disabled", "user_disabled", "no_provider"] as const)(
"answers { signal: null, ai } for %s without running the detector",
async (reason) => {
const ai = { available: false, reason, onDeviceAllowed: false };
getAiCapability.mockResolvedValue(ai);
const res = await callGet(makeReq());
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { signal: unknown; ai: unknown };
};
expect(body.data).toEqual({ signal: null, ai });
expect(detectDerivedBriefingSignals).not.toHaveBeenCalled();
},
);
it("returns { signal: null } when nothing crosses the gate (neutral fallback)", async () => {
vi.mocked(detectDerivedBriefingSignals).mockResolvedValue(null);
const res = await callGet(makeReq());
@@ -17,14 +17,19 @@
*
* Mirrors the sibling derived routes: `apiHandler` wrapper, `requireAuth`
* (userId narrowed from the session/Bearer, never a body/query field),
* analytics-read rate limit, `insights` module gate.
* analytics-read rate limit.
*
* A mixed read: the opener only exists to open the Coach, so it is served
* only while the `coach` capability is available. Otherwise the route answers
* 200 `{ signal: null, ai }`, the same neutral shape as "nothing notable",
* with the reason beside it.
*/
import { apiError, apiSuccess } from "@/lib/api-response";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { checkAnalyticsReadRateLimit } from "@/lib/rate-limit";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import type { AiCapabilityState } from "@/lib/ai/capabilities/types";
import { prisma } from "@/lib/db";
import { loadBaselineProfile } from "@/lib/insights/derived";
import { detectDerivedBriefingSignals } from "@/lib/insights/derived-briefing";
@@ -46,17 +51,19 @@ export interface CoachSeededQuestionDTO {
/** Band — `yellow` / `red` (green never surfaces as notable). */
band: string;
} | null;
/** Whether the Coach this opener feeds is available, and why not. */
ai: AiCapabilityState;
}
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// The opener feeds the Coach hero, so it gates on the Coach assistant
// matrix: with the Coach off there is no hero to seed.
await requireAssistantSurface("coach");
// The opener feeds the Coach hero: with the Coach unavailable there is no
// hero to seed, so the neutral shape answers and says why.
const ai = await getAiCapability("coach");
if (!ai.available) {
return apiSuccess({ signal: null, ai } satisfies CoachSeededQuestionDTO);
}
const rl = await checkAnalyticsReadRateLimit(user.id);
if (!rl.allowed) {
@@ -77,7 +84,7 @@ export const GET = apiHandler(async () => {
action: { name: "coach.seeded-question.resolve" },
meta: { has_signal: false, source_metric: "none", band: "none" },
});
return apiSuccess({ signal: null } satisfies CoachSeededQuestionDTO);
return apiSuccess({ signal: null, ai } satisfies CoachSeededQuestionDTO);
}
// Profile read once via the shared loader; passed into the detector,
@@ -102,5 +109,5 @@ export const GET = apiHandler(async () => {
},
});
return apiSuccess({ signal } satisfies CoachSeededQuestionDTO);
return apiSuccess({ signal, ai } satisfies CoachSeededQuestionDTO);
});
+3 -2
View File
@@ -10,15 +10,16 @@
*
* No request body — the timestamp is server-minted from `now()` so a
* client can never backdate the stamp to suppress a future nudge.
*
* No AI gate: a timestamp on the caller's own row is data, whatever the
* Coach's availability.
*/
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { prisma } from "@/lib/db";
import { requireAssistantSurface } from "@/lib/feature-flags";
export const POST = apiHandler(async () => {
const { user } = await requireAuth();
await requireAssistantSurface("coach");
const seenAt = new Date();
await prisma.user.update({
@@ -81,16 +81,21 @@ vi.mock("@/lib/insights/comprehensive-aggregator", () => ({
}));
vi.mock("@/lib/ai/provider", () => ({
resolveProvider: vi.fn(async () => ({ type: "none" })),
probeProviderPresence: vi.fn(async () => false),
}));
// The per-request `ai` block beside the body. Pinned here so the envelope
// assertions do not depend on the capability loader's own reads.
vi.mock("@/lib/ai/capabilities/gate", () => ({
getAiCapability: vi.fn(),
}));
vi.mock("@/lib/medication-category", () => ({
getMedicationCategories: vi.fn(async () => ({})),
}));
// The route gates on the `insights` module. Mock it default-enabled so the
// envelope assertions ride through; the module-off coverage lives in the
// module route-gate inventory test.
// The route no longer gates on the `insights` module (the AI analysis
// opt-out); the mock stays so a test can prove the route never asks it.
vi.mock("@/lib/modules/gate", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/modules/gate")>()),
requireModuleEnabled: vi.fn().mockResolvedValue({ enabled: true }),
@@ -100,6 +105,8 @@ vi.mock("@/lib/modules/gate", async (importOriginal) => ({
import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import { probeProviderPresence } from "@/lib/ai/provider";
import { prisma } from "@/lib/db";
import { buildComprehensiveAggregate } from "@/lib/insights/comprehensive-aggregator";
import { checkAnalyticsReadRateLimit } from "@/lib/rate-limit";
@@ -125,6 +132,12 @@ beforeEach(() => {
vi.resetAllMocks();
// resetAllMocks drops the module gate's default; restore it.
vi.mocked(requireModuleEnabled).mockResolvedValue({ enabled: true } as never);
vi.mocked(getAiCapability).mockResolvedValue({
available: true,
reason: null,
onDeviceAllowed: true,
});
vi.mocked(probeProviderPresence).mockResolvedValue(false);
__resetAllCachesForTests();
// v1.15.20 — default to an allowing analytics-read budget.
vi.mocked(checkAnalyticsReadRateLimit).mockResolvedValue({
@@ -250,6 +263,64 @@ describe("GET /api/insights/comprehensive — envelope shape", () => {
expect(res.status).toBe(200);
});
it("answers with the AI analysis opt-out on, and publishes why the AI parts are absent", async () => {
vi.mocked(requireModuleEnabled).mockResolvedValue({
enabled: false,
response: new Response(null, { status: 403 }),
} as never);
vi.mocked(getAiCapability).mockResolvedValue({
available: false,
reason: "user_disabled",
onDeviceAllowed: false,
});
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
(buildComprehensiveAggregate as ReturnType<typeof vi.fn>).mockResolvedValue(
{
summaries: {},
bpRawRows: { sys: [], dia: [] },
weightRawRows: [],
dailyByType: {},
firstMeasurementAt: null,
totalMeasurements: 0,
},
);
const res = await callGet(makeReq());
expect(res.status).toBe(200);
expect(requireModuleEnabled).not.toHaveBeenCalled();
const body = (await res.json()) as {
data: { ai: Record<string, { reason: string }> };
};
expect(body.data.ai.briefing.reason).toBe("user_disabled");
expect(body.data.ai.statusText.reason).toBe("user_disabled");
expect(
vi
.mocked(getAiCapability)
.mock.calls.map((c) => c[0])
.sort(),
).toEqual(["briefing", "statusText"]);
});
it("reports hasProvider from the presence probe, never from building a client", async () => {
vi.mocked(probeProviderPresence).mockResolvedValue(true);
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
(buildComprehensiveAggregate as ReturnType<typeof vi.fn>).mockResolvedValue(
{
summaries: {},
bpRawRows: { sys: [], dia: [] },
weightRawRows: [],
dailyByType: {},
firstMeasurementAt: null,
totalMeasurements: 0,
},
);
const res = await callGet(makeReq());
const body = (await res.json()) as { data: { hasProvider: boolean } };
expect(body.data.hasProvider).toBe(true);
expect(probeProviderPresence).toHaveBeenCalledWith("user-comp-1");
});
it("computes BMI from aggregate WEIGHT.latest and user heightCm", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
(buildComprehensiveAggregate as ReturnType<typeof vi.fn>).mockResolvedValue(
+21 -11
View File
@@ -1,5 +1,6 @@
import { prisma } from "@/lib/db";
import { resolveProvider } from "@/lib/ai/provider";
import { probeProviderPresence } from "@/lib/ai/provider";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import { apiError, apiSuccess } from "@/lib/api-response";
import type { DataPoint, DataSummary } from "@/lib/analytics/trends";
import { summarize } from "@/lib/analytics/trends";
@@ -28,7 +29,6 @@ import {
requireRecordAuth,
type AuthContext,
} from "@/lib/api-handler";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { annotate } from "@/lib/logging/context";
import { checkAnalyticsReadRateLimit } from "@/lib/rate-limit";
import {
@@ -49,19 +49,19 @@ export const GET = apiHandler(async () => {
// v1.37.0 — MANAGE-level read: computed over the whole record, with no
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// v1.15.20 — shared analytics-read budget (generous; caps runaway loops).
const rl = await checkAnalyticsReadRateLimit(user.id);
if (!rl.allowed) {
return apiError("Too many analytics requests. Please retry later.", 429);
}
// No assistant-surface gate. Every field is computed from the record
// (the provider chain is only probed for `hasProvider`), and this is the
// main read of the Insights overview: an operator who switches the
// assistant off still gets the overview.
// No AI gate, and no `insights` module gate (that module is the AI
// analysis opt-out). Every field is computed from the record (the provider
// chain is only probed for presence, for `hasProvider`), and this is the
// main read of the Insights overview: switching AI off, or never setting a
// provider up, still gets the overview. The `ai` block beside the body says
// whether the briefing and status notes that decorate the overview can be
// shown, resolved per request and never cached with the body.
// v1.4.35 — read-through the analytics cache keyed on
// (userId, "comprehensive"). The /insights page mount routinely
@@ -94,7 +94,16 @@ export const GET = apiHandler(async () => {
annotate,
);
return apiSuccess({ ...body, revalidating: outcome === "stale" });
const [briefing, statusText] = await Promise.all([
getAiCapability("briefing"),
getAiCapability("statusText"),
]);
return apiSuccess({
...body,
revalidating: outcome === "stale",
ai: { briefing, statusText },
});
});
type AuthedUser = AuthContext["user"];
@@ -599,7 +608,8 @@ export async function buildComprehensiveResponse(user: AuthedUser) {
moodPulseScatterData,
medications: medCompliance,
alerts,
hasProvider: (await resolveProvider(userId)).type !== "none",
// Presence only: no client is built and no token is refreshed on a read.
hasProvider: await probeProviderPresence(userId),
dataSpanDays,
totalMeasurements: aggregate.totalMeasurements,
};
@@ -249,10 +249,11 @@ describe("GET /api/insights/correlations", () => {
);
});
// v1.18.0 (B2) — the route now also requires the `insights` module.
it("returns 403 + module.disabled when the insights module is off", async () => {
// The `insights` module is the AI analysis opt-out. Correlations are
// statistics, so turning AI analysis off must not take them away.
it("serves the statistics with the insights module (the AI analysis opt-out) off", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(requireModuleEnabled).mockResolvedValueOnce({
vi.mocked(requireModuleEnabled).mockResolvedValue({
enabled: false,
response: apiError('Module "insights" is not enabled', 403, {
errorCode: "module.disabled",
@@ -260,13 +261,7 @@ describe("GET /api/insights/correlations", () => {
}),
});
const res = await callGet(makeReq());
expect(res.status).toBe(403);
const body = (await res.json()) as {
meta?: { errorCode?: string; module?: string };
};
expect(body.meta?.errorCode).toBe("module.disabled");
expect(body.meta?.module).toBe("insights");
// The disabled-module request never reaches the series reads.
expect(prisma.measurement.findMany).not.toHaveBeenCalled();
expect(res.status).toBe(200);
expect(requireModuleEnabled).not.toHaveBeenCalled();
});
});
+4 -7
View File
@@ -23,7 +23,6 @@ import { apiError, apiSuccess } from "@/lib/api-response";
import { cachedSwr, caches, type ServerCache } from "@/lib/cache/server-cache";
import { annotate } from "@/lib/logging/context";
import { checkAnalyticsReadRateLimit } from "@/lib/rate-limit";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { resolveServerLocale } from "@/lib/i18n/server-locale";
import { prisma } from "@/lib/db";
import { wallClockInTz } from "@/lib/tz/wall-clock";
@@ -66,12 +65,10 @@ export const GET = apiHandler(async () => {
return apiError("Too many analytics requests. Please retry later.", 429);
}
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// No assistant switch: this is statistics, not model output. The retired
// Correlations switch gated it and nothing model-written; an operator's AI
// switches never take a computation down.
// No AI gate and no `insights` module gate: this is statistics, not model
// output. The retired Correlations switch gated it and nothing model-written;
// an operator's AI switches, and the person's AI analysis opt-out, never
// take a computation down.
// Reader's locale for the narrated `interpretation` — the correlation cards
// render this string verbatim, so it MUST be localised (cookie / User.locale /
+4 -5
View File
@@ -39,7 +39,7 @@ import {
import { resolveDeterministicAssessment } from "@/lib/insights/derived/derived-assessment";
import { resolveServerLocale } from "@/lib/i18n/server-locale";
import { instructionLocale } from "@/lib/ai/prompts/output-language";
import { requireModuleEnabled, resolveModuleMap } from "@/lib/modules/gate";
import { resolveModuleMap } from "@/lib/modules/gate";
import { DERIVED_MODULE } from "../route";
export const dynamic = "force-dynamic";
@@ -117,10 +117,9 @@ export const GET = apiHandler(async (request: NextRequest) => {
// v1.37.0 — MANAGE-level read: the deterministic batch form, no provider on
// the path.
const { user, actor } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// Same deterministic compute as the single route, so no
// assistant-surface gate.
// Same deterministic compute as the single route: no AI gate, and no
// `insights` module gate (that module is the AI analysis opt-out). Per-metric
// module ownership still applies below through `DERIVED_MODULE`.
// Per-caller limiter, same posture as the compliance routes: the cold
// build fans out up to 24 rollup walks, so an unthrottled caller could
+10 -5
View File
@@ -35,6 +35,7 @@ import {
import { DERIVED_MAX_WINDOW_DAYS } from "@/lib/insights/derived/types";
import { resolveDerivedAssessment } from "@/lib/insights/derived/derived-assessment-ai";
import { resolveServerLocale } from "@/lib/i18n/server-locale";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
export const dynamic = "force-dynamic";
@@ -88,17 +89,15 @@ export const GET = apiHandler(async (request: NextRequest) => {
// enqueues nothing while a delegate is holding the request.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// v1.15.20 — shared analytics-read budget (generous; caps runaway loops).
const rl = await checkAnalyticsReadRateLimit(user.id);
if (!rl.allowed) {
return apiError("Too many analytics requests. Please retry later.", 429);
}
// Pure compute over the rollup tier, so no assistant-surface gate:
// switching the assistant off does not blank the derived tiles.
// Pure compute over the rollup tier, so no AI gate and no `insights`
// module gate (the AI analysis opt-out): switching AI off does not blank the
// derived tiles. Only the model-written assessment below depends on AI.
const parsed = derivedQuerySchema.safeParse({
metric: request.nextUrl.searchParams.get("metric"),
@@ -159,11 +158,16 @@ export const GET = apiHandler(async (request: NextRequest) => {
userLocale: user.locale ?? null,
override: localeParam,
});
// The model-written override is served, and warmed, only while
// `statusText` is available. Otherwise the deterministic text stands and
// `ai` says why there is no warmer prose.
const ai = await getAiCapability("statusText");
const assessment = await resolveDerivedAssessment({
metric,
userId: user.id,
derived,
locale: resolvedLocale,
aiAvailable: ai.available,
});
// Flatten the discriminated union for the wire: `metric` tags it,
@@ -177,5 +181,6 @@ export const GET = apiHandler(async (request: NextRequest) => {
provenance: derived.provenance,
reason: derived.status === "insufficient" ? derived.reason : null,
assessment,
ai,
});
});
+4 -6
View File
@@ -20,15 +20,14 @@
* a verdict of its own.
*
* Mirrors the `rhythm-events` gating: `apiHandler`, cookie OR Bearer auth,
* `userId` from the session, the `insights` module gate, and the
* `insightStatus` assistant-surface gate. No AI provider call.
* `userId` from the session. No AI gate and no module gate: the strip is
* device data. No AI provider call.
*/
import { NextRequest } from "next/server";
import { apiError, apiSuccess } from "@/lib/api-response";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { prisma } from "@/lib/db";
import { decryptWaveformFromBytes } from "@/lib/withings/ecg-waveform-codec";
import {
@@ -45,9 +44,8 @@ export const GET = apiHandler(
// v1.37.0 — MANAGE-level read: computed over the whole record, with no
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// The waveform is never interpreted, so no assistant-surface gate.
// The waveform is never interpreted, so neither an AI gate nor the AI
// analysis opt-out applies.
const { id } = await params;
const full = request.nextUrl.searchParams.get("full") === "1";
+5 -11
View File
@@ -28,8 +28,9 @@
*
* Both verbs mirror the `rhythm-events` route gating exactly: `apiHandler`
* wrapper, cookie OR Bearer auth, `userId` narrowed from the session (never a
* body or query field), the `insights` module gate, and the `insightStatus`
* assistant-surface gate. No AI provider call on either path.
* body or query field). No AI gate and no module gate: a recording is device
* data, and the `insights` module is the AI analysis opt-out. An ingest is
* never refused because AI is off; the POST keeps its own rate limit.
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
@@ -42,7 +43,6 @@ import {
} from "@/lib/api-response";
import { apiHandler, requireAuth, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { checkRateLimit } from "@/lib/rate-limit";
import { prisma } from "@/lib/db";
import { persistEcgRecording } from "@/lib/ecg/persist-recording";
@@ -110,10 +110,6 @@ export const GET = apiHandler(async () => {
// keeps `requireAuth()`: a delegate's phone must never move somebody else's
// sync.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// A pure read of the device's own recordings, so no assistant-surface
// gate.
const rows = await prisma.ecgRecording.findMany({
where: { userId: user.id },
@@ -179,10 +175,8 @@ export const GET = apiHandler(async () => {
*/
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// A device ingest carries no assistant prose, so switching the assistant
// off must not refuse a recording.
// A device ingest carries no model text: switching AI off, or the AI
// analysis opt-out, must never refuse a recording.
const rl = await checkRateLimit(
`insights:ecg:ingest:${user.id}`,
@@ -23,13 +23,12 @@ vi.mock("@/lib/api-handler", () => ({
})),
}));
// v1.4.31 — `requireAssistantSurface()` is gated near the top of
// the handler. The test mocks the apiHandler wrapper itself out, so
// flag reads need a deterministic mock at the module boundary.
vi.mock("@/lib/feature-flags", () => ({
requireAssistantSurface: vi.fn(async () => undefined),
AssistantDisabledError: class extends Error {},
}));
// The `briefing` capability is required near the top of both handlers.
// The test mocks the apiHandler wrapper itself out, so the gate needs a
// deterministic mock at the module boundary: available by default, and a
// refusal where a test says so.
const requireAiCapability = vi.hoisted(() => vi.fn());
vi.mock("@/lib/ai/capabilities/gate", () => ({ requireAiCapability }));
const selfContextText = vi.hoisted(() => vi.fn<() => Promise<string | null>>());
@@ -172,9 +171,15 @@ import {
FeaturesPayloadTooLargeError,
} from "@/lib/insights/features";
import { annotate } from "@/lib/logging/context";
import { AiUnavailableError } from "@/lib/ai/capabilities/refusal";
beforeEach(() => {
vi.clearAllMocks();
requireAiCapability.mockResolvedValue({
available: true,
reason: null,
onDeviceAllowed: true,
});
// The B5b fallback runner caches "last working provider" per user
// across calls; tests that assert single-provider error mapping
// need a fresh cache so the previous test's success doesn't reorder
@@ -982,3 +987,48 @@ describe("GET /api/insights/generate — read-only advisor read", () => {
expect(body.data.hasProvider).toBe(true);
});
});
describe("the briefing capability", () => {
it.each([
["operator_disabled", 403, "assistant.disabled.briefing"],
["user_disabled", 403, "module.disabled"],
["consent_required", 403, "consent.ai.required"],
["no_provider", 422, "ai.provider.none"],
] as const)(
"GET refuses with the envelope for %s before reading the cache or warming",
async (reason, status, errorCode) => {
requireAiCapability.mockRejectedValue(
new AiUnavailableError("briefing", reason),
);
const refused = await (
GET as unknown as (req: Request) => Promise<Response>
)(new Request("http://localhost/api/insights/generate")).catch(
(err: unknown) => err,
);
expect(refused).toBeInstanceOf(AiUnavailableError);
expect((refused as AiUnavailableError).status).toBe(status);
expect((refused as AiUnavailableError).meta.errorCode).toBe(errorCode);
expect(requireAiCapability).toHaveBeenCalledWith("briefing");
// Stored briefing text is never read, and nothing is warmed.
expect(prisma.user.findUnique).not.toHaveBeenCalled();
expect(enqueueForceWarm).not.toHaveBeenCalled();
},
);
it("POST refuses before any read or provider work", async () => {
requireAiCapability.mockRejectedValue(
new AiUnavailableError("briefing", "operator_disabled"),
);
const refused = await POST(jsonRequest({ force: true }) as never).catch(
(err: unknown) => err,
);
expect(refused).toBeInstanceOf(AiUnavailableError);
expect(requireAiCapability).toHaveBeenCalledWith("briefing");
expect(prisma.user.findUnique).not.toHaveBeenCalled();
expect(prisma.user.updateMany).not.toHaveBeenCalled();
});
});
+19 -10
View File
@@ -78,7 +78,8 @@ import { isLegacyInsightPayload } from "@/lib/ai/legacy-payload";
import { checkRateLimit } from "@/lib/rate-limit";
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { requireAiCapability } from "@/lib/ai/capabilities/gate";
import { AI_PROVIDER_NONE_ERROR_CODE } from "@/lib/ai/capabilities/types";
import { invalidateUserInsights } from "@/lib/cache/invalidate";
import { annotate } from "@/lib/logging/context";
import { toProfileSex } from "@/lib/profile/sex";
@@ -139,14 +140,22 @@ export function resolveInsightsRateLimit(): number {
* cron and the "prepare assessments" button use). The next read reflects
* the fresh briefing. User-initiated regeneration stays on the POST path.
*
* A pure AI read: the payload is the model-written briefing and nothing
* else, so it keeps a typed refusal rather than answering 200 with nothing.
* The `briefing` capability is required (operator switch, the AI analysis
* opt-out, provider presence, consent); an unavailable one refuses with the
* capability envelope (`assistant.disabled.briefing`, `module.disabled`,
* `consent.ai.required`, `ai.provider.none` 422, …) before the cache is read,
* so stored briefing text is never served and no warm is enqueued.
*
* `userId` is narrowed from the session / Bearer — never a body field.
*/
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
// Same surface gate as the POST + the read-only status routes: a user
// with assessments enabled but Coach disabled still reads the cached
// briefing.
await requireAssistantSurface("coach");
// The briefing is its own capability now, not the Coach's: a user with the
// Coach hidden still reads their briefing, and one who opted out of AI
// analysis does not.
await requireAiCapability("briefing");
const userId = user.id;
const dbUser = await prisma.user.findUnique({
@@ -304,11 +313,10 @@ export const POST = apiHandler((request: NextRequest) =>
// sibling consumer) for this request.
withFeatureCacheScope(async () => {
const { user } = await requireAuth();
// v1.4.31 — the advisor + daily briefing surfaces ride this
// endpoint. Operator disables Coach, every advisor consumer
// (briefing card, recommendations grid, hero strip narration)
// empties out.
await requireAssistantSurface("coach");
// The `briefing` capability, before any read or provider work. Refused
// with the capability envelope; no provider is `ai.provider.none` on the
// 422 this route has always used for it.
await requireAiCapability("briefing");
const userId = user.id;
const dbUser = await prisma.user.findUnique({
@@ -490,6 +498,7 @@ export const POST = apiHandler((request: NextRequest) =>
return apiError(
"No AI provider configured. Connect ChatGPT in settings or ask your admin to set up an API key.",
422,
{ errorCode: AI_PROVIDER_NONE_ERROR_CODE },
);
}
chain.push({ providerType: "admin-openai", instance: legacy });
+3 -5
View File
@@ -10,7 +10,9 @@
* the rollup tier: no provider call, no fabricated value, never a diagnosis.
*
* Mirrors `/api/insights/derived`: `apiHandler` wrapper, `requireAuth`, the
* `insights` module gate, the shared analytics-read budget. `userId` is always
* shared analytics-read budget. No module gate: the drift read spans every
* vital, and the `insights` module is the AI analysis opt-out, which a
* computation does not depend on. `userId` is always
* narrowed from the session. The labels are mapped client-side from the
* MeasurementType, so the wire carries the type tokens only.
*/
@@ -18,7 +20,6 @@ import { apiError, apiSuccess } from "@/lib/api-response";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { checkAnalyticsReadRateLimit } from "@/lib/rate-limit";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { prisma } from "@/lib/db";
import { loadBaselineProfile } from "@/lib/insights/derived";
import { computeCoincidentDeviation } from "@/lib/insights/derived/coincident-deviation";
@@ -32,9 +33,6 @@ export const GET = apiHandler(async () => {
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
const rl = await checkAnalyticsReadRateLimit(user.id);
if (!rl.allowed) {
return apiError("Too many analytics requests. Please retry later.", 429);
+5 -2
View File
@@ -11,7 +11,7 @@
* about recent news, and it stops being made rather than being made about a
* years-old draw. Neutral framing only — a delta is not a diagnosis.
*
* Mirrors `/api/insights/derived`: `apiHandler`, `requireAuth`, the `insights`
* Mirrors `/api/insights/derived`: `apiHandler`, `requireAuth`, the `labs`
* module gate, the shared analytics-read budget. `userId` is narrowed from the
* session; soft-deleted rows (`deletedAt`) are filtered out.
*/
@@ -30,7 +30,10 @@ export const GET = apiHandler(async () => {
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
// Lab deltas belong to labs: with the labs module off the card hides like
// every other labs surface. Not an AI read, so the `insights` module (the
// AI analysis opt-out) does not gate it.
const m = await requireModuleEnabled(user.id, "labs");
if (!m.enabled) return m.response;
const rl = await checkAnalyticsReadRateLimit(user.id);
+26 -7
View File
@@ -10,6 +10,15 @@
*
* `userId` is narrowed from the session/Bearer (never a query field); an
* unknown `period` 422s via the closed enum.
*
* A mixed read. The narrative is data when the deterministic composer wrote
* it and model output when a provider did. Model-written text is served only
* while the `periodNarrative` capability is available; otherwise `narrative`
* is null and `ai` says why. The warm is enqueued only when the capability is
* available, or when there is no servable text at all (the worker then writes
* the deterministic narrative). The `insights` module is the AI analysis
* opt-out and is folded into the capability, so it no longer refuses the
* route.
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
@@ -18,9 +27,9 @@ import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { resolveServerLocale } from "@/lib/i18n/server-locale";
import { locales, defaultLocale, type Locale } from "@/lib/i18n/config";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import { readPeriodNarrative } from "@/lib/insights/narrative/period-narrative-generate";
import { DETERMINISTIC_PROVIDER_TYPE } from "@/lib/insights/narrative/period-narrative-deterministic";
import {
PERIOD_DAYS,
type NarrativePeriod,
@@ -57,9 +66,6 @@ export const GET = apiHandler(async (request: NextRequest) => {
// record, which is not a section a scoped grant can name. The miss behind it
// enqueues nothing while a delegate is holding the request.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
await requireAssistantSurface("insightStatus");
const parsed = narrativeQuerySchema.safeParse({
period: request.nextUrl.searchParams.get("period"),
@@ -80,10 +86,21 @@ export const GET = apiHandler(async (request: NextRequest) => {
});
const locale = narrowLocale(resolved);
const existing = await readPeriodNarrative(user.id, period, locale);
const ai = await getAiCapability("periodNarrative");
const stored = await readPeriodNarrative(user.id, period, locale);
// A row without a recorded provider is treated as model text: failing
// closed hides at most a deterministic line the next warm rewrites.
const modelWritten =
stored !== null && stored.providerType !== DETERMINISTIC_PROVIDER_TYPE;
const existing =
stored !== null && (!modelWritten || ai.available) ? stored : null;
const isFresh =
existing !== null &&
Date.now() - new Date(existing.updatedAt).getTime() < NARRATIVE_FRESH_MS;
// With AI unavailable a warm is still useful when nothing servable exists:
// it produces the deterministic narrative. A stale deterministic row is
// served as it is rather than re-warmed.
const mayWarm = ai.available || existing === null;
// Read-only: never block on the provider. Warm out of band whenever the row
// is stale / missing. The generator produces AI prose when a provider is
@@ -98,7 +115,7 @@ export const GET = apiHandler(async (request: NextRequest) => {
// The stale row is still served; only the warm is withheld.
let revalidating = false;
const generationSuppressed = delegatedGenerationSuppressed();
if (!isFresh && !generationSuppressed) {
if (!isFresh && mayWarm && !generationSuppressed) {
void enqueueNarrativeWarm({ userId: user.id, period, locale });
revalidating = true;
}
@@ -110,6 +127,7 @@ export const GET = apiHandler(async (request: NextRequest) => {
has_narrative: existing !== null,
revalidating,
generation_suppressed: generationSuppressed,
model_text_hidden: modelWritten && !ai.available,
},
});
@@ -124,5 +142,6 @@ export const GET = apiHandler(async (request: NextRequest) => {
}
: null,
revalidating,
ai,
});
});
@@ -69,16 +69,19 @@ describe("PATCH /api/insights/patterns/[id]", () => {
vi.mocked(requireModuleEnabled).mockResolvedValue({ enabled: true });
});
it("refuses a dismissal when Insights is disabled", async () => {
vi.mocked(requireModuleEnabled).mockResolvedValueOnce({
it("accepts a dismissal whatever the AI analysis opt-out says (statistics are data)", async () => {
vi.mocked(requireModuleEnabled).mockResolvedValue({
enabled: false,
response: apiError('Module "insights" is not enabled', 403),
});
const response = await PATCH(request({ dismissed: true }), params);
expect(response.status).toBe(403);
expect(prisma.correlationPattern.findFirst).not.toHaveBeenCalled();
// No such pattern in this fixture: reaching the lookup proves no module
// gate stood in front of it.
expect(response.status).toBe(404);
expect(requireModuleEnabled).not.toHaveBeenCalled();
expect(prisma.correlationPattern.findFirst).toHaveBeenCalled();
});
it("stores the current evidence as the account-scoped dismissal baseline", async () => {
@@ -13,7 +13,6 @@ import { auditLog } from "@/lib/auth/audit";
import { invalidateUserCorrelationPatterns } from "@/lib/cache/invalidate";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { updateCorrelationPatternSchema } from "@/lib/validations/correlation-patterns";
type RouteParams = { params: Promise<{ id: string }> };
@@ -26,8 +25,6 @@ export const PATCH = apiHandler(
// at no level below. The dismissal stores its own evidence hash and effect
// size, so it reads back and reverses.
const { user } = await requireRecordAuth("manage", "record");
const gate = await requireModuleEnabled(user.id, "insights");
if (!gate.enabled) return gate.response;
const parsedId = patternIdSchema.safeParse((await params).id);
if (!parsedId.success) return returnAllZodIssues(parsedId.error, 422);
const id = parsedId.data;
@@ -54,15 +54,16 @@ describe("GET /api/insights/patterns", () => {
);
});
it("refuses the list when Insights is disabled", async () => {
vi.mocked(requireModuleEnabled).mockResolvedValueOnce({
it("serves the list whatever the AI analysis opt-out says (statistics are data)", async () => {
vi.mocked(requireModuleEnabled).mockResolvedValue({
enabled: false,
response: apiError('Module "insights" is not enabled', 403),
});
const response = await GET();
expect(response.status).toBe(403);
expect(prisma.correlationPattern.findMany).not.toHaveBeenCalled();
expect(response.status).toBe(200);
expect(requireModuleEnabled).not.toHaveBeenCalled();
expect(prisma.correlationPattern.findMany).toHaveBeenCalled();
});
});
+3 -3
View File
@@ -2,7 +2,6 @@ import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { apiSuccess } from "@/lib/api-response";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { requireModuleEnabled } from "@/lib/modules/gate";
export const dynamic = "force-dynamic";
@@ -10,8 +9,9 @@ export const GET = apiHandler(async () => {
// v1.37.0 — MANAGE-level read: computed over the whole record, with no
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
const gate = await requireModuleEnabled(user.id, "insights");
if (!gate.enabled) return gate.response;
// Correlation patterns are statistics over the record's own rows. No model
// writes them, so the `insights` module (the AI analysis opt-out) does not
// gate them.
const patterns = await prisma.correlationPattern.findMany({
where: { userId: user.id, isCurrent: true },
orderBy: [{ lastComputedAt: "desc" }, { canonicalKey: "asc" }],
@@ -1,21 +1,15 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
},
}));
/**
* `POST /api/insights/pregenerate` warms two AI capabilities, `briefing` and
* `statusText`. It returns no model output, so it never refuses: with
* neither available it answers 200 `{ queued: false }` and enqueues nothing;
* with either available it enqueues (the worker checks each half). The `ai`
* block always says which half can run.
*/
// v1.18.0 — the route now resolves the `insights` module gate after
// `requireAuth()`. Mock it default-enabled so the existing assertions
// ride through; the off → 403 coverage lives in the route-gate inventory
// test.
vi.mock("@/lib/modules/gate", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/modules/gate")>()),
requireModuleEnabled: vi.fn().mockResolvedValue({ enabled: true }),
resolveModuleMap: vi.fn().mockResolvedValue({}),
}));
vi.mock("@/lib/db", () => ({ prisma: {} }));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
@@ -38,8 +32,6 @@ vi.mock("next/headers", () => ({
})),
}));
// Always allow the anti-spam bucket so the surface gate is what the test
// exercises.
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn(async () => ({ allowed: true })),
}));
@@ -49,11 +41,18 @@ vi.mock("@/lib/jobs/insight-pregenerate-shared", () => ({
enqueueForceWarm: vi.fn(async () => undefined),
}));
vi.mock("@/lib/ai/capabilities/gate", () => ({ getAiCapability: vi.fn() }));
import { POST } from "../route";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/db";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { checkRateLimit } from "@/lib/rate-limit";
import { enqueueForceWarm } from "@/lib/jobs/insight-pregenerate-shared";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import type { AiCapabilityKey } from "@/lib/ai/capabilities/types";
import {
AI_AVAILABLE,
aiUnavailable,
} from "@/__tests__/helpers/ai-capability-fixtures";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
@@ -72,57 +71,73 @@ function makeReq(): NextRequest {
});
}
function capabilities(
states: Partial<Record<AiCapabilityKey, ReturnType<typeof aiUnavailable>>>,
) {
vi.mocked(getAiCapability).mockImplementation(
async (key) => states[key] ?? AI_AVAILABLE,
);
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue(null as never);
vi.mocked(requireModuleEnabled).mockResolvedValue({ enabled: true });
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
capabilities({});
});
describe("POST /api/insights/pregenerate", () => {
it("enqueues a warm when insightStatus is enabled", async () => {
it("enqueues a warm when both halves are available", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await callPost(makeReq());
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { queued: boolean } | null;
data: { queued: boolean; ai: Record<string, unknown> } | null;
error: string | null;
};
expect(body.error).toBeNull();
expect(body.data?.queued).toBe(true);
expect(body.data?.ai).toEqual({
briefing: AI_AVAILABLE,
statusText: AI_AVAILABLE,
});
expect(enqueueForceWarm).toHaveBeenCalledWith(
expect.objectContaining({ userId: "user-1" }),
);
});
it("gates on insightStatus, not coach — a coach-disabled user can still warm", async () => {
it("enqueues when only one half is available (the worker skips the other)", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.appSettings.findUnique).mockResolvedValueOnce({
assistantEnabled: true,
assistantCoachEnabled: false,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: true,
assistantDocumentAiEnabled: true,
} as never);
capabilities({ briefing: aiUnavailable("operator_disabled") });
const res = await callPost(makeReq());
expect(res.status).toBe(200);
expect(enqueueForceWarm).toHaveBeenCalledTimes(1);
});
it("403s + errorCode when insightStatus is disabled", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.appSettings.findUnique).mockResolvedValueOnce({
assistantEnabled: true,
assistantCoachEnabled: true,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: false,
assistantDocumentAiEnabled: true,
} as never);
const res = await callPost(makeReq());
expect(res.status).toBe(403);
const body = (await res.json()) as { meta?: { errorCode?: string } };
expect(body.meta?.errorCode).toBe("assistant.disabled.insightStatus");
expect(enqueueForceWarm).not.toHaveBeenCalled();
});
it.each([
"operator_disabled",
"user_disabled",
"no_provider",
"consent_required",
] as const)(
"answers 200 { queued: false } and enqueues nothing when neither half is available (%s)",
async (reason) => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
capabilities({
briefing: aiUnavailable(reason),
statusText: aiUnavailable(reason),
});
const res = await callPost(makeReq());
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { queued: boolean; ai: { briefing: { reason: string } } };
};
expect(body.data.queued).toBe(false);
expect(body.data.ai.briefing.reason).toBe(reason);
expect(enqueueForceWarm).not.toHaveBeenCalled();
// Nothing to warm, so no anti-spam bucket is spent either.
expect(checkRateLimit).not.toHaveBeenCalled();
},
);
it("401s when unauthenticated", async () => {
vi.mocked(getSession).mockResolvedValue(null);
+35 -17
View File
@@ -21,12 +21,18 @@
* `userId` is always narrowed from the session / Bearer — never a body
* field. Both web and the iOS client can call it; they read the same
* cached routes afterward.
*
* The warm covers two AI capabilities: `briefing` (the comprehensive
* insight) and `statusText` (the assessment cards). It returns no model
* output, so it never refuses: with neither capability available it answers
* 200 `{ queued: false }` and enqueues nothing; with one available it
* enqueues, and the worker checks each half before it builds anything. The
* `ai` block says which half can run.
*/
import { NextRequest } from "next/server";
import { apiSuccess, apiError } from "@/lib/api-response";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import { checkRateLimit } from "@/lib/rate-limit";
import { annotate } from "@/lib/logging/context";
import { resolveServerLocale } from "@/lib/i18n/server-locale";
@@ -40,21 +46,12 @@ const WARM_WINDOW_MS = 3 * 60 * 1000;
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// Gate on the same surface as the read-only status routes: this warms
// the assessment cards (the `insightStatus` surface), not the Coach.
// A user with assessments enabled but Coach disabled can still warm.
await requireAssistantSurface("insightStatus");
const userId = user.id;
// Short per-user bucket so the bypassed nightly budget can't be abused
// into a provider-cost amplifier by a tight POST loop. A blocked call
// is harmless — the caches are already being warmed by the prior call.
const rl = await checkRateLimit(`insights-warm:${userId}`, 1, WARM_WINDOW_MS);
if (!rl.allowed) {
return apiError("A warm is already in progress. Try again shortly.", 429);
}
const [briefing, statusText] = await Promise.all([
getAiCapability("briefing"),
getAiCapability("statusText"),
]);
const ai = { briefing, statusText };
const resolved = await resolveServerLocale({
request,
@@ -65,6 +62,27 @@ export const POST = apiHandler(async (request: NextRequest) => {
// German warm, so the whole warmed cache family was in the wrong language.
const locale = normalizeLocale(resolved);
// Nothing this warm covers can run: enqueue nothing, spend no bucket.
if (!briefing.available && !statusText.available) {
annotate({
action: { name: "insights.pregenerate.skipped" },
meta: {
locale,
briefing_reason: briefing.reason,
status_reason: statusText.reason,
},
});
return apiSuccess({ queued: false, locale, ai });
}
// Short per-user bucket so the bypassed nightly budget can't be abused
// into a provider-cost amplifier by a tight POST loop. A blocked call
// is harmless — the caches are already being warmed by the prior call.
const rl = await checkRateLimit(`insights-warm:${userId}`, 1, WARM_WINDOW_MS);
if (!rl.allowed) {
return apiError("A warm is already in progress. Try again shortly.", 429);
}
await enqueueForceWarm({ userId, locale });
annotate({
@@ -74,5 +92,5 @@ export const POST = apiHandler(async (request: NextRequest) => {
// The work runs on the worker; report that it was accepted, not that it
// is done. The client polls the read-only status GETs for the text.
return apiSuccess({ queued: true, locale });
return apiSuccess({ queued: true, locale, ai });
});
+3 -4
View File
@@ -8,7 +8,9 @@
* all history.
*
* Cookie OR Bearer auth via `requireAuth()`; `userId` is narrowed from the
* resolved session — never a body field. Gated on the `insights` module. The
* resolved session — never a body field. Pulse is a core vital, so no module
* gates it; the `insights` module is the AI analysis opt-out, and this read
* calls no model. The
* `date` defaults to the user's local today; anything but a `YYYY-MM-DD`
* literal is a 422 via `returnAllZodIssues`. The frontend day navigator
* pages this same route backward through prior days — a day outside
@@ -20,7 +22,6 @@ import { z } from "zod";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { apiSuccess, returnAllZodIssues } from "@/lib/api-response";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { NO_STORE_BUT_BFCACHE } from "@/lib/http/cache-headers";
import { resolveUserTimezone } from "@/lib/tz/resolver";
import { userDayKey } from "@/lib/tz/format";
@@ -40,8 +41,6 @@ export const GET = apiHandler(async (req: Request) => {
// v1.37.0 — MANAGE-level read: computed over the whole record, with no
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
const url = new URL(req.url);
const parsed = querySchema.safeParse({
+5 -6
View File
@@ -21,13 +21,12 @@
*
* Follows the `metric-status` / `derived` route precedent: `apiHandler`
* wrapper, cookie OR Bearer auth, `userId` narrowed from the session
* (never a query field), the `insightStatus` assistant-surface gate (no AI
* provider call — this is a pure DB read).
* (never a query field). No AI gate and no module gate: this is a pure DB
* read of device data.
*/
import { apiSuccess } from "@/lib/api-response";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { prisma } from "@/lib/db";
import { EVENT_MEASUREMENT_TYPES } from "@/lib/validations/measurement";
import type { MeasurementType } from "@/generated/prisma/client";
@@ -46,9 +45,9 @@ export const GET = apiHandler(async () => {
// v1.37.0 — MANAGE-level read: computed over the whole record, with no
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
const m = await requireModuleEnabled(user.id, "insights");
if (!m.enabled) return m.response;
// A pure read of the device's own verdicts, so no assistant-surface gate.
// A pure read of the device's own verdicts: no AI gate and no module gate.
// The `insights` module is the AI analysis opt-out, and nothing here was
// written by a model.
const rows = await prisma.measurement.findMany({
where: {
@@ -505,15 +505,15 @@ describe("GET /api/user/ai-provider — the shared-provider offer", () => {
},
);
it("never offers when the operator switched the assistant surfaces off", async () => {
it("never offers when the operator switched off everything the consent would unlock", async () => {
serverManaged();
vi.mocked(readServerProviderHealth).mockResolvedValue("healthy");
vi.mocked(getAssistantFlags).mockResolvedValue({
enabled: true,
coach: false,
briefing: true,
briefing: false,
insightStatus: true,
documentAi: true,
documentAi: false,
});
await expect(read()).resolves.toMatchObject({
serverProviderHealth: "healthy",
@@ -521,6 +521,41 @@ describe("GET /api/user/ai-provider — the shared-provider offer", () => {
});
});
it.each(["coach", "briefing", "documentAi"] as const)(
"still offers while the operator keeps %s on",
async (open) => {
serverManaged();
vi.mocked(readServerProviderHealth).mockResolvedValue("healthy");
vi.mocked(getAssistantFlags).mockResolvedValue({
enabled: true,
coach: false,
briefing: false,
insightStatus: false,
documentAi: false,
[open]: true,
});
await expect(read()).resolves.toMatchObject({
serverProviderOffer: true,
});
},
);
it("reports no AI available while the operator's master switch is off, whatever is configured", async () => {
serverManaged();
vi.mocked(getAssistantFlags).mockResolvedValue({
enabled: false,
coach: false,
briefing: false,
insightStatus: false,
documentAi: false,
});
await expect(read()).resolves.toMatchObject({
aiAvailable: false,
managedBy: "server",
serverProviderOffer: false,
});
});
it("never offers to a managed profile — a child's record does not consent for itself", async () => {
serverManaged();
vi.mocked(readServerProviderHealth).mockResolvedValue("healthy");
+20 -4
View File
@@ -53,7 +53,17 @@ export const GET = apiHandler(async () => {
// no personal provider. iOS keys its Coach visibility off `aiAvailable` so
// a server-managed provider is no longer invisible to the client.
// `managedBy` reports the origin only; no admin keys/endpoints are leaked.
const { aiAvailable, managedBy } = await resolveProviderAvailability(user.id);
//
// The operator's master switch is part of the answer: with every AI
// capability switched off there is no AI available, whatever is
// configured, so a native client that keys on this field hides its AI
// surfaces. The switches fail closed (a read error reads as all off).
const [presence, assistantFlags] = await Promise.all([
resolveProviderAvailability(user.id),
getAssistantFlags(),
]);
const aiAvailable = presence.aiAvailable && assistantFlags.enabled;
const { managedBy } = presence;
// ── v1.38.19 — the shared provider, honestly ────────────────
// `managedBy: "server"` says the operator configured a key. It has never
@@ -77,7 +87,6 @@ export const GET = apiHandler(async () => {
user.id,
"coach",
);
const assistantFlags = await getAssistantFlags();
// `personal`, not merely "not deny": a guardian's own record resolves to
// `personal`, while a managed profile resolves to `operator-default` —
// its provider is the operator's by definition, and a child's record does
@@ -93,13 +102,20 @@ export const GET = apiHandler(async () => {
// one visitor minted would turn the operator's provider on for every later
// one. A button that can only 403 into a generic toast is precisely the
// misleading failure this surface exists to remove, so there is no button.
//
// The offer is worth making while any capability it would unlock is
// switched on by the operator: the Coach, the briefing, or reading
// documents. With all three off there is nothing for the consent to open.
const demoInstance = process.env.DEMO_MODE === "true";
const offerUnlocksSomething =
assistantFlags.coach ||
assistantFlags.briefing ||
assistantFlags.documentAi;
const serverProviderOffer =
!demoInstance &&
managedBy === "server" &&
serverProviderHealth === "healthy" &&
assistantFlags.enabled &&
assistantFlags.coach &&
offerUnlocksSomething &&
credentialPolicy === "personal" &&
!serverProviderConsent;
+11 -4
View File
@@ -29,7 +29,8 @@ import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiError, apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { pickCanonicalWorkoutRows } from "@/lib/measurements/pick-canonical-workout-rows";
import { isModuleEnabled, requireModuleEnabled } from "@/lib/modules/gate";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import { getAgeFromDateOfBirth } from "@/lib/analytics/pulse-targets";
import { decryptFromBytes } from "@/lib/ai/coach/bytes-codec";
import { buildWorkoutHrSeries } from "@/lib/workouts/hr-series";
@@ -60,7 +61,11 @@ export const GET = apiHandler(
// v1.18.0 B1 — gate the detail surface behind the workouts module.
const gate = await requireModuleEnabled(user.id, "workouts");
if (!gate.enabled) return gate.response;
const insightsEnabled = await isModuleEnabled(user.id, "insights");
// The stored Activity Insight paragraph is model text: it is read and
// served only while `workoutInsights` is available (operator switch, the
// AI analysis opt-out, provider presence, consent). Otherwise the row is
// not even loaded, `aiInsight` is null, and `ai` says why.
const ai = await getAiCapability("workoutInsights");
const row = await prisma.workout.findUnique({
where: { id },
@@ -79,7 +84,7 @@ export const GET = apiHandler(
sampleCount: true,
},
},
insight: insightsEnabled
insight: ai.available
? {
select: { paragraphEncrypted: true, generatedAt: true },
}
@@ -282,7 +287,7 @@ export const GET = apiHandler(
// undecryptable paragraph degrades to no card, exactly like a workout that
// never had one.
let aiInsight: { paragraph: string; generatedAt: string } | null = null;
if (insightsEnabled && row.insight) {
if (ai.available && row.insight) {
try {
aiInsight = {
paragraph: decryptFromBytes(row.insight.paragraphEncrypted),
@@ -331,6 +336,8 @@ export const GET = apiHandler(
// re-synced one, every one on a provider-less install) serves null and
// the page's `{aiInsight ? <card/> : null}` renders nothing.
aiInsight,
// Whether the Activity Insight can be shown, and why not.
ai,
// v1.4.32 — when the requested id is a non-canonical twin the
// caller can redirect to `canonicalId` to land on the cluster
// winner. `canonicalId === id` when the requested row already
+40 -20
View File
@@ -60,14 +60,21 @@ vi.mock("@/lib/modules/gate", async (importOriginal) => {
...actual,
resolveModuleMap: vi.fn(async () => ({})),
requireModuleEnabled: vi.fn(async () => ({ enabled: true })),
isModuleEnabled: vi.fn(async () => true),
};
});
// The Activity Insight paragraph follows the `workoutInsights` capability.
vi.mock("@/lib/ai/capabilities/gate", () => ({ getAiCapability: vi.fn() }));
import { GET } from "../[id]/route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import { isModuleEnabled, requireModuleEnabled } from "@/lib/modules/gate";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { getAiCapability } from "@/lib/ai/capabilities/gate";
import {
AI_AVAILABLE,
aiUnavailable,
} from "@/__tests__/helpers/ai-capability-fixtures";
import { invalidateUserTimezone } from "@/lib/tz/resolver";
const SESSION_OK = {
@@ -139,7 +146,7 @@ describe("GET /api/workouts/{id}", () => {
vi.mocked(requireModuleEnabled).mockResolvedValue({
enabled: true,
} as never);
vi.mocked(isModuleEnabled).mockResolvedValue(true);
vi.mocked(getAiCapability).mockResolvedValue(AI_AVAILABLE);
// The timezone resolver caches per user for 60 s in process; drop the
// entry so a test that pins a zone is not served the previous one.
invalidateUserTimezone(SESSION_OK.user.id);
@@ -565,6 +572,7 @@ describe("GET /api/workouts/{id} — aiInsight", () => {
vi.clearAllMocks();
vi.stubEnv("ENCRYPTION_KEY", TEST_KEY);
_resetCryptoCacheForTests();
vi.mocked(getAiCapability).mockResolvedValue(AI_AVAILABLE);
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
sourcePriorityJson: null,
@@ -616,26 +624,38 @@ describe("GET /api/workouts/{id} — aiInsight", () => {
paragraph: "A steady, aerobic-leaning run.",
generatedAt: generatedAt.toISOString(),
});
expect(getAiCapability).toHaveBeenCalledWith("workoutInsights");
expect(body.data.ai).toEqual(AI_AVAILABLE);
});
it("does not read or expose the stored paragraph when Insights is disabled", async () => {
vi.mocked(isModuleEnabled).mockResolvedValueOnce(false);
vi.mocked(prisma.workout.findUnique).mockResolvedValue({
...BASE_ROW,
insight: {
paragraphEncrypted: new Uint8Array([1, 2, 3]),
generatedAt: new Date(`${SESSION_DAY}T07:35:00Z`),
},
} as never);
it.each([
"operator_disabled",
"user_disabled",
"module_disabled",
"consent_required",
"no_provider",
] as const)(
"does not read or expose the stored paragraph while workoutInsights is %s",
async (reason) => {
vi.mocked(getAiCapability).mockResolvedValue(aiUnavailable(reason));
vi.mocked(prisma.workout.findUnique).mockResolvedValue({
...BASE_ROW,
insight: {
paragraphEncrypted: new Uint8Array([1, 2, 3]),
generatedAt: new Date(`${SESSION_DAY}T07:35:00Z`),
},
} as never);
const body = await (await get()).json();
expect(body.data.aiInsight).toBeNull();
expect(prisma.workout.findUnique).toHaveBeenCalledWith(
expect.objectContaining({
include: expect.objectContaining({ insight: false }),
}),
);
});
const body = await (await get()).json();
expect(body.data.aiInsight).toBeNull();
expect(body.data.ai).toEqual(aiUnavailable(reason));
expect(prisma.workout.findUnique).toHaveBeenCalledWith(
expect.objectContaining({
include: expect.objectContaining({ insight: false }),
}),
);
},
);
it("degrades to no card rather than failing the page on an undecryptable row", async () => {
// `decrypt` is fail-closed by design. A key rotated away must not turn the