diff --git a/api/coach/core/library.js b/api/coach/core/library.js index 8058e03..b977680 100644 --- a/api/coach/core/library.js +++ b/api/coach/core/library.js @@ -12,6 +12,9 @@ export const LIB_BY_ID = new Map(LIBRARY.map(e => [e.id, e])); export const libraryHas = id => LIB_BY_ID.has(id); export const libraryName = id => LIB_BY_ID.get(id)?.n || null; +// The body part, for the two places that have to reason about an exercise rather than name it: +// the validator (a cardio row prescribed in reps is not a prescription) and the builder's filter. +export const libraryBp = id => LIB_BY_ID.get(id)?.bp || null; /* ---------- the library slice the model gets to choose from ---------- Bounded. The whole catalogue is 1,324 rows — 10k+ tokens on every job, which costs real money @@ -26,14 +29,56 @@ export const MAX_LIBRARY = 160; // fields beyond body part never appear in a rationale and cost ~30 tokens an entry. const slim = e => ({ id: e.id, n: e.n, bp: e.bp, ...(e.custom ? { custom: true } : {}) }); -export function librarySlice(S, equipment, { keep = [], max = MAX_LIBRARY } = {}) { +/** + * The muscle selectors from an intake answer, sanitised. + * + * This is the one intake field that reaches a filter rather than the model's reading, so it is + * the one that has to be treated as input: the payload is built from whatever the client sent. + * A selector is `{ bp }` ("back", "chest") or `{ tg }` ("biceps", "triceps" — both live under the + * single `upper arms` body part, so the body part alone cannot tell them apart); anything else is + * dropped, since an unparseable selector could only ever narrow the library for no reason. The + * list is capped because more than a handful of muscles is not a routine, it is a whole week. + */ +export function cleanGroups(groups) { + if (!Array.isArray(groups)) return null; + const out = []; + for (const g of groups.slice(0, 12)) { + const bp = typeof g?.bp === 'string' ? g.bp.trim().toLowerCase().slice(0, 30) : ''; + const tg = typeof g?.tg === 'string' ? g.tg.trim().toLowerCase().slice(0, 30) : ''; + if (bp || tg) out.push({ ...(bp ? { bp } : {}), ...(tg ? { tg } : {}) }); + } + return out.length ? out : null; +} + +/** + * The catalogue narrowed to the muscles someone picked in the routine builder. + * + * An exercise is kept when it matches any selector: "back and biceps" is one list, not two. + * + * A selector that matches nothing returns the whole pool instead. That is the same call the + * equipment filter makes, for the same reason — a Coach that cannot propose anything is a worse + * failure than one proposing from a wider list — and it is only reachable from a hand-written + * payload, since the builder's buttons are built from this same taxonomy. + */ +function withGroups(list, groups) { + if (!groups || !groups.length) return list; + const kept = list.filter(e => groups.some(g => (g.tg && e.tg === g.tg) || (g.bp && e.bp === g.bp))); + return kept.length ? kept : list; +} + +export function librarySlice(S, equipment, { keep = [], max = MAX_LIBRARY, groups = null, catalogueOnly = false } = {}) { const wanted = (equipment || []).map(x => String(x).toLowerCase()); - const customs = (S.customEx || []).map(c => ({ id: c.id, n: c.n, bp: c.bp, tg: null, eq: 'custom', custom: true })); + // `catalogueOnly` drops the person's own exercises, which carry no animation: the routine + // builder promises every exercise it picks can be watched, and those rows are the only ones + // in the app that cannot be. + const customs = catalogueOnly + ? [] + : (S.customEx || []).map(c => ({ id: c.id, n: c.n, bp: c.bp, tg: null, eq: 'custom', custom: true })); // No equipment stated (or "everything") ⇒ the whole catalogue. Filtering to nothing would // leave the Coach unable to propose anything at all, which is a worse failure than a // slightly larger payload. const filtered = wanted.length ? LIBRARY.filter(e => wanted.includes((e.eq || '').toLowerCase())) : LIBRARY; - const base = filtered.length ? filtered : LIBRARY; + const base = withGroups(filtered.length ? filtered : LIBRARY, groups); const pinned = new Set(keep.filter(id => LIB_BY_ID.has(id))); const out = []; diff --git a/api/coach/core/payload.js b/api/coach/core/payload.js index 8de1c25..8cd8297 100644 --- a/api/coach/core/payload.js +++ b/api/coach/core/payload.js @@ -10,7 +10,7 @@ * handle stands in), passkey and credential material, push subscriptions, invite data, theme * and appearance settings, and every other profile's everything. */ -import { LIBRARY, LIB_BY_ID, libraryHas, libraryName, librarySlice, MAX_LIBRARY } from './library.js'; +import { LIBRARY, LIB_BY_ID, libraryHas, libraryName, librarySlice, cleanGroups, MAX_LIBRARY } from './library.js'; export const CONTRACT = 1; // Bounds from FR-22. A review reads a training block, not a training career: more history @@ -408,7 +408,15 @@ export function build(S, opts = {}) { // A review names mostly what is already trained; 60 candidates is plenty for a swap. p.library = librarySlice(S, profile?.equipment, { keep: trainedIds(S, workouts), max: 60 }); } else { - p.library = librarySlice(S, profile?.equipment, { keep: trainedIds(S, S.workouts || []) }); + // The routine builder narrows the list to the muscles the person picked and, with it, drops + // their own exercises: the builder promises every exercise it chooses has an animation, and + // a custom row is the only kind that has none. Both answers ride in the intake, which is + // already how "which muscles" reaches the payload — no second channel for one screen. + p.library = librarySlice(S, profile?.equipment, { + keep: trainedIds(S, S.workouts || []), + groups: cleanGroups(profile?.groups), + catalogueOnly: profile?.catalogueOnly === true + }); // Creation for a returning user: what they have actually handled, so proposed baselines // start from evidence rather than optimism (B2/FR-20). const best = {}; diff --git a/api/coach/core/validate.js b/api/coach/core/validate.js index 63f3600..c0ffc39 100644 --- a/api/coach/core/validate.js +++ b/api/coach/core/validate.js @@ -14,7 +14,7 @@ * model verbatim for the one repair round (FR-48) — and a list of six problems produces a * better second attempt than the first of them does. */ -import { libraryHas, libraryName } from './library.js'; +import { libraryHas, libraryName, libraryBp } from './library.js'; // The closed list (FR-23 / C3). Adding a member here is a deliberate act with an apply // implementation on the client to match; there is no default case anywhere. @@ -99,9 +99,16 @@ export function validatePlan(data, ctx = {}) { return; } const clean = { id: e.id, sets: isInt(e.sets, 1, 10) ? e.sets : 3 }; - const mode = MODES.includes(e.mode) ? e.mode : 'reps'; + // The mode has to agree with the exercise. The catalogue is the authority on what is + // cardio, and the app resolves an absent mode the same way (modeOf in history.js), so a + // model that leaves `mode` off now gets a cardio row that behaves like cardio instead of + // "3 × 10 reps" carrying a stray `min` nothing reads. `time` is deliberately NOT inferred + // this way: nothing in the catalogue says an exercise is held for seconds, and guessing it + // from one field would rewrite a rep prescription. + const mode = MODES.includes(e.mode) ? e.mode : (libraryBp(e.id) === 'cardio' ? 'cardio' : 'reps'); const perSide = !!e.side; if (mode === 'cardio') { + clean.mode = 'cardio'; clean.min = isInt(e.min, 1, 180) ? e.min : 20; clean.speed = isNum(e.speed) && e.speed > 0 && e.speed <= MAX_SPEED ? e.speed : 8; } else if (mode === 'time') { diff --git a/api/test/payload.test.js b/api/test/payload.test.js index 5a643e6..eaeb68d 100644 --- a/api/test/payload.test.js +++ b/api/test/payload.test.js @@ -120,6 +120,53 @@ test('the library is filtered to the equipment someone actually has', () => { assert.equal(withCustom[0].id, 'cx1'); }); +// The routine builder's muscle buttons. `bp` and `tg` are both used because "biceps" and +// "triceps" live under one body part ("upper arms"), so the body part alone cannot tell them +// apart — and the promise to the person is narrower than the equipment filter: only the muscles +// they asked for. +test('the library can be narrowed to the muscles someone picked', () => { + const byId = id => payload.LIBRARY.find(e => e.id === id); + + const back = payload.librarySlice({}, [], { groups: [{ bp: 'back' }] }); + assert.ok(back.length > 0); + assert.ok(back.every(e => byId(e.id).bp === 'back'), 'only back'); + + // Two muscles, one list: back and biceps together. + const both = payload.librarySlice({}, [], { groups: [{ bp: 'back' }, { tg: 'biceps' }] }); + assert.ok(both.some(e => byId(e.id).bp === 'back')); + assert.ok(both.some(e => byId(e.id).tg === 'biceps')); + assert.ok(both.every(e => byId(e.id).bp === 'back' || byId(e.id).tg === 'biceps'), 'nothing else'); + + // The target muscle separates what the body part cannot: no triceps in a biceps slice. + const biceps = payload.librarySlice({}, [], { groups: [{ tg: 'biceps' }] }); + assert.ok(biceps.every(e => byId(e.id).tg === 'biceps')); + assert.ok(!biceps.some(e => byId(e.id).tg === 'triceps')); + + // An exercise the person already trains still rides along — a review has to be able to name it + // — and the cap still holds. + const dumbbell = payload.LIBRARY.find(e => e.eq === 'dumbbell' && e.bp !== 'back'); + const kept = payload.librarySlice({}, [], { groups: [{ bp: 'back' }], keep: [dumbbell.id] }); + assert.equal(kept[0].id, dumbbell.id); + assert.ok(kept.length <= payload.MAX_LIBRARY + 1); + + // A selector that matches nothing is ignored rather than producing an empty library: the + // builder's own buttons come from this taxonomy, so this is only reachable from a hand-written + // payload, and a Coach with nothing to propose is the worse failure. + assert.ok(payload.librarySlice({}, [], { groups: [{ bp: 'no such part' }] }).length > 0); +}); + +// The builder promises every exercise it picks can be watched, and a custom row is the only kind +// in the app with no animation. They normally travel whatever the filter says — the model cannot +// guess them — so this is the one path that leaves them out. +test('custom exercises are left out when the caller asks for the catalogue only', () => { + const S = { customEx: [{ id: 'cx1', n: 'Sandbag carry', bp: 'back' }] }; + assert.equal(payload.librarySlice(S, [], {})[0].id, 'cx1'); + const withoutCustom = payload.librarySlice(S, [], { catalogueOnly: true }); + assert.ok(!withoutCustom.some(e => e.custom)); + assert.ok(!withoutCustom.some(e => e.id === 'cx1')); + assert.ok(withoutCustom.length > 0); +}); + test('the library slice is capped, balanced across body parts, deterministic, and keeps what the user trains', () => { const { MAX_LIBRARY, LIBRARY } = payload; const all = payload.librarySlice({}, []); diff --git a/api/test/validate.test.js b/api/test/validate.test.js index 1776dca..626cadb 100644 --- a/api/test/validate.test.js +++ b/api/test/validate.test.js @@ -55,6 +55,28 @@ test('a plan may reference a custom exercise it defines in the same answer', () assert.equal(r.bundle.customEx[0].n, 'Sandbag carry'); }); +// A cardio row is defined by its body part in the catalogue, and the app resolves an absent +// `mode` the same way (modeOf in history.js). Leaving it out used to produce "3 × 10 reps" with a +// stray `min` nothing reads — which is what the routine builder's "start with cardio" answer hit, +// since a model that prescribes 8 minutes rarely also remembers to say mode: "cardio". +test('an exercise whose catalogue body part is cardio comes back as a cardio prescription', () => { + const r = validatePlan({ + routines: [{ id: 'r1', name: 'A', ex: [{ id: '3220', sets: 1, min: 8 }] }] + }); + assert.equal(r.ok, true, JSON.stringify(r.errors)); + const ex = r.bundle.routines[0].ex[0]; + assert.equal(ex.mode, 'cardio'); + assert.equal(ex.min, 8); + // …and a stated mode still wins, so nothing else about the answer is rewritten. + const timed = validatePlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '3220', sets: 1, mode: 'time', sec: 60 }] }] }); + assert.equal(timed.bundle.routines[0].ex[0].mode, 'time'); + assert.equal(timed.bundle.routines[0].ex[0].sec, 60); + // A rep exercise is untouched: the inference is only ever cardio, never "time from a stray + // field", which would rewrite a prescription nobody asked to change. + const reps = validatePlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, sec: 45 }] }] }); + assert.equal(reps.bundle.routines[0].ex[0].mode, 'reps'); +}); + test('the week may only point at routines the plan actually defines', () => { const r = validatePlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 10 }] }], week: { 1: 'ghost' } }); assert.equal(r.ok, false); diff --git a/frontend/src/lib/ai-routine.js b/frontend/src/lib/ai-routine.js new file mode 100644 index 0000000..e0fe66e --- /dev/null +++ b/frontend/src/lib/ai-routine.js @@ -0,0 +1,148 @@ +/* "Build a routine with AI" — the three questions, and what to do with the answer. + * + * The screen asks which muscles, whether the session starts with cardio, and how hard it should + * be; everything else is this module. It is pure and framework-free, like every other helper in + * lib/, because the parts that can be wrong are not the buttons — they are the sentence that goes + * to the model, which the model's own reading of the library depends on, and the routine that + * comes back, which has to be a routine this app can actually run. + * + * The AI half is the Coach that already exists: same payload builder, same validator, same + * provider adapters (see coach-api.js / coach-local.js). Nothing here talks to a model. + */ +import { EXIDX, isCardio } from './exercises.js' +import { defaultConfig } from './history.js' +import { t } from './i18n.js' + +/* ---------- the buttons ---------- + Labels are existing keys in every locale pack (they are the muscle names the Library and the + body map already show), so this adds no translation debt. `selectors` are the terms the + catalogue itself uses: a body part for most groups, and a target muscle where the body part is + too coarse — "biceps" and "triceps" are both `upper arms`, and asking for one must not hand + back the other. */ +export const MUSCLE_GROUPS = [ + { key: 'chest', label: 'Chest', selectors: [{ bp: 'chest' }] }, + { key: 'back', label: 'Back', selectors: [{ bp: 'back' }] }, + { key: 'shoulders', label: 'Shoulders', selectors: [{ bp: 'shoulders' }] }, + { key: 'biceps', label: 'Biceps', selectors: [{ tg: 'biceps' }] }, + { key: 'triceps', label: 'Triceps', selectors: [{ tg: 'triceps' }] }, + { key: 'legs', label: 'Legs', selectors: [{ bp: 'upper legs' }, { bp: 'lower legs' }] }, + { key: 'glutes', label: 'Glutes', selectors: [{ tg: 'glutes' }] }, + { key: 'core', label: 'Core', selectors: [{ bp: 'waist' }] }, +] + +/* ---------- the intensity buttons ---------- + The numbers are the prescription, and they are stated twice on purpose: once as a sentence the + model reads, and once as the intake fields it is told to obey. A model that follows the prose + and a model that follows the fields then agree. `CARDIAC_MIN` is what "start with cardio" + asks for — a warm-up, not a conditioning block. */ +export const INTENSITIES = [ + { key: 'light', label: 'Light', sets: '2-3', reps: '12-15', exercises: '4-5', sessionMin: 45 }, + { key: 'medium', label: 'Medium', sets: '3-4', reps: '8-12', exercises: '6-7', sessionMin: 60 }, + { key: 'hard', label: 'Hard', sets: '4-5', reps: '6-10', exercises: '7-9', sessionMin: 75 }, +] +export const CARDIAC_MIN = 8 +const byKey = (list, key) => list.find(x => x.key === key) || null + +/* The taxonomy words the model will find in the library it is given — English, like every other + value in the contract. Its own prose answer comes back in the profile's language (meta.lang). */ +const groupWords = group => group.selectors.map(s => s.tg || s.bp) + +/** + * The intake the Coach is asked with. + * + * `daysPerWeek: 1` is the whole point: this builds ONE routine, so the plan it returns is a + * one-day plan and `pickRoutine` below takes the routine that day names. The equipment comes from + * the active profile, so it only proposes what the person actually has. + */ +export function buildIntake({ muscles = [], cardio = false, intensity = 'medium', equipment = [], limitations = '' } = {}) { + const groups = muscles.flatMap(g => g.selectors) + // Cardio has to travel in the library as well as in the sentence: it is a body part of its own, + // and a model told to start with cardio but handed no cardio exercise can only improvise one — + // which is exactly what happened the first time this was tried. + if (cardio) groups.push({ bp: 'cardio' }) + const level = byKey(INTENSITIES, intensity) || INTENSITIES[1] + const words = muscles.flatMap(groupWords) + const cardioLine = cardio + ? `The FIRST exercise must be cardio: one whose body part is cardio, with mode "cardio" and min ${CARDIAC_MIN}.` + : 'Do not include any cardio exercise.' + return { + goal: 'build muscle', + // The intensity is a prescription, not a claim about experience; the wizard does not ask, so + // the safe reading of "light" is a beginner's short session rather than an advanced deload. + experience: level.key === 'light' ? 'beginner' : level.key === 'hard' ? 'advanced' : 'intermediate', + daysPerWeek: 1, + sessionMin: level.sessionMin, + equipment, + limitations: limitations || '', + likes: '', + dislikes: '', + groups, + // Every exercise the builder picks has to be watchable: the catalogue's rows all have an + // animation, and the person's own exercises are the only ones that do not. + catalogueOnly: true, + notes: [ + `Build ONE routine, for this session only: ${words.join(', ') || 'the whole body'}.`, + `Intensity: ${level.key} — about ${level.exercises} exercises, ${level.sets} sets each, ${level.reps} reps.`, + cardioLine, + 'Every exercise id must come from the library you were given, and each one must be a real exercise for the muscles named above.', + 'Order the session: the hardest compound work first, isolation last.' + ].join(' ') + } +} + +/** The muscles asked for, as the payload's own vocabulary — for a routine name and for tests. */ +export const muscleWords = muscles => muscles.flatMap(groupWords) + +/** + * The routine to keep, out of the one-day plan that came back. + * + * The plan names its routine for the day it scheduled (week: { "0": "r1" }), and that is the one + * the person asked for; the first routine is the fallback for an answer whose week the validator + * let through pointing somewhere else. + */ +export function pickRoutine(bundle) { + const routines = (bundle?.routines || []).filter(r => r && Array.isArray(r.ex)) + if (!routines.length) return null + const scheduled = new Set(Object.values(bundle.week || {}).flat().map(String)) + return routines.find(r => scheduled.has(String(r.id))) || routines[0] +} + +/** + * One exercise of the generated routine, as this app stores it. + * + * The validator has already made every field legal; what is left is what the catalogue knows and + * the answer does not. A cardio exercise is one bout — a model asked for "8 minutes of cardio" + * hands back `sets: 3` about half the time, and "3 × 8 min" is not the warm-up anybody meant — + * and a mode the answer left out is read from the exercise itself, the same way `modeOf` reads it + * everywhere else. + */ +export function normalizeExercise(ex) { + const lib = EXIDX[ex.id] || null + const out = { ...ex } + if (!out.mode) out.mode = isCardio(ex.id) ? 'cardio' : 'reps' + if (out.mode === 'cardio') { + out.sets = 1 + if (!(out.min > 0)) out.min = CARDIAC_MIN + } + // Bodyweight is a fact about the exercise, not about the prescription, and the Coach writes it + // only when it disagrees with the catalogue — so the builder states it, and the routine editor + // and the workout screen then treat a push-up as a push-up. + if (lib && out.mode !== 'cardio' && !('bodyweight' in out)) { + const def = defaultConfig(ex.id) + if (def.bodyweight) out.bodyweight = true + } + return out +} + +/** The routine to push into the plan: the answer's name and emoji, every exercise normalised. */ +export function routineFrom(bundle, { fallbackName } = {}) { + const r = pickRoutine(bundle) + if (!r) return null + const ex = r.ex.map(normalizeExercise) + return { + name: (r.name || '').trim() || fallbackName || t('AI routine'), + emoji: r.emoji || '🤖', + ...(r.prog ? { prog: r.prog } : {}), + ex + } +} diff --git a/frontend/src/lib/ai-routine.test.js b/frontend/src/lib/ai-routine.test.js new file mode 100644 index 0000000..9c871f8 --- /dev/null +++ b/frontend/src/lib/ai-routine.test.js @@ -0,0 +1,125 @@ +// The routine builder's two halves that can be wrong: the sentence that goes to the model (the +// model's reading of the library depends on it) and the routine that comes back (it has to be +// something this app can run). The buttons themselves are not worth a test; these are. +import { describe, it, expect } from 'vitest' +import { MUSCLE_GROUPS, INTENSITIES, CARDIAC_MIN, buildIntake, muscleWords, pickRoutine, normalizeExercise, routineFrom } from './ai-routine.js' + +const group = key => MUSCLE_GROUPS.find(g => g.key === key) + +describe('what the builder asks the model for', () => { + it('asks for exactly one day, because it builds one routine', () => { + const intake = buildIntake({ muscles: [group('back')], cardio: false, intensity: 'medium' }) + expect(intake.daysPerWeek).toBe(1) + expect(intake.sessionMin).toBe(INTENSITIES[1].sessionMin) + // Never the person's own exercises: the builder promises every pick has an animation. + expect(intake.catalogueOnly).toBe(true) + }) + + it('narrows the library to the muscles picked, target muscle included', () => { + const intake = buildIntake({ muscles: [group('back'), group('biceps')] }) + expect(intake.groups).toEqual([{ bp: 'back' }, { tg: 'biceps' }]) + // Legs is two body parts in the catalogue, and both have to travel. + expect(buildIntake({ muscles: [group('legs')] }).groups).toEqual([{ bp: 'upper legs' }, { bp: 'lower legs' }]) + }) + + it('puts cardio in the library, not only in the sentence', () => { + const withCardio = buildIntake({ muscles: [group('back')], cardio: true }) + // A model told to start with cardio but handed no cardio exercise can only improvise, which + // is what it did the first time this shipped without the selector. + expect(withCardio.groups).toContainEqual({ bp: 'cardio' }) + expect(withCardio.notes).toContain('mode "cardio"') + expect(withCardio.notes).toContain(String(CARDIAC_MIN)) + + const without = buildIntake({ muscles: [group('back')], cardio: false }) + expect(without.groups).not.toContainEqual({ bp: 'cardio' }) + expect(without.notes).toContain('Do not include any cardio exercise') + }) + + it('states the intensity as numbers the model can follow', () => { + for (const level of INTENSITIES) { + const intake = buildIntake({ muscles: [group('chest')], intensity: level.key }) + expect(intake.notes).toContain(`${level.exercises} exercises`) + expect(intake.notes).toContain(`${level.sets} sets`) + expect(intake.notes).toContain(`${level.reps} reps`) + expect(intake.sessionMin).toBe(level.sessionMin) + } + }) + + it('falls back to a whole-body session when nothing was picked, and to medium when unknown', () => { + const intake = buildIntake({ muscles: [], intensity: 'nonsense' }) + expect(intake.groups).toEqual([]) + expect(intake.notes).toContain('the whole body') + expect(intake.sessionMin).toBe(INTENSITIES[1].sessionMin) + }) + + it('names the muscles in the payload vocabulary, not the button labels', () => { + expect(muscleWords([group('biceps')])).toEqual(['biceps']) + expect(muscleWords([group('legs')])).toEqual(['upper legs', 'lower legs']) + // The sentence the model reads uses those words, so it can match them against `bp`/`tg`. + expect(buildIntake({ muscles: [group('glutes')] }).notes).toContain('glutes') + }) +}) + +describe('the routine that comes back', () => { + const bundle = over => ({ + name: 'Plan', summary: '', basedOn: '', customEx: [], + week: { 0: 'r1' }, + routines: [{ id: 'r1', name: 'Espalda y bíceps', emoji: '💪', ex: [{ id: '0027', sets: 3, reps: 10, mode: 'reps' }] }], + ...over + }) + + it('keeps the routine the answer scheduled, not just the first one', () => { + const two = bundle({ + week: { 3: 'r2' }, + routines: [ + { id: 'r1', name: 'Warm-up day', ex: [{ id: '0001', sets: 1, reps: 5, mode: 'reps' }] }, + { id: 'r2', name: 'The one asked for', ex: [{ id: '0027', sets: 3, reps: 10, mode: 'reps' }] } + ] + }) + expect(pickRoutine(two).name).toBe('The one asked for') + // …and the first is the fallback when the week points nowhere this validator allowed. + const orphan = bundle({ week: {} }) + expect(pickRoutine(orphan).id).toBe('r1') + expect(pickRoutine({ routines: [] })).toBe(null) + expect(pickRoutine(null)).toBe(null) + }) + + it('turns a cardio exercise into one bout, whatever set count the model sent', () => { + // 3220 is "astride jumps (male)" in the catalogue — a real cardio row. + const ex = normalizeExercise({ id: '3220', sets: 3, min: 8 }) + expect(ex.mode).toBe('cardio') + expect(ex.sets).toBe(1) + expect(ex.min).toBe(8) + // A cardio row with no minutes at all still gets the warm-up length. + expect(normalizeExercise({ id: '3220', sets: 1 }).min).toBe(CARDIAC_MIN) + }) + + it('reads a missing mode from the exercise, and leaves a stated one alone', () => { + expect(normalizeExercise({ id: '3220', sets: 1 }).mode).toBe('cardio') + expect(normalizeExercise({ id: '0027', sets: 3, reps: 10 }).mode).toBe('reps') + expect(normalizeExercise({ id: '3220', sets: 1, mode: 'time', sec: 60 }).mode).toBe('time') + // A timed hold keeps its set count: only cardio is forced to a single bout. + expect(normalizeExercise({ id: '0001', sets: 3, mode: 'time', sec: 45 }).sets).toBe(3) + }) + + it('states bodyweight on the exercises the catalogue says are bodyweight', () => { + // 0001 is "3/4 sit-up" — body weight equipment, and the routine editor reads the flag to + // decide whether a load is asked for. + expect(normalizeExercise({ id: '0001', sets: 3, reps: 10, mode: 'reps' }).bodyweight).toBe(true) + expect(normalizeExercise({ id: '0027', sets: 3, reps: 10, mode: 'reps' }).bodyweight).toBeUndefined() + // A cardio row is not asked for a load either way. + expect(normalizeExercise({ id: '3220', sets: 1 }).bodyweight).toBeUndefined() + // …and an explicit answer is never overwritten. + expect(normalizeExercise({ id: '0001', sets: 3, reps: 10, bodyweight: false }).bodyweight).toBe(false) + }) + + it('builds the routine to add, with a name and an emoji', () => { + const r = routineFrom(bundle(), { fallbackName: 'Fallback' }) + expect(r.name).toBe('Espalda y bíceps') + expect(r.emoji).toBe('💪') + expect(r.ex).toHaveLength(1) + // A nameless answer still lands somewhere the person can find it. + expect(routineFrom(bundle({ routines: [{ id: 'r1', name: ' ', ex: [] }] }), { fallbackName: 'Fallback' }).name).toBe('Fallback') + expect(routineFrom({ routines: [] }, { fallbackName: 'Fallback' })).toBe(null) + }) +})