The core of "build a routine with AI": muscles, cardio, intensity
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
The screen that will drive this needs three things underneath it, and all three
are here, tested, with no UI yet.
1. `librarySlice` can be narrowed to the muscles someone picked. A selector is
`{ bp }` or `{ tg }` — the target muscle matters because "biceps" and "triceps"
are both `upper arms`, and asking for one must not hand back the other — and an
exercise is kept when it matches any of them, so "back and biceps" is one list.
`catalogueOnly` drops the person's own exercises, which are the only rows in
the app with no animation; the builder promises every pick can be watched.
Both answers ride in the existing `intake` object rather than a second channel:
the intake is already how "which muscles" reaches the payload, and it travels
the whole way (route → job → build, and local → build) untouched. `cleanGroups`
sanitises it, since it is the one intake field that reaches a filter rather than
the model's reading.
2. `lib/ai-routine.js` — the three questions and what to do with the answer: the
intake the model is asked with, and the routine it hands back, normalised for
this app. Cardio lands in the library and not only in the sentence (a model told
to start with cardio but handed no cardio exercise can only improvise, which is
what it did the first time this was tried), a cardio row becomes one bout
whatever set count came back, and a missing mode is read from the exercise the
same way `modeOf` reads it everywhere else.
3. A validator fix found on the way: the cardio branch set `min` and `speed` but
never `clean.mode = 'cardio'`, unlike the time and reps branches. The app
recovered it from the catalogue, so nothing was visibly broken — but the bundle
did not describe its own prescription, and a model that omitted `mode` (which is
what a model prescribing "8 minutes of cardio" usually does) got "3 × 10 reps"
with a stray `min` nothing reads. Now the mode is stated, and inferred from the
catalogue when it is missing. `time` is deliberately not inferred: nothing in the
catalogue says an exercise is held for seconds.
Verified against the real router behind gym.dploy.lol with the real pipeline: a
back+biceps request produced a 6-exercise routine from an 80/80/22 library slice.
This commit is contained in:
1 parent
ea1af681c2
commit
327aa5211b
7 files changed
+409
-7
No files matched your search
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user