fix(insights): scope generation guard to prompt fields, clear cache on restore

This commit is contained in:
Marc-André Bombeck committed 2026-07-28 21:11:43 +02:00
1 parent 666a85d311
commit 3aff2c16db
104 files changed
+8082 -651

No files matched your search

@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_HEALTH_PROFILE_AI_SECTIONS,
HEALTH_PROFILE_AI_SECTIONS,
removedHealthProfileFactSchema,
} from "../health-profile-facts";
describe("health profile AI inclusion defaults", () => {
it("keeps the legacy opt-in list independent from accepted section values", () => {
expect(DEFAULT_HEALTH_PROFILE_AI_SECTIONS).not.toBe(
HEALTH_PROFILE_AI_SECTIONS,
);
expect(DEFAULT_HEALTH_PROFILE_AI_SECTIONS).toEqual([
"ABOUT_ME",
"CONDITIONS",
"ALLERGIES",
"COACH_FOCUS",
"FAMILY_HISTORY",
"SMOKING_STATUS",
"ALCOHOL_PATTERN",
"SHIFT_SCHEDULE",
]);
});
});
describe("health profile fact removal response", () => {
it("contains only revision metadata and a valid removal instant", () => {
expect(
removedHealthProfileFactSchema.parse({
id: "fact-1",
kind: "SMOKING_STATUS",
removedAt: "2026-07-28T12:00:00.000Z",
value: "FORMER",
}),
).toEqual({
id: "fact-1",
kind: "SMOKING_STATUS",
removedAt: "2026-07-28T12:00:00.000Z",
});
expect(
removedHealthProfileFactSchema.safeParse({
id: "fact-1",
kind: "SMOKING_STATUS",
removedAt: "not-a-date",
}).success,
).toBe(false);
});
});
+27 -15
View File
@@ -12,6 +12,7 @@
* (`src/lib/ai/coach/about-me.ts`) into the generator script.
*/
import { z } from "zod/v4";
import { healthProfileAiSectionSchema } from "@/lib/validations/health-profile-facts";
/** Hard cap enforced BEFORE encryption. */
export const ABOUT_ME_MAX_CHARS = 4000;
@@ -30,21 +31,32 @@ const structuredField = z
// string clears it (mirrors the `aboutMe` semantics).
.optional();
export const aboutMePutSchema = z.object({
/**
* The user's free-text self-description. An empty / whitespace-only
* value clears the stored text.
*/
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 const aboutMePutSchema = z
.object({
/**
* The user's free-text self-description. An empty / whitespace-only
* value clears the stored text; omission leaves it untouched.
*/
aboutMe: z
.string()
.max(ABOUT_ME_MAX_CHARS, `Maximum ${ABOUT_ME_MAX_CHARS} characters`)
.optional(),
conditions: structuredField,
/** Allergies / intolerances, short free text. */
allergies: structuredField,
/** What the Coach should pay attention to, short free text. */
coachFocus: structuredField,
/** Closed inclusion list for self-context sent to AI surfaces. */
aiIncludedSections: z
.array(healthProfileAiSectionSchema)
.max(8)
.refine((values) => new Set(values).size === values.length)
.optional(),
})
.refine(
(value) => Object.values(value).some((field) => field !== undefined),
"At least one self-context field is required",
);
export type AboutMePutInput = z.infer<typeof aboutMePutSchema>;
+52
View File
@@ -54,6 +54,12 @@ import {
SecondarySymptom,
SleepStage,
} from "@/generated/prisma/enums";
import {
DEFAULT_HEALTH_PROFILE_AI_SECTIONS,
healthProfileAiSectionSchema,
healthProfileFactKindSchema,
isHealthProfileFactValue,
} from "@/lib/validations/health-profile-facts";
export const BACKUP_SCHEMA_VERSION = "2" as const;
const LEGACY_BACKUP_SCHEMA_VERSION = "1" as const;
@@ -405,6 +411,9 @@ const healthProfileBackupSchema = z
conditions: z.string().nullable().default(null),
allergies: z.string().nullable().default(null),
coachFocus: z.string().nullable().default(null),
aiIncludedSections: z
.array(healthProfileAiSectionSchema)
.default([...DEFAULT_HEALTH_PROFILE_AI_SECTIONS]),
aboutMeEncrypted: base64BytesSchema.nullable().optional(),
conditionsEncrypted: base64BytesSchema.nullable().optional(),
allergiesEncrypted: base64BytesSchema.nullable().optional(),
@@ -415,6 +424,44 @@ const healthProfileBackupSchema = z
})
.passthrough();
const healthProfileFactBackupSchema = z
.object({
id: z.string().min(1),
kind: healthProfileFactKindSchema,
value: z.string().nullable().default(null),
valueEncrypted: base64BytesSchema.optional(),
validFrom: isoDateTime,
validUntil: isoDateTime.nullable(),
provenance: z.enum(["USER_REPORTED", "USER_CORRECTION"]),
supersededByRevisionId: z.string().min(1).nullable(),
createdAt: isoDateTime,
})
.passthrough()
.superRefine((fact, ctx) => {
if (fact.valueEncrypted === undefined) {
if (
fact.value === null ||
!isHealthProfileFactValue(fact.kind, fact.value)
) {
ctx.addIssue({
code: "custom",
path: ["value"],
message: "A portable profile fact requires a valid readable value",
});
}
}
if (
fact.validUntil !== null &&
Date.parse(fact.validUntil) <= Date.parse(fact.validFrom)
) {
ctx.addIssue({
code: "custom",
path: ["validUntil"],
message: "validUntil must be later than validFrom",
});
}
});
/** One reading of a user-defined metric, nested under the metric that owns it. */
const customMetricEntryBackupSchema = z
.object({
@@ -693,6 +740,7 @@ const workoutBackupSchema = z
pauseDurationSec: z.number().int().nullable().optional(),
source: z.enum(MeasurementSource),
externalId: z.string().nullable().optional(),
metadata: z.json().optional(),
createdAt: isoDateTime.optional(),
updatedAt: isoDateTime.optional(),
})
@@ -777,6 +825,7 @@ export const backupPayloadSchema = z
// before either rode the wire still parse; an account with neither writes
// `null` / `[]`.
healthProfile: healthProfileBackupSchema.nullable().default(null),
healthProfileFacts: z.array(healthProfileFactBackupSchema).default([]),
customMetrics: z.array(customMetricBackupSchema).default([]),
correlationPatterns: z.array(correlationPatternBackupSchema).default([]),
// The hourly shape of a cumulative day. Defaulted for the same reason as
@@ -836,6 +885,8 @@ export interface BackupSummary {
documents: number;
/** 1 when the account's durable self-context rides the file, 0 otherwise. */
healthProfile: number;
/** Effective-dated structured health-profile revisions. */
healthProfileFactRevisions: number;
/** Metrics the account defined itself. */
customMetrics: number;
/** Readings across every user-defined metric. */
@@ -870,6 +921,7 @@ export function summarizeBackup(payload: BackupPayload): BackupSummary {
workouts: payload.workouts.length,
documents: payload.documents.length,
healthProfile: payload.healthProfile ? 1 : 0,
healthProfileFactRevisions: payload.healthProfileFacts.length,
customMetrics: payload.customMetrics.length,
customMetricEntries: payload.customMetrics.reduce(
(sum, metric) => sum + metric.entries.length,
+128
View File
@@ -0,0 +1,128 @@
import { z } from "zod/v4";
export const HEALTH_PROFILE_AI_SECTIONS = [
"ABOUT_ME",
"CONDITIONS",
"ALLERGIES",
"COACH_FOCUS",
"FAMILY_HISTORY",
"SMOKING_STATUS",
"ALCOHOL_PATTERN",
"SHIFT_SCHEDULE",
] as const;
export type HealthProfileAiSection =
(typeof HEALTH_PROFILE_AI_SECTIONS)[number];
export const DEFAULT_HEALTH_PROFILE_AI_SECTIONS = [
"ABOUT_ME",
"CONDITIONS",
"ALLERGIES",
"COACH_FOCUS",
"FAMILY_HISTORY",
"SMOKING_STATUS",
"ALCOHOL_PATTERN",
"SHIFT_SCHEDULE",
] as const satisfies readonly HealthProfileAiSection[];
export const healthProfileAiSectionSchema = z.enum(HEALTH_PROFILE_AI_SECTIONS);
export const SMOKING_STATUS_VALUES = ["NEVER", "FORMER", "CURRENT"] as const;
export const ALCOHOL_PATTERN_VALUES = [
"NONE",
"OCCASIONAL",
"WEEKLY",
"MOST_DAYS",
] as const;
export const SHIFT_SCHEDULE_VALUES = [
"NONE",
"FIXED_SHIFT",
"ROTATING",
] as const;
export const HEALTH_PROFILE_FACT_KINDS = [
"SMOKING_STATUS",
"ALCOHOL_PATTERN",
"SHIFT_SCHEDULE",
] as const;
export type HealthProfileFactKind = (typeof HEALTH_PROFILE_FACT_KINDS)[number];
export type SmokingStatusValue = (typeof SMOKING_STATUS_VALUES)[number];
export type AlcoholPatternValue = (typeof ALCOHOL_PATTERN_VALUES)[number];
export type ShiftScheduleValue = (typeof SHIFT_SCHEDULE_VALUES)[number];
export type HealthProfileFactValue =
SmokingStatusValue | AlcoholPatternValue | ShiftScheduleValue;
export const HEALTH_PROFILE_FACT_VALUES: Record<
HealthProfileFactKind,
Readonly<Record<string, true>>
> = {
SMOKING_STATUS: { NEVER: true, FORMER: true, CURRENT: true },
ALCOHOL_PATTERN: {
NONE: true,
OCCASIONAL: true,
WEEKLY: true,
MOST_DAYS: true,
},
SHIFT_SCHEDULE: { NONE: true, FIXED_SHIFT: true, ROTATING: true },
};
export const healthProfileFactKindSchema = z.enum(HEALTH_PROFILE_FACT_KINDS);
export function isHealthProfileFactValue(
kind: HealthProfileFactKind,
value: string,
): value is HealthProfileFactValue {
return HEALTH_PROFILE_FACT_VALUES[kind][value] === true;
}
export const healthProfileFactWriteSchema = z.discriminatedUnion("kind", [
z.object({
kind: z.literal("SMOKING_STATUS"),
value: z.enum(SMOKING_STATUS_VALUES),
}),
z.object({
kind: z.literal("ALCOHOL_PATTERN"),
value: z.enum(ALCOHOL_PATTERN_VALUES),
}),
z.object({
kind: z.literal("SHIFT_SCHEDULE"),
value: z.enum(SHIFT_SCHEDULE_VALUES),
}),
]);
export const healthProfileFactCorrectionSchema = z.object({
value: z.string().trim().min(1),
});
export function validateCorrectedFactValue(
kind: HealthProfileFactKind,
value: string,
): HealthProfileFactValue | null {
return isHealthProfileFactValue(kind, value) ? value : null;
}
export const healthProfileFactDtoSchema = z.object({
id: z.string(),
kind: healthProfileFactKindSchema,
value: z.string().nullable(),
unreadable: z.boolean(),
validFrom: z.iso.datetime({ offset: true }),
validUntil: z.iso.datetime({ offset: true }).nullable(),
provenance: z.enum(["USER_REPORTED", "USER_CORRECTION"]),
supersededByRevisionId: z.string().nullable(),
createdAt: z.iso.datetime({ offset: true }),
});
export const healthProfileFactsResponseSchema = z.object({
current: z.object({
SMOKING_STATUS: healthProfileFactDtoSchema.nullable(),
ALCOHOL_PATTERN: healthProfileFactDtoSchema.nullable(),
SHIFT_SCHEDULE: healthProfileFactDtoSchema.nullable(),
}),
history: z.array(healthProfileFactDtoSchema),
});
export const removedHealthProfileFactSchema = z.object({
id: z.string(),
kind: healthProfileFactKindSchema,
removedAt: z.iso.datetime({ offset: true }),
});