Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
fix(coach): plans stay within your equipment profile, and the admin card says why an answer was rejected
Duarte Santos55bd7728a7f4
diff --git a/api/coach/core/library.js b/api/coach/core/library.jsindex 00947f1aa..3f6ffc653 100644--- a/api/coach/core/library.js+++ b/api/coach/core/library.js@@ -13,6 +13,18 @@ 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;+/* Whether the person's equipment covers a catalogue exercise. Body weight is never gated, the+ same rule the app's own equipment profiles follow (frontend lib/equipment.js), and an id the+ catalogue does not hold (one of their own exercises) is theirs to judge, not ours. No+ equipment stated means the whole catalogue. */+const ALWAYS_AVAILABLE = 'body weight';+export function equipmentAllows(equipment, id) {+ const wanted = (equipment || []).map(x => String(x).toLowerCase());+ if (!wanted.length) return true;+ const eq = (LIB_BY_ID.get(id)?.eq || '').toLowerCase();+ return !eq || eq === ALWAYS_AVAILABLE || wanted.includes(eq);+}+/* ---------- 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 moneyagainst a cloud API and does not fit a small local model's context at all; and a model does@@ -68,7 +80,7 @@ export function librarySlice(S, equipment, { keep = [], max = MAX_LIBRARY } = {}// 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 filtered = wanted.length ? LIBRARY.filter(e => equipmentAllows(wanted, e.id)) : LIBRARY;const equipped = filtered.length ? filtered : LIBRARY;// Same reasoning as the equipment fallback: a filter that removed everything is not a filter// worth honouring. Someone whose only kit reaches nothing but stretches gets the stretches.diff --git a/api/coach/core/payload.js b/api/coach/core/payload.jsindex a78dff9a3..f03616f0e 100644--- a/api/coach/core/payload.js+++ b/api/coach/core/payload.js@@ -89,6 +89,12 @@ const num = v => ((typeof v === 'number' && Number.isFinite(v)) || (typeof v ===// A date is the ISO day every screen writes; anything else is not a date.const day = v => (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}/.test(v) ? v.slice(0, 10) : null);const list = v => (Array.isArray(v) ? v : []);+// The equipment of the profile the app is filtering by, or nothing when filtering is off.+function activeEquipment(S) {+ if (!S.equipFilterOn) return [];+ const prof = list(S.equipProfiles).find(x => x && x.id === S.activeEquipId);+ return list(prof?.equipment);+}function cleanProfile(profile) {const days = Array.isArray(profile.preferredDays) ? profile.preferredDays : [];const equipment = Array.isArray(profile.equipment) ? profile.equipment : [];@@ -486,6 +492,12 @@ export function build(S, opts = {}) {coachProfile: profile && typeof profile === 'object' ? cleanProfile(profile) : null,plan: cleanPlan(S)};+ // Someone who set up a home gym under Settings → Equipment and left the Coach's own equipment+ // question empty was handed the whole catalogue, leverage machines and all. The profile they+ // are filtering the app with is the better answer than "everything".+ if (p.coachProfile && !p.coachProfile.equipment.length) {+ p.coachProfile.equipment = cleanProfile({ equipment: activeEquipment(S) }).equipment;+ }// What the user already turned down, so the Coach does not re-propose it without new// evidence (FR-26). Summaries only — the log's full before/after stays on the device.diff --git a/api/coach/core/pipeline.js b/api/coach/core/pipeline.jsindex 98be4ab95..ab2914353 100644--- a/api/coach/core/pipeline.js+++ b/api/coach/core/pipeline.js@@ -59,12 +59,14 @@ export async function attemptOnce({ adapter, cfg, kind, payload, model, timeoutM// The user's own exercises are in the library slice the model was given (flagged `custom`),// so they are a legitimate thing for it to name back — the validator has to agree.const customIds = (payload.library || []).filter(e => e && e.custom).map(e => e.id);+ const equipment = payload.coachProfile?.equipment || [];+ const offered = new Set((payload.library || []).map(e => e && e.id));const checked = kind === 'review'- ? validateReview(parsed.value, payload.plan, { customIds })+ ? validateReview(parsed.value, payload.plan, { customIds, equipment, offered }): kind === 'debrief'? validateDebrief(parsed.value): validatePlan(parsed.value, {- customIds,+ customIds, equipment, offered,workingWeights: payload.history?.workingWeights,daysPerWeek: payload.coachProfile?.daysPerWeek});diff --git a/api/coach/core/validate.js b/api/coach/core/validate.jsindex 2d43dceca..685e18f29 100644--- a/api/coach/core/validate.js+++ b/api/coach/core/validate.js@@ -14,7 +14,15 @@* 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, equipmentAllows } from './library.js';++// A catalogue exercise the person's equipment does not reach, and that was not in the library+// slice they were offered (which already pins what they train). The prompt says "their+// equipment"; a model that names a leverage machine anyway is told so on the repair round+// instead of the plan arriving with a machine they do not own.+const offEquipment = (ctx, id) => !!ctx.equipment?.length && libraryHas(id)+ && !(ctx.offered && ctx.offered.has(id)) && !equipmentAllows(ctx.equipment, id);+const OFF_EQUIPMENT = (where, id) => `${where} "${id}" needs equipment the user does not have — use an exercise from the library provided in the payload`;import { glyphStr } from './glyphs.js';// The closed list (FR-23 / C3). Adding a member here is a deliberate act with an apply@@ -109,6 +117,7 @@ export function validatePlan(data, ctx = {}) {errors.push(`${where}.id "${e.id}" is not in the exercise library and is not one of your own customEx entries — use an id from the library provided in the payload`);return;}+ if (offEquipment(ctx, e.id)) { errors.push(OFF_EQUIPMENT(`${where}.id`, e.id)); return; }const clean = { id: e.id, sets: isInt(e.sets, 1, 10) ? e.sets : 3 };const mode = MODES.includes(e.mode) ? e.mode : 'reps';const perSide = !!e.side;@@ -318,6 +327,7 @@ export function validateReview(data, plan, ctx = {}) {}const a = c.after || {};if (!isStr(a.id) || !knownEx(a.id)) { errors.push(`${where}.after.id must be an exercise id from the library`); return; }+ if (offEquipment(ctx, a.id)) { errors.push(OFF_EQUIPMENT(`${where}.after.id`, a.id)); return; }const perSide = !!a.side;if (perSide && isInt(a.reps, 1, 100) && a.reps % 2) { errors.push(ODD_PER_SIDE(`${where}.after.reps`)); return; }if (isInt(a.repsMax, 1, 100) && isInt(a.repsMin, 1, 100) && a.repsMax < a.repsMin) { errors.push(INVERTED_RANGE(`${where}.after`)); return; }@@ -345,6 +355,7 @@ export function validateReview(data, plan, ctx = {}) {}const a = c.after || {};if (!isStr(a.id) || !knownEx(a.id)) { errors.push(`${where}.after.id must be an exercise id from the library`); return; }+ if (offEquipment(ctx, a.id)) { errors.push(OFF_EQUIPMENT(`${where}.after.id`, a.id)); return; }if (a.id === target.exId) { errors.push(`${where} swaps an exercise for itself`); return; }out.after = {id: a.id, name: libraryName(a.id),@@ -419,6 +430,8 @@ export function validateReview(data, plan, ctx = {}) {const listed = Array.isArray(a.ex) ? a.ex : [];const bad = listed.find(e => !e || !isStr(e.id) || !knownEx(e.id));if (bad) { errors.push(`${where}.after.ex "${bad.id}" is not in the exercise library — use an id from the library provided in the payload`); return; }+ const offEq = listed.find(e => offEquipment(ctx, e.id));+ if (offEq) { errors.push(OFF_EQUIPMENT(`${where}.after.ex`, offEq.id)); return; }const ex = listed.slice(0, MAX_EX_PER_ROUTINE);if (!ex.length) { errors.push(`${where}.after.ex must list at least one exercise from the library`); return; }const odd = ex.find(e => e.side && isInt(e.reps, 1, 100) && e.reps % 2);diff --git a/api/coach/jobs.js b/api/coach/jobs.jsindex 16091e524..512bec66d 100644--- a/api/coach/jobs.js+++ b/api/coach/jobs.js@@ -266,6 +266,15 @@ function pump() {}}+/* Why an answer was rejected, for the admin card. "Couldn't use" with no reason left people+ guessing whether the model, the key or the app was at fault. The validator's own lines say+ which rule broke; quoted values are cut out, because they can carry a routine name or other+ words from the person's plan, and the instance log carries outcomes, not content (FR-12/42). */+export function whyUnusable(errors) {+ if (!Array.isArray(errors) || !errors.length) return null;+ return errors.slice(0, 3).map(e => String(e).replace(/"[^"]*"/g, '"…"')).join('; ').slice(0, 300);+}+function finish(job, result) {cfgStore.logJob({at: new Date().toISOString(), uid: job.uid, kind: job.kind, trigger: job.trigger,@@ -363,7 +372,7 @@ async function execute(job) {if (!attempt.ok) {// Cancelled by a forget, not failed by the provider: the log must not blame the job budget.const errorClass = ctl.signal.aborted ? 'forgotten' : attempt.errorClass;- return finish(job, { outcome: 'failed', errorClass, detail: attempt.detail });+ return finish(job, { outcome: 'failed', errorClass, detail: attempt.detail || whyUnusable(attempt.errors) });}if (attempt.nochange) {return finish(job, { outcome: 'nochange', pending: null, detail: null, reading: attempt.reading });diff --git a/api/test/coach-limits.test.js b/api/test/coach-limits.test.jsindex 822c833bc..660eac6f5 100644--- a/api/test/coach-limits.test.js+++ b/api/test/coach-limits.test.js@@ -225,3 +225,11 @@ test('a proposal nobody has answered is not replaced by the next scheduled revieawait settle(uid);assert.equal(jobs.readUser(uid).history.filter(h => h.outcome === 'ready').length, 2);});++test('a rejected answer tells the admin which rule broke, without quoting the plan', async () => {+ const { whyUnusable } = await import('../coach/jobs.js');+ assert.equal(whyUnusable([]), null);+ const why = whyUnusable(['routines[0].ex[1].id "0009" needs equipment the user does not have', 'routines[1].name is required']);+ assert.ok(why.includes('needs equipment') && why.includes('routines[1].name is required'));+ assert.ok(!why.includes('0009'), 'quoted values are cut out');+});diff --git a/api/test/payload.test.js b/api/test/payload.test.jsindex e71ac41fc..2fc0fb0fd 100644--- a/api/test/payload.test.js+++ b/api/test/payload.test.js@@ -112,7 +112,9 @@ test('the library is filtered to the equipment someone actually has', () => {const eqOf = id => (payload.LIBRARY.find(e => e.id === id) || {}).eq;const dumbbell = payload.librarySlice({}, ['dumbbell']);assert.ok(dumbbell.length > 0);- assert.ok(dumbbell.every(e => eqOf(e.id) === 'dumbbell'), 'nothing outside the filter');+ // Body weight is never gated, the same rule as the app's own equipment profiles.+ assert.ok(dumbbell.every(e => ['dumbbell', 'body weight'].includes(eqOf(e.id))), 'nothing outside the filter');+ assert.ok(dumbbell.some(e => eqOf(e.id) === 'body weight'), 'push-ups and pull-ups stay on the table');assert.ok(dumbbell.every(e => e.eq === undefined && e.id && e.n && e.bp), 'entries are slim');assert.ok(payload.librarySlice({}, ['dumbbell', 'barbell']).some(e => eqOf(e.id) === 'barbell'));// Custom exercises always travel: they exist nowhere else and the model cannot guess them.@@ -393,3 +395,23 @@ test('a session note reaches the model whole, bounded only at the app\'s own capassert.equal(full.note, whole, 'the session note arrives whole (was cut at 300)');assert.equal(edited.note.length, payload.NOTE_MAX, 'a note no app could have written is bounded at the cap');});++test('the app\'s active equipment profile stands in when the Coach was told no equipment', () => {+ const eqOf = id => (payload.LIBRARY.find(e => e.id === id) || {}).eq;+ const S = sampleState();+ S.coach = { ...(S.coach || {}), profile: { goal: 'muscle', daysPerWeek: 3, equipment: [] } };+ S.equipProfiles = [{ id: 'home', name: 'Home gym', equipment: ['dumbbell', 'cable'] }];+ S.activeEquipId = 'home';+ S.equipFilterOn = true;+ const p = payload.build(S, { handle: handleFor('u1'), kind: 'create' });+ assert.deepEqual(p.coachProfile.equipment, ['dumbbell', 'cable']);+ const trained = new Set((S.workouts || []).flatMap(w => (w.entries || []).map(en => en.id)));+ assert.ok(!p.library.some(e => eqOf(e.id) === 'leverage machine' && !trained.has(e.id)), 'no leverage machine offered');+ // Filtering switched off in the app: the Coach goes back to the whole catalogue.+ S.equipFilterOn = false;+ assert.deepEqual(payload.build(S, { handle: handleFor('u1'), kind: 'create' }).coachProfile.equipment, []);+ // Equipment answered in the Coach's own questions wins over the app's profile.+ S.equipFilterOn = true;+ S.coach.profile.equipment = ['barbell'];+ assert.deepEqual(payload.build(S, { handle: handleFor('u1'), kind: 'create' }).coachProfile.equipment, ['barbell']);+});diff --git a/api/test/validate.test.js b/api/test/validate.test.jsindex dfbeff449..c3266dcca 100644--- a/api/test/validate.test.js+++ b/api/test/validate.test.js@@ -46,6 +46,22 @@ test('a plan referencing an unknown exercise is rejected, not quietly trimmed',assert.ok(r.errors.some(e => e.includes('not-a-real-id')));});+test('a plan naming a machine the person does not have goes back for repair', () => {+ // 0009 is a leverage machine, 1274 a dumbbell lift, 0001 body weight.+ const ctx = { equipment: ['dumbbell'], offered: new Set(['1274', '0001']) };+ const r = validatePlan({ routines: [{ name: 'A', ex: [{ id: '1274', sets: 3, reps: 10 }, { id: '0009', sets: 3, reps: 10 }] }] }, ctx);+ assert.equal(r.ok, false);+ assert.ok(r.errors.some(e => e.includes('0009') && e.includes('equipment')));+ // Body weight is never gated, and nothing is gated when no equipment was stated.+ assert.equal(validatePlan({ routines: [{ name: 'A', ex: [{ id: '0001', sets: 3, reps: 10 }] }] }, { equipment: ['dumbbell'], offered: new Set() }).ok, true);+ assert.equal(validatePlan({ routines: [{ name: 'A', ex: [{ id: '0009', sets: 3, reps: 10 }] }] }, { equipment: [] }).ok, true);+ // A machine they already train was in the slice they were offered, so it stays allowed.+ assert.equal(validatePlan({ routines: [{ name: 'A', ex: [{ id: '0009', sets: 3, reps: 10 }] }] }, { equipment: ['dumbbell'], offered: new Set(['0009']) }).ok, true);+ // The same rule holds for a swap in a review.+ const sw = validateReview({ changes: [change({ type: 'swap-exercise', after: { id: '0009' } })] }, PLAN, { equipment: ['dumbbell'], offered: new Set() });+ assert.equal(sw.ok, false);+});+test('a plan may reference a custom exercise it defines in the same answer', () => {const r = validatePlan({routines: [{ name: 'A', ex: [{ id: 'cx1', sets: 3, reps: 10 }] }],diff --git a/frontend/src/views/CoachIntake.jsx b/frontend/src/views/CoachIntake.jsxindex 6f665cc11..c07c2aeaf 100644--- a/frontend/src/views/CoachIntake.jsx+++ b/frontend/src/views/CoachIntake.jsx@@ -19,6 +19,7 @@ import { emptyCoach, coachAvailable, hasConsent, CONSENT_VERSION, CATEGORY_TEXT,import { requestPlan, disclosure, JOB_ERRORS } from '../lib/coach-api.js'import { DEMO } from '../lib/demo.js'import { MOBILE } from '../lib/mobile.js'+import { activeProfile } from '../lib/equipment.js'import Icon from '../components/Icon.jsx'import { Button, TextArea } from '../components/ui.jsx'import '../coach.css'@@ -72,7 +73,8 @@ export default function CoachIntake() {const [busy, setBusy] = useState(false)const [p, setP] = useState(() => ({goal: null, experience: null, daysPerWeek: 3, preferredDays: [1, 3, 5],- sessionMin: 60, equipment: [], limitations: '', likes: '', dislikes: '', notes: '',+ // A home gym already set up under Settings → Equipment is the best first guess here.+ sessionMin: 60, equipment: (activeProfile(S)?.equipment || []).filter(e => EQUIPMENT.includes(e)), limitations: '', likes: '', dislikes: '', notes: '',...(S.coach?.profile || {})}))const set = patch => setP(v => ({ ...v, ...patch }))