mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
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:
1 parent
f434ba7d29
commit
3309ac177c
104 files changed
+3299
-1636
No files matched your search
@@ -2,8 +2,14 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { insightsPaths } from "../routes/insights/paths";
|
||||
|
||||
describe("insight patterns module gate OpenAPI contract", () => {
|
||||
it("documents module.disabled for list and dismissal updates", () => {
|
||||
/**
|
||||
* Correlation patterns are statistics, not model output. The `insights`
|
||||
* module is the AI analysis opt-out, so it no longer gates them, and the
|
||||
* contract must not promise a `module.disabled` refusal the routes never
|
||||
* send. The 403 that remains is the sharing fence.
|
||||
*/
|
||||
describe("insight patterns OpenAPI contract", () => {
|
||||
it("documents the sharing refusal and no module refusal for list and dismissal updates", () => {
|
||||
const listResponses =
|
||||
insightsPaths["/api/insights/patterns"]?.get?.responses;
|
||||
const updateResponses =
|
||||
@@ -11,7 +17,9 @@ describe("insight patterns module gate OpenAPI contract", () => {
|
||||
|
||||
for (const responses of [listResponses, updateResponses]) {
|
||||
expect(Object.keys(responses ?? {})).toContain("403");
|
||||
expect(responses?.["403"]?.description).toContain("module.disabled");
|
||||
const description = responses?.["403"]?.description ?? "";
|
||||
expect(description).toContain("sharing.access.denied");
|
||||
expect(description).not.toContain("module.disabled");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* The published wording for an AI capability refusal, shared by every
|
||||
* operation that asks `requireAiCapability`.
|
||||
*
|
||||
* One envelope, three statuses: 403 for the operator, record, module, opt-out
|
||||
* and consent reasons; 422 for a missing provider (unless the route keeps a
|
||||
* typed code of its own); 503 when the capability could not be resolved. The
|
||||
* mapping from reason to `meta.errorCode` is written once on `ErrorEnvelope`
|
||||
* (`meta.reason`); these strings name the capability and point there.
|
||||
*/
|
||||
import {
|
||||
AI_CAPABILITIES,
|
||||
type AiCapabilityKey,
|
||||
} from "@/lib/ai/capabilities/types";
|
||||
|
||||
import { errorEnvelope } from "./shared";
|
||||
|
||||
/** The 403 sentence for one capability. */
|
||||
export function aiRefusal403Description(key: AiCapabilityKey): string {
|
||||
const operatorSwitch = AI_CAPABILITIES[key].operatorSwitch;
|
||||
return `The \`${key}\` AI capability is unavailable for this record. \`meta.capability\` = \`${key}\` and \`meta.reason\` says which layer refused: the operator's switch (\`assistant.disabled.${operatorSwitch}\`, or \`assistant.disabled.enabled\` for the master switch), an owning module or the person's own AI opt-out (\`module.disabled\` with \`meta.module\`), a delegate inside somebody else's record (\`ai.record.notPermitted\`), or a missing consent receipt (\`consent.ai.required\`). Nothing was generated, read from a stored model answer, or enqueued.`;
|
||||
}
|
||||
|
||||
/** The 422 a capability answers when no provider can serve it. */
|
||||
export function aiNoProviderResponse(key: AiCapabilityKey) {
|
||||
return {
|
||||
description: `No configured AI provider can serve the \`${key}\` capability: \`meta.errorCode\` = \`ai.provider.none\`, \`meta.reason\` = \`no_provider\`.`,
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
};
|
||||
}
|
||||
|
||||
/** The 503 every capability answers when its inputs could not be read. */
|
||||
export const aiCheckFailedResponse = {
|
||||
description:
|
||||
"The AI capability could not be resolved (its inputs could not be read) and the answer failed closed: `meta.errorCode` = `ai.unavailable`, `meta.reason` = `check_failed`. Retry later; no data depends on it.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
};
|
||||
@@ -58,6 +58,8 @@ import {
|
||||
recordRefusal,
|
||||
stdResponses,
|
||||
} from "./shared";
|
||||
import { aiCheckFailedResponse, aiRefusal403Description } from "./ai-refusal";
|
||||
import { aiCapabilityState } from "./profile";
|
||||
|
||||
// The assigning form, deliberately: `schema.meta({...})` as a bare statement
|
||||
// returns a clone and registers nothing, so the component id would never
|
||||
@@ -738,7 +740,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "List the caller's Coach conversations",
|
||||
description:
|
||||
'v1.18.0 — cursor-paginated list of the caller\'s Coach conversations for the history rail, most-recent activity first. Metadata only (id, title, timestamps, message count); message bodies are not decrypted here. `limit` defaults to 20, capped at 50; pass the returned `nextCursor` back as `cursor` for the next page (null at the end). v1.30.2 — optional `q` narrows the page to conversations whose TITLE contains the text (case-insensitive substring, capped at 200 chars); message bodies are encrypted at rest and are not searched. Coach-gated (`requireAssistantSurface("coach")`); a disabled surface 403s. Auth via cookie or Bearer; the owner is narrowed from the session.',
|
||||
"v1.18.0 — cursor-paginated list of the caller's Coach conversations for the history rail, most-recent activity first. Metadata only (id, title, timestamps, message count); message bodies are not decrypted here. `limit` defaults to 20, capped at 50; pass the returned `nextCursor` back as `cursor` for the next page (null at the end). v1.30.2 — optional `q` narrows the page to conversations whose TITLE contains the text (case-insensitive substring, capped at 200 chars); message bodies are encrypted at rest and are not searched. Never AI-gated: stored conversations are the person's data and stay listable, readable and deletable while the Coach is unavailable for any reason. Auth via cookie or Bearer; the owner is narrowed from the session.",
|
||||
parameters: [
|
||||
{
|
||||
name: "cursor",
|
||||
@@ -783,7 +785,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Send a Coach turn (streaming reply)",
|
||||
description:
|
||||
"v1.18.0 — sends a user turn and streams the assistant reply as Server-Sent Events. The response is `text/event-stream`, not JSON: one `data: <json>\\n\\n` frame per event. Frame `type` is one of `token` (a chunk of reply text: `{ type, token }`), `provenance` (the evidence envelope: `{ type, metricSource }`), `suggestion` (a cadence-suggestion card: `{ type, suggestion }`), `reasoning` (v1.18.9, optional reasoning-summary text: `{ type, text }` — emitted only by reasoning-capable providers; absent otherwise), `done` (`{ type, conversationId, messageId, usage? }` — v1.18.9 adds the optional `usage` envelope `{ totalTokens, promptTokens?, completionTokens?, model? }`, server-authoritative; clients display it, never recompute), or `error` (`{ type, code, message }`). The HTTP status is 200 even for a provider/refusal outcome — clients dispatch on the `error` frame, not the status. Clients ignore unknown frame types (additive evolution). Omitting `conversationId` starts a new conversation. Coach-gated; budget- and rate-limited. Auth via cookie or Bearer.",
|
||||
'v1.18.0 — sends a user turn and streams the assistant reply as Server-Sent Events. The response is `text/event-stream`, not JSON: one `data: <json>\\n\\n` frame per event. Frame `type` is one of `token` (a chunk of reply text: `{ type, token }`), `provenance` (the evidence envelope: `{ type, metricSource }`), `suggestion` (a cadence-suggestion card: `{ type, suggestion }`), `reasoning` (v1.18.9, optional reasoning-summary text: `{ type, text }` — emitted only by reasoning-capable providers; absent otherwise), `done` (`{ type, conversationId, messageId, usage? }` — v1.18.9 adds the optional `usage` envelope `{ totalTokens, promptTokens?, completionTokens?, model? }`, server-authoritative; clients display it, never recompute), or `error` (`{ type, code, message, reason? }`). The HTTP status is 200 even for a provider/refusal outcome — clients dispatch on the `error` frame, not the status. Clients ignore unknown frame types (additive evolution). Omitting `conversationId` starts a new conversation. Requires the `coach` AI capability, checked right after auth: an unavailable Coach is refused with the capability envelope before the stream opens, except a missing provider, which keeps its `coach.provider.none` error frame and adds `reason: "no_provider"`. Budget- and rate-limited. Auth via cookie or Bearer.',
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
@@ -805,14 +807,14 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
"403": {
|
||||
description:
|
||||
"Coach surface disabled (`errorCode: assistant.disabled.coach`) or AI consent required (`errorCode: consent.ai.required`).",
|
||||
description: aiRefusal403Description("coach"),
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"413": {
|
||||
description: "Request body exceeds the 64 KB cap.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"503": aiCheckFailedResponse,
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
@@ -822,7 +824,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Read one Coach conversation with all messages",
|
||||
description:
|
||||
"v1.18.0 — returns one conversation with every message decrypted server-side and ordered oldest-first, plus the rolling `summary` when one is on file. The client renders the bodies directly; no decryption key is involved. A foreign / unknown id maps to 404 (never 403) so the existence channel does not leak across accounts. Coach-gated. Auth via cookie or Bearer.",
|
||||
"v1.18.0 — returns one conversation with every message decrypted server-side and ordered oldest-first, plus the rolling `summary` when one is on file. The client renders the bodies directly; no decryption key is involved. A foreign / unknown id maps to 404 (never 403) so the existence channel does not leak across accounts. Never AI-gated: a stored conversation stays readable while the Coach is unavailable. Auth via cookie or Bearer.",
|
||||
parameters: [
|
||||
{
|
||||
name: "id",
|
||||
@@ -855,7 +857,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Rename one Coach conversation",
|
||||
description:
|
||||
"Sets the conversation's title. The only field this verb writes — the body is `.strict()`, so an unrecognised key is REFUSED rather than ignored, unlike most partial updates on this surface. The title is trimmed and must be 1..80 characters after trimming. A foreign or unknown id maps to 404 (never 403), so the existence channel does not leak across accounts. Coach-gated. Auth via cookie or Bearer; the caller is always resolved as themselves, so a conversation in a shared record is not reachable here.",
|
||||
"Sets the conversation's title. The only field this verb writes — the body is `.strict()`, so an unrecognised key is REFUSED rather than ignored, unlike most partial updates on this surface. The title is trimmed and must be 1..80 characters after trimming. A foreign or unknown id maps to 404 (never 403), so the existence channel does not leak across accounts. Never AI-gated. Auth via cookie or Bearer; the caller is always resolved as themselves, so a conversation in a shared record is not reachable here.",
|
||||
parameters: [
|
||||
{
|
||||
name: "id",
|
||||
@@ -901,7 +903,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Delete one Coach conversation",
|
||||
description:
|
||||
"v1.18.0 — hard-deletes a conversation and every message under it. A foreign / unknown id maps to 404 (never 403). Coach-gated. Auth via cookie or Bearer.",
|
||||
"v1.18.0 — hard-deletes a conversation and every message under it. A foreign / unknown id maps to 404 (never 403). Never AI-gated: erasure works while the Coach is unavailable. Auth via cookie or Bearer.",
|
||||
parameters: [
|
||||
{
|
||||
name: "id",
|
||||
@@ -1119,7 +1121,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "List the caller's durable Coach facts",
|
||||
description:
|
||||
"v1.11.1 — returns the active facts the Coach has extracted about the caller (highest-confidence then newest first), each decrypted on the fly. The GDPR 'what do you know about me' surface. Coach-gated (`requireAssistantSurface(\"coach\")`). Auth via cookie or Bearer; the owner is always narrowed from the session, never the body. Undecryptable rows are omitted rather than failing the read.",
|
||||
"v1.11.1 — returns the active facts the Coach has extracted about the caller (highest-confidence then newest first), each decrypted on the fly. The GDPR 'what do you know about me' surface. Never AI-gated: the facts stay readable and erasable while the Coach is unavailable for any reason. Auth via cookie or Bearer; the owner is always narrowed from the session, never the body. Undecryptable rows are omitted rather than failing the read.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The caller's active facts.",
|
||||
@@ -1136,7 +1138,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Forget all of the caller's Coach facts",
|
||||
description:
|
||||
"v1.11.1 — bulk 'forget what you know about me': soft-deletes every active fact for the caller and returns the count cleared. Idempotent (a second call clears 0). Coach-gated. Auth via cookie or Bearer.",
|
||||
"v1.11.1 — bulk 'forget what you know about me': soft-deletes every active fact for the caller and returns the count cleared. Idempotent (a second call clears 0). Never AI-gated. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "All active facts cleared; the count is returned.",
|
||||
@@ -1158,7 +1160,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Forget one Coach fact",
|
||||
description:
|
||||
"v1.11.1 — soft-deletes a single fact owned by the caller. An unknown / cross-user / already-deleted id is an idempotent no-op returning `{ deleted: false }`, never revealing whether the id exists under another account. Coach-gated. Auth via cookie or Bearer.",
|
||||
"v1.11.1 — soft-deletes a single fact owned by the caller. An unknown / cross-user / already-deleted id is an idempotent no-op returning `{ deleted: false }`, never revealing whether the id exists under another account. Never AI-gated. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
"200": {
|
||||
description:
|
||||
@@ -1181,7 +1183,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Whether an unopened Coach message is waiting",
|
||||
description:
|
||||
'v1.18.6 (CCH-03) — server-authoritative unread signal for the Coach FAB. `unread` is true when the caller\'s newest Coach ASSISTANT message (a proactive nudge or any reply) is newer than `User.coachLastSeenAt`; a user who has never opened the Coach reads an existing nudge as unread exactly once. `nudgedAt` carries that newest assistant-message timestamp (null when none exists) so the client can key a local seen-mirror on a stable value. Coach-gated (`requireAssistantSurface("coach")`); a disabled surface 403s. Auth via cookie or Bearer; the owner is narrowed from the session.',
|
||||
"v1.18.6 (CCH-03) — server-authoritative unread signal for the Coach FAB. `unread` is true when the caller's newest Coach ASSISTANT message (a proactive nudge or any reply) is newer than `User.coachLastSeenAt`; a user who has never opened the Coach reads an existing nudge as unread exactly once. `nudgedAt` carries that newest assistant-message timestamp (null when none exists) so the client can key a local seen-mirror on a stable value. Never refused for an AI reason: while the `coach` capability is unavailable the answer is the quiet `{ unread: false, nudgedAt: null, conversationId: null }` with `ai` saying why. Auth via cookie or Bearer; the owner is narrowed from the session.",
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
@@ -1207,6 +1209,9 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
.describe(
|
||||
"Conversation holding the newest assistant message; null when none exists. The client deep-links into it (`/coach?c=<id>`) on the unread path.",
|
||||
),
|
||||
ai: aiCapabilityState.describe(
|
||||
"The `coach` capability. While unavailable the three fields above are the quiet empty values.",
|
||||
),
|
||||
}),
|
||||
"CoachNudgeStatus",
|
||||
),
|
||||
@@ -1222,7 +1227,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Mark the Coach as opened (clear the unread dot)",
|
||||
description:
|
||||
"v1.18.6 (CCH-03) — opening the Coach (drawer or full page) stamps `User.coachLastSeenAt = now()`, so `GET /api/insights/coach/nudge-status` then reports no assistant message newer than the stamp and the FAB drops the unread dot. Server-authoritative, so the cleared state follows the caller across web + iOS rather than just the opening device. No request body — the timestamp is server-minted, so a client can never backdate the stamp to suppress a future nudge. Coach-gated; a disabled surface 403s. Auth via cookie or Bearer.",
|
||||
"v1.18.6 (CCH-03) — opening the Coach (drawer or full page) stamps `User.coachLastSeenAt = now()`, so `GET /api/insights/coach/nudge-status` then reports no assistant message newer than the stamp and the FAB drops the unread dot. Server-authoritative, so the cleared state follows the caller across web + iOS rather than just the opening device. No request body — the timestamp is server-minted, so a client can never backdate the stamp to suppress a future nudge. Never AI-gated: a timestamp on the caller's own row. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The Coach was marked opened; the stamp is echoed back.",
|
||||
@@ -1248,7 +1253,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Read the caller's self-context",
|
||||
description:
|
||||
"v1.16.0 — returns the structured self-context (free text plus chronic conditions, allergies, coach focus) the Coach system prompt and the daily briefing inject as a delimited, user-provided context block, alongside any pending clarifying questions. Every field is stored encrypted at rest; an undecryptable payload reads as null (fail closed). Auth via cookie or Bearer; the owner is always narrowed from the session.",
|
||||
"v1.16.0 — returns the structured self-context (free text plus chronic conditions, allergies, coach focus) the Coach system prompt and the daily briefing inject as a delimited, user-provided context block, alongside any pending clarifying questions. Every field is stored encrypted at rest; an undecryptable payload reads as null (fail closed). The questions are the one AI part: stored questions cannot be told apart by origin, so while the `aboutMeQuestions` capability is unavailable an outstanding set is replaced by the deterministic completion hints for the same profile, and `ai` says why. Auth via cookie or Bearer; the owner is always narrowed from the session.",
|
||||
responses: {
|
||||
"200": {
|
||||
description:
|
||||
@@ -1266,6 +1271,9 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
updatedAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
maxChars: z.number().int(),
|
||||
fieldMaxChars: z.number().int(),
|
||||
ai: aiCapabilityState.describe(
|
||||
"The `aboutMeQuestions` capability behind model-written questions.",
|
||||
),
|
||||
}),
|
||||
"GetCoachAboutMeResponse",
|
||||
),
|
||||
@@ -1279,7 +1287,7 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Write (or clear) the caller's self-context",
|
||||
description:
|
||||
"v1.16.0 — persists the free text (4 000-char cap) and the three structured fields (500-char cap each) encrypted at rest; caps are enforced before encryption. Structured fields are optional: omitted leaves the stored value untouched, an empty string clears it. After a non-empty save the server derives up to 3 clarifying questions (AI when a provider and the daily Coach token budget allow, deterministic completion hints otherwise) and returns them as `pendingQuestions`. Rate-limited per user. Optimistic concurrency (v1.32.21): send `baseUpdatedAt` (the `updatedAt` from a prior read) and the write 409s if the stored self-context changed since; omit it for the legacy unconditional write. The token is per-surface (`UserHealthProfile.updatedAt`), so it is not perturbed by unrelated account writes.",
|
||||
"v1.16.0 — persists the free text (4 000-char cap) and the three structured fields (500-char cap each) encrypted at rest; caps are enforced before encryption. Structured fields are optional: omitted leaves the stored value untouched, an empty string clears it. After a non-empty save the server derives up to 3 clarifying questions (AI when the `aboutMeQuestions` capability is available and the daily Coach token budget allows, deterministic completion hints otherwise, with no provider call) and returns them as `pendingQuestions`. Rate-limited per user. Optimistic concurrency (v1.32.21): send `baseUpdatedAt` (the `updatedAt` from a prior read) and the write 409s if the stored self-context changed since; omit it for the legacy unconditional write. The token is per-surface (`UserHealthProfile.updatedAt`), so it is not perturbed by unrelated account writes.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
@@ -1307,6 +1315,9 @@ export const coachPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
updatedAt: z.iso.datetime({ offset: true }),
|
||||
maxChars: z.number().int(),
|
||||
fieldMaxChars: z.number().int(),
|
||||
ai: aiCapabilityState.describe(
|
||||
"The `aboutMeQuestions` capability the derivation ran under.",
|
||||
),
|
||||
}),
|
||||
"PutCoachAboutMeResponse",
|
||||
),
|
||||
@@ -1918,7 +1929,7 @@ export const coachFeedbackPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Rate a Coach assistant message",
|
||||
description:
|
||||
"Persists a helpful/unhelpful rating for a single Coach reply. Reuses the v1.4.16 RecommendationFeedback table via the polymorphic `targetType` column. The aggregator buckets ratings by (promptVersion, tone, verbosity).",
|
||||
"Persists a helpful/unhelpful rating for a single Coach reply. Reuses the v1.4.16 RecommendationFeedback table via the polymorphic `targetType` column. The aggregator buckets ratings by (promptVersion, tone, verbosity). Never AI-gated: a rating on a message that already exists calls no model.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
* GET /api/daily/digest returns the `DailyDigest` DTO the Today surface, the
|
||||
* daily push, and a future iOS widget all consume. It is a pure read of
|
||||
* already-cached data (nightly briefing lift + dashboard-snapshot ingredients
|
||||
* + two light deterministic reads) — no provider call, no warm-on-mount. Gated
|
||||
* on the `insights` module. Part of the OpenAPI route table; aggregated in
|
||||
* `./index.ts`.
|
||||
* + two light deterministic reads) — no provider call, no warm-on-mount. No
|
||||
* module or AI gate; its AI parts follow their capabilities. Part of the
|
||||
* OpenAPI route table; aggregated in `./index.ts`.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
import type { ZodOpenApiObject } from "zod-openapi";
|
||||
@@ -14,14 +14,9 @@ import type { ZodOpenApiObject } from "zod-openapi";
|
||||
import { ARRIVAL_KINDS } from "@/lib/arrivals/types";
|
||||
import { PRIORITY_ITEM_KINDS } from "@/lib/daily/priority-item";
|
||||
import { dismissPriorityItemSchema } from "@/lib/validations/daily";
|
||||
import {
|
||||
MODULE_DISABLED_DESCRIPTION,
|
||||
dataEnvelope,
|
||||
moduleDisabledResponse,
|
||||
recordRefusal,
|
||||
stdResponses,
|
||||
} from "./shared";
|
||||
import { dataEnvelope, recordRefusal, stdResponses } from "./shared";
|
||||
import { healthScoreBasis } from "./insights/schemas";
|
||||
import { aiCapabilityState } from "./profile";
|
||||
|
||||
const priorityItemSchema = z
|
||||
.object({
|
||||
@@ -123,12 +118,14 @@ const dailyDigestResponse = z
|
||||
})
|
||||
.nullable()
|
||||
.describe(
|
||||
"Clinical-priority top signal, lifted from the cached briefing.",
|
||||
"Clinical-priority top signal, lifted from the cached briefing. Null while the `briefing` capability is unavailable.",
|
||||
),
|
||||
briefingLead: z
|
||||
.string()
|
||||
.nullable()
|
||||
.describe("First sentence of the cached briefing paragraph."),
|
||||
.describe(
|
||||
"First sentence of the cached briefing paragraph. Null while the `briefing` capability is unavailable; `line` then falls to its deterministic floor.",
|
||||
),
|
||||
line: z
|
||||
.string()
|
||||
.describe(
|
||||
@@ -156,7 +153,16 @@ const dailyDigestResponse = z
|
||||
.string()
|
||||
.nullable()
|
||||
.describe(
|
||||
"One-sentence generated reaction to that arrival, standing for the rest of the local day. Null whenever no line was generated (no provider, no consent, budget exhausted, or generation failed) — consumers fall back to `briefingLead` / `line`. Additive since v1.31.0.",
|
||||
"One-sentence generated reaction to that arrival, standing for the rest of the local day. Null whenever no line was generated (no provider, no consent, budget exhausted, or generation failed), and whenever the `reactionLines` capability is unavailable, however recent the stored line — consumers fall back to `briefingLead` / `line`. Additive since v1.31.0.",
|
||||
),
|
||||
ai: z
|
||||
.object({
|
||||
briefing: aiCapabilityState,
|
||||
coach: aiCapabilityState,
|
||||
reactionLines: aiCapabilityState,
|
||||
})
|
||||
.describe(
|
||||
"The three AI capabilities the digest carries text or a card for: `briefing` (the lead and top signal), `coach` (the Coach check-in card, which opens the Coach) and `reactionLines` (the reaction line). Everything else in the digest is data.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
@@ -171,7 +177,7 @@ export const dailyPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "The unified daily digest",
|
||||
description:
|
||||
"Assembles the day's read from already-cached data: the nightly briefing lifted read-only from the insights cache, the dashboard-snapshot health score / meds-today / sleep freshness, plus deterministic integration-status and Vorsorge reads for the 'worth a look' rail. No provider call, no warm-on-mount. Requires the insights module. Cookie or Bearer auth.",
|
||||
"Assembles the day's read from already-cached data: the nightly briefing lifted read-only from the insights cache, the dashboard-snapshot health score / meds-today / sleep freshness, plus deterministic integration-status and Vorsorge reads for the 'worth a look' rail. No provider call, no warm-on-mount. No module gate and no AI gate: the digest is data, and the `insights` module is the AI analysis opt-out. Its AI parts follow their capabilities, published in `ai`. Cookie or Bearer auth.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The daily digest.",
|
||||
@@ -181,7 +187,7 @@ export const dailyPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
@@ -191,7 +197,7 @@ export const dailyPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Dismiss a Today rail item",
|
||||
description:
|
||||
'"Dismiss / mark seen" for the Today rail\'s OBSERVATIONAL PriorityItem kinds only — milestone, ecg_new_recording, tension_window. The ACTIONABLE kinds (dose_window, sync_issue, preventive_care, coach_checkin) are structurally unreachable: itemKey must be namespaced under one of the three dismissible kinds or the request 422s before any lookup runs. Persisted server-side so the dismissal survives reload / a second device; an upsert, so a repeat dismiss of the same instance is a no-op. Requires the insights module. Cookie or Bearer auth.',
|
||||
'"Dismiss / mark seen" for the Today rail\'s OBSERVATIONAL PriorityItem kinds only — milestone, ecg_new_recording, tension_window. The ACTIONABLE kinds (dose_window, sync_issue, preventive_care, coach_checkin) are structurally unreachable: itemKey must be namespaced under one of the three dismissible kinds or the request 422s before any lookup runs. Persisted server-side so the dismissal survives reload / a second device; an upsert, so a repeat dismiss of the same instance is a no-op. No module gate. Cookie or Bearer auth.',
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
@@ -210,7 +216,6 @@ export const dailyPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
...moduleDisabledResponse,
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -6,16 +6,18 @@
|
||||
import type { ZodOpenApiObject } from "zod-openapi";
|
||||
import { z } from "zod/v4";
|
||||
import {
|
||||
AI_CONSENT_REQUIRED_DESCRIPTION,
|
||||
MODULE_DISABLED_DESCRIPTION,
|
||||
dataEnvelope,
|
||||
errorEnvelope,
|
||||
idempotencyKeyParameter,
|
||||
idempotentWrite,
|
||||
moduleDisabledResponse,
|
||||
recordRefusal,
|
||||
stdResponses,
|
||||
} from "../shared";
|
||||
import {
|
||||
aiCheckFailedResponse,
|
||||
aiNoProviderResponse,
|
||||
aiRefusal403Description,
|
||||
} from "../ai-refusal";
|
||||
import {
|
||||
insightsCardsResponse,
|
||||
insightsComprehensiveResponse,
|
||||
@@ -80,7 +82,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Dashboard"],
|
||||
summary: "Unified dashboard first-paint snapshot",
|
||||
description:
|
||||
"Assembles every above-the-fold tile field in one round-trip from the rollup / mood / widget helpers plus a read-only lift of the pre-generated daily briefing. Two-phase: `tiles` always present, `extras` nullable on a rollup-coverage miss. No LLM is reachable from this path. Cookie or Bearer auth.",
|
||||
"Assembles every above-the-fold tile field in one round-trip from the rollup / mood / widget helpers plus a read-only lift of the pre-generated daily briefing. Two-phase: `tiles` always present, `extras` nullable on a rollup-coverage miss. No LLM is reachable from this path. The briefing is model text: it, its recall (`briefingMemory`) and its timestamp are served only while the `briefing` AI capability is available for the record, decided on every read rather than cached with the body; `briefingAi` carries the state and `briefingState` reads `no-provider` or `disabled` otherwise. Every other field is data and never depends on AI. Cookie or Bearer auth.",
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
@@ -101,12 +103,12 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
"/api/insights/comprehensive": {
|
||||
get: {
|
||||
tags: ["Insights"],
|
||||
summary: "Comprehensive AI insights bundle",
|
||||
summary: "The Insights overview's computed read",
|
||||
description:
|
||||
"Full Insights surface — daily briefing, recommendations with rationale, optional weekly report + storyboard annotations. Strict-schema validated server-side. Requires an active ConsentReceipt when the resolved provider chain egresses via the operator's server-managed key (see POST /api/consent/ai).",
|
||||
"The main read of the Insights overview: summaries, classifications, correlations, medication compliance and rule alerts, all computed from the record. No provider is called and no AI switch, opt-out, provider or consent refuses it; `hasProvider` is provider presence only. The `ai` block beside the body says whether the briefing and the status notes that decorate the overview can be shown, resolved per request. Served stale-while-revalidate; `revalidating` marks a stale body. Delegable at MANAGE level over the whole record. Cookie or Bearer auth.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Insights bundle.",
|
||||
description: "The overview read.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
@@ -117,7 +119,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
...recordRefusal(AI_CONSENT_REQUIRED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -126,7 +128,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Insight cards (iOS adapter)",
|
||||
description:
|
||||
"v1.4.31 — the native-client adapter over the same alert rule engine the web comprehensive surface consumes: measurements, BP-in-target, weight trend, pulse, and cadence-aware medication compliance are fed through `generateAlerts()` and each resulting `HealthAlert` is re-shaped to the iOS Insight card model. Deterministic — no LLM call on this path. Module-gated on `insights` and the operator `insightStatus` assistant surface. Auth via cookie or Bearer.",
|
||||
'v1.4.31 — the native-client adapter over the same alert rule engine the web comprehensive surface consumes: measurements, BP-in-target, weight trend, pulse, and cadence-aware medication compliance are fed through `generateAlerts()` and each resulting `HealthAlert` is re-shaped to the iOS Insight card model. Deterministic — no LLM call on this path, so no AI switch, opt-out or module refuses it. Every card is a rule alert: `provider` is `"rules"` and `summary` is never null. Auth via cookie or Bearer.',
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The list of insight cards (possibly empty).",
|
||||
@@ -139,7 +141,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
@@ -149,7 +151,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Warm all AI assessments for the calling user",
|
||||
description:
|
||||
"v1.8.7.1 — enqueue a full warm of every AI assessment for the authenticated user (comprehensive insight + the seven specialised status cards + every data-bearing generic metric assessment) in the active locale, so the read-only status GETs serve cached text instantly. Returns immediately; the generation runs out of band on the worker. Empty metrics and provider-less accounts never trigger an LLM call. Short anti-spam bucket (`insights-warm:<userId>`, one warm per 3 minutes) → 429 on a tight loop. Auth via cookie or Bearer; `userId` is taken from the session, never the body.",
|
||||
"v1.8.7.1 — enqueue a full warm of every AI assessment for the authenticated user (comprehensive insight + the seven specialised status cards + every data-bearing generic metric assessment) in the active locale, so the read-only status GETs serve cached text instantly. Returns immediately; the generation runs out of band on the worker. Covers two AI capabilities, `briefing` and `statusText`, and never refuses: with neither available it answers `queued: false` and enqueues nothing (and spends no anti-spam bucket); with one available it enqueues and the worker checks each half before it builds anything. The `ai` block says which half can run. Empty metrics and provider-less accounts never trigger an LLM call. Short anti-spam bucket (`insights-warm:<userId>`, one warm per 3 minutes) → 429 on a tight loop. Auth via cookie or Bearer; `userId` is taken from the session, never the body.",
|
||||
requestBody: {
|
||||
required: false,
|
||||
content: {
|
||||
@@ -159,7 +161,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
responses: {
|
||||
"200": {
|
||||
description:
|
||||
"Warm accepted and enqueued. The work runs on the worker; poll the read-only status routes for the text.",
|
||||
"`queued: true`: the warm was enqueued; the work runs on the worker, so poll the read-only status routes for the text. `queued: false`: neither capability is available and nothing was enqueued; `ai` says why.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
@@ -199,7 +201,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Read the cached advisor briefing (never generates)",
|
||||
description:
|
||||
'The read-only advisor. It serves the cached payload and NEVER calls a provider — the surfaces that mount on page load used to POST here, which blocked first paint on the whole provider chain. When the cache is stale or missing AND a provider exists it enqueues an out-of-band warm and says so in `revalidating`; the next read reflects it. User-initiated regeneration is the POST. Four honesty signals ride the payload and are the whole point of it: `hasProvider: false` means no warm pass can ever refresh what is shown, so stop polling and offer to connect one; `generationFailed` means the last attempt failed and the text is HELD rather than fresh; `generationFailureClass` says which lever to point at; and `briefingOmittedReason: "ungrounded"` means a generation SUCCEEDED and the grounding gate withheld the briefing, which is a different state from a failure. Gated on the Coach assistant surface — an operator who turns Coach off empties every advisor consumer. Cookie or Bearer auth; the caller is always resolved as themselves, so this read cannot be delegated to a shared record.',
|
||||
'The read-only advisor. It serves the cached payload and NEVER calls a provider — the surfaces that mount on page load used to POST here, which blocked first paint on the whole provider chain. When the cache is stale or missing AND a provider exists it enqueues an out-of-band warm and says so in `revalidating`; the next read reflects it. User-initiated regeneration is the POST. Four honesty signals ride the payload and are the whole point of it: `hasProvider: false` means no warm pass can ever refresh what is shown, so stop polling and offer to connect one; `generationFailed` means the last attempt failed and the text is HELD rather than fresh; `generationFailureClass` says which lever to point at; and `briefingOmittedReason: "ungrounded"` means a generation SUCCEEDED and the grounding gate withheld the briefing, which is a different state from a failure. A pure AI read: the payload is the model-written briefing and nothing else, so it requires the `briefing` AI capability and refuses with the capability envelope before the cache is read; stored briefing text is never served, and no warm is enqueued, while the capability is unavailable. Cookie or Bearer auth; the caller is always resolved as themselves, so this read cannot be delegated to a shared record.',
|
||||
responses: {
|
||||
"200": {
|
||||
description:
|
||||
@@ -214,10 +216,11 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
"403": {
|
||||
description:
|
||||
"The operator has switched the Coach assistant surface off (`meta.errorCode` = `assistant.disabled.coach`).",
|
||||
description: aiRefusal403Description("briefing"),
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"422": aiNoProviderResponse("briefing"),
|
||||
"503": aiCheckFailedResponse,
|
||||
"401": stdResponses["401"],
|
||||
"429": stdResponses["429"],
|
||||
},
|
||||
@@ -226,7 +229,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Generate the advisor briefing inline (costs tokens)",
|
||||
description:
|
||||
"The only path in the advisor family that calls a provider, and it does so INLINE. Two gates bound it, and they bound different things. The RATE gate is `insights:<userId>`, ten generations per hour by default and configurable by the operator through `INSIGHTS_RATE_LIMIT_PER_HOUR` (a value below 1 falls back to the default); it is checked AFTER the cache short-circuit, so a cache hit never spends a token. The BUDGET gate is the day's token ceiling, refused at reservation time before any provider is contacted — so it is not a provider failure, records no failure marker, and answers 429 with `meta.errorCode` = `insights.generate.budgetExceeded`, which is how a client tells 'you asked too often' from 'the day's spend is gone'. Two more things a caller should know before integrating: a plain 200 does NOT mean a provider ran — a fresh cache inside 24 hours answers `cached: true`, and so does an exhausted quota when the fresh cache merely lacked a briefing — and a request that TIMES OUT client-side may still complete on the server, writing the briefing to the cache or a dated failure marker, which is exactly the pair the read GET reports so a client can settle an aborted regenerate by polling rather than guessing. Gated on the Coach assistant surface, consent-gated when the resolved chain egresses through the operator's server-managed key. Cookie or Bearer auth; not delegable.",
|
||||
"The only path in the advisor family that calls a provider, and it does so INLINE. Two gates bound it, and they bound different things. The RATE gate is `insights:<userId>`, ten generations per hour by default and configurable by the operator through `INSIGHTS_RATE_LIMIT_PER_HOUR` (a value below 1 falls back to the default); it is checked AFTER the cache short-circuit, so a cache hit never spends a token. The BUDGET gate is the day's token ceiling, refused at reservation time before any provider is contacted — so it is not a provider failure, records no failure marker, and answers 429 with `meta.errorCode` = `insights.generate.budgetExceeded`, which is how a client tells 'you asked too often' from 'the day's spend is gone'. Two more things a caller should know before integrating: a plain 200 does NOT mean a provider ran — a fresh cache inside 24 hours answers `cached: true`, and so does an exhausted quota when the fresh cache merely lacked a briefing — and a request that TIMES OUT client-side may still complete on the server, writing the briefing to the cache or a dated failure marker, which is exactly the pair the read GET reports so a client can settle an aborted regenerate by polling rather than guessing. Requires the `briefing` AI capability (the operator's briefing switch, the AI analysis opt-out, a provider, and consent when the chain egresses through the operator's server-managed key), checked before any read or provider work. Cookie or Bearer auth; not delegable.",
|
||||
requestBody: {
|
||||
required: false,
|
||||
content: {
|
||||
@@ -247,8 +250,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
"403": {
|
||||
description:
|
||||
"The Coach assistant surface is off (`assistant.disabled.coach`), or the resolved chain egresses through the operator's key and no consent receipt is on file (`consent.ai.required`).",
|
||||
description: aiRefusal403Description("briefing"),
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"409": {
|
||||
@@ -258,7 +260,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
"422": {
|
||||
description:
|
||||
"No AI provider is configured anywhere for this account, or the provider answered something that was not valid JSON (`meta.errorCode` = `ai_response_truncated` when the answer was cut off mid-stream rather than malformed), or the finished prose was withheld by the outbound safety screen (`insights.generate.outboundScreened`).",
|
||||
"No AI provider can serve the `briefing` capability (`meta.errorCode` = `ai.provider.none`, `meta.reason` = `no_provider`), or the provider answered something that was not valid JSON (`meta.errorCode` = `ai_response_truncated` when the answer was cut off mid-stream rather than malformed), or the finished prose was withheld by the outbound safety screen (`insights.generate.outboundScreened`).",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"429": {
|
||||
@@ -268,7 +270,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
"503": {
|
||||
description:
|
||||
"Every provider in the chain failed for a reason that is not a rate limit — auth, timeout or an upstream 5xx. A dated failure marker is written, so the read GET reports the briefing as held rather than fresh.",
|
||||
"Every provider in the chain failed for a reason that is not a rate limit — auth, timeout or an upstream 5xx. A dated failure marker is written, so the read GET reports the briefing as held rather than fresh. Also: the `briefing` capability could not be resolved (`meta.errorCode` = `ai.unavailable`, `meta.reason` = `check_failed`); nothing was generated.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"401": stdResponses["401"],
|
||||
@@ -378,10 +380,10 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "The two-line Coach read for one metric",
|
||||
description:
|
||||
"The own-baseline placement and the single strongest lagged association whose outcome is the named metric — the two server-authoritative lines a metric sub-page renders above its chart. Pure compute over the baseline and correlation engines: no provider call and no cache table, so web and native decode the same DTO rather than each deriving one. Line two arrives as a finished sentence in the reader's language and is printed verbatim, so the resolved locale decides the row; a correlation failure degrades it to null and never sinks line one. Module-gated on `insights` and gated on the Coach assistant surface, because the strip is the ambient Coach presence on that page. Shared analytics-read budget. Delegable at MANAGE level over the whole record: it is computed across the record with no provider on the path. Cookie or Bearer auth.",
|
||||
"The own-baseline placement and the single strongest lagged association whose outcome is the named metric — the two server-authoritative lines a metric sub-page renders above its chart. Pure compute over the baseline and correlation engines: no provider call and no cache table, so web and native decode the same DTO rather than each deriving one. Line two arrives as a finished sentence in the reader's language and is printed verbatim, so the resolved locale decides the row; a correlation failure degrades it to null and never sinks line one. Both lines are computed, so no AI switch, opt-out or module refuses it (the name is historical). Shared analytics-read budget. Delegable at MANAGE level over the whole record: it is computed across the record with no provider on the path. Cookie or Bearer auth.",
|
||||
requestParams: { query: coachReadQuery },
|
||||
responses: {
|
||||
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description: "The strip.",
|
||||
content: {
|
||||
@@ -402,7 +404,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Today's suggested Coach opener",
|
||||
description:
|
||||
"Resolves today's single most notable derived wellness signal into a tappable opener for the Coach's blank-chat hero, using the same confidence-gated detector the daily briefing uses. The selection happens SERVER-side and the client renders it rather than recomputing. `signal: null` is the ordinary answer and means the hero keeps its neutral greeting — never a fabricated opener. Two different causes produce that null and are indistinguishable on the wire: nothing crossed the notability gate, or the account has turned proactive suggestions off, in which case the detector does not run at all. Module-gated on `insights` and on the Coach assistant surface. Shared analytics-read budget. Cookie or Bearer auth; not delegable.",
|
||||
"Resolves today's single most notable derived wellness signal into a tappable opener for the Coach's blank-chat hero, using the same confidence-gated detector the daily briefing uses. The selection happens SERVER-side and the client renders it rather than recomputing. `signal: null` is the ordinary answer and means the hero keeps its neutral greeting — never a fabricated opener. Two different causes produce that null and are indistinguishable on the wire: nothing crossed the notability gate, or the account has turned proactive suggestions off, in which case the detector does not run at all. The opener exists only to open the Coach, so it is served only while the `coach` AI capability is available; otherwise the answer is the same neutral `signal: null` and `ai` says why. Never refused for an AI reason. Shared analytics-read budget. Cookie or Bearer auth; not delegable.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The opener, or the neutral null.",
|
||||
@@ -415,7 +417,6 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
...moduleDisabledResponse,
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
@@ -425,10 +426,10 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "The latest week or month retrospective",
|
||||
description:
|
||||
"The last generated period summary for the record. Read-only by construction: it never blocks on a provider, serves the last good row immediately, and warms out of band when the row is stale or missing. A provider-less account is not left empty — the generator falls back to deterministic, non-causal prose, so even the no-key demo gets a retrospective on the next read. `revalidating` reports whether this read enqueued a warm, and is always FALSE on a delegated request: the route warms unconditionally rather than on a miss, so without that suppression a manager's first navigation here would be an egress of the owner's record the owner never asked for. Rows are keyed per locale, so `locale` selects a different stored row rather than translating one. Module-gated on `insights` and on the `insightStatus` assistant surface. Delegable at MANAGE level over the whole record. Cookie or Bearer auth.",
|
||||
"The last generated period summary for the record. Read-only by construction: it never blocks on a provider, serves the last good row immediately, and warms out of band when the row is stale or missing. A provider-less account is not left empty — the generator falls back to deterministic, non-causal prose, so even the no-key demo gets a retrospective on the next read. `revalidating` reports whether this read enqueued a warm, and is always FALSE on a delegated request: the route warms unconditionally rather than on a miss, so without that suppression a manager's first navigation here would be an egress of the owner's record the owner never asked for. Rows are keyed per locale, so `locale` selects a different stored row rather than translating one. A mixed read: a narrative the deterministic composer wrote is data and always served; one a model wrote is served only while the `periodNarrative` AI capability is available, otherwise `narrative` is null and `ai` says why. While the capability is unavailable a warm is enqueued only when nothing servable exists (the worker then writes the deterministic narrative). Never refused for an AI reason. Delegable at MANAGE level over the whole record. Cookie or Bearer auth.",
|
||||
requestParams: { query: narrativeQuery },
|
||||
responses: {
|
||||
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description:
|
||||
"The retrospective, or `narrative: null` when none is on file yet. Always 200 — absence is a normal answer.",
|
||||
@@ -471,10 +472,10 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "One day's intraday heart-rate shape",
|
||||
description:
|
||||
"The day's ten-minute mean heart-rate series plus, when every confidence gate holds, at most ONE cautious elevated-at-rest window. Computed from raw samples through the read-swap pattern rather than persisted as ten-minute rollups for all history, so a day outside the dense-retention window reads back at the coarser hourly grain instead of empty — `resolution` says which, and `tension` is always null on an hourly day because that read needs per-sample resolution. The bar for a tension window is deliberately high; under-flagging is the intended failure mode, and it is awareness, never a diagnosis. `date` is STRICT here, unlike the forgiving date filters elsewhere on the surface: anything but a `YYYY-MM-DD` literal is a 422. Module-gated on `insights`. Delegable at MANAGE level over the whole record. Cookie or Bearer auth.",
|
||||
"The day's ten-minute mean heart-rate series plus, when every confidence gate holds, at most ONE cautious elevated-at-rest window. Computed from raw samples through the read-swap pattern rather than persisted as ten-minute rollups for all history, so a day outside the dense-retention window reads back at the coarser hourly grain instead of empty — `resolution` says which, and `tension` is always null on an hourly day because that read needs per-sample resolution. The bar for a tension window is deliberately high; under-flagging is the intended failure mode, and it is awareness, never a diagnosis. `date` is STRICT here, unlike the forgiving date filters elsewhere on the surface: anything but a `YYYY-MM-DD` literal is a 422. Pulse is a core vital, so no module gates it and no AI switch refuses it. Delegable at MANAGE level over the whole record. Cookie or Bearer auth.",
|
||||
requestParams: { query: intradayPulseQuery },
|
||||
responses: {
|
||||
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
description:
|
||||
"The day's series. `Cache-Control` is the bfcache-friendly `private, max-age=0, must-revalidate` rather than `no-store`.",
|
||||
@@ -804,7 +805,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Derived wellness metric (compute-once)",
|
||||
description:
|
||||
"v1.10.0 — the compute-once `Derived<T>` value for any registered derived wellness metric (personal typical-range vitals baseline, cardio-fitness band, vascular-age delta, sleep score, readiness, coincident-deviation flag). One generic route over a closed registry enum; an unknown `metric` 422s. Pure compute over the rollup tier with a per-type live fallback on a coverage miss — no LLM call, no narrative, no cache table. Returns the flat `Derived<T>` union so the native client can decode one stable shape and combine values across metrics. `windowDays` widens or narrows the trailing window a metric summarises; `provenance.windowDays` always reports the window actually used and `coverage.historyDays` the days that actually backed it. Auth via cookie or Bearer.",
|
||||
"v1.10.0 — the compute-once `Derived<T>` value for any registered derived wellness metric (personal typical-range vitals baseline, cardio-fitness band, vascular-age delta, sleep score, readiness, coincident-deviation flag). One generic route over a closed registry enum; an unknown `metric` 422s. Pure compute over the rollup tier with a per-type live fallback on a coverage miss — no LLM call, no narrative, no cache table. Returns the flat `Derived<T>` union so the native client can decode one stable shape and combine values across metrics. `windowDays` widens or narrows the trailing window a metric summarises; `provenance.windowDays` always reports the window actually used and `coverage.historyDays` the days that actually backed it. Never refused for an AI reason and not gated on the `insights` module (the AI analysis opt-out). The one AI part is the warmer model-written `assessment` text, served (and warmed) only while the `statusText` capability is available; otherwise the deterministic assessment stands and `ai` says why. Auth via cookie or Bearer.",
|
||||
requestParams: {
|
||||
query: derivedMetricQuery,
|
||||
},
|
||||
@@ -830,7 +831,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Derived wellness metrics (batched compute-once)",
|
||||
description:
|
||||
"v1.10.0 — resolve several derived wellness metrics in ONE request. The `metrics` CSV names the metrics (a `metric:type` token sub-targets a VITALS_BASELINE vital); the server fans out under a bounded limiter with the profile loaded once and returns a map keyed by the per-request token. Collapses the Insights cold-mount fan-out of 14+ independent single-metric requests — the pool-starvation class that surfaces as a hang-then-recover. The single-metric route stays for the per-score detail pages. Auth via cookie or Bearer.",
|
||||
"v1.10.0 — resolve several derived wellness metrics in ONE request. The `metrics` CSV names the metrics (a `metric:type` token sub-targets a VITALS_BASELINE vital); the server fans out under a bounded limiter with the profile loaded once and returns a map keyed by the per-request token. Collapses the Insights cold-mount fan-out of 14+ independent single-metric requests — the pool-starvation class that surfaces as a hang-then-recover. The single-metric route stays for the per-score detail pages. Deterministic assessments only, so no AI gate and no `insights` module gate; each metric keeps its own owning module. Auth via cookie or Bearer.",
|
||||
requestParams: {
|
||||
query: derivedBatchQuery,
|
||||
},
|
||||
@@ -879,7 +880,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "ECG recording list (metadata only)",
|
||||
description:
|
||||
"v1.28.50 — the authenticated user's ECG recordings as a cheap, index-covered metadata list (recorded time, duration, sampling rate, sample count, average heart rate, lead, and the DEVICE's own rhythm classification). NEVER decrypts or returns the waveform — the per-recording strip is fetched on demand from GET /api/insights/ecg/{id}. Reflects only the recording device's certified on-device classification, verbatim; HealthLog never re-classifies an ECG or produces a diagnosis. Data-availability-gated: an empty account returns `hasRecordings: false`. Module-gated on `insights`; no assistant-surface gate and no LLM call. Auth via cookie or Bearer.",
|
||||
"v1.28.50 — the authenticated user's ECG recordings as a cheap, index-covered metadata list (recorded time, duration, sampling rate, sample count, average heart rate, lead, and the DEVICE's own rhythm classification). NEVER decrypts or returns the waveform — the per-recording strip is fetched on demand from GET /api/insights/ecg/{id}. Reflects only the recording device's certified on-device classification, verbatim; HealthLog never re-classifies an ECG or produces a diagnosis. Data-availability-gated: an empty account returns `hasRecordings: false`. Device data: no module gate, no AI gate and no LLM call. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The ECG recording list (possibly empty).",
|
||||
@@ -889,7 +890,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
@@ -897,7 +898,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Ingest one ECG recording",
|
||||
description:
|
||||
"The live ECG ingest: one Apple Watch recording per request, for a client draining its HealthKit ECG observer. Before this existed, a watch ECG could only reach HealthLog inside a full `export.zip`. One recording per request because a 30 s / 512 Hz strip is ~15 360 samples. Samples are INTEGER MICRO-VOLTS (convert from HealthKit's Volts), stored AES-256-GCM encrypted; `sampleCount` and `durationSeconds` are derived server-side. The `classification` is the device's own verdict stored verbatim — HealthLog never reads the waveform to produce or revise one. `source` accepts `APPLE_HEALTH` only; `userId` comes from the session and is never a body field. Unknown body keys are rejected with a 422 naming them. No `Idempotency-Key` is needed: the recording carries its own identity, so a retry resolves to the same row by construction — see `status` for what a re-post reports. Limits: 32 768 samples, 2 MB body, 60 recordings per minute per user. Module-gated on `insights`; no assistant-surface gate and no LLM call. Auth via cookie or Bearer.",
|
||||
"The live ECG ingest: one Apple Watch recording per request, for a client draining its HealthKit ECG observer. Before this existed, a watch ECG could only reach HealthLog inside a full `export.zip`. One recording per request because a 30 s / 512 Hz strip is ~15 360 samples. Samples are INTEGER MICRO-VOLTS (convert from HealthKit's Volts), stored AES-256-GCM encrypted; `sampleCount` and `durationSeconds` are derived server-side. The `classification` is the device's own verdict stored verbatim — HealthLog never reads the waveform to produce or revise one. `source` accepts `APPLE_HEALTH` only; `userId` comes from the session and is never a body field. Unknown body keys are rejected with a 422 naming them. No `Idempotency-Key` is needed: the recording carries its own identity, so a retry resolves to the same row by construction — see `status` for what a re-post reports. Limits: 32 768 samples, 2 MB body, 60 recordings per minute per user. Device data: never refused because AI is off or the AI analysis opt-out is on; no module gate and no LLM call. Auth via cookie or Bearer.",
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
@@ -928,7 +929,6 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
...moduleDisabledResponse,
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
@@ -938,7 +938,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "One ECG recording with waveform",
|
||||
description:
|
||||
"v1.28.50 — one recording's decrypted waveform plus metadata and the DEVICE's verbatim classification. Ownership is narrowed in the query where (`{ id, userId }`) so a cross-user read is structurally impossible; a foreign or unknown id 404s (existence sealed). The waveform is AES-256-GCM at rest, decrypted through the fail-closed codec. By default the ~9000-sample strip is min/max-decimated to ~2500 display points so R-wave peaks survive; `?full=1` returns the raw array. HealthLog does not interpret the trace, measure intervals, annotate beats, or emit a verdict of its own. Module-gated on `insights`; no assistant-surface gate and no LLM call. `no-store`. Auth via cookie or Bearer.",
|
||||
"v1.28.50 — one recording's decrypted waveform plus metadata and the DEVICE's verbatim classification. Ownership is narrowed in the query where (`{ id, userId }`) so a cross-user read is structurally impossible; a foreign or unknown id 404s (existence sealed). The waveform is AES-256-GCM at rest, decrypted through the fail-closed codec. By default the ~9000-sample strip is min/max-decimated to ~2500 display points so R-wave peaks survive; `?full=1` returns the raw array. HealthLog does not interpret the trace, measure intervals, annotate beats, or emit a verdict of its own. Device data: no module gate, no AI gate and no LLM call. `no-store`. Auth via cookie or Bearer.",
|
||||
requestParams: {
|
||||
path: z.object({
|
||||
id: z.string().describe("The ECG recording id (cuid)."),
|
||||
@@ -963,7 +963,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
"No ECG recording with that id for the authenticated user (existence sealed — a foreign id is indistinguishable from a missing one).",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
@@ -973,7 +973,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Device-flagged rhythm/HR/steadiness event timeline",
|
||||
description:
|
||||
"v1.10.0 (WX-B) — the authenticated user's timeline of device-flagged EVENT rows: irregular-rhythm / high-HR / low-HR / walking-steadiness / breathing-disturbance notifications the user's wearable (Apple Watch / Withings ScanWatch) already produced and synced. AWARENESS / SCREENING of the DEVICE's own decision — HealthLog stores and reflects ONLY the classification result the device's certified on-device algorithm emitted, verbatim; it never re-classifies and never produces a HealthLog diagnosis. `classification` carries the full six-value verdict set (the three ECG verdicts plus the two walking-steadiness severities plus the neutral FIRED verdict) — a distinct, wider enum than the three-value one on GET /api/insights/ecg. Data-availability-gated: an account with no event rows returns `hasEvents: false`. Module-gated on `insights`; no assistant-surface gate and no LLM call. Auth via cookie or Bearer.",
|
||||
"v1.10.0 (WX-B) — the authenticated user's timeline of device-flagged EVENT rows: irregular-rhythm / high-HR / low-HR / walking-steadiness / breathing-disturbance notifications the user's wearable (Apple Watch / Withings ScanWatch) already produced and synced. AWARENESS / SCREENING of the DEVICE's own decision — HealthLog stores and reflects ONLY the classification result the device's certified on-device algorithm emitted, verbatim; it never re-classifies and never produces a HealthLog diagnosis. `classification` carries the full six-value verdict set (the three ECG verdicts plus the two walking-steadiness severities plus the neutral FIRED verdict) — a distinct, wider enum than the three-value one on GET /api/insights/ecg. Data-availability-gated: an account with no event rows returns `hasEvents: false`. Device data: no module gate, no AI gate and no LLM call. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "The device-flagged event timeline (possibly empty).",
|
||||
@@ -986,7 +986,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
@@ -996,7 +996,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Correlation discovery (FDR-controlled)",
|
||||
description:
|
||||
"v1.10.0 — scans a curated behaviour × outcome matrix (daylight / mood / glucose / BP / steps × sleep / HRV / resting HR / weight), lag-joins each behaviour day to the next day's outcome, runs Pearson with the exact Student-t p-value, and applies Benjamini-Hochberg FDR control across every tested pair. Only statistically-defensible pairs surface, each carrying n, r, p, and the BH-adjusted q. Descriptive, never causal. Gated by the operator `correlations` assistant surface. Auth via cookie or Bearer.",
|
||||
"v1.10.0 — scans a curated behaviour × outcome matrix (daylight / mood / glucose / BP / steps × sleep / HRV / resting HR / weight), lag-joins each behaviour day to the next day's outcome, runs Pearson with the exact Student-t p-value, and applies Benjamini-Hochberg FDR control across every tested pair. Only statistically-defensible pairs surface, each carrying n, r, p, and the BH-adjusted q. Descriptive, never causal. Statistics, not model output: no AI switch, opt-out or `insights` module gate refuses them. Auth via cookie or Bearer.",
|
||||
responses: {
|
||||
...recordRefusal(),
|
||||
"200": {
|
||||
@@ -1019,7 +1019,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "List current correlation patterns",
|
||||
description:
|
||||
"Returns the authenticated account's currently accepted persisted correlation identities, evidence, and dismissal timestamps.",
|
||||
"Returns the authenticated account's currently accepted persisted correlation identities, evidence, and dismissal timestamps. Statistics, not model output, so no AI or `insights` module gate applies.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Current persisted correlation patterns.",
|
||||
@@ -1032,7 +1032,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
@@ -1042,7 +1042,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Insights"],
|
||||
summary: "Update correlation pattern dismissal",
|
||||
description:
|
||||
"Dismisses or restores one current account-owned pattern. A dismissal remains effective until the accepted evidence changes materially.",
|
||||
"Dismisses or restores one current account-owned pattern. A dismissal remains effective until the accepted evidence changes materially. No AI or `insights` module gate applies.",
|
||||
requestParams: { path: z.object({ id: z.string() }) },
|
||||
requestBody: {
|
||||
required: true,
|
||||
@@ -1066,7 +1066,7 @@ export const insightsPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
description: "No current pattern with that id for this account.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...recordRefusal(MODULE_DISABLED_DESCRIPTION),
|
||||
...recordRefusal(),
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
import { ANALYTICS_RANGES } from "@/lib/analytics/range-delta";
|
||||
import { PROVIDER_CHAIN_TYPES } from "@/lib/ai/provider-chain";
|
||||
import { PERIOD_DAYS } from "@/lib/insights/narrative/period-narrative";
|
||||
import { aiCapabilityState } from "../profile";
|
||||
|
||||
/** The retrospective periods the narrative route accepts, read off the engine. */
|
||||
const NARRATIVE_PERIOD_VALUES = Object.keys(PERIOD_DAYS);
|
||||
@@ -42,11 +43,25 @@ export const insightsComprehensiveResponse = z
|
||||
.describe(
|
||||
"True when the body is served from last-good cache (stale-while-revalidate) while a fresh aggregation runs in the background. The client keeps polling on `revalidating` (bounded) so the open page converges on the fresh body.",
|
||||
),
|
||||
hasProvider: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"Whether a configured AI provider exists for the record: provider presence and nothing else. False never means the operator switched AI off or consent is missing; `ai` says that.",
|
||||
),
|
||||
ai: z
|
||||
.object({
|
||||
briefing: aiCapabilityState,
|
||||
statusText: aiCapabilityState,
|
||||
})
|
||||
.describe(
|
||||
"Whether the AI parts that decorate the overview can be shown: the daily briefing and the per-metric status notes. Resolved per request, never cached with the body. The overview itself is computed data and loads whatever these say.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "InsightsComprehensiveResponse",
|
||||
description:
|
||||
"AI-generated insights bundle. Strict-schema validated server-side; Coach-routed when the insight surface needs day-level grounding.",
|
||||
"The Insights overview's computed read. No provider is called on this path; every figure is computed from the record.",
|
||||
});
|
||||
|
||||
// v1.8.7.1 — generic per-HealthKit-metric assessment. The query enum is
|
||||
@@ -391,7 +406,12 @@ export const derivedMetricResponse = z
|
||||
assessment: derivedAssessment
|
||||
.nullable()
|
||||
.describe(
|
||||
"v1.13.2 — short 'why is this score what it is' explanation, keyed to the SAME requested id (only for the per-score ids READINESS, SLEEP_SCORE, RECOVERY_SCORE, STRAIN_SCORE, STRESS_SCORE). Null for any other metric and whenever status !== 'ok'. Always non-empty when present: a deterministic text fills it (so provider-less accounts + the demo always get one) and warmer AI prose overrides it once cached.",
|
||||
"v1.13.2 — short 'why is this score what it is' explanation, keyed to the SAME requested id (only for the per-score ids READINESS, SLEEP_SCORE, RECOVERY_SCORE, STRAIN_SCORE, STRESS_SCORE). Null for any other metric and whenever status !== 'ok'. Always non-empty when present: a deterministic text fills it (so provider-less accounts + the demo always get one) and warmer AI prose overrides it once cached, but only while the `statusText` AI capability is available; otherwise the deterministic text is served and nothing is warmed.",
|
||||
),
|
||||
ai: aiCapabilityState
|
||||
.optional()
|
||||
.describe(
|
||||
"The `statusText` capability behind the model-written assessment. Present on the single-metric route; absent on the batch route, whose assessments are always the deterministic text.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
@@ -946,15 +966,25 @@ export const insightsPregenerateResponse = z
|
||||
.object({
|
||||
queued: z
|
||||
.boolean()
|
||||
.describe("True when the full warm was accepted and enqueued."),
|
||||
.describe(
|
||||
"True when the warm was accepted and enqueued; false when neither AI capability it covers is available, in which case nothing was enqueued.",
|
||||
),
|
||||
locale: z
|
||||
.enum(["de", "en"])
|
||||
.string()
|
||||
.describe("The locale the assessments are being warmed in."),
|
||||
ai: z
|
||||
.object({
|
||||
briefing: aiCapabilityState,
|
||||
statusText: aiCapabilityState,
|
||||
})
|
||||
.describe(
|
||||
"The two capabilities the warm covers. The worker skips the half whose capability is unavailable.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "InsightsPregenerateResponse",
|
||||
description:
|
||||
"Acknowledgement that a full assessment warm was enqueued for the calling user. The generation runs out of band; the text lands in the read-only status routes.",
|
||||
"Acknowledgement of a full assessment warm for the calling user, or of why none was enqueued. The generation runs out of band; the text lands in the read-only status routes.",
|
||||
});
|
||||
|
||||
// v1.7.0 — unified dashboard first-paint snapshot. One GET that
|
||||
@@ -1389,12 +1419,22 @@ export const dashboardSnapshotResponse = z
|
||||
.describe(
|
||||
"The briefing recall + forward-look: `recall` is the prior period's narrative headline, `forward` points ahead to the most salient trend drift (or a calm 'holding steady' line). Both are already-localised prose the client renders verbatim. Null when no prior narrative is on file or no briefing is shown. Optional so older cached snapshots without the field stay valid.",
|
||||
),
|
||||
briefingState: z.enum(["ready", "preparing", "disabled", "no-provider"]),
|
||||
briefingState: z
|
||||
.enum(["ready", "preparing", "disabled", "no-provider"])
|
||||
.describe(
|
||||
"`disabled` whenever the `briefing` AI capability is unavailable for a reason other than a missing provider (then `briefingAi` names it); `no-provider` when no provider can serve it.",
|
||||
),
|
||||
briefingUpdatedAt: z.string().nullable(),
|
||||
briefingStale: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"True when `briefing` carries the last good (expired-TTL) briefing while a refresh is pending (`preparing`) or impossible (`no-provider`). Render the stale content with its `briefingUpdatedAt` timestamp instead of a blank tile.",
|
||||
"True when `briefing` carries the last good (expired-TTL) briefing while a refresh is pending (`preparing`). Render the stale content with its `briefingUpdatedAt` timestamp instead of a blank tile.",
|
||||
),
|
||||
briefingAi: aiCapabilityState
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"The `briefing` AI capability for this record, applied on every read after the cache: while it is unavailable `briefing`, `briefingMemory` and `briefingUpdatedAt` are null, whatever the cache holds. Nullable and optional so older cached bodies stay valid.",
|
||||
),
|
||||
generatedAt: z.string(),
|
||||
})
|
||||
@@ -1406,8 +1446,8 @@ export const dashboardSnapshotResponse = z
|
||||
|
||||
// v1.4.31 — the iOS "cards" adapter over the same alert rule engine the
|
||||
// web comprehensive surface consumes. Each card is one `HealthAlert`
|
||||
// re-shaped to the iOS Insight model. Module-gated on `insights` and the
|
||||
// operator `insightStatus` assistant surface.
|
||||
// re-shaped to the iOS Insight model. Rule output, not model output, so no
|
||||
// AI or module gate applies.
|
||||
const insightCard = z
|
||||
.object({
|
||||
id: z.string().describe("Stable per-card id (e.g. `alert-1`)."),
|
||||
@@ -1437,7 +1477,7 @@ const insightCard = z
|
||||
provider: z
|
||||
.string()
|
||||
.describe(
|
||||
"Lower-cased AI provider label for the account (e.g. `claude`).",
|
||||
"Who wrote the card: always `rules`, the threshold engine. It used to echo the account's AI provider although no model wrote any card.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
@@ -2657,8 +2697,11 @@ export const coachSeededQuestionResponse = z
|
||||
})
|
||||
.nullable()
|
||||
.describe(
|
||||
"Null whenever nothing crossed the detector's confidence and notability gate, AND whenever the account has turned proactive suggestions off — the two are indistinguishable on the wire, and both mean the hero keeps its neutral greeting rather than showing a fabricated opener.",
|
||||
"Null whenever nothing crossed the detector's confidence and notability gate, AND whenever the account has turned proactive suggestions off, AND whenever the `coach` capability is unavailable (then `ai` says why) — all mean the hero keeps its neutral greeting rather than showing a fabricated opener.",
|
||||
),
|
||||
ai: aiCapabilityState.describe(
|
||||
"The `coach` capability the opener exists for.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "CoachSeededQuestion",
|
||||
@@ -2697,12 +2740,17 @@ export const narrativeResponse = z
|
||||
updatedAt: z.iso.datetime({ offset: true }),
|
||||
})
|
||||
.nullable()
|
||||
.describe("Null when no row exists for this period and locale yet."),
|
||||
.describe(
|
||||
"Null when no row exists for this period and locale yet, and when the stored row is model-written while the `periodNarrative` capability is unavailable (a deterministic row is always served).",
|
||||
),
|
||||
revalidating: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"True when this read enqueued a warm. Always FALSE on a delegated request even when the row is stale: this route warms unconditionally rather than on a miss, so a manager's first navigation here would otherwise be an egress of the owner's record the owner never asked for. The stale row is still served; only the warm is withheld.",
|
||||
"True when this read enqueued a warm. Always FALSE on a delegated request even when the row is stale: this route warms unconditionally rather than on a miss, so a manager's first navigation here would otherwise be an egress of the owner's record the owner never asked for. The stale row is still served; only the warm is withheld. Also false while `periodNarrative` is unavailable and a servable row exists.",
|
||||
),
|
||||
ai: aiCapabilityState.describe(
|
||||
"The `periodNarrative` capability behind model-written narratives.",
|
||||
),
|
||||
})
|
||||
.meta({
|
||||
id: "NarrativeResponse",
|
||||
|
||||
@@ -609,7 +609,7 @@ const aiProviderResponse = z
|
||||
aiAvailable: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"True when ANY provider can serve this user — including the operator's server-managed key when the user set none. iOS keys Coach visibility off this.",
|
||||
"True when ANY provider can serve this user — including the operator's server-managed key when the user set none — AND the operator's master AI switch is on. With every AI capability switched off there is no AI available, whatever is configured. iOS keys Coach visibility off this. The per-capability answer is `ai` on `/api/auth/me`.",
|
||||
),
|
||||
managedBy: z
|
||||
.enum(["user", "local", "server"])
|
||||
@@ -665,7 +665,7 @@ const aiProviderResponse = z
|
||||
serverProviderOffer: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"Whether the shared provider may honestly be offered to this caller in one tap. True only when all of: the operator's provider is the one that would serve them (`managedBy: \"server\"`), `serverProviderHealth` is `healthy`, the operator's assistant master + coach flags are on, the acting record holds its own credentials (a managed profile never does), the caller holds no receipt yet, and the instance is not running in demo mode (where the grant the tap makes is refused at the edge). Anything unknown makes it false.",
|
||||
'Whether the shared provider may honestly be offered to this caller in one tap. True only when all of: the operator\'s provider is the one that would serve them (`managedBy: "server"`), `serverProviderHealth` is `healthy`, the operator keeps at least one capability the consent would unlock switched on (the Coach, the daily briefing, or reading documents; the master switch off turns all three off), the acting record holds its own credentials (a managed profile never does), the caller holds no receipt yet, and the instance is not running in demo mode (where the grant the tap makes is refused at the edge). Anything unknown makes it false.',
|
||||
),
|
||||
serverProviderConsent: z
|
||||
.boolean()
|
||||
|
||||
@@ -532,23 +532,12 @@ export function recordRefusal(...alsoRefusesFor: string[]): RefusalResponse {
|
||||
return response;
|
||||
}
|
||||
|
||||
// ── AI-consent precondition (v1.16.13) ───────────────────────────────
|
||||
// The server-managed AI-egress gate requires an active ConsentReceipt
|
||||
// (`ai_full`, or the surface-specific `ai_insights_only` / `ai_coach`)
|
||||
// before any health snapshot leaves for the operator's global LLM key.
|
||||
// Interactive routes surface this as a 403 with
|
||||
// `meta.errorCode = "consent.ai.required"`; clients render an inline
|
||||
// grant-consent notice and call POST /api/consent/ai (or, on web, POST
|
||||
// /api/consent/ai/web) to mint the receipt. BYOK / local / ChatGPT-OAuth
|
||||
// chains are the user's own egress and never trip this gate.
|
||||
//
|
||||
// There is no `consentRequiredResponse` beside this description any more, and
|
||||
// the absence is deliberate. Every route that could answer it is also a route
|
||||
// the sharing fence can refuse, and OpenAPI allows one response per status, so
|
||||
// the two 403s share a single description built by `recordRefusal(...)`. A
|
||||
// second exported 403 body would be a second way to write the same operation.
|
||||
export const AI_CONSENT_REQUIRED_DESCRIPTION =
|
||||
"AI consent required: no active ConsentReceipt for the server-managed provider. `meta.errorCode` = `consent.ai.required`. Mint a receipt via POST /api/consent/ai before retrying.";
|
||||
// ── AI-consent precondition ──────────────────────────────────────────
|
||||
// A missing consent receipt is one reason an AI capability is unavailable:
|
||||
// the refusal is the capability envelope (`meta.errorCode` =
|
||||
// `consent.ai.required`, `meta.reason` = `consent_required`), described once on
|
||||
// `ErrorEnvelope` and per capability in `./ai-refusal.ts`. Data routes never
|
||||
// answer it.
|
||||
|
||||
// ── Module-disabled gate (v1.18.0) ───────────────────────────────────
|
||||
// Every module-scoped route runs `requireModuleEnabled(userId, key)`,
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
recordRefusal,
|
||||
stdResponses,
|
||||
} from "./shared";
|
||||
import { aiCapabilityState } from "./profile";
|
||||
|
||||
// v1.4.25 W16b — typed workout batch ingest response envelope. Mirrors
|
||||
// the measurements batch shape but reports the `workouts` count rather
|
||||
@@ -239,6 +240,9 @@ const workoutDetailResponse = z
|
||||
// feature was live, over the duration floor, under the day's cap and with
|
||||
// a provider reachable. Reading this endpoint never generates one.
|
||||
aiInsight: workoutActivityInsight.nullable(),
|
||||
ai: aiCapabilityState.describe(
|
||||
"The `workoutInsights` AI capability. While it is unavailable `aiInsight` is null and the stored paragraph is not even read.",
|
||||
),
|
||||
canonicalId: z.string(),
|
||||
/**
|
||||
* The canonical session before this one in the same sport, or null when
|
||||
@@ -284,7 +288,7 @@ export const workoutPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Measurements"],
|
||||
summary: "Workout detail (v1.4.32)",
|
||||
description:
|
||||
"Single-workout envelope. Owns the optional `WorkoutRoute` GeoJSON geometry + `canonicalId` pointer that resolves to the cluster winner so deep-links into non-canonical twin rows can redirect cleanly. Additive enrichment fields (`hrSeries`, `zones`, `splits`, `sportContext`) are computed server-side. `aiInsight` is a pure read of a per-workout paragraph written by a background job when the workout landed; it is null for every workout that predates the feature or was re-synced, and reading this endpoint never generates one. `compact=1` (sent by the web client) drops the raw `samples.samples` HR blob and `route.sampleTimestamps` array from the response; without it the payload is byte-identical to the v1.4.32 contract. Cross-user rows surface as 404 (existence channel sealed).",
|
||||
"Single-workout envelope. Owns the optional `WorkoutRoute` GeoJSON geometry + `canonicalId` pointer that resolves to the cluster winner so deep-links into non-canonical twin rows can redirect cleanly. Additive enrichment fields (`hrSeries`, `zones`, `splits`, `sportContext`) are computed server-side. `aiInsight` is a pure read of a per-workout paragraph written by a background job when the workout landed; it is null for every workout that predates the feature or was re-synced, and while the `workoutInsights` AI capability is unavailable (`ai` says why), and reading this endpoint never generates one. `compact=1` (sent by the web client) drops the raw `samples.samples` HR blob and `route.sampleTimestamps` array from the response; without it the payload is byte-identical to the v1.4.32 contract. Cross-user rows surface as 404 (existence channel sealed).",
|
||||
requestParams: {
|
||||
path: z.object({ id: z.string() }),
|
||||
query: z.object({
|
||||
|
||||
Reference in new issue
Block a user