Merge !103: feat: use Epley-based targets for automatic deloads

This commit is contained in:
Duarte Santos committed 2026-09-07 19:37:22 +02:00
commit 6d2b22da63
9 files changed
+393 -18

No files matched your search

+3
View File
@@ -43,6 +43,9 @@ function cleanEx(e) {
// without its rule is just a list of weights.
if (e.prog) o.prog = e.prog
if (e.inc > 0) o.inc = e.inc
// Epley deload factor is a per-occurrence progression setting. Omit the default so older
// exports remain compact and importing them preserves the default 90% behaviour.
if (e.deloadFactor != null && Number(e.deloadFactor) !== 0.9) o.deloadFactor = e.deloadFactor
if (e.repsMin != null) o.repsMin = e.repsMin
if (e.repsMax != null) o.repsMax = e.repsMax
// The exercise's own rest (issue #10) is part of how it is prescribed, so it travels too —
+5
View File
@@ -24,6 +24,11 @@ describe('what survives a shared plan', () => {
expect(roundTrip({ warmupSets: 3 }).warmupSets).toBe(3)
})
it('carries a non-default Epley deload factor and omits the default', () => {
expect(roundTrip({ deloadFactor: 0.8 }).deloadFactor).toBe(0.8)
expect('deloadFactor' in roundTrip({ deloadFactor: 0.9 })).toBe(false)
})
it('carries progression exclusion on a routine through export and merge', () => {
const source = stateWith({})
source.routines[0].excludeFromProgression = true
+155 -12
View File
@@ -16,7 +16,7 @@
// · fewer sets than prescribed → miss
// So a session that fell apart can never advance the load as though it had succeeded.
import { modeOf, repStep, rerampWarmups } from './history.js'
import { modeOf, repStep, rerampWarmups, isBw, isPerSide } from './history.js'
import { EXIDX } from './exercises.js'
import { isWarmupRow } from './workout-model.js'
import { normalizeRepRange } from './rep-range.js'
@@ -45,10 +45,35 @@ export const POLICY_DESC = {
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.
// The Epley target is a soft objective mapped onto the exercise's real load grid. Keep the
// default out of saved configs so plans written before this policy stays byte-for-byte compatible.
export const DELOAD_FACTOR = 0.9
export const DELOAD_AFTER = { linear: 3, greyskull: 1, double: 3, time: 3 }
const DELOAD_FACTOR = 0.9
export const DELOAD_FACTOR_MIN = 0.5
export const DELOAD_FACTOR_MAX = 0.95
export function isValidDeloadFactor(value) {
const factor = Number(value)
return Number.isFinite(factor) && factor >= DELOAD_FACTOR_MIN && factor <= DELOAD_FACTOR_MAX
}
export function deloadFactorOf(cfg) {
return isValidDeloadFactor(cfg?.deloadFactor) ? Number(cfg.deloadFactor) : DELOAD_FACTOR
}
// Epley uses the reps performed by one side for unilateral work. Callers pass the stored total
// reps and this helper makes the split explicit rather than allowing a total to inflate the 1RM.
export function epley1RM(weight, reps) {
const w = Number(weight)
const r = Number(reps)
if (!Number.isFinite(w) || !Number.isFinite(r) || w <= 0 || r < 1) return null
const result = w * (1 + r / 30)
return Number.isFinite(result) && result > 0 ? round1(result) : null
}
export function deloadTarget1RM(weight, reps, factor = DELOAD_FACTOR, perSide = false) {
const base = epley1RM(weight, perSide ? Number(reps) / 2 : reps)
const f = isValidDeloadFactor(factor) ? Number(factor) : DELOAD_FACTOR
return base == null ? null : round1(base * f)
}
// Body parts where a 5 kg jump is normal rather than brutal.
const HEAVY_BP = ['upper legs', 'lower legs', 'back', 'hips', 'glutes']
@@ -96,16 +121,82 @@ export function stepWeight(value, step, direction) {
const next = v + direction * step
return Math.max(0, onGrid ? snapWeight(next, step) : round1(next))
}
// 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 = snapWeight(cur * DELOAD_FACTOR, step)
// Back off by a factor, landing on something you can actually load. This remains the old policy
// used by Greyskull and timed progression; linear/double loaded reps use the Epley selector below.
export function deloadTo(cur, step, factor = DELOAD_FACTOR) {
let next = snapWeight(cur * factor, step)
if (next >= cur) next = snapWeight(cur - step, step)
return Math.max(step, next)
}
const positiveGridAround = (ideal, step, maxWeight, strictLower) => {
if (!(ideal > 0) || !(step > 0) || !(maxWeight > 0)) return []
const low = Math.floor(ideal / step) * step
const high = Math.ceil(ideal / step) * step
const values = [...new Set([low, high].map(v => snapWeight(v, step)))]
return values
.filter(v => v > 0 && v <= maxWeight + 1e-9 && (!strictLower || v < maxWeight - 1e-9))
.sort((a, b) => a - b)
}
/**
* Pick a bounded load/reps pair for an Epley target. The search is deliberately lexicographic:
* hard constraints first, then closest estimated 1RM, fewer rep changes, and greater load. That
* makes a grid tie predictable without hiding a product decision in arbitrary score weights.
*/
export function selectDeloadCandidate({ currentWeight, targetWeight, targetReps, step, factor = DELOAD_FACTOR, reps, repsMin, perSide = false }) {
const current = Number(currentWeight)
const baseWeight = Number(targetWeight)
const baseReps = Number(targetReps)
const stride = perSide ? 2 : 1
const upper = Math.max(stride, Math.ceil(baseReps / stride) * stride)
const range = repsMin == null ? null : normalizeRepRange(reps, repsMin, stride)
const top = range ? Math.min(range.reps, Math.max(range.repsMin, upper)) : upper
const bottom = range ? range.repsMin : top
const repValues = []
for (let r = top; r >= bottom; r -= stride) repValues.push(r)
const target1RM = deloadTarget1RM(baseWeight, upper, factor, perSide)
if (!(current > 0) || target1RM == null || !repValues.length || !(step > 0)) return null
const candidates = []
repValues.forEach(candidateReps => {
const ideal = target1RM / (1 + (perSide ? candidateReps / 2 : candidateReps) / 30)
const allowCurrent = repsMin != null && candidateReps < upper
const grid = positiveGridAround(ideal, step, current, !allowCurrent)
if (allowCurrent && !grid.includes(current)) grid.push(current)
grid.forEach(candidateWeight => {
const epley = epley1RM(candidateWeight, perSide ? candidateReps / 2 : candidateReps)
candidates.push({
weight: candidateWeight,
reps: candidateReps,
epley,
error: Math.abs(epley - target1RM),
repChange: Math.abs(candidateReps - upper),
fallback: false
})
})
})
// A tiny or below-step lift may have no positive lower grid point. Holding the actual attempted
// load is safer than rounding it up to one step; it is an explicit, deterministic fallback.
if (!candidates.length) {
repValues.forEach(candidateReps => {
const epley = epley1RM(current, perSide ? candidateReps / 2 : candidateReps)
candidates.push({
weight: current,
reps: candidateReps,
epley,
error: Math.abs(epley - target1RM),
repChange: Math.abs(candidateReps - upper),
fallback: true
})
})
}
if (!candidates.length) return null
candidates.sort((a, b) => a.error - b.error || a.repChange - b.repChange || b.weight - a.weight || b.reps - a.reps)
return { ...candidates[0], target1RM, factor: deloadFactorOf({ deloadFactor: factor }), upper, bottom }
}
/**
* Reduce one finished workout entry to what a policy needs to judge it.
*
@@ -128,7 +219,7 @@ export function readSession(entry, fallback) {
const goal = target.sec || 0
const held = sets.map(s => (s.done ? (s.sec || 0) : 0))
return {
mode, goal, held,
mode, target, 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)
@@ -137,7 +228,7 @@ export function readSession(entry, fallback) {
const goal = target.reps || 0
const reps = sets.map(s => (s.done ? (s.r || 0) : 0))
return {
mode, goal, reps,
mode, target, goal, reps,
weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)),
count: reps.length, // the dimension bodyweight work grows (#33)
low: reps.length ? Math.min(...reps) : 0,
@@ -249,12 +340,62 @@ export function nextPrescription(S, cfg, routine) {
const next = goal + repStep(cfg)
return { policy, kind: 'up', weight: 0, reps: next, why: ['Bodyweight — every rep last time, so go for {0} this time.', next] }
}
// Epley deloads apply only to externally loaded rep work. Keep the prescribed target from the
// session that stalled (falling back field-by-field to the current config), while the logged
// weight remains the hard upper bound for the selected candidate.
const epleyDeload = () => {
if (mode !== 'reps' || (policy !== 'linear' && policy !== 'double')) return null
const previous = last.target || {}
const target = {
...cfg,
...previous,
weight: previous.weight ?? cfg.weight,
reps: previous.reps ?? cfg.reps,
repsMin: previous.repsMin ?? cfg.repsMin,
sets: previous.sets ?? cfg.sets,
bodyweight: previous.bodyweight ?? cfg.bodyweight,
side: previous.side ?? cfg.side,
intensifier: previous.intensifier ?? cfg.intensifier
}
// Rest-pause rows have burst reps rather than an independent rep prescription. Warm-up rows
// are already removed by readSession; bodyweight (including added-weight bodyweight) stays
// on the ordinary non-load progression path.
if (isBw(target) || target.intensifier?.type === 'restpause') return null
const candidate = selectDeloadCandidate({
currentWeight: w,
targetWeight: target.weight,
targetReps: target.reps,
step: inc,
factor: deloadFactorOf(cfg),
reps: target.reps,
repsMin: policy === 'double' ? target.repsMin : undefined,
perSide: isPerSide(target)
})
if (!candidate) return null
const held = candidate.weight >= w
return {
policy,
kind: 'deload',
weight: candidate.weight,
reps: candidate.reps,
sets: target.sets,
target1RM: candidate.target1RM,
deloadFactor: candidate.factor,
why: held
? ['Stalled {0} sessions — hold {1} {2} and use {3} reps.', stalls, candidate.weight, unit, candidate.reps]
: ['Stalled {0} sessions — Epley deload to {1} {2} for {3} reps.', stalls, candidate.weight, unit, candidate.reps]
}
}
if (policy === 'double') {
const range = normalizeRepRange(cfg.reps || last.goal || 10, cfg.repsMin, repStep(cfg))
const top = range.reps
const bottom = range.repsMin
if (last.ok) return { policy, kind: 'up', weight: snapWeight(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 selected = epleyDeload()
if (selected) return selected
const dw = deloadTo(w, inc)
return { policy, kind: 'deload', weight: dw, reps: bottom, why: ['Stalled {0} sessions — deload to {1} {2}.', stalls, dw, unit] }
}
@@ -276,6 +417,8 @@ export function nextPrescription(S, cfg, routine) {
}
}
if (stalls >= deloadAt) {
const selected = epleyDeload()
if (selected) return selected
const dw = deloadTo(w, inc)
return {
policy, kind: 'deload', weight: dw,
+83 -4
View File
@@ -1,11 +1,12 @@
import { describe, it, expect } from 'vitest'
import {
readSession, sessionsFor, stallCount, nextPrescription, applyPrescription,
policyFor, defaultIncrement, weightIncrement, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
policyFor, defaultIncrement, weightIncrement, epley1RM, deloadTarget1RM,
deloadFactorOf, DELOAD_FACTOR, POLICIES_FOR, DELOAD_AFTER, MAX_BW_SETS
} 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 LIFT = EXDB.find(e => e.bp !== 'cardio' && !['upper legs', 'lower legs', 'back', 'hips', 'glutes'].includes(e.bp) && !['body weight', 'band', 'resistance band'].includes(e.eq)).id
const HEAVY = EXDB.find(e => e.bp === 'upper legs').id
const CARDIO = EXDB.find(e => e.bp === 'cardio').id
@@ -129,6 +130,21 @@ describe('weightIncrement', () => {
})
})
describe('Epley deload helpers', () => {
it('maps a prescribed target pair to the requested Epley 1RM factor', () => {
expect(epley1RM(60, 8)).toBe(76)
expect(deloadTarget1RM(60, 8)).toBe(68.4)
expect(deloadTarget1RM(60, 8, 0.8)).toBe(60.8)
})
it('uses the configured factor and keeps the ratio backward-compatible', () => {
expect(DELOAD_FACTOR).toBe(0.9)
expect(deloadFactorOf({})).toBe(0.9)
expect(deloadFactorOf({ deloadFactor: 0.8 })).toBe(0.8)
expect(deloadFactorOf({ deloadFactor: 0.1 })).toBe(0.9)
})
})
describe('linear progression', () => {
const cfg = { id: LIFT, sets: 3, reps: 5, weight: 60, prog: 'linear' }
@@ -163,6 +179,30 @@ describe('linear progression', () => {
expect(DELOAD_AFTER.linear).toBe(3)
})
it('deloads from the prescribed target reps, not partial actual reps', () => {
const target = { sets: 3, reps: 8, weight: 60 }
const p = nextPrescription(hist(LIFT, [[60, 6, 6, 6], [60, 6, 6, 6], [60, 6, 6, 6]], target), { ...cfg, reps: 8 })
expect(p.kind).toBe('deload')
expect(p.target1RM).toBe(deloadTarget1RM(60, 8))
expect(p.target1RM).not.toBe(deloadTarget1RM(60, 6))
expect(p.reps).toBe(8)
})
it('uses a configured Epley factor when selecting the deload load', () => {
const p = nextPrescription(hist(LIFT, [[60, 4, 4, 4], [60, 4, 4, 4], [60, 4, 4, 4]], { sets: 3, reps: 5, weight: 60 }), { ...cfg, deloadFactor: 0.8 })
expect(p.kind).toBe('deload')
expect(p.deloadFactor).toBe(0.8)
expect(p.target1RM).toBe(56)
expect(p.weight).toBe(47.5)
})
it('holds a below-step load instead of deloading upward', () => {
const p = nextPrescription(hist(LIFT, [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]), { ...cfg, weight: 1, inc: 2.5 })
expect(p.kind).toBe('deload')
expect(p.weight).toBe(1)
expect(p.why[0]).toMatch(/hold/i)
})
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')
@@ -340,7 +380,17 @@ describe('double progression', () => {
// Training exactly what it asked for: its weight, its reps, every set checked off.
const asPrescribed = [deload.weight, ...Array(target.sets).fill(deload.reps)]
const next = nextPrescription(hist(LIFT, [...stalled, asPrescribed], target), cfg)
const effectiveTarget = { ...target, weight: deload.weight, reps: deload.reps }
const completed = hist(LIFT, stalled, target)
completed.workouts.push({
d: '2026-01-04',
entries: [{
id: LIFT,
target: effectiveTarget,
sets: asPrescribed.slice(1).map(r => ({ w: asPrescribed[0], r, done: true }))
}]
})
const next = nextPrescription(completed, cfg)
// Complying with the app's own prescription must not be scored as another failure.
expect(next.kind).not.toBe('deload')
@@ -364,7 +414,7 @@ describe('double progression', () => {
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
expect(p.weight).toBe(40) // 40 × 8 is the closest valid Epley candidate
})
it('climbs a range wider than the deload budget instead of cutting on the way up', () => {
@@ -396,7 +446,36 @@ describe('double progression', () => {
const p = nextPrescription(hist(LIFT, [[40, 12, 12, 12]], { sets: 3, reps: 13 }), perSide)
expect(p.kind).toBe('hold')
expect(p.reps).toBe(14)
it('selects a lower in-range rep target and never increases the attempted load', () => {
const target = { sets: 3, reps: 12, weight: 40 }
const p = nextPrescription(hist(LIFT, [[40, 9, 9, 9], [40, 9, 9, 9], [40, 9, 9, 9]], target), cfg)
expect(p.kind).toBe('deload')
expect(p.reps).toBeGreaterThanOrEqual(8)
expect(p.reps).toBeLessThanOrEqual(12)
expect(p.weight).toBeLessThanOrEqual(40)
expect(p.target1RM).toBe(deloadTarget1RM(40, 12))
})
it('keeps a 5 kg load and lowers reps when that is closer than a 50% weight cut', () => {
const small = { id: LIFT, sets: 3, reps: 8, repsMin: 4, weight: 5, inc: 2.5, prog: 'double' }
const target = { sets: 3, reps: 8, weight: 5 }
const p = nextPrescription(hist(LIFT, [[5, 6, 6, 6], [5, 6, 6, 6], [5, 6, 6, 6]], target), small)
expect(p.kind).toBe('deload')
expect(p.weight).toBe(5)
expect(p.reps).toBe(4)
expect(p.target1RM).toBe(deloadTarget1RM(5, 8))
})
it('uses half the reps for per-side Epley and returns an even total', () => {
const perSide = { ...cfg, reps: 8, side: true }
const target = { sets: 3, reps: 8, weight: 60, side: true }
const p = nextPrescription(hist(LIFT, [[60, 6, 6, 6], [60, 6, 6, 6], [60, 6, 6, 6]], target), perSide)
expect(p.kind).toBe('deload')
expect(p.reps % 2).toBe(0)
expect(p.target1RM).toBe(deloadTarget1RM(60, 8, 0.9, true))
})
})
describe('timed progression', () => {
+6 -1
View File
@@ -18,7 +18,12 @@ export function buildSessionEntries(st, r) {
// default for its optional load.
const step = modeOf(cfg) === 'reps' ? weightIncrement(cfg, st.unit) : defaultIncrement(cfg.id, st.unit)
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step, useTarget: plan.kind === 'off' }), plan, step), cfg)
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
const target = { ...cfg }
if (plan.weight != null) target.weight = plan.weight
if (plan.reps != null) target.reps = plan.reps
if (plan.sec != null) target.sec = plan.sec
if (plan.sets != null) target.sets = plan.sets
return { id: cfg.id, sg: cfg.sg, target, plan, sets }
})
return { entries, excluded }
}
+25
View File
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest'
import { buildSessionEntries } from './session-start.js'
import { readSession } from './progression.js'
import { isWarmupRow } from './workout-model.js'
// The session builder used by the live start and by "log a past workout".
@@ -20,4 +21,28 @@ describe('buildSessionEntries', () => {
const { entries } = buildSessionEntries(st, r)
expect(entries[0].sets.every(s => s.sec === 30)).toBe(true)
})
it('persists the effective deload target so completing the opened rows reads as a hit', () => {
const cfg = { id: '0025', sets: 3, reps: 8, weight: 60, prog: 'linear' }
const st = {
unit: 'kg', exWeights: {}, routines: [],
workouts: [1, 2, 3].map((n) => ({
d: `2026-01-0${n}`,
entries: [{
id: cfg.id,
target: { sets: 3, reps: 8, weight: 60 },
sets: [6, 6, 6].map(r => ({ w: 60, r, done: true }))
}]
}))
}
const r = { id: 'r', prog: 'linear', ex: [cfg] }
const { entries } = buildSessionEntries(st, r)
const entry = entries[0]
const work = entry.sets.filter(s => !isWarmupRow(s))
expect(entry.plan.kind).toBe('deload')
expect(entry.target).toMatchObject({ reps: entry.plan.reps, weight: entry.plan.weight })
expect(readSession({ ...entry, sets: entry.sets.map(s => ({ ...s, done: true })) }, cfg).ok).toBe(true)
expect(work.every(s => s.r === entry.target.reps && s.w === entry.target.weight)).toBe(true)
})
})
+10
View File
@@ -1063,6 +1063,8 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit, perSide }) {
const invalid = !progressionStepIsValid(inc, active)
const stride = mode === 'reps' && perSide ? 2 : 1
const range = active === 'double' ? normalizeRepRange(c.reps, c.repsMin, stride) : null
const epleyEligible = mode === 'reps' && !isBw({ ...c, id: ex.id }) && (active === 'linear' || active === 'double')
const deloadPercent = Math.round((Number(c.deloadFactor) > 0 ? Number(c.deloadFactor) : 0.9) * 100)
const setRule = v => setC(x => {
const next = { ...x, prog: v || undefined }
return policyFor({ ...next, id: ex.id }, routine, mode) === 'double'
@@ -1089,6 +1091,8 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit, perSide }) {
<Stepper label={t('Reps up to')} value={c.reps ?? range.reps} step={stride} decimal={false}
onChange={v => setC(x => ({ ...x, reps: v }))} />
</>}
{epleyEligible && <Stepper label={t('Deload 1RM (%)')} value={deloadPercent} step={5} decimal={false}
onChange={v => setC(x => ({ ...x, deloadFactor: Math.max(0.5, Math.min(0.95, Number(v) / 100)) }))} />}
</div>}
{invalid && <div className="small" role="alert" style={{ color: 'var(--red)', marginTop: -10, marginBottom: 18 }}>
{t('Enter a positive step to use this progression rule.')}
@@ -1132,6 +1136,12 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
const prog = {}
if (c.prog) prog.prog = c.prog
if (c.inc > 0) prog.inc = c.inc
// Epley deloading is configurable per occurrence, but the default stays omitted so older
// plans retain their compact shape and keep the existing 90% behaviour.
if (mode === 'reps' && !bw && (activePolicy === 'linear' || activePolicy === 'double')) {
const deloadFactor = Math.max(0.5, Math.min(0.95, Number(c.deloadFactor) || 0.9))
if (deloadFactor !== 0.9) prog.deloadFactor = deloadFactor
}
// Written only when it differs from what the dataset already says, so a barbell config
// stays exactly the shape it was before these flags existed.
// `bodyweight` is true of a hold as much as of a set of reps; `side` is not — it counts