diff --git a/knip.json b/knip.json
index fb9aa973e..4b0f6accf 100644
--- a/knip.json
+++ b/knip.json
@@ -73,7 +73,6 @@
"ignoreExportsUsedInFile": true,
"ignoreIssues": {
"src/components/ui/**": ["exports", "types"],
- "src/lib/validations/**": ["types"],
- "src/lib/insights/narrative/**": ["exports"]
+ "src/lib/validations/**": ["types"]
}
}
diff --git a/messages/de.json b/messages/de.json
index 527c4e5e2..652dd2153 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -1540,6 +1540,16 @@
"regenerateSuccess": "Analyse wurde neu erstellt",
"warmAssessments": "Auswertungen vorbereiten",
"warmStarted": "Auswertungen werden im Hintergrund erstellt",
+ "narrativeTitle": "Dein Zeitraum im Rückblick",
+ "narrativeWeek": "Diese Woche",
+ "narrativeMonth": "Dieser Monat",
+ "narrativePreparing": "Deine Zusammenfassung wird erstellt…",
+ "narrativeUpdating": "Wird aktualisiert…",
+ "narrativeUpdated": "Aktualisiert {time}",
+ "narrativeProvenanceLabel": "Wie das zustande kam",
+ "narrativeProvenanceMethod": "Eine Zusammenfassung des Zeitraums in einfacher Sprache, ausschließlich aus deinen erfassten Werten und den Zusammenhängen, die die statistische Mehrfachvergleichskorrektur überstanden haben. Beschreibend, nie eine Ursache.",
+ "narrativeProvenanceMetrics": "Basierend auf: {metrics}",
+ "narrativeProvenanceWindow": "Zeitfenster: {from} bis {to}",
"heroFallbackSubtitle": "Täglicher Blick auf deine Trends — direkt aus den Zahlen, die du protokollierst.",
"heroGreetingMorning": "Guten Morgen",
"heroGreetingAfternoon": "Guten Tag",
diff --git a/messages/en.json b/messages/en.json
index f3ec7ab62..aecdfcbae 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -1540,6 +1540,16 @@
"regenerateSuccess": "Analysis refreshed",
"warmAssessments": "Prepare assessments",
"warmStarted": "Assessments are being prepared in the background",
+ "narrativeTitle": "Your period in review",
+ "narrativeWeek": "This week",
+ "narrativeMonth": "This month",
+ "narrativePreparing": "Preparing your summary…",
+ "narrativeUpdating": "Updating…",
+ "narrativeUpdated": "Updated {time}",
+ "narrativeProvenanceLabel": "How this was put together",
+ "narrativeProvenanceMethod": "A plain-language summary of the period, drawn only from your logged numbers and the associations that survived statistical multiple-comparison control. Descriptive, never a cause.",
+ "narrativeProvenanceMetrics": "Based on: {metrics}",
+ "narrativeProvenanceWindow": "Window: {from} to {to}",
"heroFallbackSubtitle": "A daily read of your trends, drawn straight from the numbers you've logged.",
"heroGreetingMorning": "Good morning",
"heroGreetingAfternoon": "Good afternoon",
diff --git a/messages/es.json b/messages/es.json
index 33323462c..44af26e15 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -1540,6 +1540,16 @@
"regenerateSuccess": "Análisis regenerado",
"warmAssessments": "Preparar evaluaciones",
"warmStarted": "Las evaluaciones se están preparando en segundo plano",
+ "narrativeTitle": "Tu período en resumen",
+ "narrativeWeek": "Esta semana",
+ "narrativeMonth": "Este mes",
+ "narrativePreparing": "Preparando tu resumen…",
+ "narrativeUpdating": "Actualizando…",
+ "narrativeUpdated": "Actualizado {time}",
+ "narrativeProvenanceLabel": "Cómo se elaboró esto",
+ "narrativeProvenanceMethod": "Un resumen del período en lenguaje sencillo, basado únicamente en tus valores registrados y en las asociaciones que superaron el control estadístico de comparaciones múltiples. Descriptivo, nunca una causa.",
+ "narrativeProvenanceMetrics": "Basado en: {metrics}",
+ "narrativeProvenanceWindow": "Ventana: del {from} al {to}",
"heroFallbackSubtitle": "Una mirada diaria a tus tendencias — directamente de los datos que registras.",
"heroGreetingMorning": "Buenos días",
"heroGreetingAfternoon": "Buenas tardes",
diff --git a/messages/fr.json b/messages/fr.json
index 17456de80..8a07a68c9 100644
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -1540,6 +1540,16 @@
"regenerateSuccess": "Analyse regénérée",
"warmAssessments": "Préparer les évaluations",
"warmStarted": "Les évaluations sont en cours de préparation en arrière-plan",
+ "narrativeTitle": "Votre période en revue",
+ "narrativeWeek": "Cette semaine",
+ "narrativeMonth": "Ce mois-ci",
+ "narrativePreparing": "Préparation de votre résumé…",
+ "narrativeUpdating": "Mise à jour…",
+ "narrativeUpdated": "Mis à jour {time}",
+ "narrativeProvenanceLabel": "Comment cela a été établi",
+ "narrativeProvenanceMethod": "Un résumé de la période en langage clair, établi uniquement à partir de vos valeurs enregistrées et des associations ayant survécu au contrôle statistique des comparaisons multiples. Descriptif, jamais une cause.",
+ "narrativeProvenanceMetrics": "Basé sur : {metrics}",
+ "narrativeProvenanceWindow": "Fenêtre : du {from} au {to}",
"heroFallbackSubtitle": "Un coup d’œil quotidien sur tes tendances — directement issu des chiffres que tu saisis.",
"heroGreetingMorning": "Bonjour",
"heroGreetingAfternoon": "Bonjour",
diff --git a/messages/it.json b/messages/it.json
index c4d7756b4..e25ad9ad5 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -1540,6 +1540,16 @@
"regenerateSuccess": "Analisi rigenerata",
"warmAssessments": "Prepara le valutazioni",
"warmStarted": "Le valutazioni vengono preparate in background",
+ "narrativeTitle": "Il tuo periodo in sintesi",
+ "narrativeWeek": "Questa settimana",
+ "narrativeMonth": "Questo mese",
+ "narrativePreparing": "Preparazione del riepilogo…",
+ "narrativeUpdating": "Aggiornamento…",
+ "narrativeUpdated": "Aggiornato {time}",
+ "narrativeProvenanceLabel": "Come è stato realizzato",
+ "narrativeProvenanceMethod": "Un riepilogo del periodo in linguaggio semplice, basato esclusivamente sui valori registrati e sulle associazioni che hanno superato il controllo statistico dei confronti multipli. Descrittivo, mai una causa.",
+ "narrativeProvenanceMetrics": "Basato su: {metrics}",
+ "narrativeProvenanceWindow": "Finestra: dal {from} al {to}",
"heroFallbackSubtitle": "Uno sguardo quotidiano ai tuoi trend — direttamente dai numeri che registri.",
"heroGreetingMorning": "Buongiorno",
"heroGreetingAfternoon": "Buon pomeriggio",
diff --git a/messages/pl.json b/messages/pl.json
index 8efa74dbe..461326124 100644
--- a/messages/pl.json
+++ b/messages/pl.json
@@ -1540,6 +1540,16 @@
"regenerateSuccess": "Analiza wygenerowana ponownie",
"warmAssessments": "Przygotuj analizy",
"warmStarted": "Analizy są przygotowywane w tle",
+ "narrativeTitle": "Twój okres w skrócie",
+ "narrativeWeek": "Ten tydzień",
+ "narrativeMonth": "Ten miesiąc",
+ "narrativePreparing": "Przygotowywanie podsumowania…",
+ "narrativeUpdating": "Aktualizowanie…",
+ "narrativeUpdated": "Zaktualizowano {time}",
+ "narrativeProvenanceLabel": "Jak to powstało",
+ "narrativeProvenanceMethod": "Podsumowanie okresu w prostym języku, oparte wyłącznie na zarejestrowanych wartościach i powiązaniach, które przeszły statystyczną korektę dla porównań wielokrotnych. Opisowe, nigdy nie przyczynowe.",
+ "narrativeProvenanceMetrics": "Na podstawie: {metrics}",
+ "narrativeProvenanceWindow": "Okno: od {from} do {to}",
"heroFallbackSubtitle": "Codzienne spojrzenie na twoje trendy — prosto z liczb, które rejestrujesz.",
"heroGreetingMorning": "Dzień dobry",
"heroGreetingAfternoon": "Dzień dobry",
diff --git a/prisma/migrations/0113_v1110_insight_narratives/migration.sql b/prisma/migrations/0113_v1110_insight_narratives/migration.sql
new file mode 100644
index 000000000..b4655a390
--- /dev/null
+++ b/prisma/migrations/0113_v1110_insight_narratives/migration.sql
@@ -0,0 +1,43 @@
+-- v1.11.0 — period-narrative cache (Pillar P1).
+--
+-- One durable, typed row per (user, period, locale) holding the latest
+-- generated period summary ("how your week/month went"). Delete +
+-- regenerate clean: the unique index on (user_id, period, locale) enforces
+-- a single row per slot, so a regeneration upserts in place and there is
+-- never a stale duplicate to disambiguate.
+--
+-- The generated prose is held AES-256-GCM at rest in `encrypted_content`
+-- (BYTEA), following the `coach_messages.encrypted_content` precedent. The
+-- `provenance_json` envelope is labels-only (metric names, the read window,
+-- the FDR footer) and carries no PII, so it stays plaintext for a stable,
+-- queryable shape — matching `coach_messages.metric_source_json`.
+--
+-- Purely additive: one new table, no enum changes, no backfill. Deleting the
+-- user cascades every narrative away (clean GDPR-erasure).
+
+CREATE TABLE IF NOT EXISTS "insight_narratives" (
+ "id" TEXT NOT NULL,
+ "user_id" TEXT NOT NULL,
+ "period" TEXT NOT NULL,
+ "locale" TEXT NOT NULL,
+ "date_key" TEXT NOT NULL,
+ "encrypted_content" BYTEA NOT NULL,
+ "provenance_json" TEXT,
+ "provider_type" TEXT,
+ "prompt_version" TEXT,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "insight_narratives_pkey" PRIMARY KEY ("id")
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS "insight_narratives_user_id_period_locale_key"
+ ON "insight_narratives" ("user_id", "period", "locale");
+
+CREATE INDEX IF NOT EXISTS "insight_narratives_user_id_updated_at_idx"
+ ON "insight_narratives" ("user_id", "updated_at" DESC);
+
+ALTER TABLE "insight_narratives"
+ ADD CONSTRAINT "insight_narratives_user_id_fkey"
+ FOREIGN KEY ("user_id") REFERENCES "users" ("id")
+ ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index bc7918d87..35bfcc8b9 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -428,6 +428,9 @@ model User {
// provider chain entry) so a known-bad credential is negatively cached
// across workers instead of re-burning a 401 every generation.
providerHealth ProviderHealth[]
+ // v1.11.0 W3 — one durable period-narrative row per (period, locale).
+ // Delete/regenerate-clean; the generated prose is AES-256-GCM at rest.
+ insightNarratives InsightNarrative[]
// v1.7.0 profile — optional patient-identity fields surfaced on the
// health-record export cover (PDF) and the FHIR `Patient` resource.
@@ -2830,3 +2833,49 @@ model ClinicianShareLink {
@@index([expiresAt])
@@map("clinician_share_links")
}
+
+// v1.11.0 W3 — period-narrative cache (Pillar P1).
+//
+// One durable, typed row per (user, period, locale) carrying the latest
+// generated period summary ("how your week/month went"). Delete +
+// regenerate clean: the unique constraint enforces a single row per slot,
+// so a regeneration upserts in place and there is never a stale duplicate
+// to disambiguate. The generated prose is held AES-256-GCM at rest in
+// `encryptedContent` (Bytes), following the `CoachMessage.encryptedContent`
+// precedent — the body is descriptive health narrative and is treated as
+// sensitive even though it carries labels-plus-numbers, not raw rows.
+//
+// `provenanceJson` is the labels-only provenance envelope the surface
+// renders as ⓘ chips (metric names + the read window + the FDR footer);
+// it carries no PII so it stays plaintext for a stable, queryable shape,
+// matching `CoachMessage.metricSourceJson`. `providerType` + `promptVersion`
+// mirror the attribution columns so the cross-feature aggregator can slice
+// quality per (provider × prompt). `period` is `week` | `month`; `dateKey`
+// is the UTC `YYYY-MM-DD` boundary the row was generated for, so the
+// stale-while-revalidate read can tell "today's" narrative from an older
+// one without decrypting.
+model InsightNarrative {
+ id String @id @default(cuid())
+ userId String @map("user_id")
+ /// "week" | "month".
+ period String
+ /// Resolved UI locale of the prose ("de" | "en").
+ locale String
+ /// UTC YYYY-MM-DD boundary the narrative was generated for.
+ dateKey String @map("date_key")
+ /// AES-256-GCM ciphertext of the generated narrative prose.
+ encryptedContent Bytes @map("encrypted_content")
+ /// Labels-only provenance envelope (metric names, window, FDR footer).
+ provenanceJson String? @map("provenance_json")
+ providerType String? @map("provider_type")
+ promptVersion String? @map("prompt_version")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ // One row per (user, period, locale) — regeneration upserts in place.
+ @@unique([userId, period, locale])
+ @@index([userId, updatedAt(sort: Desc)])
+ @@map("insight_narratives")
+}
diff --git a/src/app/api/insights/narrative/route.ts b/src/app/api/insights/narrative/route.ts
new file mode 100644
index 000000000..5b48b8868
--- /dev/null
+++ b/src/app/api/insights/narrative/route.ts
@@ -0,0 +1,95 @@
+/**
+ * v1.11.0 W3 — period-narrative read route (Pillar P1).
+ *
+ * `GET /api/insights/narrative?period=week|month` serves the latest generated
+ * period summary for the calling user. Read-only by construction (the v1.8.3
+ * freeze posture): it NEVER blocks on the provider. It returns the last good
+ * narrative immediately (stale-while-revalidate) and, when the row is missing
+ * or stale and a provider is configured, fire-and-forget enqueues a warm so
+ * the next read reflects the latest period.
+ *
+ * `userId` is narrowed from the session/Bearer (never a query field); an
+ * unknown `period` 422s via the closed enum.
+ */
+import { NextRequest } from "next/server";
+import { z } from "zod/v4";
+import { apiSuccess, returnAllZodIssues } from "@/lib/api-response";
+import { apiHandler, requireAuth } from "@/lib/api-handler";
+import { annotate } from "@/lib/logging/context";
+import { resolveServerLocale } from "@/lib/i18n/server-locale";
+import { requireAssistantSurface } from "@/lib/feature-flags";
+import { hasUsableStatusProvider } from "@/lib/insights/status-provider";
+import { readPeriodNarrative } from "@/lib/insights/narrative/period-narrative-generate";
+import { PERIOD_DAYS, type NarrativePeriod } from "@/lib/insights/narrative/period-narrative";
+import { enqueueNarrativeWarm } from "@/lib/jobs/period-narrative-shared";
+
+export const dynamic = "force-dynamic";
+
+const NARRATIVE_PERIODS = Object.keys(PERIOD_DAYS) as [string, ...string[]];
+
+const narrativeQuerySchema = z.object({
+ period: z.enum(NARRATIVE_PERIODS),
+});
+
+/** A narrative read this recently is considered fresh; no warm is enqueued. */
+const NARRATIVE_FRESH_MS = 20 * 60 * 60 * 1000;
+
+function narrowLocale(locale: string): "de" | "en" {
+ return locale === "en" ? "en" : "de";
+}
+
+export const GET = apiHandler(async (request: NextRequest) => {
+ const { user } = await requireAuth();
+ await requireAssistantSurface("insightStatus");
+
+ const parsed = narrativeQuerySchema.safeParse({
+ period: request.nextUrl.searchParams.get("period"),
+ });
+ if (!parsed.success) {
+ annotate({
+ action: { name: "insights.narrative.invalid-period" },
+ meta: { issue_count: parsed.error.issues.length },
+ });
+ return returnAllZodIssues(parsed.error, 422);
+ }
+ const period = parsed.data.period as NarrativePeriod;
+
+ const resolved = await resolveServerLocale({
+ request,
+ userLocale: user.locale ?? null,
+ override: request.nextUrl.searchParams.get("locale"),
+ });
+ const locale = narrowLocale(resolved);
+
+ const existing = await readPeriodNarrative(user.id, period, locale);
+ const isFresh =
+ existing !== null &&
+ Date.now() - new Date(existing.updatedAt).getTime() < NARRATIVE_FRESH_MS;
+
+ // Read-only: never block on the provider. Warm out of band only when stale
+ // / missing AND a provider is configured (a provider-less account costs one
+ // cheap chain-resolve and shows the no-key state instead).
+ let revalidating = false;
+ if (!isFresh && (await hasUsableStatusProvider(user.id))) {
+ void enqueueNarrativeWarm({ userId: user.id, period, locale });
+ revalidating = true;
+ }
+
+ annotate({
+ action: { name: "insights.narrative" },
+ meta: { period, has_narrative: existing !== null, revalidating },
+ });
+
+ return apiSuccess({
+ period,
+ locale,
+ narrative: existing
+ ? {
+ text: existing.text,
+ provenance: existing.provenance,
+ updatedAt: existing.updatedAt,
+ }
+ : null,
+ revalidating,
+ });
+});
diff --git a/src/app/insights/page.tsx b/src/app/insights/page.tsx
index 5e13eae83..8c771c38b 100644
--- a/src/app/insights/page.tsx
+++ b/src/app/insights/page.tsx
@@ -120,6 +120,27 @@ const CoincidentDeviationCard = dynamic(
},
);
+// v1.11.0 — period-narrative card (Pillar P1). The calm "your week/month in
+// review" summary, drawn from the read-only stale-while-revalidate narrative
+// route. Deferred behind `next/dynamic` like the other below-the-hero blocks;
+// it owns its own query and un-mounts when no narrative exists. The loader
+// skeleton shares the card's `min-h-40` footprint so the page does not shift.
+const PeriodNarrativeCard = dynamic(
+ () =>
+ import("@/components/insights/period-narrative-card").then((mod) => ({
+ default: mod.PeriodNarrativeCard,
+ })),
+ {
+ ssr: false,
+ loading: () => (
+