diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js new file mode 100644 index 0000000..dd950b7 --- /dev/null +++ b/frontend/src/lib/progression.js @@ -0,0 +1,242 @@ +// Automatic progression (issue #17). +// +// Everything here is a pure function of the workout history. Nothing writes back into a +// finished workout: the log is what happened, and the next prescription is *derived* from +// it every time it is needed. That means changing a policy — or fixing a mistyped set — +// immediately produces the right next target, with no stored counters to drift out of sync. +// +// It replaces a single hard-coded rule ("all reps done → add 2.5") with a small set of named +// policies. The rule that applies is always visible in the app, together with the reason it +// picked this weight, because a suggestion you can't audit is one you stop trusting. +// +// Reading a session honestly is the whole game: +// · a set checked off with at least its target reps → hit +// · a set checked off with fewer reps → miss (you logged what you got) +// · a set never checked off → miss (it was not performed) +// · fewer sets than prescribed → miss +// So a session that fell apart can never advance the load as though it had succeeded. + +import { modeOf } from './history.js' +import { EXIDX } from './exercises.js' + +export const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time'] + +// Which policies can sensibly drive which logging mode. +export const POLICIES_FOR = { + reps: ['off', 'linear', 'greyskull', 'double'], + time: ['off', 'time'], + cardio: ['off'] +} + +export const POLICY_NAME = { + off: 'No automatic progression', + linear: 'Linear progression', + greyskull: 'Greyskull LP', + double: 'Double progression', + time: 'Add time' +} +export const POLICY_DESC = { + off: 'Targets stay where you set them.', + linear: 'Hit every rep in every set and the weight goes up. Repeated misses trigger a deload.', + greyskull: 'Two straight sets plus a final set taken to failure. Beat the target on that set and the weight goes up — double if you double the reps. One failure resets 10 %.', + double: 'Work up through a rep range at the same weight. Reach the top of the range in every set and the weight goes up, reps back to the bottom.', + time: 'Hold every set for the full duration and the target goes up.' +} + +// Sessions of repeated misses before a deload. Greyskull resets on the first failure by +// design; the general linear policy gives you two more cracks at it first. +export const DELOAD_AFTER = { linear: 3, greyskull: 1, double: 3, time: 3 } +const DELOAD_FACTOR = 0.9 + +// Body parts where a 5 kg jump is normal rather than brutal. +const HEAVY_BP = ['upper legs', 'lower legs', 'back', 'hips', 'glutes'] + +// Default load step. Lower-body lifts take the bigger jump — that is the "lift-specific +// increment" a linear program lives on; an exercise can override it with cfg.inc. +export function defaultIncrement(exId, unit) { + const ex = EXIDX[exId] + const heavy = ex && HEAVY_BP.includes(ex.bp) + if (unit === 'lb') return heavy ? 10 : 5 + return heavy ? 5 : 2.5 +} +export const DEFAULT_SEC_INCREMENT = 5 + +// The policy in force for one exercise: its own override, else the routine's default, else +// the mode's default. Reps keeps behaving the way the app always did (all reps → add a step). +export function policyFor(cfg, routine, mode) { + const m = mode || modeOf(cfg || {}) + const allowed = POLICIES_FOR[m] || ['off'] + const pick = (cfg && cfg.prog) || (routine && routine.prog) || (m === 'reps' ? 'linear' : 'off') + return allowed.includes(pick) ? pick : 'off' +} + +const round1 = v => Math.round(v * 10) / 10 +// Snap to a loadable multiple of the step. +function snap(v, step) { + if (!(step > 0)) return round1(v) + return round1(Math.round(v / step) * step) +} +// Back off by DELOAD_FACTOR, landing on something you can actually load. Rounding to the +// nearest step keeps the cut close to the intended 10 %, but on small weights the nearest +// step can be the weight you started from — so a deload that did not actually reduce +// anything takes one step down instead. Never goes below a single step. +function deloadTo(cur, step) { + let next = snap(cur * DELOAD_FACTOR, step) + if (next >= cur) next = snap(cur - step, step) + return Math.max(step, next) +} + +/** + * Reduce one finished workout entry to what a policy needs to judge it. + * + * Workouts only started recording their prescription in v1.2.2, so most existing history has + * no `target` at all. Judging those against nothing would score every past session as a miss + * — and then greet a long-standing user with "missed reps 11 sessions running, deload". So an + * entry without its own target is judged against `fallback`, the exercise's current plan, + * which is exactly what the app's old weight hint compared against. + */ +export function readSession(entry, fallback) { + const target = (entry && entry.target) || fallback || {} + const mode = modeOf({ ...target, id: entry && entry.id }) + const sets = (entry && entry.sets) || [] + const planned = target.sets || sets.length + const enough = sets.length >= planned + + if (mode === 'time') { + const goal = target.sec || 0 + const held = sets.map(s => (s.done ? (s.sec || 0) : 0)) + return { + mode, goal, held, + weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)), + best: Math.max(0, ...held), + ok: goal > 0 && enough && held.length > 0 && held.every(h => h >= goal) + } + } + const goal = target.reps || 0 + const reps = sets.map(s => (s.done ? (s.r || 0) : 0)) + return { + mode, goal, reps, + weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)), + low: reps.length ? Math.min(...reps) : 0, + amrap: reps.length ? reps[reps.length - 1] : 0, // Greyskull's final set + ok: goal > 0 && enough && reps.length > 0 && reps.every(r => r >= goal) + } +} + +/** Every past session for one exercise, oldest first. `fallback` — see readSession. */ +export function sessionsFor(S, exId, fallback) { + const out = [] + ;(S.workouts || []).forEach(w => { + const entry = w.entries.find(e => e.id === exId) + if (entry && entry.sets.some(s => s.done)) out.push({ d: w.d, ...readSession(entry, fallback) }) + }) + return out +} + +// How many sessions in a row ended in a miss, counting back from the most recent. +export function stallCount(sessions) { + let n = 0 + for (let i = sessions.length - 1; i >= 0; i--) { + if (sessions[i].ok) break + n++ + } + return n +} + +/** + * The next prescription for one exercise. + * + * Returns `{ weight, reps, sec, why, kind }` — `kind` being one of + * first | up | hold | deload | off, and `why` a translatable template + args so the app can + * always answer "why this number?". A field the policy has no opinion on comes back + * undefined and the caller keeps whatever the plan said. + */ +export function nextPrescription(S, cfg, routine) { + const mode = modeOf(cfg) + const policy = policyFor(cfg, routine, mode) + const unit = S.unit || 'kg' + const inc = cfg.inc > 0 ? cfg.inc : (mode === 'time' ? DEFAULT_SEC_INCREMENT : defaultIncrement(cfg.id, unit)) + if (policy === 'off') return { policy, kind: 'off' } + + const sessions = sessionsFor(S, cfg.id, cfg).filter(s => s.mode === mode) + const last = sessions[sessions.length - 1] + if (!last) return { policy, kind: 'first', why: ['Nothing logged yet — this session sets the baseline.'] } + + const stalls = stallCount(sessions) + const deloadAt = DELOAD_AFTER[policy] || 3 + + if (mode === 'time') { + if (last.ok) { + const sec = (last.goal || cfg.sec || 0) + inc + return { policy, kind: 'up', sec, why: ['Held every set for the full time — target up by {0}s.', inc] } + } + if (stalls >= deloadAt) { + const sec = deloadTo(last.goal || cfg.sec || 0, 5) + return { policy, kind: 'deload', sec, why: ['Short {0} sessions in a row — back off to {1}s and build up again.', stalls, sec] } + } + return { policy, kind: 'hold', sec: last.goal || cfg.sec, why: ['Last time came up short — same target again.'] } + } + + const w = last.weight + // Bodyweight work carries no external load, so there is nothing to add or take away — + // "deload your push-ups to 2.5 kg" is not advice. Progress in reps instead. This runs + // ahead of the individual policies because it is true for all of them; a rep range set on + // top of it simply gets passed once you exceed it, which is the right moment to add load + // or move to a harder variation anyway. + if (w <= 0) { + const goal = last.goal || cfg.reps || 0 + if (last.ok && goal > 0) return { policy, kind: 'up', weight: 0, reps: goal + 1, why: ['Bodyweight — every rep last time, so go for {0} this time.', goal + 1] } + return { policy, kind: 'hold', weight: 0, reps: goal || undefined, why: ['Bodyweight — same target again until every set is clean.'] } + } + if (policy === 'double') { + const top = cfg.reps || last.goal || 10 + const bottom = Math.min(cfg.repsMin || Math.max(1, top - 2), top) + if (last.ok) return { policy, kind: 'up', weight: snap(w + inc, inc), reps: bottom, why: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom] } + if (stalls >= deloadAt) { + const dw = deloadTo(w, inc) + return { policy, kind: 'deload', weight: dw, reps: bottom, why: ['Stalled {0} sessions — deload to {1} {2}.', stalls, dw, unit] } + } + const aim = Math.min(top, Math.max(bottom, last.low + 1)) + return { policy, kind: 'hold', weight: w, reps: aim, why: ['Same weight — aim for {0} reps this time.', aim] } + } + + // linear + greyskull + if (last.ok) { + // Greyskull's final set is taken to failure: double the target reps there and you have + // earned a double jump. + const dbl = policy === 'greyskull' && last.goal > 0 && last.amrap >= last.goal * 2 + const step = dbl ? inc * 2 : inc + return { + policy, kind: 'up', weight: snap(w + step, inc), + why: dbl + ? ['Last set hit {0} reps — twice the target, so take a double jump of {1} {2}.', last.amrap, step, unit] + : ['Every rep last time — {0} {1} more.', step, unit] + } + } + if (stalls >= deloadAt) { + const dw = deloadTo(w, inc) + return { + policy, kind: 'deload', weight: dw, + why: stalls > 1 + ? ['Missed reps {0} sessions running — reset to {1} {2} and work back up.', stalls, dw, unit] + : ['Missed reps — reset to {0} {1} and work back up.', dw, unit] + } + } + return { policy, kind: 'hold', weight: w, why: ['Missed reps last time — same weight again ({0} of {1} to go).', deloadAt - stalls, deloadAt] } +} + +/** + * Apply a prescription to freshly built sets. Only the fields the policy actually decided + * are touched, and only on sets that have not been logged yet. + */ +export function applyPrescription(sets, p) { + if (!p || p.kind === 'off' || p.kind === 'first') return sets + return sets.map(s => { + if (s.done) return s + const out = { ...s } + if (p.weight != null) out.w = p.weight + if (p.reps != null) out.r = p.reps + if (p.sec != null) out.sec = p.sec + return out + }) +} diff --git a/frontend/src/lib/progression.test.js b/frontend/src/lib/progression.test.js new file mode 100644 index 0000000..9847ec9 --- /dev/null +++ b/frontend/src/lib/progression.test.js @@ -0,0 +1,393 @@ +import { describe, it, expect } from 'vitest' +import { + readSession, sessionsFor, stallCount, nextPrescription, applyPrescription, + policyFor, defaultIncrement, POLICIES_FOR, DELOAD_AFTER +} from './progression.js' +import { EXDB } from './exercises.js' + +const LIFT = EXDB.find(e => e.bp !== 'cardio' && !['upper legs', 'lower legs', 'back', 'hips', 'glutes'].includes(e.bp)).id +const HEAVY = EXDB.find(e => e.bp === 'upper legs').id +const CARDIO = EXDB.find(e => e.bp === 'cardio').id + +// Build a state whose history is a list of sessions given as [weight, ...repsPerSet]. +// A rep count of null means "the set was never checked off". +const hist = (id, rows, target) => ({ + unit: 'kg', + workouts: rows.map((row, i) => ({ + d: '2026-01-0' + (i + 1), + entries: [{ + id, + target: target || { sets: 3, reps: 5, weight: row[0] }, + sets: row.slice(1).map(r => (r === null ? { w: row[0], r: 0, done: false } : { w: row[0], r, done: true })) + }] + })) +}) + +describe('readSession', () => { + const T = { sets: 3, reps: 5 } + it('counts a session where every set made its reps as a hit', () => { + const s = readSession({ id: LIFT, target: T, sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 6, done: true }] }) + expect(s.ok).toBe(true) + expect(s.weight).toBe(60) + expect(s.amrap).toBe(6) + expect(s.low).toBe(5) + }) + + it('counts short reps as a miss even when the set was checked off', () => { + expect(readSession({ id: LIFT, target: T, sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 3, done: true }] }).ok).toBe(false) + }) + + it('counts an unchecked set as a miss — it was not performed', () => { + const s = readSession({ id: LIFT, target: T, sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }, { w: 60, r: 0, done: false }] }) + expect(s.ok).toBe(false) + expect(s.weight).toBe(60) // the working weight is still known from the sets that counted + }) + + it('counts fewer sets than prescribed as a miss', () => { + expect(readSession({ id: LIFT, target: T, sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }] }).ok).toBe(false) + }) + + it('refuses to call a session a hit when nothing was prescribed', () => { + expect(readSession({ id: LIFT, target: {}, sets: [{ w: 60, r: 5, done: true }] }).ok).toBe(false) + }) + + it('reads a timed session by the hold, not by reps', () => { + const s = readSession({ id: LIFT, target: { sets: 2, sec: 45, mode: 'time' }, sets: [{ sec: 45, w: 0, done: true }, { sec: 50, w: 0, done: true }] }) + expect(s.mode).toBe('time') + expect(s.ok).toBe(true) + expect(s.best).toBe(50) + expect(readSession({ id: LIFT, target: { sets: 2, sec: 45, mode: 'time' }, sets: [{ sec: 45, done: true }, { sec: 30, done: true }] }).ok).toBe(false) + }) +}) + +describe('stallCount', () => { + it('counts consecutive misses back from the most recent session', () => { + expect(stallCount([{ ok: true }, { ok: true }])).toBe(0) + expect(stallCount([{ ok: true }, { ok: false }])).toBe(1) + expect(stallCount([{ ok: false }, { ok: false }, { ok: false }])).toBe(3) + expect(stallCount([{ ok: false }, { ok: true }, { ok: false }])).toBe(1) + expect(stallCount([])).toBe(0) + }) +}) + +describe('policyFor', () => { + it('keeps the app\'s long-standing behaviour as the default for reps work', () => { + expect(policyFor({ id: LIFT }, null, 'reps')).toBe('linear') + }) + it('leaves timed and cardio work alone unless asked', () => { + expect(policyFor({ id: LIFT, mode: 'time' }, null, 'time')).toBe('off') + expect(policyFor({ id: CARDIO }, null, 'cardio')).toBe('off') + }) + it('lets the exercise override the routine, and the routine override the default', () => { + expect(policyFor({ id: LIFT }, { prog: 'greyskull' }, 'reps')).toBe('greyskull') + expect(policyFor({ id: LIFT, prog: 'double' }, { prog: 'greyskull' }, 'reps')).toBe('double') + }) + it('refuses a policy that makes no sense for the mode', () => { + expect(policyFor({ id: LIFT, mode: 'time', prog: 'greyskull' }, null, 'time')).toBe('off') + expect(policyFor({ id: CARDIO, prog: 'linear' }, null, 'cardio')).toBe('off') + expect(POLICIES_FOR.cardio).toEqual(['off']) + }) +}) + +describe('defaultIncrement', () => { + it('gives lower-body lifts the bigger jump', () => { + expect(defaultIncrement(LIFT, 'kg')).toBe(2.5) + expect(defaultIncrement(HEAVY, 'kg')).toBe(5) + }) + it('scales to pounds', () => { + expect(defaultIncrement(LIFT, 'lb')).toBe(5) + expect(defaultIncrement(HEAVY, 'lb')).toBe(10) + }) + it('falls back for an unknown exercise', () => { + expect(defaultIncrement('nope', 'kg')).toBe(2.5) + }) +}) + +describe('linear progression', () => { + const cfg = { id: LIFT, sets: 3, reps: 5, weight: 60, prog: 'linear' } + + it('says nothing useful before there is any history', () => { + const p = nextPrescription({ unit: 'kg', workouts: [] }, cfg) + expect(p.kind).toBe('first') + expect(p.weight).toBeUndefined() + }) + + it('adds the increment after a clean session', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, 5]]), cfg) + expect(p.kind).toBe('up') + expect(p.weight).toBe(62.5) + }) + + it('repeats the weight after a miss instead of advancing', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, 3]]), cfg) + expect(p.kind).toBe('hold') + expect(p.weight).toBe(60) + }) + + it('does not advance when the last set was left unchecked', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, null]]), cfg) + expect(p.kind).toBe('hold') + expect(p.weight).toBe(60) + }) + + it('deloads after three misses in a row, onto a loadable weight', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, 3], [60, 5, 4, 4], [60, 5, 5, 4]]), cfg) + expect(p.kind).toBe('deload') + expect(p.weight).toBe(55) // 60 × 0.9 = 54 → nearest loadable 2.5 step + expect(DELOAD_AFTER.linear).toBe(3) + }) + + it('a good session in between clears the stall', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, 3], [60, 5, 5, 5], [60, 5, 5, 3]]), cfg) + expect(p.kind).toBe('hold') + }) + + it('never deloads below one increment, however light the lift already is', () => { + const p = nextPrescription(hist(LIFT, [[2.5, 1, 1, 1], [2.5, 1, 1, 1], [2.5, 1, 1, 1]]), cfg) + expect(p.kind).toBe('deload') + expect(p.weight).toBe(2.5) + }) + + it('always makes a deload actually lighter, even when rounding would not', () => { + // 20 × 0.9 = 18 → nearest 2.5 step is 17.5, fine. 5 × 0.9 = 4.5 → nearest step is 5, + // which is no deload at all, so it has to step down instead. + const p = nextPrescription(hist(LIFT, [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]), cfg) + expect(p.weight).toBeLessThan(5) + }) + + it('uses the heavier step for a lower-body lift', () => { + const p = nextPrescription(hist(HEAVY, [[100, 5, 5, 5]]), { id: HEAVY, sets: 3, reps: 5, prog: 'linear' }) + expect(p.weight).toBe(105) + }) + + it('honours a per-exercise increment override', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, 5]]), { ...cfg, inc: 1 }) + expect(p.weight).toBe(61) + }) + + it('works in pounds', () => { + const S = { ...hist(LIFT, [[135, 5, 5, 5]]), unit: 'lb' } + expect(nextPrescription(S, cfg).weight).toBe(140) + }) +}) + +describe('bodyweight exercises', () => { + const cfg = { id: LIFT, sets: 3, reps: 10, weight: 0, prog: 'linear' } + const bw = rows => hist(LIFT, rows, { sets: 3, reps: 10 }) + + it('never invents a weight to deload to — there is nothing to take off a push-up', () => { + const p = nextPrescription(bw([[0, 10, 10, 8], [0, 10, 10, 9], [0, 10, 10, 8]]), cfg) + expect(p.kind).toBe('hold') + expect(p.weight).toBe(0) + expect(p.reps).toBe(10) + }) + + it('progresses in reps instead of load after a clean session', () => { + const p = nextPrescription(bw([[0, 10, 10, 10]]), cfg) + expect(p.kind).toBe('up') + expect(p.weight).toBe(0) + expect(p.reps).toBe(11) + }) + + it('applies to every policy, not just linear', () => { + for (const prog of ['linear', 'greyskull', 'double']) { + const p = nextPrescription(bw([[0, 10, 10, 4], [0, 10, 10, 4], [0, 10, 10, 4]]), { ...cfg, prog }) + expect(p.weight, prog).toBe(0) + expect(p.kind, prog).toBe('hold') + } + }) + + it('still adds load the moment the exercise is actually weighted', () => { + const p = nextPrescription(hist(LIFT, [[10, 10, 10, 10]], { sets: 3, reps: 10 }), cfg) + expect(p.kind).toBe('up') + expect(p.weight).toBe(12.5) + }) +}) + +describe('Greyskull LP', () => { + const cfg = { id: LIFT, sets: 3, reps: 5, weight: 60, prog: 'greyskull' } + + it('advances when the final set makes the target', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, 5]]), cfg) + expect(p.kind).toBe('up') + expect(p.weight).toBe(62.5) + }) + + it('takes a double jump when the last set doubles the target reps', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, 10]]), cfg) + expect(p.kind).toBe('up') + expect(p.weight).toBe(65) + expect(p.why[0]).toContain('double') + }) + + it('resets 10 % on the very first failure, unlike plain linear', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, 3]]), cfg) + expect(p.kind).toBe('deload') + expect(p.weight).toBe(55) + expect(DELOAD_AFTER.greyskull).toBe(1) + }) + + it('keeps resetting from the reduced weight, not the original', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, 3], [55, 5, 5, 2]]), cfg) + expect(p.kind).toBe('deload') + expect(p.weight).toBe(50) // 55 × 0.9 = 49.5 → nearest loadable 2.5 step + }) +}) + +describe('double progression', () => { + const cfg = { id: LIFT, sets: 3, reps: 12, repsMin: 8, weight: 40, prog: 'double' } + + it('adds weight and drops back to the bottom of the range at the top of it', () => { + const p = nextPrescription(hist(LIFT, [[40, 12, 12, 12]], { sets: 3, reps: 12 }), cfg) + expect(p.kind).toBe('up') + expect(p.weight).toBe(42.5) + expect(p.reps).toBe(8) + }) + + it('keeps the weight and asks for one more rep while inside the range', () => { + const p = nextPrescription(hist(LIFT, [[40, 10, 9, 9]], { sets: 3, reps: 12 }), cfg) + expect(p.kind).toBe('hold') + expect(p.weight).toBe(40) + expect(p.reps).toBe(10) // worst set was 9 → aim for 10 + }) + + it('never asks for more than the top of the range', () => { + const p = nextPrescription(hist(LIFT, [[40, 12, 12, 11]], { sets: 3, reps: 12 }), cfg) + expect(p.reps).toBeLessThanOrEqual(12) + }) + + it('deloads after a run of stalls and restarts at the bottom of the range', () => { + const rows = [[40, 9, 9, 9], [40, 9, 9, 9], [40, 9, 9, 9]] + const p = nextPrescription(hist(LIFT, rows, { sets: 3, reps: 12 }), cfg) + expect(p.kind).toBe('deload') + expect(p.reps).toBe(8) + expect(p.weight).toBe(35) // 40 × 0.9 = 36 → nearest loadable 2.5 step + }) +}) + +describe('timed progression', () => { + const cfg = { id: LIFT, mode: 'time', sets: 2, sec: 45, prog: 'time' } + const T = { sets: 2, sec: 45, mode: 'time' } + const timeHist = rows => ({ + unit: 'kg', + workouts: rows.map((row, i) => ({ + d: '2026-02-0' + (i + 1), + entries: [{ id: LIFT, target: T, sets: row.map(sec => ({ sec, w: 0, done: true })) }] + })) + }) + + it('adds time when every set went the full duration', () => { + const p = nextPrescription(timeHist([[45, 45]]), cfg) + expect(p.kind).toBe('up') + expect(p.sec).toBe(50) + expect(p.weight).toBeUndefined() + }) + + it('repeats the target when a hold came up short', () => { + const p = nextPrescription(timeHist([[45, 38]]), cfg) + expect(p.kind).toBe('hold') + expect(p.sec).toBe(45) + }) + + it('backs the target off after a run of short sessions', () => { + const p = nextPrescription(timeHist([[45, 30], [45, 32], [45, 31]]), cfg) + expect(p.kind).toBe('deload') + expect(p.sec).toBe(40) // 45 × 0.9 = 40.5 → nearest 5 s step + }) + + it('ignores reps history when the exercise switched to time', () => { + const S = hist(LIFT, [[60, 5, 5, 5]]) + const p = nextPrescription({ ...S, unit: 'kg' }, cfg) + expect(p.kind).toBe('first') // no timed session yet, so no opinion + }) +}) + +describe('policy "off"', () => { + it('has no opinion at all', () => { + const p = nextPrescription(hist(LIFT, [[60, 5, 5, 5]]), { id: LIFT, sets: 3, reps: 5, prog: 'off' }) + expect(p.kind).toBe('off') + expect(p.weight).toBeUndefined() + }) + it('is what cardio always gets', () => { + expect(nextPrescription({ unit: 'kg', workouts: [] }, { id: CARDIO, sets: 1, min: 20 }).kind).toBe('off') + }) +}) + +describe('sessionsFor', () => { + it('skips workouts where the exercise was never actually logged', () => { + const S = { + unit: 'kg', + workouts: [ + { d: '2026-01-01', entries: [{ id: LIFT, target: { sets: 1, reps: 5 }, sets: [{ w: 60, r: 5, done: true }] }] }, + { d: '2026-01-02', entries: [{ id: LIFT, target: { sets: 1, reps: 5 }, sets: [{ w: 60, r: 0, done: false }] }] }, + { d: '2026-01-03', entries: [{ id: 'other', target: {}, sets: [{ w: 20, r: 5, done: true }] }] } + ] + } + expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-01-01']) + }) + + it('reads a legacy entry that has no target without crashing', () => { + const S = { unit: 'kg', workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 5, done: true }] }] }] } + expect(sessionsFor(S, LIFT)).toHaveLength(1) + }) +}) + +// Workouts only began storing their prescription in v1.2.2. Everything logged before that is +// targetless, and reading it as "missed" would tell every long-standing user to deload on +// their first session after updating — which is exactly what the demo history did. +describe('history logged before targets were recorded', () => { + const legacy = rows => ({ + unit: 'kg', + workouts: rows.map((row, i) => ({ + d: '2026-03-' + String(i + 1).padStart(2, '0'), + entries: [{ id: LIFT, sets: row.slice(1).map(r => ({ w: row[0], r, done: true })) }] // no target + })) + }) + const cfg = { id: LIFT, sets: 3, reps: 5, weight: 60, prog: 'linear' } + + it('judges a targetless session against the current plan instead of calling it a miss', () => { + const p = nextPrescription(legacy([[60, 5, 5, 5]]), cfg) + expect(p.kind).toBe('up') + expect(p.weight).toBe(62.5) + }) + + it('does not manufacture a stall out of a long clean history', () => { + const p = nextPrescription(legacy(Array.from({ length: 11 }, () => [60, 5, 5, 5])), cfg) + expect(p.kind).toBe('up') + }) + + it('still spots a genuine miss in old data', () => { + expect(nextPrescription(legacy([[60, 5, 5, 2]]), cfg).kind).toBe('hold') + }) + + it('matches the weight hint the app showed before this engine existed', () => { + // Old rule: every set at or above the plan's reps, with a real weight → suggest a step up. + expect(nextPrescription(legacy([[60, 5, 6, 5]]), cfg).weight).toBe(62.5) + expect(nextPrescription(legacy([[60, 5, 4, 5]]), cfg).kind).toBe('hold') + }) +}) + +describe('applyPrescription', () => { + const sets = [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: false }] + + it('rewrites only what the policy decided, and only unlogged sets', () => { + const out = applyPrescription(sets, { kind: 'up', weight: 62.5 }) + expect(out[0]).toEqual({ w: 60, r: 5, done: true }) + expect(out[1]).toEqual({ w: 62.5, r: 5, done: false }) + }) + + it('sets reps too when the policy has an opinion about them', () => { + expect(applyPrescription(sets, { kind: 'up', weight: 42.5, reps: 8 })[1]).toEqual({ w: 42.5, r: 8, done: false }) + }) + + it('touches nothing for "off" or a first session', () => { + expect(applyPrescription(sets, { kind: 'off' })).toBe(sets) + expect(applyPrescription(sets, { kind: 'first' })).toBe(sets) + expect(applyPrescription(sets, null)).toBe(sets) + }) + + it('adjusts a timed set without inventing a weight', () => { + const timed = [{ sec: 45, w: 0, done: false }] + expect(applyPrescription(timed, { kind: 'up', sec: 50 })).toEqual([{ sec: 50, w: 0, done: false }]) + }) +})