feat(coach,admin): finish the self-context and invite surfaces end to end

Invites move into their own admin section with a real ledger: status
badges, expiry, uses, a redemption history of who joined when (new
redemption table, revocation is now soft so history survives), and an
honest one-time link/QR moment. The assistant self-context grows
structured fields for conditions, allergies and focus — encrypted like
the free text — merges age and gender from the profile into one fenced
prompt block, and asks up to three targeted follow-up questions that
surface as tappable chips above the coach composer. A fourth nudge
trigger gently suggests a check-up when the self-context is stale and
the coach is actually in use.
This commit is contained in:
Marc-André Bombeck committed 2026-06-10 16:18:48 +02:00
1 parent 9fe5673251
commit 5b75184649
32 files changed
+2648 -423

No files matched your search

@@ -0,0 +1,178 @@
/**
* v1.16.0 — structured self-context unit tests.
*
* Pins the pure pieces of the questionnaire feature without a DB:
* - `deriveAgeYears` — whole-year age math incl. the pre-birthday edge.
* - `composeSelfContextText` — merge order (profile facts → structured
* answers → free text), the profile-facts-alone-stay-silent rule,
* and the de/en label split.
* - `clampPendingQuestions` — count + length caps, non-string drops.
* - `parseQuestionsReply` — tolerant JSON-array extraction from a
* model reply (fences, prose, garbage).
* - `buildFallbackQuestions` — deterministic two-hint fallback in
* priority order, localised.
*/
import { describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({ prisma: {} }));
import {
clampPendingQuestions,
composeSelfContextText,
deriveAgeYears,
PENDING_QUESTION_MAX_CHARS,
type SelfContext,
} from "../about-me";
import {
buildFallbackQuestions,
parseQuestionsReply,
} from "../self-context-questions";
const emptyCtx: SelfContext = {
aboutMe: null,
conditions: null,
allergies: null,
coachFocus: null,
};
describe("deriveAgeYears", () => {
const now = new Date("2026-06-10T12:00:00Z");
it("counts whole years after the birthday", () => {
expect(deriveAgeYears(new Date("1980-06-01"), now)).toBe(46);
});
it("does not count the year before the birthday", () => {
expect(deriveAgeYears(new Date("1980-06-20"), now)).toBe(45);
});
it("returns null for unknown or implausible dates", () => {
expect(deriveAgeYears(null, now)).toBeNull();
expect(deriveAgeYears(new Date("1850-01-01"), now)).toBeNull();
expect(deriveAgeYears(new Date("2030-01-01"), now)).toBeNull();
});
});
describe("composeSelfContextText", () => {
const profile = { ageYears: 46, gender: "MALE" };
it("stays null when the user wrote nothing — profile facts alone are not a self-description", () => {
expect(composeSelfContextText(emptyCtx, profile, "de")).toBeNull();
});
it("merges profile facts, structured answers, and free text in order (de labels)", () => {
const text = composeSelfContextText(
{
aboutMe: "Schichtarbeit, Halbmarathon-Training.",
conditions: "Hypertonie",
allergies: "Laktose",
coachFocus: "Blutdruck",
},
profile,
"de",
);
expect(text).toBe(
[
"Profil: Alter: 46 · Geschlecht: männlich",
"Chronische Erkrankungen: Hypertonie",
"Allergien / Unverträglichkeiten: Laktose",
"Darauf soll der Coach achten: Blutdruck",
"",
"Schichtarbeit, Halbmarathon-Training.",
].join("\n"),
);
});
it("uses English labels for every non-de locale", () => {
const text = composeSelfContextText(
{ ...emptyCtx, conditions: "asthma" },
{ ageYears: null, gender: "OTHER" },
"pl",
);
expect(text).toBe(
["Profile: Gender: non-binary", "Chronic conditions: asthma"].join("\n"),
);
});
it("skips unknown gender codes instead of echoing them", () => {
const text = composeSelfContextText(
{ ...emptyCtx, aboutMe: "hello" },
{ ageYears: null, gender: "SOMETHING_ELSE" },
"en",
);
expect(text).toBe("hello");
});
});
describe("clampPendingQuestions", () => {
it("caps at 3 questions and per-question length", () => {
const long = "x".repeat(PENDING_QUESTION_MAX_CHARS + 50);
const result = clampPendingQuestions(["a", "b", long, "d"]);
expect(result).toHaveLength(3);
expect(result[2]).toHaveLength(PENDING_QUESTION_MAX_CHARS);
});
it("drops non-strings, blanks, and non-arrays", () => {
expect(clampPendingQuestions([" ok ", 42, "", null])).toEqual(["ok"]);
expect(clampPendingQuestions("not an array")).toEqual([]);
expect(clampPendingQuestions(undefined)).toEqual([]);
});
});
describe("parseQuestionsReply", () => {
it("parses a bare JSON array", () => {
expect(parseQuestionsReply('["Frage 1?", "Frage 2?"]')).toEqual([
"Frage 1?",
"Frage 2?",
]);
});
it("tolerates code fences and prose around the array", () => {
const reply =
'Sure! Here are the questions:\n```json\n["A?", "B?"]\n```\nHope that helps.';
expect(parseQuestionsReply(reply)).toEqual(["A?", "B?"]);
});
it("yields [] for garbage so the caller falls back", () => {
expect(parseQuestionsReply("no array here")).toEqual([]);
expect(parseQuestionsReply("[broken")).toEqual([]);
expect(parseQuestionsReply('{"not": "an array"}')).toEqual([]);
});
});
describe("buildFallbackQuestions", () => {
it("returns the first two missing fields in priority order, localised", () => {
const hints = buildFallbackQuestions(emptyCtx, "de");
expect(hints).toEqual([
"Hast du chronische Erkrankungen, die der Coach kennen sollte?",
"Gibt es etwas Bestimmtes, worauf der Coach achten soll?",
]);
});
it("skips answered fields", () => {
const hints = buildFallbackQuestions(
{
aboutMe: "text",
conditions: "hypertension",
allergies: null,
coachFocus: "bp",
},
"en",
);
expect(hints).toEqual(["Do you have any allergies or intolerances?"]);
});
it("returns nothing for a fully answered questionnaire", () => {
expect(
buildFallbackQuestions(
{
aboutMe: "a",
conditions: "b",
allergies: "c",
coachFocus: "d",
},
"en",
),
).toEqual([]);
});
});
+252 -25
View File
@@ -1,49 +1,274 @@
/**
* v1.15.20 — user-authored "about me" self-description for the AI surfaces.
* v1.16.0 — extended into a structured self-context: alongside the free
* text the user can answer three short questions (chronic conditions,
* allergies/intolerances, what the Coach should watch). Age and gender
* are NOT stored here — they live on the User profile and are merged
* into the composed prompt text at assembly time, so the questionnaire
* never duplicates profile data.
*
* The user writes a short free-text introduction (conditions they want the
* Coach to know about, life context, goals — whatever they choose to share)
* in Settings → AI. The text is stored encrypted at rest
* (`UserHealthProfile.aboutMeEncrypted`, the shared Bytes codec) and is
* injected into two prompts as a clearly delimited, user-provided context
* block:
* Storage: every field is encrypted at rest
* (`UserHealthProfile.*Encrypted`, the shared Bytes codec) and injected
* into two prompts as a clearly delimited, user-provided context block:
*
* - the Coach system prompt (`getCoachSystemPrompt`, third argument), and
* - the daily-briefing user prompt (`/api/insights/generate` +
* `comprehensive-generate.ts`).
*
* The block carries an explicit instruction frame: the text is the user's
* OWN words, the single source for personal context, and nothing beyond it
* OWN words, the single source for personal context, and nothing beyond it
* may be invented. Reads are fail-closed per row — an undecryptable payload
* (key rotated out of the map) yields `null` rather than ciphertext.
*
* `pendingQuestions` — up to 3 clarifying questions the server derives
* after a save (see `self-context-questions.ts`); the Coach composer
* renders them as tappable suggestion chips. Encrypted JSON string[].
*
* Server-only — reads `@/lib/db`.
*/
import { prisma } from "@/lib/db";
import { decryptFromBytes } from "@/lib/ai/coach/bytes-codec";
import {
decryptFromBytes,
encryptToBytes,
} from "@/lib/ai/coach/bytes-codec";
export { ABOUT_ME_MAX_CHARS } from "@/lib/validations/about-me";
export interface SelfContext {
aboutMe: string | null;
conditions: string | null;
allergies: string | null;
coachFocus: string | null;
}
function decryptOrNull(payload: Uint8Array | null): string | null {
if (!payload) return null;
try {
const text = decryptFromBytes(payload).trim();
return text.length > 0 ? text : null;
} catch {
// Fail closed per field — never surface ciphertext, never throw
// into a prompt-assembly path.
return null;
}
}
/**
* Load + decrypt the caller's "about me" text. Returns `null` when the
* user never wrote one, cleared it, or the payload no longer decrypts
* (fail closed — never surface ciphertext, never throw into a prompt
* assembly path).
* Load + decrypt the caller's structured self-context. Every field is
* independently fail-closed; a row that never existed yields all-null.
*/
export async function getAboutMeForUser(userId: string): Promise<string | null> {
export async function getSelfContextForUser(
userId: string,
): Promise<SelfContext> {
try {
const row = await prisma.userHealthProfile.findUnique({
where: { userId },
select: { aboutMeEncrypted: true },
select: {
aboutMeEncrypted: true,
conditionsEncrypted: true,
allergiesEncrypted: true,
coachFocusEncrypted: true,
},
});
if (!row?.aboutMeEncrypted) return null;
const text = decryptFromBytes(row.aboutMeEncrypted).trim();
return text.length > 0 ? text : null;
return {
aboutMe: decryptOrNull(row?.aboutMeEncrypted ?? null),
conditions: decryptOrNull(row?.conditionsEncrypted ?? null),
allergies: decryptOrNull(row?.allergiesEncrypted ?? null),
coachFocus: decryptOrNull(row?.coachFocusEncrypted ?? null),
};
} catch {
return { aboutMe: null, conditions: null, allergies: null, coachFocus: null };
}
}
/**
* Back-compat shim for callers that only need the free text (kept so
* the questions generator can cheaply inspect the prose alone).
*/
export async function getAboutMeForUser(
userId: string,
): Promise<string | null> {
return (await getSelfContextForUser(userId)).aboutMe;
}
/** Whole years between `dateOfBirth` and `now`; null when unknown. */
export function deriveAgeYears(
dateOfBirth: Date | null,
now: Date = new Date(),
): number | null {
if (!dateOfBirth) return null;
let age = now.getFullYear() - dateOfBirth.getFullYear();
const beforeBirthday =
now.getMonth() < dateOfBirth.getMonth() ||
(now.getMonth() === dateOfBirth.getMonth() &&
now.getDate() < dateOfBirth.getDate());
if (beforeBirthday) age -= 1;
return age >= 0 && age < 130 ? age : null;
}
const GENDER_LABELS: Record<"de" | "en", Record<string, string>> = {
de: { MALE: "männlich", FEMALE: "weiblich", OTHER: "divers" },
en: { MALE: "male", FEMALE: "female", OTHER: "non-binary" },
};
/**
* Compose the merged self-context text the prompt block quotes: profile
* facts first (age/gender from the User row — the single source, never
* duplicated into the questionnaire), then the structured answers, then
* the free text. Returns `null` when there is nothing to say — the
* prompt assembly skips the whole block in that case.
*
* Labels follow the de/en split of the surrounding block builders; the
* quoted values themselves stay in whatever language the user wrote.
*/
export function composeSelfContextText(
ctx: SelfContext,
profile: { ageYears: number | null; gender: string | null },
locale: string,
): string | null {
const de = locale === "de";
const lines: string[] = [];
const facts: string[] = [];
if (profile.ageYears !== null) {
facts.push(de ? `Alter: ${profile.ageYears}` : `Age: ${profile.ageYears}`);
}
if (profile.gender) {
const label =
GENDER_LABELS[de ? "de" : "en"][profile.gender.toUpperCase()] ?? null;
if (label) {
facts.push(de ? `Geschlecht: ${label}` : `Gender: ${label}`);
}
}
if (facts.length > 0) {
lines.push(
(de ? "Profil: " : "Profile: ") + facts.join(" · "),
);
}
if (ctx.conditions) {
lines.push(
(de ? "Chronische Erkrankungen: " : "Chronic conditions: ") +
ctx.conditions,
);
}
if (ctx.allergies) {
lines.push(
(de
? "Allergien / Unverträglichkeiten: "
: "Allergies / intolerances: ") + ctx.allergies,
);
}
if (ctx.coachFocus) {
lines.push(
(de ? "Darauf soll der Coach achten: " : "The Coach should watch: ") +
ctx.coachFocus,
);
}
if (ctx.aboutMe) {
if (lines.length > 0) lines.push("");
lines.push(ctx.aboutMe);
}
// Profile facts alone are not a self-description — without at least
// one user-authored field the block stays absent, exactly like before
// the structured fields existed.
const hasUserContent =
ctx.aboutMe !== null ||
ctx.conditions !== null ||
ctx.allergies !== null ||
ctx.coachFocus !== null;
if (!hasUserContent) return null;
return lines.join("\n");
}
/**
* One-call variant for the prompt-assembly paths: load the structured
* context + the profile facts and return the composed text (or `null`
* when the user never wrote anything). Replaces the v1.15.20
* `getAboutMeForUser` call sites.
*/
export async function getSelfContextTextForUser(
userId: string,
locale: string,
): Promise<string | null> {
try {
const [ctx, user] = await Promise.all([
getSelfContextForUser(userId),
prisma.user.findUnique({
where: { id: userId },
select: { dateOfBirth: true, gender: true },
}),
]);
return composeSelfContextText(
ctx,
{
ageYears: deriveAgeYears(user?.dateOfBirth ?? null),
gender: user?.gender ?? null,
},
locale,
);
} catch {
return null;
}
}
/** Hard caps on the persisted clarifying questions. */
export const PENDING_QUESTIONS_MAX = 3;
export const PENDING_QUESTION_MAX_CHARS = 200;
/** Clamp + sanitise a candidate question list before persisting. */
export function clampPendingQuestions(questions: unknown): string[] {
if (!Array.isArray(questions)) return [];
return questions
.filter((q): q is string => typeof q === "string")
.map((q) => q.trim())
.filter((q) => q.length > 0)
.map((q) => q.slice(0, PENDING_QUESTION_MAX_CHARS))
.slice(0, PENDING_QUESTIONS_MAX);
}
/**
* Read the caller's pending clarifying questions. Fail-closed: a
* missing row, NULL payload, or undecryptable ciphertext yields `[]`.
*/
export async function getPendingQuestionsForUser(
userId: string,
): Promise<string[]> {
try {
const row = await prisma.userHealthProfile.findUnique({
where: { userId },
select: { pendingQuestionsEncrypted: true },
});
if (!row?.pendingQuestionsEncrypted) return [];
return clampPendingQuestions(
JSON.parse(decryptFromBytes(row.pendingQuestionsEncrypted)),
);
} catch {
return [];
}
}
/**
* Persist (or clear, with `null` / `[]`) the pending questions.
* Upserts so a user who never saved a self-context can still receive
* the deterministic fallback hints.
*/
export async function setPendingQuestionsForUser(
userId: string,
questions: string[] | null,
): Promise<void> {
const clamped = questions === null ? [] : clampPendingQuestions(questions);
const payload =
clamped.length > 0 ? encryptToBytes(JSON.stringify(clamped)) : null;
await prisma.userHealthProfile.upsert({
where: { userId },
create: { userId, pendingQuestionsEncrypted: payload },
update: { pendingQuestionsEncrypted: payload },
});
}
/**
* Compose the delimited context block the briefing user prompt appends
* (the GLP-1-plateau / derived-signal precedent: a SYSTEM CONTEXT block
@@ -62,10 +287,11 @@ SYSTEM CONTEXT — SELBSTAUSKUNFT (vom Nutzer bereitgestellt):
"""
${aboutMe}
"""
Dieser Text stammt wörtlich vom Nutzer und ist die EINZIGE Quelle für
persönlichen Kontext jenseits der Messdaten. Nutze ihn, um die Einordnung
zu personalisieren. Behandle ihn beschreibend, nie diagnostisch. Erfinde
nichts, was weder in den Daten noch in diesem Text steht.`;
Dieser Text stammt vom Nutzer (plus Alter/Geschlecht aus dem Profil) und
ist die EINZIGE Quelle für persönlichen Kontext jenseits der Messdaten.
Nutze ihn, um die Einordnung zu personalisieren. Behandle ihn
beschreibend, nie diagnostisch. Erfinde nichts, was weder in den Daten
noch in diesem Text steht.`;
}
return `
@@ -73,8 +299,9 @@ SYSTEM CONTEXT — ABOUT ME (provided by the user):
"""
${aboutMe}
"""
This text is the user's own words and the ONLY source of personal context
beyond the measurement data. Use it to personalise the assessment. Treat
it as descriptive, never diagnostic. Do not invent anything that is in
neither the data nor this text.`;
This text comes from the user (plus age/gender from their profile) and
is the ONLY source of personal context beyond the measurement data. Use
it to personalise the assessment. Treat it as descriptive, never
diagnostic. Do not invent anything that is in neither the data nor this
text.`;
}
+163
View File
@@ -0,0 +1,163 @@
/**
* v1.16.0 — clarifying questions for the self-context questionnaire.
*
* After the user saves Settings → AI → "About me", the server derives
* up to 3 short follow-up questions that would best complete the
* picture for the Coach, and persists them encrypted
* (`UserHealthProfile.pendingQuestionsEncrypted`). The Coach composer
* renders them as tappable suggestion chips; answering or dismissing a
* chip removes it.
*
* Two paths, gated in order:
* 1. AI path — only when the user has a working provider
* (`hasAnyConfiguredProvider`) AND the daily Coach token budget
* is not exhausted. One single-shot completion (no fallback
* chain — this is a nicety, not a core flow); spend is recorded
* against the same per-day ledger the Coach uses.
* 2. Deterministic path — two static completion hints for the first
* two unanswered fields, localised through the server translator.
* Also the landing spot for every AI-path failure (no provider,
* budget gone, model error, unparseable output).
*
* Server-only — reads `@/lib/db` through the provider resolver.
*/
import {
hasAnyConfiguredProvider,
resolveProvider,
} from "@/lib/ai/provider";
import {
buildDateKey,
getDailyTokenSpend,
MAX_TOKENS_PER_USER_PER_DAY,
recordSpend,
} from "@/lib/ai/coach/budget";
import {
clampPendingQuestions,
type SelfContext,
} from "@/lib/ai/coach/about-me";
import { getServerTranslator } from "@/lib/i18n/server-translator";
import type { Locale } from "@/lib/i18n/config";
import { defaultLocale, locales } from "@/lib/i18n/config";
import { annotate } from "@/lib/logging/context";
/** Token ceiling for the single-shot questions completion. */
const QUESTIONS_MAX_TOKENS = 300;
const LANGUAGE_NAMES: Record<Locale, string> = {
de: "German",
en: "English",
es: "Spanish",
fr: "French",
it: "Italian",
pl: "Polish",
};
function resolveLocale(locale: string | null | undefined): Locale {
return locales.includes(locale as Locale)
? (locale as Locale)
: defaultLocale;
}
/**
* Deterministic fallback: completion hints for the first two unanswered
* fields, in a fixed priority order (conditions → focus → allergies →
* free text). Fully answered questionnaires get no hints — there is
* nothing left to complete.
*/
export function buildFallbackQuestions(
ctx: SelfContext,
locale: string | null | undefined,
): string[] {
const t = getServerTranslator(resolveLocale(locale)).t;
const hints: string[] = [];
if (!ctx.conditions) hints.push(t("coachNudges.questionConditions"));
if (!ctx.coachFocus) hints.push(t("coachNudges.questionFocus"));
if (!ctx.allergies) hints.push(t("coachNudges.questionAllergies"));
if (!ctx.aboutMe) hints.push(t("coachNudges.questionAboutMe"));
return hints.slice(0, 2);
}
/**
* Extract a string[] from a model reply that should be a JSON array.
* Tolerates code fences and prose around the array; everything else
* yields `[]` so the caller falls back deterministically.
*/
export function parseQuestionsReply(content: string): string[] {
const start = content.indexOf("[");
const end = content.lastIndexOf("]");
if (start === -1 || end === -1 || end <= start) return [];
try {
return clampPendingQuestions(JSON.parse(content.slice(start, end + 1)));
} catch {
return [];
}
}
function buildPrompts(
ctx: SelfContext,
locale: Locale,
): { systemPrompt: string; userPrompt: string } {
const language = LANGUAGE_NAMES[locale];
const systemPrompt = `You help complete a health-app user's self-description for their AI health coach. Based on what the user has already shared, write AT MOST 3 short, specific follow-up questions that would best complete the picture (e.g. unstated conditions a stated medication implies, missing context for a stated goal). Never ask for anything already answered. Never ask for a diagnosis. Write the questions in ${language}, addressed informally to the user. Reply with ONLY a JSON array of strings — no prose, no code fences.`;
const fieldLines = [
`conditions: ${ctx.conditions ?? "(not answered)"}`,
`allergies/intolerances: ${ctx.allergies ?? "(not answered)"}`,
`coach focus: ${ctx.coachFocus ?? "(not answered)"}`,
`free text: ${ctx.aboutMe ?? "(not answered)"}`,
];
return { systemPrompt, userPrompt: fieldLines.join("\n") };
}
/**
* Derive the pending questions for a freshly saved self-context.
* Never throws — every failure path lands on the deterministic
* fallback so the PUT route stays robust.
*/
export async function deriveClarifyingQuestions(
userId: string,
ctx: SelfContext,
locale: string | null | undefined,
): Promise<{ questions: string[]; source: "ai" | "fallback" }> {
const fallback = () => ({
questions: buildFallbackQuestions(ctx, locale),
source: "fallback" as const,
});
try {
if (!(await hasAnyConfiguredProvider(userId))) return fallback();
// Budget gate — same per-day ledger the Coach chat enforces.
const dateKey = buildDateKey();
const spent = await getDailyTokenSpend(userId, dateKey);
if (spent >= MAX_TOKENS_PER_USER_PER_DAY) return fallback();
const provider = await resolveProvider(userId);
const { systemPrompt, userPrompt } = buildPrompts(
ctx,
resolveLocale(locale),
);
const result = await provider.generateCompletion({
systemPrompt,
userPrompt,
temperature: 0.4,
maxTokens: QUESTIONS_MAX_TOKENS,
});
if (typeof result.tokensUsed === "number" && result.tokensUsed > 0) {
await recordSpend({ userId, tokens: result.tokensUsed, dateKey });
}
const questions = parseQuestionsReply(result.content);
if (questions.length === 0) return fallback();
annotate({
meta: {
self_context_questions_source: "ai",
self_context_questions_count: questions.length,
},
});
return { questions, source: "ai" };
} catch {
return fallback();
}
}
+131
View File
@@ -0,0 +1,131 @@
/**
* v1.16.0 — invite-token consume-path unit tests.
*
* Pins the gate order against a mocked Prisma client:
* - shape gate (`looksLikeInviteToken`) short-circuits before any DB hit,
* - revoked > expired > exhausted refusal precedence,
* - the guarded-increment WHERE carries `revokedAt: null`,
* - `recordInviteConsumer` writes the `usedBy` stamp AND the
* redemption-ledger row in one transaction.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
const findUnique = vi.fn();
const updateMany = vi.fn();
const update = vi.fn();
const redemptionCreate = vi.fn();
const transaction = vi.fn(async (ops: unknown[]) => ops);
vi.mock("@/lib/db", () => ({
prisma: {
inviteToken: {
findUnique: (...args: unknown[]) => findUnique(...args),
updateMany: (...args: unknown[]) => updateMany(...args),
update: (...args: unknown[]) => update(...args),
},
inviteRedemption: {
create: (...args: unknown[]) => redemptionCreate(...args),
},
$transaction: (...args: unknown[]) => transaction(...(args as [unknown[]])),
},
}));
import {
consumeInviteToken,
generateInviteToken,
looksLikeInviteToken,
recordInviteConsumer,
} from "../invite-token";
const FUTURE = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
const PAST = new Date(Date.now() - 60 * 60 * 1000);
function baseInvite(overrides: Record<string, unknown> = {}) {
return {
id: "inv1",
expiresAt: FUTURE,
uses: 0,
maxUses: 1,
revokedAt: null,
...overrides,
};
}
beforeEach(() => {
vi.clearAllMocks();
process.env.API_TOKEN_HMAC_KEY = "0".repeat(64);
});
describe("consumeInviteToken", () => {
it("rejects malformed tokens before touching the DB", async () => {
const result = await consumeInviteToken("not-a-token");
expect(result).toEqual({ ok: false, reason: "not_found" });
expect(findUnique).not.toHaveBeenCalled();
});
it("refuses a revoked invite ahead of every other state", async () => {
findUnique.mockResolvedValue(
baseInvite({ revokedAt: PAST, expiresAt: PAST, uses: 5, maxUses: 1 }),
);
const result = await consumeInviteToken(generateInviteToken());
expect(result).toEqual({ ok: false, reason: "revoked" });
expect(updateMany).not.toHaveBeenCalled();
});
it("refuses an expired invite", async () => {
findUnique.mockResolvedValue(baseInvite({ expiresAt: PAST }));
const result = await consumeInviteToken(generateInviteToken());
expect(result).toEqual({ ok: false, reason: "expired" });
});
it("refuses an exhausted invite", async () => {
findUnique.mockResolvedValue(baseInvite({ uses: 1, maxUses: 1 }));
const result = await consumeInviteToken(generateInviteToken());
expect(result).toEqual({ ok: false, reason: "exhausted" });
});
it("consumes a valid invite with a revocation-guarded increment", async () => {
findUnique.mockResolvedValue(baseInvite());
updateMany.mockResolvedValue({ count: 1 });
const result = await consumeInviteToken(generateInviteToken());
expect(result).toEqual({ ok: true, inviteId: "inv1" });
const where = updateMany.mock.calls[0][0].where;
expect(where.revokedAt).toBeNull();
expect(where.uses).toEqual({ lt: 1 });
});
it("treats a lost increment race as exhausted", async () => {
findUnique.mockResolvedValue(baseInvite({ maxUses: 2, uses: 1 }));
updateMany.mockResolvedValue({ count: 0 });
const result = await consumeInviteToken(generateInviteToken());
expect(result).toEqual({ ok: false, reason: "exhausted" });
});
});
describe("recordInviteConsumer", () => {
it("stamps usedBy and appends a redemption-ledger row", async () => {
await recordInviteConsumer("inv1", "user1");
expect(transaction).toHaveBeenCalledTimes(1);
expect(update).toHaveBeenCalledWith({
where: { id: "inv1" },
data: { usedBy: "user1" },
});
expect(redemptionCreate).toHaveBeenCalledWith({
data: { inviteId: "inv1", userId: "user1" },
});
});
it("swallows failures — the use is already counted", async () => {
transaction.mockRejectedValueOnce(new Error("boom"));
await expect(recordInviteConsumer("inv1", "user1")).resolves.toBeUndefined();
});
});
describe("looksLikeInviteToken", () => {
it("accepts the generated shape and rejects near-misses", () => {
expect(looksLikeInviteToken(generateInviteToken())).toBe(true);
expect(looksLikeInviteToken("hlk_" + "a".repeat(64))).toBe(false);
expect(looksLikeInviteToken("hlv_" + "a".repeat(63))).toBe(false);
expect(looksLikeInviteToken("hlv_" + "G".repeat(64))).toBe(false);
});
});
+30 -10
View File
@@ -66,7 +66,7 @@ export type InviteConsumeResult =
| { ok: true; inviteId: string }
| {
ok: false;
reason: "not_found" | "expired" | "exhausted";
reason: "not_found" | "expired" | "exhausted" | "revoked";
};
/**
@@ -85,11 +85,22 @@ export async function consumeInviteToken(
const tokenHash = hashToken(rawToken);
const invite = await prisma.inviteToken.findUnique({
where: { tokenHash },
select: { id: true, expiresAt: true, uses: true, maxUses: true },
select: {
id: true,
expiresAt: true,
uses: true,
maxUses: true,
revokedAt: true,
},
});
if (!invite) return { ok: false, reason: "not_found" };
const now = new Date();
// v1.16.0 — a revoked invite is refused like an expired one; the row
// stays so the admin table keeps its redemption history visible.
if (invite.revokedAt !== null) {
return { ok: false, reason: "revoked" };
}
if (invite.expiresAt.getTime() <= now.getTime()) {
return { ok: false, reason: "expired" };
}
@@ -101,6 +112,7 @@ export async function consumeInviteToken(
where: {
id: invite.id,
expiresAt: { gt: now },
revokedAt: null,
// Guarded increment — Postgres evaluates the predicate and the
// UPDATE atomically, so a concurrent consumer of the last use
// makes this a no-op instead of an overshoot.
@@ -119,20 +131,28 @@ export async function consumeInviteToken(
}
/**
* Stamp the consumer account onto the invite after the user row exists.
* Best-effort + last-consumer-wins on multi-use invites; a failure here
* never unwinds the registration.
* Stamp the consumer account onto the invite after the user row exists
* AND append a row to the per-signup redemption ledger (v1.16.0 —
* `usedBy` only ever holds the LAST consumer; the ledger holds them
* all, so multi-use invites keep their full history). Best-effort; a
* failure here never unwinds the registration.
*/
export async function recordInviteConsumer(
inviteId: string,
userId: string,
): Promise<void> {
try {
await prisma.inviteToken.update({
where: { id: inviteId },
data: { usedBy: userId },
});
await prisma.$transaction([
prisma.inviteToken.update({
where: { id: inviteId },
data: { usedBy: userId },
}),
prisma.inviteRedemption.create({
data: { inviteId, userId },
}),
]);
} catch {
// Informational column only — the use itself is already counted.
// Informational rows only — the use itself is already counted by
// the guarded increment in `consumeInviteToken`.
}
}
+2 -2
View File
@@ -36,7 +36,7 @@ import {
import { buildSystemPromptWithReferences } from "@/lib/ai/prompts/insight-generator";
import {
buildAboutMeInsightBlock,
getAboutMeForUser,
getSelfContextTextForUser,
} from "@/lib/ai/coach/about-me";
import { metricsFromPresentSections } from "@/lib/ai/medical-references";
import { summarize, type DataPoint } from "@/lib/analytics/trends";
@@ -569,7 +569,7 @@ export async function generateComprehensiveInsight(
// v1.15.20 — fold the user-authored "about me" self-description
// (Settings → AI) into the nightly briefing exactly like the
// on-demand route. Null (no text / undecryptable) costs nothing.
const aboutMe = await getAboutMeForUser(userId);
const aboutMe = await getSelfContextTextForUser(userId, locale);
if (aboutMe) {
userPrompt += buildAboutMeInsightBlock(aboutMe, locale);
}
+70 -2
View File
@@ -21,6 +21,7 @@ import {
evaluateBpTrigger,
evaluateComplianceTrigger,
evaluateScoreTrigger,
evaluateSelfContextTrigger,
} from "../coach-nudge";
function dose(taken: boolean, skipped = false) {
@@ -137,10 +138,77 @@ describe("buildCoachNudgePayload", () => {
it("produces a distinct payload per trigger", () => {
const titles = new Set(
(["compliance", "bp", "score"] as const).map(
(["compliance", "bp", "score", "selfContext"] as const).map(
(trigger) => buildCoachNudgePayload(trigger, "en").title,
),
);
expect(titles.size).toBe(3);
expect(titles.size).toBe(4);
});
});
describe("evaluateSelfContextTrigger", () => {
const now = new Date("2026-06-10T05:15:00Z");
const daysAgo = (days: number) =>
new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
const fullProfile = (updatedAt: Date) => ({
hasAboutMe: true,
hasConditions: true,
hasAllergies: true,
hasCoachFocus: true,
updatedAt,
});
it("never fires without recent Coach activity", () => {
expect(
evaluateSelfContextTrigger(
{ profile: null, lastCoachUseAt: null },
now,
),
).toBe(false);
expect(
evaluateSelfContextTrigger(
{ profile: null, lastCoachUseAt: daysAgo(15) },
now,
),
).toBe(false);
});
it("fires for an active user with no profile at all", () => {
expect(
evaluateSelfContextTrigger(
{ profile: null, lastCoachUseAt: daysAgo(2) },
now,
),
).toBe(true);
});
it("fires for an incomplete profile", () => {
expect(
evaluateSelfContextTrigger(
{
profile: { ...fullProfile(daysAgo(1)), hasAllergies: false },
lastCoachUseAt: daysAgo(2),
},
now,
),
).toBe(true);
});
it("fires for a complete-but-stale profile (60+ days)", () => {
expect(
evaluateSelfContextTrigger(
{ profile: fullProfile(daysAgo(61)), lastCoachUseAt: daysAgo(2) },
now,
),
).toBe(true);
});
it("stays silent for a complete, fresh profile", () => {
expect(
evaluateSelfContextTrigger(
{ profile: fullProfile(daysAgo(10)), lastCoachUseAt: daysAgo(2) },
now,
),
).toBe(false);
});
});
+98 -1
View File
@@ -32,6 +32,11 @@
* - `score`: recovery score falling sharply — the last 7-day mean
* sits ≥ 15 points under the previous 7-day mean (≥ 3 samples in
* each window).
* - `selfContext` (v1.16.0): the self-context questionnaire is
* incomplete or 60+ days stale AND the user actively talks to the
* Coach (a CoachUsage row in the last 14 days) — a gentle check-up
* nudge to refresh the personal context the Coach reads. Presence
* is checked on the encrypted columns only; nothing is decrypted.
*/
import type { PrismaClient } from "@/generated/prisma/client";
import { getAssistantFlags } from "@/lib/feature-flags";
@@ -67,8 +72,12 @@ export const COACH_NUDGE_BP_MIN_READINGS = 3;
export const COACH_NUDGE_SCORE_DROP = 15;
/** Score trigger: minimum samples per weekly window. */
export const COACH_NUDGE_SCORE_MIN_SAMPLES = 3;
/** Self-context trigger: profile older than this counts as stale. */
export const COACH_NUDGE_SELF_CONTEXT_STALE_DAYS = 60;
/** Self-context trigger: Coach usage within this window counts as active. */
export const COACH_NUDGE_COACH_ACTIVE_DAYS = 14;
export type CoachNudgeTrigger = "compliance" | "bp" | "score";
export type CoachNudgeTrigger = "compliance" | "bp" | "score" | "selfContext";
export interface CoachNudgeSummary {
candidatesScanned: number;
@@ -114,6 +123,49 @@ export function evaluateBpTrigger(
return mean > greenMax;
}
export interface SelfContextTriggerInput {
/** Presence-only view of the questionnaire (encrypted columns). */
profile: {
hasAboutMe: boolean;
hasConditions: boolean;
hasAllergies: boolean;
hasCoachFocus: boolean;
updatedAt: Date;
} | null;
/** Most recent CoachUsage activity, or null when never used. */
lastCoachUseAt: Date | null;
}
/**
* v1.16.0 — fourth trigger: the self-context is incomplete (any of the
* four fields empty, or no profile at all) or stale (60+ days), AND
* the user actively talks to the Coach. Without the activity gate this
* would nag every passive account forever.
*/
export function evaluateSelfContextTrigger(
input: SelfContextTriggerInput,
now: Date,
): boolean {
const { profile, lastCoachUseAt } = input;
if (
lastCoachUseAt === null ||
now.getTime() - lastCoachUseAt.getTime() >
COACH_NUDGE_COACH_ACTIVE_DAYS * MS_PER_DAY
) {
return false;
}
if (profile === null) return true;
const incomplete =
!profile.hasAboutMe ||
!profile.hasConditions ||
!profile.hasAllergies ||
!profile.hasCoachFocus;
const stale =
now.getTime() - profile.updatedAt.getTime() >
COACH_NUDGE_SELF_CONTEXT_STALE_DAYS * MS_PER_DAY;
return incomplete || stale;
}
export function evaluateScoreTrigger(
recentValues: number[],
priorValues: number[],
@@ -155,6 +207,11 @@ export function buildCoachNudgePayload(
title: t("coachNudges.scoreTitle"),
body: t("coachNudges.scoreBody"),
};
case "selfContext":
return {
title: t("coachNudges.selfContextTitle"),
body: t("coachNudges.selfContextBody"),
};
}
}
@@ -235,6 +292,46 @@ export async function findTriggerForUser(
.map((m) => m.value);
if (evaluateScoreTrigger(recent, prior)) return "score";
// 4) Self-context incomplete / stale while the Coach is in active
// use. Presence-only reads on the encrypted columns — nothing is
// decrypted in this job.
const coachActiveCutoff = new Date(
now.getTime() - COACH_NUDGE_COACH_ACTIVE_DAYS * MS_PER_DAY,
);
const recentUsage = await prisma.coachUsage.findFirst({
where: { userId: user.id, updatedAt: { gte: coachActiveCutoff } },
orderBy: { updatedAt: "desc" },
select: { updatedAt: true },
});
if (recentUsage) {
const profileRow = await prisma.userHealthProfile.findUnique({
where: { userId: user.id },
select: {
aboutMeEncrypted: true,
conditionsEncrypted: true,
allergiesEncrypted: true,
coachFocusEncrypted: true,
updatedAt: true,
},
});
const triggered = evaluateSelfContextTrigger(
{
profile: profileRow
? {
hasAboutMe: profileRow.aboutMeEncrypted !== null,
hasConditions: profileRow.conditionsEncrypted !== null,
hasAllergies: profileRow.allergiesEncrypted !== null,
hasCoachFocus: profileRow.coachFocusEncrypted !== null,
updatedAt: profileRow.updatedAt,
}
: null,
lastCoachUseAt: recentUsage.updatedAt,
},
now,
);
if (triggered) return "selfContext";
}
return null;
}
+94 -11
View File
@@ -4346,19 +4346,25 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
"/api/coach/about-me": {
get: {
tags: ["Insights"],
summary: "Read the caller's \"about me\" self-description",
summary: "Read the caller's self-context",
description:
"v1.15.20 — returns the user-authored free-text self-description the Coach system prompt and the daily briefing inject as a delimited, user-provided context block. 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). Auth via cookie or Bearer; the owner is always narrowed from the session.",
responses: {
"200": {
description: "The stored text (null when never written / cleared).",
description:
"The stored fields (null when never written / cleared) plus pending clarifying questions.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({
aboutMe: z.string().nullable(),
conditions: z.string().nullable(),
allergies: z.string().nullable(),
coachFocus: z.string().nullable(),
pendingQuestions: z.array(z.string()),
updatedAt: z.iso.datetime({ offset: true }).nullable(),
maxChars: z.number().int(),
fieldMaxChars: z.number().int(),
}),
"GetCoachAboutMeResponse",
),
@@ -4370,23 +4376,29 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
put: {
tags: ["Insights"],
summary: "Write (or clear) the caller's \"about me\" self-description",
summary: "Write (or clear) the caller's self-context",
description:
"v1.15.20 — persists the free text encrypted at rest (4 000-char cap enforced before encryption). An empty / whitespace-only value clears the text while keeping the row so `updatedAt` documents the deletion instant. Rate-limited per user.",
"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.",
requestBody: {
required: true,
content: { "application/json": { schema: aboutMePutSchema } },
},
responses: {
"200": {
description: "The saved (trimmed) text echoed back.",
description:
"The effective (trimmed) state echoed back plus the freshly derived pending questions.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({
aboutMe: z.string().nullable(),
conditions: z.string().nullable(),
allergies: z.string().nullable(),
coachFocus: z.string().nullable(),
pendingQuestions: z.array(z.string()),
updatedAt: z.iso.datetime({ offset: true }),
maxChars: z.number().int(),
fieldMaxChars: z.number().int(),
}),
"PutCoachAboutMeResponse",
),
@@ -4397,12 +4409,69 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/coach/about-me/questions": {
get: {
tags: ["Insights"],
summary: "Read the pending clarifying questions",
description:
"v1.16.0 — the up-to-3 clarifying questions derived after the last self-context save. The Coach composer renders them as tappable suggestion chips. Stored encrypted; an undecryptable payload reads as an empty list (fail closed).",
responses: {
"200": {
description: "The pending questions (possibly empty).",
content: {
"application/json": {
schema: dataEnvelope(
z.object({ questions: z.array(z.string()) }),
"GetCoachAboutMeQuestionsResponse",
),
},
},
},
...stdResponses,
},
},
delete: {
tags: ["Insights"],
summary: "Dismiss pending clarifying questions",
description:
"v1.16.0 — dismisses one question (body `{ question }`, exact match) or all of them (empty body). Tapping a chip in the Coach composer inserts the question into the chat input and dismisses it here.",
requestBody: {
required: false,
content: {
"application/json": {
schema: z.object({
question: z
.string()
.optional()
.describe(
"Exact question text to dismiss. Omitted = dismiss all.",
),
}),
},
},
},
responses: {
"200": {
description: "The remaining questions after the dismissal.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({ questions: z.array(z.string()) }),
"DeleteCoachAboutMeQuestionsResponse",
),
},
},
},
...stdResponses,
},
},
},
"/api/admin/invites": {
get: {
tags: ["Admin"],
summary: "List registration invites",
description:
"v1.15.20 — every invite with creator / consumer usernames and use counters. Metadata only — the raw token is never derivable from this endpoint (only its HMAC hash is persisted). Admin session cookie required; Bearer tokens cannot reach admin endpoints.",
"v1.16.0 — every invite with creator / consumer usernames, use counters, soft-revocation timestamp, and the full per-signup redemption ledger (`redemptions`; `consumer` only carries the LAST account on a multi-use invite). Metadata only — the raw token is never derivable from this endpoint (only its HMAC hash is persisted). Admin session cookie required; Bearer tokens cannot reach admin endpoints.",
responses: {
"200": {
description: "All invites, newest first.",
@@ -4415,6 +4484,7 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
createdAt: z.iso.datetime({ offset: true }),
expiresAt: z.iso.datetime({ offset: true }),
usedAt: z.iso.datetime({ offset: true }).nullable(),
revokedAt: z.iso.datetime({ offset: true }).nullable(),
uses: z.number().int(),
maxUses: z.number().int(),
creator: z
@@ -4423,6 +4493,19 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
consumer: z
.object({ id: z.string(), username: z.string() })
.nullable(),
redemptions: z.array(
z.object({
id: z.string(),
redeemedAt: z.iso.datetime({ offset: true }),
user: z
.object({
id: z.string(),
username: z.string(),
email: z.string().nullable(),
})
.nullable(),
}),
),
}),
),
"AdminInviteList",
@@ -4480,16 +4563,16 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
requestParams: { path: z.object({ id: z.string() }) },
summary: "Revoke a registration invite",
description:
"v1.15.20 — hard-deletes the invite (no plaintext secret, no health data; mint + revoke live in the audit log). Idempotent: an unknown id returns `{ deleted: false }` instead of 404. Admin session cookie required.",
"v1.16.0 — soft-revokes the invite (`revokedAt`): the row keeps its redemption history visible in the admin table while the consume path refuses the link like an expired one. Idempotent: an unknown or already-revoked id returns `{ revoked: false }` instead of 404. Admin session cookie required.",
responses: {
"200": {
description:
"The invite was deleted (`deleted: true`) or the id matched nothing (`deleted: false`).",
"The invite was revoked (`revoked: true`) or nothing matched (`revoked: false`).",
content: {
"application/json": {
schema: dataEnvelope(
z.object({ deleted: z.boolean() }),
"AdminInviteDeleted",
z.object({ revoked: z.boolean() }),
"AdminInviteRevoked",
),
},
},
+2
View File
@@ -395,6 +395,8 @@ export const queryKeys = {
coachFacts: () => ["coach-facts"] as const,
/** v1.15.20 — Settings → AI "about me" self-description. */
coachAboutMe: () => ["coach-about-me"] as const,
/** v1.16.0 — pending clarifying questions (Coach composer chips). */
coachAboutMeQuestions: () => ["coach-about-me", "questions"] as const,
/**
* v1.4.41 — admin surfaces. Pre-fix every admin section declared its
+24
View File
@@ -1,5 +1,9 @@
/**
* v1.15.20 — request schema for `PUT /api/coach/about-me`.
* v1.16.0 — extended with three structured self-context fields
* (conditions, allergies, coach focus). Age/gender deliberately stay
* on the User profile and are merged into the prompt block at assembly
* time — the questionnaire never duplicates them.
*
* Lives outside the route file so the OpenAPI registry
* (`src/lib/openapi/routes.ts`) can import it without touching the
@@ -12,6 +16,20 @@ import { z } from "zod/v4";
/** Hard cap enforced BEFORE encryption. */
export const ABOUT_ME_MAX_CHARS = 4000;
/** Per-field cap for the structured answers, BEFORE encryption. */
export const ABOUT_ME_FIELD_MAX_CHARS = 500;
const structuredField = z
.string()
.max(
ABOUT_ME_FIELD_MAX_CHARS,
`Maximum ${ABOUT_ME_FIELD_MAX_CHARS} characters`,
)
// Optional so older clients that only send `aboutMe` keep working;
// an omitted field leaves the stored value untouched, an empty
// string clears it (mirrors the `aboutMe` semantics).
.optional();
export const aboutMePutSchema = z.object({
/**
* The user's free-text self-description. An empty / whitespace-only
@@ -20,6 +38,12 @@ export const aboutMePutSchema = z.object({
aboutMe: z
.string()
.max(ABOUT_ME_MAX_CHARS, `Maximum ${ABOUT_ME_MAX_CHARS} characters`),
/** Chronic conditions, short free text. */
conditions: structuredField,
/** Allergies / intolerances, short free text. */
allergies: structuredField,
/** What the Coach should pay attention to, short free text. */
coachFocus: structuredField,
});
export type AboutMePutInput = z.infer<typeof aboutMePutSchema>;