feat(workouts): add the per-workout insight model

Its own table, cascading from the workout row, because workout deletes are
hard deletes. The paragraph is AES-256-GCM at rest and registered for key
rotation; the input hash and prompt version make a re-post of the same
session a free no-op.
This commit is contained in:
Marc-André Bombeck committed 2026-07-19 13:47:25 +02:00
1 parent bfb4dbd7da
commit 0dba15e902
2 files changed
+99

No files matched your search

@@ -0,0 +1,52 @@
-- The per-workout Activity Insight paragraph.
--
-- Its own table rather than a column on `workouts` because a workout delete is
-- a HARD delete: the FK below cascades, so the paragraph can never outlive the
-- session it describes. Keeping it out of `workouts` also keeps the generation
-- provenance off the row every list read selects from.
--
-- Rows are written ONLY by the `workout-insight-generate` worker, dispatched by
-- the data-arrival spine when a workout genuinely lands. No read path creates
-- one, so every workout that predates this migration stays without a row — and
-- renders no card — forever, at zero provider cost.
--
-- `paragraph_encrypted` is AES-256-GCM at rest, following the
-- `insight_narratives.encrypted_content` precedent, and is registered in
-- `src/lib/crypto/encrypted-columns.ts` so key rotation covers it.
--
-- `input_hash` fingerprints the deterministic evidence the paragraph was built
-- from together with the prompt version: a device re-post of the same session
-- hashes identically and is refused before any provider is resolved.
CREATE TABLE "workout_insights" (
"id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"workout_id" TEXT NOT NULL,
"paragraph_encrypted" BYTEA NOT NULL,
"input_hash" TEXT NOT NULL,
"prompt_version" TEXT NOT NULL,
"provider_type" TEXT,
"locale" TEXT NOT NULL,
"generated_at" TIMESTAMP(3) NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "workout_insights_pkey" PRIMARY KEY ("id")
);
-- One paragraph per workout. This is also the second half of the
-- double-post defence: the singleton queue key collapses a burst, and this
-- constraint makes the claim durable even if two workers do run.
CREATE UNIQUE INDEX "workout_insights_workout_id_key"
ON "workout_insights"("workout_id");
-- The daily-cap count: rows for one user inside a generated_at window.
CREATE INDEX "workout_insights_user_id_generated_at_idx"
ON "workout_insights"("user_id", "generated_at");
ALTER TABLE "workout_insights"
ADD CONSTRAINT "workout_insights_user_id_fkey"
FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "workout_insights"
ADD CONSTRAINT "workout_insights_workout_id_fkey"
FOREIGN KEY ("workout_id") REFERENCES "workouts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+47
View File
@@ -796,6 +796,7 @@ model User {
// row per (kind, local day); the unique index IS the once-per-kind-per-day
// claim every reaction surface reads. Retained 14 days.
arrivalReactions ArrivalReaction[]
workoutInsights WorkoutInsight[]
// v1.17.1 — preventive-care / measurement (Vorsorge) reminders. One row
// per user-created reminder ("BP every 7 days", "annual blood panel").
// Server computes the canonical `nextDueAt`; the cron fires through the
@@ -1939,6 +1940,7 @@ model Workout {
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
route WorkoutRoute?
samples WorkoutSamples?
insight WorkoutInsight?
/// Ingest dedup. NULL externalId is distinct so two manual
/// entries on the same day never collide here.
@@ -2029,6 +2031,51 @@ model WorkoutSamples {
@@map("workout_samples")
}
// ─── Per-workout Activity Insight (v1.31.0) ─────────────────
//
// The grounded paragraph the workout-detail seam renders. Its OWN model
// rather than a column on `Workout` for one concrete reason: workout deletes
// are HARD deletes (see the note on the `Workout` unique above), so the row
// has to disappear with its workout. A column would go with it too, but a
// separate model also keeps the generation provenance (`inputHash`,
// `promptVersion`, `providerType`) off the hot workout row that every list
// read selects from, and gives the daily-cap count an index of its own.
//
// Written ONLY by the `workout-insight-generate` worker, which the arrival
// spine dispatches when a workout genuinely LANDS. Nothing on a read path
// ever creates one: a workout with no row renders no card, and that includes
// every workout that predates this model.
model WorkoutInsight {
id String @id @default(cuid())
userId String @map("user_id")
workoutId String @unique @map("workout_id")
/// AES-256-GCM ciphertext of the generated paragraph. Follows the
/// `InsightNarrative.encryptedContent` precedent, NOT the plaintext pattern
/// the status cards use. Registered in `src/lib/crypto/encrypted-columns.ts`
/// and rotated by `scripts/rotate-encryption-key.ts`.
paragraphEncrypted Bytes @map("paragraph_encrypted")
/// Fingerprint of the deterministic evidence the paragraph was generated
/// from, plus the prompt version. A re-sync of the same session hashes
/// identically and costs nothing.
inputHash String @map("input_hash")
promptVersion String @map("prompt_version")
providerType String? @map("provider_type")
/// The UI locale the paragraph was WRITTEN in. Provenance only: a later
/// language switch does not regenerate, because a read path may never
/// trigger a provider call. Stored so that is visible rather than guessed.
locale String
generatedAt DateTime @map("generated_at")
createdAt DateTime @default(now()) @map("created_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
workout Workout @relation(fields: [workoutId], references: [id], onDelete: Cascade)
/// The per-day cap count reads this: rows for one user in a generatedAt
/// window.
@@index([userId, generatedAt])
@@map("workout_insights")
}
// ─── Strain personal anchor cache (v1.10.3) ─────────────────
//
// Server-internal per-(user, day) cache that lets the nightly Strain