diff --git a/mcp/src/tools.js b/mcp/src/tools.js index edf77c5..07db2f5 100644 --- a/mcp/src/tools.js +++ b/mcp/src/tools.js @@ -9,16 +9,27 @@ import { import { modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId } from '../../frontend/src/lib/history.js' -import { EXIDX, exOr } from '../../frontend/src/lib/exercises.js' +import { exOr } from '../../frontend/src/lib/exercises.js' +import { isWarmupRow } from '../../frontend/src/lib/workout-model.js' import { estimate1RM, best1RM, e1rmSeries, DEFAULT_FORMULA, REP_CAP } from '../../frontend/src/lib/onerm.js' import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js' +import { policyFor } from '../../frontend/src/lib/progression.js' /* ---------- helpers ---------- */ +// A custom exercise lives in S.customEx and is merged into EXIDX by registerCustom() at +// store load (useStore.js:54). The MCP server deliberately never calls it: http.js serves +// several profiles from one process behind withRemoteState, so mutating the module-global +// index would leak one profile's customs into another's reads. +const customOf = (id, S) => (S.customEx || []).find(ex => ex.id === id) +// exOr's miss is a placeholder object, not null — callers that only need a name are fine +// with it, callers feeding muscle resolution are NOT. Use customOf directly there. +const exerciseOf = (id, S) => customOf(id, S) || exOr(id) + function entryView(e, S) { - const ex = exOr(e.id) + const ex = exerciseOf(e.id, S) // Spread id into the cfg the way every call site in the app does (Workout.jsx, Stats.jsx, // progression.js) — the sheet saves a cardio target as {sets, min, speed} with no id and no // mode, so modeOf needs the id to fall through to isCardio(id). @@ -43,15 +54,17 @@ function entryView(e, S) { } // Best estimate per exercise, mirroring the UI's PR table: every eligible set across history, biggest wins. +// Warm-ups are skipped for the same reason bestSetOf() skips them (onerm.js): a heavy ramp row is not a +// record. Without this the coach's PR and the athlete's PR silently disagree for the same exercise. function prTable(S, formula) { const byId = new Map() for (const w of (S.workouts || [])) { for (const e of (w.entries || [])) { + const ex = exerciseOf(e.id, S) for (const s of (e.sets || [])) { - if (!s.done) continue + if (!s.done || isWarmupRow(s)) continue const est = estimate1RM(s.w, s.r, formula) if (est == null) continue - const ex = exOr(e.id) const prev = byId.get(e.id) if (!prev || est > prev.est) { // exId as well as exName: the consumer needs an id, not a name — exOr() treats any @@ -82,7 +95,7 @@ export const listRoutines = { emoji: r.emoji || null, exercise_count: (r.ex || []).length, superset_groups: [...new Set((r.ex || []).map(e => e.sg).filter(Boolean))].length || 0, - policy: r.policy || 'off' + policy: policyFor(null, r, 'reps') })) } } @@ -102,11 +115,11 @@ export const getRoutine = { id: r.id, name: r.name, emoji: r.emoji || null, - policy: r.policy || 'off', - policy_name: policyName(r.policy || 'off'), + policy: policyFor(null, r, 'reps'), + policy_name: policyName(policyFor(null, r, 'reps')), unit: S.unit || 'kg', exercises: (r.ex || []).map((cfg, i) => { - const ex = exOr(cfg.id) + const ex = exerciseOf(cfg.id, S) const mode = modeOf(cfg) return { position: i + 1, @@ -117,12 +130,14 @@ export const getRoutine = { sets: cfg.sets || 1, reps: mode === 'reps' ? (cfg.reps || 0) : undefined, reps_min: mode === 'reps' && cfg.repsMin != null ? cfg.repsMin : undefined, + reps_max: mode === 'reps' && cfg.repsMax != null ? cfg.repsMax : undefined, sec: mode === 'time' ? (cfg.sec || 0) : undefined, min: mode === 'cardio' ? (cfg.min || 0) : undefined, speed: mode === 'cardio' ? (cfg.speed || 0) : undefined, weight: cfg.weight != null ? cfg.weight : undefined, increment: cfg.inc != null ? cfg.inc : undefined, - policy_override: cfg.policy || null, + policy: policyFor(cfg, r, mode), + policy_override: cfg.prog || null, superset_group: cfg.sg || null, summary: exLine(cfg, S.unit || 'kg') } @@ -266,7 +281,10 @@ export const getWorkout = { sets_done: setsDone(w), sets_planned: plannedSets(w), duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null, - prs: (w.prs || []).map(id => EXIDX[id]?.n || id), + prs: (w.prs || []).map(id => { + const ex = exerciseOf(id, S) + return ex.missing ? id : ex.n + }), entries: (w.entries || []).map(e => entryView(e, S)) } } @@ -317,7 +335,7 @@ export const estimate1rm = { if (!S) return noState() const f = formula || DEFAULT_FORMULA if (exercise_id) { - const ex = exOr(exercise_id) + const ex = exerciseOf(exercise_id, S) const best = best1RM(S, exercise_id, f) const series = e1rmSeries(S, exercise_id, f) // A null best has two very different causes: never trained, or trained only above the @@ -361,7 +379,19 @@ export const muscleBalance = { : period === 'month' ? now - 30 * 86400000 : Number.NEGATIVE_INFINITY const workouts = (S.workouts || []).filter(w => (w.start || new Date(w.d + 'T12:00:00').getTime()) >= cutoff) - const load = loadOfWorkouts(workouts) + // loadOf() resolves each entry through EXIDX, which holds the catalogue only, so a + // custom exercise's sets score zero here. Attaching the custom itself lets loadOf's own + // `historical` branch resolve it. Only a *found* custom: exOr's miss placeholder carries + // no muscle metadata and no muscleSnapshot, so attaching that would displace the entry + // and silently zero a *deleted* custom, whose snapshot loadOf reads off the entry + // (muscles.js:245 → metadataOf, snapshot written at sheets.jsx:421-426). + const load = loadOfWorkouts(workouts.map(w => ({ + ...w, + entries: (w.entries || []).map(e => { + const c = e.exercise ? null : customOf(e.id, S) + return c ? { ...e, exercise: c } : e + }) + }))) const { worked, missed } = rankOf(load) const levels = levelsOf(load) return { diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js index 17f2c70..b5c3cf0 100644 --- a/mcp/test/tools.test.js +++ b/mcp/test/tools.test.js @@ -7,6 +7,7 @@ import { buildDemoState } from '../../frontend/src/lib/demoSeed.js' import { EXDB } from '../../frontend/src/lib/exercises.js' import { _seedStateForTests } from '../src/state.js' import { TOOLS } from '../src/tools.js' +import { bestSetOf } from '../../frontend/src/lib/onerm.js' // Re-stated here so the assertions stand alone without reaching into lib internals to learn // the demo state's exact values. @@ -98,6 +99,58 @@ describe('get_routine', () => { }) }) + test('resolves custom exercises from the current profile state', () => { + const custom = { id: 'cx-sled-drag', n: 'Sled drag', bp: 'upper legs' } + S.customEx = [custom] + S.routines[0].ex.push({ id: custom.id, sets: 3, reps: 20 }) + + const r = call('get_routine', { routine_id: S.routines[0].id }) + expect(r.exercises.at(-1)).toMatchObject({ + id: custom.id, + name: 'Sled drag', + body_part: 'upper legs' + }) + }) + + test('returns both bounds of a reps range', () => { + const cfg = S.routines[0].ex[0] + Object.assign(cfg, { mode: 'reps', reps: 8, repsMin: 8, repsMax: 12 }) + + const r = call('get_routine', { routine_id: S.routines[0].id }) + expect(r.exercises[0]).toMatchObject({ reps: 8, reps_min: 8, reps_max: 12 }) + }) + + test('projects routine and exercise progression rules from prog', () => { + S.routines[0].prog = 'greyskull' + S.routines[0].ex[0].prog = 'double' + + const r = call('get_routine', { routine_id: S.routines[0].id }) + expect(r).toMatchObject({ policy: 'greyskull', policy_name: 'Greyskull LP' }) + expect(r.exercises[0].policy_override).toBe('double') + }) + + test('a routine with no prog reports the policy the app actually runs, not off', () => { + delete S.routines[0].prog + delete S.routines[0].ex[0].prog + + // policyFor defaults reps to linear (progression.js:73) and RoutineEdit.jsx:59 shows + // that same default, so reporting 'off' here would misdescribe every untouched routine. + const r = call('get_routine', { routine_id: S.routines[0].id }) + expect(r.policy).toBe('linear') + expect(r.exercises[0].policy).toBe('linear') + expect(r.exercises[0].policy_override).toBeNull() + }) + + test('a policy the mode cannot run is clamped, not echoed back raw', () => { + S.routines[0].prog = 'greyskull' // reps-only policy + S.customEx = [{ id: 'cx-plank', n: 'Plank', bp: 'waist' }] + S.routines[0].ex.push({ id: 'cx-plank', mode: 'time', sets: 3, sec: 60 }) + + const view = call('get_routine', { routine_id: S.routines[0].id }).exercises.at(-1) + expect(view.mode).toBe('time') + expect(view.policy).toBe('off') // POLICIES_FOR.time excludes greyskull + }) + test('throws ENOENT on a bogus routine id', () => { expect(() => call('get_routine', { routine_id: 'bogus' })).toThrow() }) @@ -423,6 +476,35 @@ describe('estimate_1rm', () => { expect(table).toEqual([]) }) + test('a heavy warm-up is never a PR — the table matches the app, which excludes warm-ups', () => { + // The app scans with bestSetOf(), which skips warm-ups (onerm.js). prTable used to gate on + // s.done alone, so a ramp row heavier than the work set became a record the coach reported + // and the athlete never saw — for the same exercise, from the same state. + S.workouts = [{ + id: 'w-ramp', d: '2026-07-26', name: 'Legs', start: 1000, end: 1000 + 30 * 60000, + vol: 0, prs: [], + entries: [{ + id: LEG_PRESS_ID, target: { sets: 2, reps: 5, mode: 'reps' }, + sets: [ + { w: 200, r: 5, done: true, phase: 'warmup' }, // mistyped/greedy ramp row + { w: 100, r: 5, done: true } // the only real work set + ] + }] + }] + _seedStateForTests(S) + + const app = bestSetOf(S.workouts[0].entries[0]) + expect(app.w).toBe(100) // the app ignores the 200 kg warm-up + + const best = call('estimate_1rm', { exercise_id: LEG_PRESS_ID }).best + expect(best.w).toBe(100) + expect(best.est).toBeCloseTo(app.est, 1) + + const row = call('estimate_1rm', {}).pr_table.find(p => p.exId === LEG_PRESS_ID) + expect(row.w).toBe(100) + expect(row.est).toBeCloseTo(app.est, 1) + }) + test('a null estimate says which kind of null it is', () => { // "Never trained" and "trained, but always above the rep cap" are opposite facts that both // arrive as best: null. Undistinguished, the second one reads as the first and an assistant @@ -488,6 +570,45 @@ describe('muscle_balance', () => { expect([...neg].every(s => all.has(s))).toBe(true) }) + test('counts custom exercises — they resolve from state, not from the catalogue', () => { + const total = r => r.worked.reduce((n, w) => n + w.effective_sets, 0) + const before = call('muscle_balance', { period: 'all' }) + + // A custom exercise is absent from EXIDX in this process: the app merges S.customEx in + // via registerCustom() at store load, the MCP server does not. Its sets used to vanish + // from the muscle map entirely. + S.customEx = [{ id: 'cx-hollow-hold', n: 'Hollow hold', bp: 'waist', tg: 'abs' }] + S.workouts[0].entries.push({ + id: 'cx-hollow-hold', + sets: [{ sec: 45, done: true }, { sec: 45, done: true }] + }) + + const after = call('muscle_balance', { period: 'all' }) + expect(total(after)).toBeGreaterThan(total(before)) + expect(after.worked.find(w => w.slug === 'abs')?.effective_sets) + .toBeGreaterThan(before.worked.find(w => w.slug === 'abs')?.effective_sets || 0) + }) + + test('still counts a DELETED custom, from the snapshot left on the entry', () => { + const total = r => r.worked.reduce((n, w) => n + w.effective_sets, 0) + const before = total(call('muscle_balance', { period: 'all' })) + + // Exactly what sheets.jsx:421-426 leaves behind when a custom exercise is deleted: the + // customEx row is gone, the history entry keeps `n` + `muscleSnapshot`. loadOf reads that + // snapshot off the entry — so nothing may be attached over the top of it. + S.customEx = [] + S.workouts[0].entries.push({ + id: 'cx-deleted-hold', + n: 'Hollow hold', + muscleSnapshot: { n: 'Hollow hold', bp: 'waist', muscleWeights: { abs: 1 } }, + sets: [{ sec: 45, done: true }, { sec: 45, done: true }] + }) + + const after = call('muscle_balance', { period: 'all' }) + expect(total(after)).toBeGreaterThan(before) + expect(after.worked.find(w => w.slug === 'abs')?.effective_sets).toBeGreaterThan(0) + }) + test('period windows are inclusive: week ≤ month ≤ all', () => { const all = call('muscle_balance', { period: 'all' }).workouts_in_period const month = call('muscle_balance', { period: 'month' }).workouts_in_period