diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 71297681..be089504 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -110,6 +110,7 @@ The separate Personal health experience (see [DELIVERY_PLAN.md](DELIVERY_PLAN.md - Regions are keyboard-focusable buttons (Enter/Space); the mirrored half is hidden from assistive tech. - Colour transitions run only under `prefers-reduced-motion: no-preference`. - Illustration is decorative anatomy, not medical imagery, and never implies diagnosis or injury. +- The map is interactive (Planned / Logged / Preview, with a 7, 28 or 90 day period): see [P1_MUSCLE_EXPLORER.md](P1_MUSCLE_EXPLORER.md). Segmented controls reuse the Front/Back tab styling with 44px targets; the figure never moves when controls change. ## History: Luxe (superseded) diff --git a/docs/P1_MUSCLE_EXPLORER.md b/docs/P1_MUSCLE_EXPLORER.md new file mode 100644 index 00000000..5281b380 --- /dev/null +++ b/docs/P1_MUSCLE_EXPLORER.md @@ -0,0 +1,31 @@ +# Personal interactive muscle map + +**Status:** implemented on `/me/body`. No schema change, no new route, no new dependency. + +## What it does +- **Planned** (default): the original map from declared activities plus club visits the user has allowed. +- **Logged**: the same map from the user's own completed workouts (`WorkoutSession` from P1-B), over 7, 28 or 90 days. Each muscle shows weighted set-equivalents, when it was last worked and which exercises contributed most. +- **Preview**: pick any catalogue activity and see which muscles it trains. It is a lens, not history. +- Tap or press Enter on a muscle for its detail; every value is also in the text list. + +## How workouts become muscles +- Logged exercise names are free text, so `src/lib/personal/exercise-catalog.ts` maps keywords to muscles. Matching is lower-cased words, a keyword must start at a word boundary, and the longest keyword wins ("romanian deadlift" is not a plain deadlift, "leg curl" is not a biceps curl). +- A set counts 1; a primary muscle gets weight 1 and a secondary 0.4 (the same constants as `muscleLoad`). A timed set with no reps counts one set-equivalent per 10 minutes. Empty sets count nothing. +- A workout with no usable exercises falls back to its declared `activityKey`: one set-equivalent per 10 minutes, at least 3. +- Names the catalogue cannot place are **listed to the user as not counted**, never guessed. +- Load is relative to the most-worked muscle in the chosen window, so 100% means "most", not "a lot". + +## Privacy and gating +- Reads only the signed-in user's rows. Nothing flows to clubs; the map never feeds leaderboards or club data. +- Logged data reuses P1-B's own gate (`assertWellnessEnabled`, `assertWellnessAdult` in `wellness-policy.ts`), so it is off unless `PERSONAL_WELLNESS_ENABLED=true` and the user is a clear adult. When off, "Logged" is disabled and the page says why. +- Descriptive only: no recovery score, readiness, injury or health claim. + +## Files (all new unless noted) +`src/lib/personal/exercise-catalog.ts`, `muscle-training.ts`, `muscle-explorer-service.ts`; `src/components/personal/body-map/muscle-explorer.tsx`; `body-map.tsx` and `body-map.css` extended; `src/app/me/body/page.tsx` rewired. Tests: `tests/unit/personal-muscle-training.test.mjs`, two cases in `tests/integration/personal-service.test.mjs`. + +## Coordination +Built to avoid Codex's in-flight work: it imports P1-B code but edits none of it, and adds no Prisma change, so it cannot conflict with the P1-C Health Connect schema branch. + +## Known limits +- The exercise catalogue covers common lifts and cardio only; unusual names go to "not counted". A user-editable mapping is a possible follow-up. +- Set-equivalents are a descriptive volume count, not a validated training-load model. diff --git a/src/app/me/body/page.tsx b/src/app/me/body/page.tsx index 76bb7c55..ea49a070 100644 --- a/src/app/me/body/page.tsx +++ b/src/app/me/body/page.tsx @@ -1,14 +1,14 @@ import { prisma } from "@/lib/prisma"; import { requireSession } from "@/lib/required-session"; -import { getOverview } from "@/lib/personal/personal-service"; +import { getMuscleExplorer } from "@/lib/personal/muscle-explorer-service"; import { displayUnit, type MeasurementKind } from "@/lib/personal/measurements"; import { MEASUREMENT_LABEL, MEASUREMENT_MUSCLE } from "@/lib/personal/measurement-muscles"; import type { MuscleId } from "@/lib/personal/muscle-map"; -import { BodyMap } from "@/components/personal/body-map/body-map"; +import { MuscleExplorer } from "@/components/personal/body-map/muscle-explorer"; export default async function BodyPage() { const session = await requireSession(); - const o = await getOverview(prisma, session.user.id); + const { overview: o, logged } = await getMuscleExplorer(prisma, session.user.id); // Latest logged girth per muscle, across left and right. const notes: Partial> = {}; @@ -29,11 +29,9 @@ export default async function BodyPage() { <>

My muscle map

-

- Shaded by how much your activities train each muscle. Tap a muscle for details. -

+

Tap a muscle to see what trains it.

- + ); } diff --git a/src/components/personal/body-map/body-map.css b/src/components/personal/body-map/body-map.css index 59c33e9e..eedb337b 100644 --- a/src/components/personal/body-map/body-map.css +++ b/src/components/personal/body-map/body-map.css @@ -135,3 +135,25 @@ padding: 0.25rem 0; font-variant-numeric: tabular-nums; } + +/* Interactive explorer controls (source, period, preview). */ +.hm-explorer { + display: grid; + gap: 0.75rem; +} +.hm-explorer-controls { + display: grid; + gap: 0.5rem; + justify-items: center; +} +.hm-explorer-controls .hm-me-field { + width: min(100%, 20rem); +} +.hm-explorer-summary { + text-align: center; + margin: 0; +} +.hm-bodymap-tab:disabled { + opacity: 0.45; + cursor: not-allowed; +} diff --git a/src/components/personal/body-map/body-map.tsx b/src/components/personal/body-map/body-map.tsx index 942711de..9ffbe5e0 100644 --- a/src/components/personal/body-map/body-map.tsx +++ b/src/components/personal/body-map/body-map.tsx @@ -19,6 +19,8 @@ import { } from "./body-paths"; import "./body-map.css"; +/** Primary activities come first, so the cap keeps the most relevant ones. */ +const MAX_ACTIVITIES_SHOWN = 5; const MIRROR = "translate(200 0) scale(-1 1)"; const SIDES: { side: MuscleSide; label: string }[] = [ { side: "front", label: "Front" }, @@ -29,10 +31,12 @@ export interface BodyMapProps { /** Load per muscle on a 0..1 scale (see muscleLoad). Missing muscles count as 0. */ load: Partial>; /** Optional short text per muscle, e.g. a recent girth measurement, shown in the detail panel. */ - notes?: Partial>; + notes?: Partial>; + /** Wording for the load figure in the detail panel, e.g. "of your most-worked muscle". */ + loadPhrase?: string; } -export function BodyMap({ load, notes }: BodyMapProps) { +export function BodyMap({ load, notes, loadPhrase = "of your most-worked muscle" }: BodyMapProps) { const [side, setSide] = useState("front"); const [selected, setSelected] = useState(null); @@ -138,14 +142,25 @@ export function BodyMap({ load, notes }: BodyMapProps) { {selectedMuscle ? ( <>

{selectedMuscle.label}

-

Training load {percent(selectedMuscle.id)}% of your most-worked muscle.

- {notes?.[selectedMuscle.id] ?

{notes[selectedMuscle.id]}

: null} +

+ Training load {percent(selectedMuscle.id)}% {loadPhrase}. +

+ {[notes?.[selectedMuscle.id] ?? []].flat().map((line) => ( +

{line}

+ ))}
    - {activitiesForMuscle(selectedMuscle.id).map((a) => ( -
  • - {a.label} ({a.role}) + {activitiesForMuscle(selectedMuscle.id) + .slice(0, MAX_ACTIVITIES_SHOWN) + .map((a) => ( +
  • + {a.label} ({a.role}) +
  • + ))} + {activitiesForMuscle(selectedMuscle.id).length > MAX_ACTIVITIES_SHOWN && ( +
  • + +{activitiesForMuscle(selectedMuscle.id).length - MAX_ACTIVITIES_SHOWN} more
  • - ))} + )}
) : ( diff --git a/src/components/personal/body-map/muscle-explorer.tsx b/src/components/personal/body-map/muscle-explorer.tsx new file mode 100644 index 00000000..75f68c9c --- /dev/null +++ b/src/components/personal/body-map/muscle-explorer.tsx @@ -0,0 +1,156 @@ +"use client"; + +import Link from "next/link"; +import { useMemo, useState } from "react"; +import { ACTIVITIES, muscleLoad, type ActivityKey, type MuscleId } from "@/lib/personal/muscle-map"; +import { daysAgoLabel, type MuscleTraining } from "@/lib/personal/muscle-training"; +import { BodyMap } from "./body-map"; + +type Source = "planned" | "logged" | "preview"; +type Window = 7 | 28 | 90; +const WINDOWS: Window[] = [7, 28, 90]; + +export interface MuscleExplorerProps { + /** Declared activities plus consented club visits, 0..1. */ + planned: Record; + /** Completed workouts per window; null when workout tracking is not available to this user. */ + logged: Record | null; + /** Latest logged girth per muscle, already worded (e.g. "Latest chest: 96 cm (2026-10-01)"). */ + measurementNotes: Partial>; +} + +export function MuscleExplorer({ planned, logged, measurementNotes }: MuscleExplorerProps) { + const hasLogged = logged !== null && logged[28].workouts + logged[90].workouts > 0; + const [source, setSource] = useState(hasLogged ? "logged" : "planned"); + const [days, setDays] = useState(28); + const [lens, setLens] = useState(ACTIVITIES[0].key); + + const training = logged?.[days] ?? null; + const lensDef = ACTIVITIES.find((a) => a.key === lens) ?? ACTIVITIES[0]; + + const { load, notes, phrase } = useMemo(() => { + const out: Partial> = {}; + const push = (id: MuscleId, line: string) => (out[id] = [...(out[id] ?? []), line]); + for (const [id, line] of Object.entries(measurementNotes) as [MuscleId, string][]) + push(id, line); + + if (source === "logged" && training) { + for (const id of Object.keys(training.load) as MuscleId[]) { + const sets = training.setEquivalents[id]; + if (sets > 0) { + const ago = training.lastWorkedDaysAgo[id]; + push( + id, + `${sets} set-equivalents in the last ${days} days` + + (ago === undefined ? "" : `, last worked ${daysAgoLabel(ago)}.`) + ); + const who = training.contributors[id]; + if (who?.length) push(id, `Mostly from: ${who.join(", ")}.`); + } else { + push(id, `Not worked in the last ${days} days.`); + } + } + return { + load: training.load, + notes: out, + phrase: "of your most-worked muscle in this period", + }; + } + if (source === "preview") { + for (const id of lensDef.primary) push(id, `${lensDef.label} trains this as a main muscle.`); + for (const id of lensDef.secondary) push(id, `${lensDef.label} also works this one.`); + return { + load: muscleLoad([{ key: lensDef.key, sessionsPerWeek: 1 }]), + notes: out, + phrase: `of ${lensDef.label}'s heaviest muscle`, + }; + } + return { load: planned, notes: out, phrase: "of your most-worked muscle" }; + }, [source, training, days, lensDef, planned, measurementNotes]); + + return ( +
+
+
+ {( + [ + ["planned", "Planned"], + ["logged", "Logged"], + ["preview", "Preview"], + ] as [Source, string][] + ).map(([value, label]) => ( + + ))} +
+ + {source === "logged" && training && ( +
+ {WINDOWS.map((w) => ( + + ))} +
+ )} + + {source === "preview" && ( + + )} +
+ +

+ {source === "planned" && + "Your declared activities, plus club visits you have allowed. Tap a muscle for details."} + {source === "preview" && + `What ${lensDef.label} trains. This is a preview, not your history.`} + {source === "logged" && training && training.workouts > 0 && ( + <> + {training.workouts} workout{training.workouts === 1 ? "" : "s"} in the last {days} days. + {training.unmatchedExercises.length > 0 && ( + <> + {" "} + Not counted, because we could not place them:{" "} + {training.unmatchedExercises.join(", ")}. + + )} + + )} + {source === "logged" && training && training.workouts === 0 && ( + <> + No workouts logged in the last {days} days.{" "} + Log a workout + + )} + {logged === null && + source !== "preview" && + " Workout-based mapping appears here once workout tracking is available for your account."} +

+ + +
+ ); +} diff --git a/src/lib/personal/exercise-catalog.ts b/src/lib/personal/exercise-catalog.ts new file mode 100644 index 00000000..bbc4fb91 --- /dev/null +++ b/src/lib/personal/exercise-catalog.ts @@ -0,0 +1,327 @@ +import type { MuscleId } from "./muscle-map"; + +// Maps a logged exercise name (free text) to the muscles it trains. Matching is deliberately simple and +// explainable: lower-cased words, keyword must start at a word boundary, the longest keyword wins. +// Unmatched names are reported back to the user instead of being guessed at. +export interface ExerciseDef { + key: string; + label: string; + keywords: readonly string[]; + primary: readonly MuscleId[]; + secondary: readonly MuscleId[]; +} + +export const EXERCISES: readonly ExerciseDef[] = [ + { + key: "bench-press", + label: "Bench press", + keywords: ["bench press", "chest press", "incline press", "decline press"], + primary: ["pectorals"], + secondary: ["deltoid-front", "triceps"], + }, + { + key: "push-up", + label: "Push-up", + keywords: ["push up", "pushup", "press up"], + primary: ["pectorals"], + secondary: ["triceps", "deltoid-front", "abs"], + }, + { + key: "chest-fly", + label: "Chest fly", + keywords: ["chest fly", "pec fly", "pec deck", "cable fly", "dumbbell fly", "crossover"], + primary: ["pectorals"], + secondary: ["deltoid-front"], + }, + { + key: "dip", + label: "Dip", + keywords: ["dip"], + primary: ["triceps", "pectorals"], + secondary: ["deltoid-front"], + }, + { + key: "overhead-press", + label: "Overhead press", + keywords: ["overhead press", "shoulder press", "military press", "arnold press", "push press"], + primary: ["deltoid-front", "deltoid-side"], + secondary: ["triceps", "trapezius"], + }, + { + key: "lateral-raise", + label: "Lateral raise", + keywords: ["lateral raise", "side raise"], + primary: ["deltoid-side"], + secondary: ["trapezius"], + }, + { + key: "front-raise", + label: "Front raise", + keywords: ["front raise"], + primary: ["deltoid-front"], + secondary: ["deltoid-side"], + }, + { + key: "rear-delt", + label: "Rear delt work", + keywords: ["rear delt", "reverse fly", "rear fly", "face pull"], + primary: ["deltoid-rear"], + secondary: ["trapezius"], + }, + { + key: "shrug", + label: "Shrug", + keywords: ["shrug"], + primary: ["trapezius"], + secondary: ["forearms-back"], + }, + { + key: "pull-up", + label: "Pull-up", + keywords: ["pull up", "pullup", "chin up", "chinup"], + primary: ["lats"], + secondary: ["biceps", "deltoid-rear", "forearms-front"], + }, + { + key: "lat-pulldown", + label: "Lat pulldown", + keywords: ["lat pulldown", "pulldown", "pull down"], + primary: ["lats"], + secondary: ["biceps", "deltoid-rear"], + }, + { + key: "row", + label: "Row", + keywords: ["row"], + primary: ["lats", "trapezius"], + secondary: ["biceps", "deltoid-rear", "lower-back"], + }, + { + key: "deadlift", + label: "Deadlift", + keywords: ["deadlift"], + primary: ["glutes", "hamstrings", "lower-back"], + secondary: ["trapezius", "forearms-front", "quadriceps", "lats"], + }, + { + key: "romanian-deadlift", + label: "Romanian deadlift", + keywords: ["romanian deadlift", "rdl", "stiff leg", "good morning"], + primary: ["hamstrings", "glutes"], + secondary: ["lower-back"], + }, + { + key: "squat", + label: "Squat", + keywords: ["squat"], + primary: ["quadriceps", "glutes"], + secondary: ["hamstrings", "adductors", "lower-back", "abs"], + }, + { + key: "lunge", + label: "Lunge", + keywords: ["lunge", "split squat", "step up"], + primary: ["quadriceps", "glutes"], + secondary: ["hamstrings", "adductors", "calves"], + }, + { + key: "leg-press", + label: "Leg press", + keywords: ["leg press", "hack squat"], + primary: ["quadriceps"], + secondary: ["glutes", "adductors"], + }, + { + key: "leg-extension", + label: "Leg extension", + keywords: ["leg extension"], + primary: ["quadriceps"], + secondary: [], + }, + { + key: "leg-curl", + label: "Leg curl", + keywords: ["leg curl", "hamstring curl", "nordic"], + primary: ["hamstrings"], + secondary: ["calves"], + }, + { + key: "hip-thrust", + label: "Hip thrust", + keywords: ["hip thrust", "glute bridge", "glute kickback"], + primary: ["glutes"], + secondary: ["hamstrings"], + }, + { + key: "adductor", + label: "Inner thigh work", + keywords: ["adductor", "hip adduction", "copenhagen"], + primary: ["adductors"], + secondary: [], + }, + { + key: "calf-raise", + label: "Calf raise", + keywords: ["calf raise", "calf press", "heel raise", "donkey calf"], + primary: ["calves"], + secondary: [], + }, + { + key: "tibialis", + label: "Shin work", + keywords: ["tibialis", "toe raise"], + primary: ["tibialis"], + secondary: [], + }, + { + key: "biceps-curl", + label: "Curl", + keywords: ["curl", "bicep", "biceps"], + primary: ["biceps"], + secondary: ["forearms-front"], + }, + { + key: "wrist-curl", + label: "Forearm work", + keywords: ["wrist curl", "reverse curl", "dead hang", "grip"], + primary: ["forearms-front", "forearms-back"], + secondary: [], + }, + { + key: "triceps", + label: "Triceps work", + keywords: [ + "tricep", + "triceps", + "pushdown", + "skull crusher", + "skullcrusher", + "close grip bench", + ], + primary: ["triceps"], + secondary: [], + }, + { + key: "crunch", + label: "Crunch", + keywords: ["crunch", "sit up", "situp", "ab wheel", "ab rollout"], + primary: ["abs"], + secondary: ["obliques", "hip-flexors"], + }, + { + key: "plank", + label: "Plank", + keywords: ["plank", "hollow", "dead bug", "mountain climber"], + primary: ["abs"], + secondary: ["obliques", "deltoid-front", "lower-back"], + }, + { + key: "leg-raise", + label: "Leg raise", + keywords: ["leg raise", "knee raise", "hanging raise", "v up"], + primary: ["abs", "hip-flexors"], + secondary: [], + }, + { + key: "oblique", + label: "Oblique work", + keywords: [ + "russian twist", + "woodchop", + "wood chop", + "side bend", + "pallof", + "side plank", + "oblique", + ], + primary: ["obliques"], + secondary: ["abs"], + }, + { + key: "back-extension", + label: "Back extension", + keywords: ["back extension", "hyperextension", "superman", "reverse hyper"], + primary: ["lower-back"], + secondary: ["glutes", "hamstrings"], + }, + { + key: "carry", + label: "Carry", + keywords: ["farmer", "suitcase carry", "carry"], + primary: ["forearms-front", "trapezius"], + secondary: ["obliques", "abs"], + }, + { + key: "kettlebell-swing", + label: "Kettlebell swing", + keywords: ["kettlebell swing", "swing"], + primary: ["glutes", "hamstrings"], + secondary: ["lower-back", "deltoid-front", "abs"], + }, + { + key: "olympic", + label: "Olympic lift", + keywords: ["power clean", "hang clean", "clean", "snatch", "thruster"], + primary: ["quadriceps", "glutes", "trapezius"], + secondary: ["hamstrings", "deltoid-front", "lower-back"], + }, + { + key: "run", + label: "Running", + keywords: ["run", "jog", "treadmill", "sprint"], + primary: ["quadriceps", "hamstrings", "calves", "glutes"], + secondary: ["hip-flexors", "tibialis", "abs"], + }, + { + key: "cycle", + label: "Cycling", + keywords: ["cycle", "cycling", "bike", "spin"], + primary: ["quadriceps", "glutes", "calves"], + secondary: ["hamstrings", "hip-flexors"], + }, + { + key: "swim", + label: "Swimming", + keywords: ["swim"], + primary: ["lats", "deltoid-front", "deltoid-rear", "pectorals"], + secondary: ["triceps", "abs"], + }, + { + key: "burpee", + label: "Burpee", + keywords: ["burpee"], + primary: ["pectorals", "quadriceps", "deltoid-front"], + secondary: ["triceps", "abs", "glutes"], + }, +]; + +function words(text: string): string { + return ( + " " + + text + .toLowerCase() + .replace(/[^a-z0-9]+/g, " ") + .trim() + + " " + ); +} + +/** Longest matching keyword wins, so "romanian deadlift" is not read as a plain "deadlift". */ +export function matchExercise(name: string): ExerciseDef | null { + const haystack = words(name); + let best: { def: ExerciseDef; length: number } | null = null; + for (const def of EXERCISES) { + for (const keyword of def.keywords) { + const needle = + " " + + keyword + .toLowerCase() + .replace(/[^a-z0-9]+/g, " ") + .trim(); + if (haystack.includes(needle) && (!best || needle.length > best.length)) { + best = { def, length: needle.length }; + } + } + } + return best?.def ?? null; +} diff --git a/src/lib/personal/muscle-explorer-service.ts b/src/lib/personal/muscle-explorer-service.ts new file mode 100644 index 00000000..b3c435f1 --- /dev/null +++ b/src/lib/personal/muscle-explorer-service.ts @@ -0,0 +1,57 @@ +import type { PrismaClient } from "@/generated/prisma/client"; +import { OnboardingError } from "@/lib/club-onboarding"; +import { getOverview } from "./personal-service"; +import { trainingFromWorkouts, type MuscleTraining } from "./muscle-training"; +import { assertWellnessAdult, assertWellnessEnabled } from "./wellness-policy"; + +export const EXPLORER_WINDOWS = [7, 28, 90] as const; +export type ExplorerWindow = (typeof EXPLORER_WINDOWS)[number]; + +const MAX_WORKOUTS = 400; + +/** + * Everything the interactive muscle map needs, for the signed-in user only. + * `logged` is null whenever the wellness feature is off or the user is not a clear adult: that is the + * same gate the workout routes use (wellness-policy.ts), reused here so the two cannot drift apart. + */ +export async function getMuscleExplorer(db: PrismaClient, userId: string, now = new Date()) { + const overview = await getOverview(db, userId, now); + return { overview, logged: await loggedTraining(db, userId, now) }; +} + +async function loggedTraining( + db: PrismaClient, + userId: string, + now: Date +): Promise | null> { + try { + assertWellnessEnabled(); + await assertWellnessAdult(db, userId, now); + } catch (error) { + if (error instanceof OnboardingError) return null; + throw error; + } + const since = new Date(now.getTime() - Math.max(...EXPLORER_WINDOWS) * 86_400_000); + const rows = await db.workoutSession.findMany({ + where: { userId, endedAt: { gte: since, lte: now } }, + orderBy: { endedAt: "desc" }, + take: MAX_WORKOUTS, + select: { + endedAt: true, + activityKey: true, + durationMinutes: true, + exercises: { + orderBy: { position: "asc" }, + select: { + name: true, + sets: { + select: { reps: true, weightGrams: true, durationSeconds: true, distanceMeters: true }, + }, + }, + }, + }, + }); + return Object.fromEntries( + EXPLORER_WINDOWS.map((days) => [days, trainingFromWorkouts(rows, days, now)]) + ) as Record; +} diff --git a/src/lib/personal/muscle-training.ts b/src/lib/personal/muscle-training.ts new file mode 100644 index 00000000..d056d950 --- /dev/null +++ b/src/lib/personal/muscle-training.ts @@ -0,0 +1,144 @@ +import { matchExercise } from "./exercise-catalog"; +import { + ACTIVITIES, + MUSCLE_IDS, + PRIMARY_WEIGHT, + SECONDARY_WEIGHT, + type MuscleId, +} from "./muscle-map"; + +// Turns a user's own completed workouts into a per-muscle picture over a time window. +// Descriptive only: counts of work done, never advice, recovery scoring or a health judgement. + +export interface WorkoutSet { + reps?: number | null; + weightGrams?: number | null; + durationSeconds?: number | null; + distanceMeters?: number | null; +} +export interface WorkoutLike { + endedAt: Date; + activityKey: string; + durationMinutes: number; + exercises: { name: string; sets: WorkoutSet[] }[]; +} +export interface MuscleTraining { + /** 0..1, relative to the most-worked muscle in this window. */ + load: Record; + /** Weighted set-equivalents, one decimal. A secondary muscle counts 0.4 of a set. */ + setEquivalents: Record; + /** Whole days since the muscle last got any work; absent when not worked in the window. */ + lastWorkedDaysAgo: Partial>; + /** Up to three exercise or activity names that contributed most, biggest first. */ + contributors: Partial>; + workouts: number; + /** Logged exercise names the catalogue could not place; shown to the user, never guessed. */ + unmatchedExercises: string[]; +} + +const DAY_MS = 86_400_000; +/** A workout with no recognisable exercises counts as one set-equivalent per 10 minutes, at least 3. */ +const FALLBACK_MINUTES_PER_SET = 10; +const FALLBACK_MIN_SETS = 3; +/** A timed set with no reps counts one set-equivalent per 10 minutes, at least 1. */ +const TIMED_SECONDS_PER_SET = 600; +const MAX_UNMATCHED = 8; + +function setCount(sets: WorkoutSet[]): number { + let total = 0; + for (const s of sets) { + const reps = s.reps ?? 0; + const grams = s.weightGrams ?? 0; + const secs = s.durationSeconds ?? 0; + const metres = s.distanceMeters ?? 0; + if (reps > 0 || grams > 0) total += 1; + else if (secs > 0) total += Math.max(1, Math.round(secs / TIMED_SECONDS_PER_SET)); + else if (metres > 0) total += 1; + } + return total; +} + +export function trainingFromWorkouts( + workouts: readonly WorkoutLike[], + days: number, + now: Date +): MuscleTraining { + const since = now.getTime() - days * DAY_MS; + const raw = Object.fromEntries(MUSCLE_IDS.map((id) => [id, 0])) as Record; + const last: Partial> = {}; + const by = new Map>(); + const unmatched = new Set(); + let counted = 0; + + const add = (id: MuscleId, amount: number, name: string, endedAt: Date) => { + if (amount <= 0) return; + raw[id] += amount; + const ago = Math.max(0, Math.floor((now.getTime() - endedAt.getTime()) / DAY_MS)); + last[id] = Math.min(last[id] ?? ago, ago); + const names = by.get(id) ?? new Map(); + names.set(name, (names.get(name) ?? 0) + amount); + by.set(id, names); + }; + + for (const w of workouts) { + const t = w.endedAt.getTime(); + if (t < since || t > now.getTime()) continue; + counted += 1; + let placed = false; + for (const ex of w.exercises) { + const def = matchExercise(ex.name); + if (!def) { + if (unmatched.size < MAX_UNMATCHED) unmatched.add(ex.name.trim()); + continue; + } + const sets = setCount(ex.sets); + if (sets === 0) continue; + placed = true; + for (const id of def.primary) add(id, sets * PRIMARY_WEIGHT, def.label, w.endedAt); + for (const id of def.secondary) add(id, sets * SECONDARY_WEIGHT, def.label, w.endedAt); + } + if (!placed) { + // No exercise detail we can use: fall back to the workout's declared activity and its length. + const activity = ACTIVITIES.find((a) => a.key === w.activityKey); + if (activity) { + const sets = Math.max( + FALLBACK_MIN_SETS, + Math.round(w.durationMinutes / FALLBACK_MINUTES_PER_SET) + ); + for (const id of activity.primary) + add(id, sets * PRIMARY_WEIGHT, activity.label, w.endedAt); + for (const id of activity.secondary) + add(id, sets * SECONDARY_WEIGHT, activity.label, w.endedAt); + } + } + } + + const max = Math.max(0, ...Object.values(raw)); + const load = Object.fromEntries( + MUSCLE_IDS.map((id) => [id, max === 0 ? 0 : Math.round((raw[id] / max) * 1000) / 1000]) + ) as Record; + const setEquivalents = Object.fromEntries( + MUSCLE_IDS.map((id) => [id, Math.round(raw[id] * 10) / 10]) + ) as Record; + const contributors: Partial> = {}; + for (const [id, names] of by) { + contributors[id] = [...names] + .sort((a, b) => b[1] - a[1]) + .slice(0, 3) + .map(([n]) => n); + } + return { + load, + setEquivalents, + lastWorkedDaysAgo: last, + contributors, + workouts: counted, + unmatchedExercises: [...unmatched], + }; +} + +export function daysAgoLabel(days: number): string { + if (days <= 0) return "today"; + if (days === 1) return "yesterday"; + return `${days} days ago`; +} diff --git a/tests/integration/personal-service.test.mjs b/tests/integration/personal-service.test.mjs index c4bcfacb..809d41d0 100644 --- a/tests/integration/personal-service.test.mjs +++ b/tests/integration/personal-service.test.mjs @@ -9,6 +9,7 @@ register("./helpers/src-alias-hook.mjs", import.meta.url); const { PrismaClient } = await import("../../src/generated/prisma/client.ts"); const { PrismaPg } = await import("@prisma/adapter-pg"); const svc = await import("../../src/lib/personal/personal-service.ts"); +const explorer = await import("../../src/lib/personal/muscle-explorer-service.ts"); const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); const db = new PrismaClient({ adapter: new PrismaPg(pool) }); @@ -198,3 +199,75 @@ test("activities replace the set, and delete-all erases personal data but keeps await db.user.delete({ where: { id: u.id } }); // cascades any leftover Personal rows } }); + +async function withWellness(value, task) { + const before = process.env.PERSONAL_WELLNESS_ENABLED; + process.env.PERSONAL_WELLNESS_ENABLED = value; + try { + await task(); + } finally { + if (before === undefined) delete process.env.PERSONAL_WELLNESS_ENABLED; + else process.env.PERSONAL_WELLNESS_ENABLED = before; + } +} +const addWorkout = (tx, userId, daysAgo, exercises) => + tx.workoutSession.create({ + data: { + userId, + requestId: `ps-w-${randomUUID()}`, + title: "Session", + activityKey: "gym-lifting", + startedAt: new Date(NOW.getTime() - daysAgo * 86_400_000 - 3_600_000), + endedAt: new Date(NOW.getTime() - daysAgo * 86_400_000), + durationMinutes: 60, + exercises: { + create: exercises.map((name, position) => ({ + name, + position, + sets: { create: [{ position: 0, reps: 8, weightGrams: 50000 }] }, + })), + }, + }, + }); + +test("the muscle explorer stays dark while wellness is off and for non-adults", async () => { + await inRolledBackTx(async (tx) => { + const adult = await newUser(tx, "xa"); + const minor = await newUser(tx, "xm"); + await svc.updateBio(tx, adult.id, { birthYear: 1990 }); + await svc.updateBio(tx, minor.id, { birthYear: 2015 }); + await addWorkout(tx, adult.id, 1, ["Bench press"]); + await addWorkout(tx, minor.id, 1, ["Bench press"]); + + await withWellness("false", async () => { + assert.equal((await explorer.getMuscleExplorer(tx, adult.id, NOW)).logged, null); + }); + await withWellness("true", async () => { + assert.ok((await explorer.getMuscleExplorer(tx, adult.id, NOW)).logged); + assert.equal((await explorer.getMuscleExplorer(tx, minor.id, NOW)).logged, null); + }); + }); +}); + +test("the muscle explorer maps only the signed-in user's own workouts", async () => { + await inRolledBackTx(async (tx) => { + const me = await newUser(tx, "xme"); + const other = await newUser(tx, "xother"); + for (const u of [me, other]) await svc.updateBio(tx, u.id, { birthYear: 1990 }); + await addWorkout(tx, me.id, 2, ["Back squat"]); + await addWorkout(tx, me.id, 40, ["Bench press"]); // outside the 28 day window, inside 90 + for (let i = 1; i <= 10; i++) await addWorkout(tx, other.id, i, ["Pull-up"]); // never mine + + await withWellness("true", async () => { + const { logged } = await explorer.getMuscleExplorer(tx, me.id, NOW); + assert.equal(logged[28].workouts, 1); + assert.equal(logged[90].workouts, 2); + assert.equal(logged[28].setEquivalents.lats, 0); // the other user's pull-ups + assert.ok(logged[28].setEquivalents.quadriceps > 0); + assert.equal(logged[28].setEquivalents.pectorals, 0); // bench was 40 days ago + assert.ok(logged[90].setEquivalents.pectorals > 0); + assert.equal(logged[28].lastWorkedDaysAgo.quadriceps, 2); + assert.deepEqual(logged[28].unmatchedExercises, []); + }); + }); +}); diff --git a/tests/unit/personal-muscle-training.test.mjs b/tests/unit/personal-muscle-training.test.mjs new file mode 100644 index 00000000..41b1bc88 --- /dev/null +++ b/tests/unit/personal-muscle-training.test.mjs @@ -0,0 +1,142 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { register } from "node:module"; + +// Same loader hook the integration tests use: resolves extensionless imports inside src/. +register("../integration/helpers/src-alias-hook.mjs", import.meta.url); +const { EXERCISES, matchExercise } = await import("../../src/lib/personal/exercise-catalog.ts"); +const { MUSCLE_IDS } = await import("../../src/lib/personal/muscle-map.ts"); +const { daysAgoLabel, trainingFromWorkouts } = + await import("../../src/lib/personal/muscle-training.ts"); + +const NOW = new Date("2026-11-19T12:00:00Z"); +const daysAgo = (n) => new Date(NOW.getTime() - n * 86_400_000); +const workout = (over) => ({ + endedAt: daysAgo(1), + activityKey: "gym-lifting", + durationMinutes: 60, + exercises: [], + ...over, +}); +const sets = (n) => Array.from({ length: n }, () => ({ reps: 8, weightGrams: 60000 })); + +test("catalogue only refers to real muscles and has unique keys and no empty keywords", () => { + const keys = new Set(); + for (const e of EXERCISES) { + assert.ok(!keys.has(e.key), `duplicate key ${e.key}`); + keys.add(e.key); + assert.ok(e.primary.length > 0, `${e.key} has no primary muscle`); + assert.ok( + e.keywords.every((k) => k.trim().length > 1), + `${e.key} has an empty keyword` + ); + for (const id of [...e.primary, ...e.secondary]) + assert.ok(MUSCLE_IDS.includes(id), `${e.key}: ${id}`); + } +}); + +test("matching handles casing, punctuation and plurals", () => { + assert.equal(matchExercise("Barbell Bench Press").key, "bench-press"); + assert.equal(matchExercise("incline bench-press!").key, "bench-press"); + assert.equal(matchExercise("Weighted Pull-ups").key, "pull-up"); + assert.equal(matchExercise("Seated cable rows").key, "row"); +}); + +test("the longest keyword wins, so specific lifts are not read as generic ones", () => { + assert.equal(matchExercise("Romanian Deadlift").key, "romanian-deadlift"); + assert.equal(matchExercise("Deadlift").key, "deadlift"); + assert.equal(matchExercise("Leg curl").key, "leg-curl"); // not a biceps curl + assert.equal(matchExercise("Hammer curl").key, "biceps-curl"); + assert.equal(matchExercise("Bulgarian split squat").key, "lunge"); + assert.equal(matchExercise("Back squat").key, "squat"); +}); + +test("keywords must start at a word boundary and unknown names stay unmatched", () => { + assert.equal(matchExercise("Arrow practice"), null); // "row" inside a word + assert.equal(matchExercise("Stretching"), null); + assert.equal(matchExercise(""), null); +}); + +test("sets are weighted primary 1 and secondary 0.4 and load is normalised", () => { + const t = trainingFromWorkouts( + [workout({ exercises: [{ name: "Bench press", sets: sets(5) }] })], + 28, + NOW + ); + assert.equal(t.setEquivalents.pectorals, 5); + assert.equal(t.setEquivalents.triceps, 2); + assert.equal(t.load.pectorals, 1); + assert.equal(t.load.triceps, 0.4); + assert.equal(t.load.quadriceps, 0); + assert.deepEqual(t.contributors.pectorals, ["Bench press"]); + assert.equal(t.lastWorkedDaysAgo.pectorals, 1); + assert.equal(t.lastWorkedDaysAgo.quadriceps, undefined); +}); + +test("the time window excludes older and future workouts", () => { + const w = [ + workout({ endedAt: daysAgo(3), exercises: [{ name: "Squat", sets: sets(4) }] }), + workout({ endedAt: daysAgo(20), exercises: [{ name: "Bench press", sets: sets(4) }] }), + workout({ + endedAt: new Date(NOW.getTime() + 3_600_000), + exercises: [{ name: "Row", sets: sets(9) }], + }), + ]; + const week = trainingFromWorkouts(w, 7, NOW); + assert.equal(week.workouts, 1); + assert.equal(week.setEquivalents.pectorals, 0); + assert.equal(week.setEquivalents.lats, 0); + const month = trainingFromWorkouts(w, 28, NOW); + assert.equal(month.workouts, 2); + assert.equal(month.setEquivalents.pectorals, 4); + assert.equal(month.lastWorkedDaysAgo.quadriceps, 3); +}); + +test("empty sets add nothing, timed sets scale, and unmatched names are reported", () => { + const t = trainingFromWorkouts( + [ + workout({ + exercises: [ + { name: "Squat", sets: [{}, { reps: 0 }] }, + { name: "Treadmill", sets: [{ durationSeconds: 1800 }] }, + { name: "Mystery machine", sets: sets(3) }, + ], + }), + ], + 28, + NOW + ); + assert.equal(t.setEquivalents.glutes, 3 + 0); // treadmill 1800s -> 3 set-equivalents; empty squat -> 0 + assert.deepEqual(t.unmatchedExercises, ["Mystery machine"]); +}); + +test("a workout with no usable exercises falls back to its declared activity and length", () => { + const t = trainingFromWorkouts( + [workout({ activityKey: "yoga", durationMinutes: 60, exercises: [] })], + 28, + NOW + ); + assert.equal(t.setEquivalents.abs, 6); // 60 min / 10 = 6 set-equivalents, primary weight 1 + assert.deepEqual(t.contributors.abs, ["Yoga"]); + const short = trainingFromWorkouts( + [workout({ activityKey: "yoga", durationMinutes: 5, exercises: [] })], + 28, + NOW + ); + assert.equal(short.setEquivalents.abs, 3); // minimum of 3 + const unknown = trainingFromWorkouts( + [workout({ activityKey: "curling", exercises: [] })], + 28, + NOW + ); + assert.ok(Object.values(unknown.load).every((v) => v === 0)); +}); + +test("an empty history gives an all-zero map and day labels read naturally", () => { + const t = trainingFromWorkouts([], 90, NOW); + assert.ok(Object.values(t.load).every((v) => v === 0)); + assert.equal(t.workouts, 0); + assert.equal(daysAgoLabel(0), "today"); + assert.equal(daysAgoLabel(1), "yesterday"); + assert.equal(daysAgoLabel(5), "5 days ago"); +});