Skip to content

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.

Merge PR #436 into v140-db: sets-based fatigue with per-muscle recovery, RIR quality and estimated effort

Duarte Santos3242d558ea01
diff --cc frontend/src/lib/effort.js
index e09ea7922,b857ef808..6254cfd68
--- a/frontend/src/lib/effort.js
+++ b/frontend/src/lib/effort.js
@@@ -6,9 -6,10 +6,10 @@@
// half-empty series. So everything aggregates in RIR and is converted back for display.
// RIR is the internal unit because it has a real zero — a set taken to failure — where RPE's
// floor of 6 is only a convention about which sets are worth rating. RPE 8 == RIR 2.
-import { EFFORT, effortOf } from './history.js'
+import { EFFORT, effortOf, workoutAt } from './history.js'
import { weekKey, weekStartOf, startOfWeek } from './format.js'
import { isWarmupRow } from './workout-model.js'
+ import { isAssisted } from './exercises.js'
// At or below this a set is close enough to failure to be the kind that drives adaptation.
// 3 rather than 2: the line is a convention, and drawn one rep too generously it still
@@@ -51,8 -52,18 +52,18 @@@ function eachDoneSet(S, fn)
// A window in days, counted back from now. 0 = everything, which is also what an empty
// history means for every caller here.
const inWindow = (w, days) =>
- !days || (w.start || new Date(w.d).getTime()) > Date.now() - days * 86400000
+ !days || workoutAt(w) > Date.now() - days * 86400000
+ // A set's RIR plus where it came from. The default resolver is logged effort only
+ // (historical behaviour, unchanged); pass a resolver built on
+ // recovery.js:resolveSetRir for the estimated fallback, which keeps stats and the
+ // fatigue map in agreement about every set.
+ const normRir = r => {
+ if (r == null) return null
+ if (typeof r === 'number') return { rir: r, estimated: false }
+ return { rir: r.rir, estimated: r.source ? r.source !== 'logged' : !!r.estimated }
+ }
+
export const avgRir = sets => {
const vs = (sets || []).map(rirOf).filter(v => v != null)
return vs.length ? vs.reduce((a, b) => a + b, 0) / vs.length : null
diff --cc frontend/src/lib/recovery.js
index c28297c99,035c90d8d..f94e0fbff
--- a/frontend/src/lib/recovery.js
+++ b/frontend/src/lib/recovery.js
@@@ -1,26 -1,61 +1,66 @@@
- import { EXIDX } from './exercises.js'
+ import { EXIDX, isAssisted } from './exercises.js'
+import { workoutAt } from './history.js'
import { MUSCLES, musclesOf } from './muscles.js'
- import { isWarmupRow, dropsOf } from './workout-model.js'
- import { weightedEstimate, WEIGHTED_REP_CAP } from './onerm.js'
-
- // A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve
- // 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting
- // fatigue level without ever pinning it, and the value can then fade asymptotically.
- export const FATIGUE_REF_VOLUME = 2000 // default reference: kg of intensity-weighted volume per session
- export const FATIGUE_MIN_SESSIONS = 3 // smoothing horizon for the causal per-muscle reference
- // Computational bound for the stimulus scan, not a semantic cliff: after 30 days (20
- // half-lives) a session contributes below 1e-6 to the accumulated value.
+ import { isWarmupRow, dropsOf, isSideSet } from './workout-model.js'
+ import { estimate1RM, REP_CAP } from './onerm.js'
+ import { rirOf, HARD_RIR } from './effort.js'
+
+ // Fatigue stimulus in effective hard sets, not tonnage: hypertrophy dose-response
+ // tracks sets near failure (~5-30 reps), while tonnage overweights heavy compounds
+ // (a 250x7 leg press counts ~50x a 5x12 fly for a comparable growth stimulus).
+ // One full session on a muscle (~8 hard sets, the per-session growth plateau)
+ // scores 1.0 raw unit; secondary movers count 0.4 via musclesOf weights.
+ export const FATIGUE_SETS_PER_UNIT = 8
+ // Per-session cap per muscle: beyond ~10-12 sets the growth response plateaus,
+ // so extra junk volume must not extend the red tail linearly.
+ export const FATIGUE_MAX_SETS_PER_SESSION = 12
+ // Computational bound for the stimulus scan, not a semantic cliff: after 30 days
+ // even a 24h half-life muscle retains below 1e-9 of the stimulus.
export const FATIGUE_SCAN_MS = 30 * 24 * 60 * 60 * 1000
- export const BODYWEIGHT_REF_LOAD = 75 // kg assumed for bodyweight exercises when no load is logged
- export const CARDIO_TONNAGE_PER_MIN = 50 // duration proxy for cardio/timed work
-
- // Preserve the shipped set-count signal when a completed custom/imported exercise has no load.
- // Two such sets therefore retain the old 1 - exp(-2 / 3) starting-fatigue reading.
- const ZERO_LOAD_SET_STIMULUS = FATIGUE_REF_VOLUME / 3
+ // Capacity anchors and chronic exposure look further back than the stimulus scan:
+ // a 90-day rolling best still knows the lifter's recent strength, and 28 days of
+ // exposure is the chronic side of the acute:chronic pair. Sessions older than the
+ // stimulus scan never emit stimulus themselves - they only inform these two.
+ export const FATIGUE_RIR_WINDOW_MS = 90 * 24 * 60 * 60 * 1000
+ export const FATIGUE_ACUTE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000
+ export const FATIGUE_CHRONIC_WINDOW_MS = 28 * 24 * 60 * 60 * 1000
+ // A far-from-failure set still moves blood and practices the lift: it costs no less
+ // than this fraction of a hard set.
+ export const FATIGUE_RIR_FLOOR_WEIGHT = 0.3
+ // The acute:chronic gain is clamped: doubling volume at most doubles the scored
+ // stimulus, halving at most halves it. Maintenance (~1.0) reproduces phase-1 values.
+ export const FATIGUE_RATIO_MIN = 0.5
+ export const FATIGUE_RATIO_MAX = 2
+ // Prior weekly exposure for a muscle never trained in the chronic window: the novice
+ // anchor. A first session therefore scores amplified (unadapted), a maintained
+ // veteran scores ~1.0 (adapted) - the repeated-bout effect as arithmetic.
+ export const FATIGUE_NOVICE_WEEKLY_SETS = 4
++// kg assumed for a bodyweight exercise's body mass when neither the workout nor the profile
++// carries a bodyweight. Only the RIR estimate reads it (a load against the anchor), so a wrong
++// guess shifts loaded and unloaded bodyweight sets together.
++export const BODYWEIGHT_REF_LOAD = 75
+
+ // Exponential half-life for fatigue stimulus, per muscle. Lower body (heavier
+ // absolute loads, more damage) recovers slower than upper body: 10RM
+ // reproducibility data shows squat still down -6.6% at 36h while bench is -3.0%,
+ // both fully back by 48-72h. Small/core muscles share the fast 24h lane.
+ const FATIGUE_HL_24H = 24 * 60 * 60 * 1000
+ const FATIGUE_HL_30H = 30 * 60 * 60 * 1000
+ const FATIGUE_HL_48H = 48 * 60 * 60 * 1000
+ const FATIGUE_HL_BY_MUSCLE = {
+ trapezius: FATIGUE_HL_30H, deltoids: FATIGUE_HL_24H, chest: FATIGUE_HL_30H,
+ 'upper-back': FATIGUE_HL_30H, serratus: FATIGUE_HL_24H,
+ biceps: FATIGUE_HL_24H, triceps: FATIGUE_HL_24H, forearm: FATIGUE_HL_24H,
+ abs: FATIGUE_HL_24H, obliques: FATIGUE_HL_24H, 'lower-back': FATIGUE_HL_48H,
+ gluteal: FATIGUE_HL_48H, quadriceps: FATIGUE_HL_48H, hamstring: FATIGUE_HL_48H,
+ adductors: FATIGUE_HL_48H, 'hip-flexors': FATIGUE_HL_24H,
+ calves: FATIGUE_HL_48H, tibialis: FATIGUE_HL_24H,
+ }
- /** Exponential half-life for fatigue stimulus. */
- export const FATIGUE_HALF_LIFE_MS = 129600000
+ /** Exponential half-life for fatigue stimulus of one muscle. */
+ export function fatigueHalfLifeOf(slug) {
+ return FATIGUE_HL_BY_MUSCLE[slug] || FATIGUE_HL_30H
+ }
/** Period after training during which retained strength remains at full value. */
export const STRENGTH_FULL_MS = 1209600000
@@@ -100,170 -136,193 +140,266 @@@ function kgOf(value, unit)
return Math.max(0, n) * (isPounds(unit) ? LB_TO_KG : 1)
}
-function rowWkg(row, set, entry, workout, opts) {
- return kgOf(row?.w, unitOf(row, set, entry?.target, entry, workout, opts))
+// A bodyweight value stamped on a workout is the best historical value. When old records do not
+// carry one, use the current profile's canonical bodyweight supplied by Stats, then the stable
- // fallback used by the original fatigue model. `bodyweightKg` is already canonical; `bodyweight`
- // is accepted for callers that provide a display-unit value explicitly.
++// fallback. `bodyweightKg` is already canonical; `bodyweight` is accepted for callers that
++// provide a display-unit value explicitly.
+function bodyweightKgFor(workout, opts = {}, stampedLoadUnit) {
+ const stamped = numeric(workout?.bw) ?? numeric(workout?.bodyweight)
+ if (stamped !== null) {
+ return kgOf(stamped, unitOf(
+ { unit: workout?.bwUnit },
+ { unit: workout?.bodyweightUnit },
+ workout,
+ stampedLoadUnit && { unit: stampedLoadUnit },
+ opts,
+ ))
+ }
+ const canonical = numeric(opts.bodyweightKg)
+ if (canonical !== null) return Math.max(0, canonical)
+ const display = numeric(opts.bodyweight)
+ if (display !== null) return kgOf(display, opts.bodyweightUnit || opts.unit || opts.profileUnit)
+ return BODYWEIGHT_REF_LOAD
+}
+
+function bodyweightTarget(entry) {
+ const target = entry?.target
+ if (target && Object.prototype.hasOwnProperty.call(target, 'bodyweight')) return !!target.bodyweight
+ if (entry && Object.prototype.hasOwnProperty.call(entry, 'bodyweight')) return !!entry.bodyweight
+ return null
+}
+
+function hasUnitStamp(...records) {
+ return records.some(record => record && typeof record === 'object'
+ && ['unit', 'u', 'weightUnit', 'weight_unit', 'loadUnit'].some(key => Object.prototype.hasOwnProperty.call(record, key)
+ && record[key] !== undefined && record[key] !== null && String(record[key]).trim() !== ''))
+}
+
+function bodyweightConfigured(ex, entry, set, workout, opts = {}) {
+ const configured = bodyweightTarget(entry)
+ if (configured !== null) return configured
+ // Before target.bodyweight was persisted, a positive `w` on a catalogue bodyweight exercise
+ // already meant an explicitly entered load. Keep those rows compatible when no body-mass
+ // context is available; a stamped workout or a profile bodyweight makes the intended total-load
+ // semantics unambiguous even for old entries.
+ const added = kgOf(set?.w, unitOf(set, entry?.target, entry, workout, opts))
+ const hasBodyweightContext = numeric(workout?.bw) !== null
+ || numeric(workout?.bodyweight) !== null
+ || numeric(opts.bodyweightKg) !== null
+ || numeric(opts.bodyweight) !== null
+ || hasUnitStamp(set, entry?.target, entry, workout)
+ return ex?.eq === 'body weight' && (added === 0 || hasBodyweightContext)
+}
+
- function loadKgFor(ex, entry, set, workout, opts = {}) {
- const setUnit = unitOf(set, entry?.target, entry, workout, opts)
- const addedKg = kgOf(set?.w, setUnit)
- const loadUnit = hasUnitStamp(set, entry?.target, entry) ? setUnit : undefined
++// The load a row actually moved, in kg: its own `w` canonicalised from whatever unit is stamped
++// nearest, plus the body mass when the exercise is configured as bodyweight. `row` is the set
++// itself, one side of a side set, or a drop; whether the exercise counts body mass is decided by
++// the parent set so a drop never flips the semantics of its own row. Without the body mass a
++// weighted dip's back-off (+10 kg after +20 kg) would read as RIR 10 against a 20 kg "max".
++function loadKgFor(ex, entry, set, workout, opts = {}, row = set) {
++ const rowUnit = unitOf(row, set, entry?.target, entry, workout, opts)
++ const addedKg = kgOf(row?.w, rowUnit)
++ const loadUnit = hasUnitStamp(row, set, entry?.target, entry) ? rowUnit : undefined
+ return bodyweightConfigured(ex, entry, set, workout, opts)
+ ? bodyweightKgFor(workout, opts, loadUnit) + addedKg
+ : addedKg
}
- // Best Epley estimate inside one session. Keeping intensity context on the session makes a
- // scored stimulus independent of later imports/deletes; unlike an all-history maximum, a
- // 90-day-old CSV row cannot retroactively reweight today's sets.
- function session1RMs(workout, opts = {}) {
- const best = new Map()
+ /**
+ * How much of a hard set a proximity-to-failure reading is worth. Logged effort
+ * (`rir`/`rpe` via effort.js) always wins; otherwise the RIR is estimated against
+ * the exercise's 90-day rolling best (see `estimateSetRir`). At or near failure a
+ * set counts full, far from it no less than the floor: easy work still moves blood.
+ *
+ * @param {number|null} rir Reps in reserve, or null when intensity is unknown.
+ * @returns {number} Set weight in [0.3, 1].
+ */
+ export function rirWeightFor(rir) {
+ if (rir == null) return 1
+ if (rir <= HARD_RIR) return 1
+ if (rir >= 6) return FATIGUE_RIR_FLOOR_WEIGHT
+ return 1 - (1 - FATIGUE_RIR_FLOOR_WEIGHT) * (rir - HARD_RIR) / (6 - HARD_RIR)
+ }
+
+ /**
+ * Estimate a set's reps in reserve from a capacity anchor (Epley inverse, both in
+ * kg so mixed-unit histories anchor correctly). The anchor is the exercise's recent
+ * best 1RM estimate, so `80x8` against a 110 max reads ~RIR 3 while the same set
+ * against a 100 max reads failure. Returns null wherever an honest answer is
+ * impossible: no anchor, no load, no reps, or above the rep cap (where estimators
+ * diverge past 10%).
+ *
+ * @param {{w?: number, r?: number}} set A completed set with load and reps.
+ * @param {number|null} anchorKg Recent best 1RM estimate for the exercise, in kg.
+ * @returns {{rir: number, source: 'estimated'}|null} Clamped RIR in [0, 10].
+ */
+ export function estimateSetRir(set, anchorKg, unit) {
+ const w = numeric(set?.w)
+ const r = numeric(set?.r)
+ if (!(anchorKg > 0) || !(w > 0) || !(r >= 1) || r > REP_CAP) return null
+ const wKg = kgOf(w, unit ?? set?.unit)
+ if (!(wKg > 0)) return null
+ const maxReps = 30 * (anchorKg / wKg - 1)
+ const rir = Math.min(10, Math.max(0, maxReps - r))
+ return { rir, source: 'estimated' }
+ }
+
+ // One session's per-muscle stimulus in quality-weighted effective sets. Every
-// completed set counts (warm-ups included: mechanical work is mechanical work);
++// completed set counts (warm-ups included: mechanical work is mechanical work, but a
++// row flagged as warm-up without a logged effort is far from failure by definition and
++// costs the floor weight even when no anchor exists yet to estimate it from);
+ // drop-set drops count as extra sets; rest-pause `clusters` are NOT extra because
+ // the row's own set already totals every burst (see applyIntensifierPlan/history.js).
+ // Cardio/timed rows count as sets too. Each set is scaled by its RIR weight -
+ // logged effort first, Epley-inverse estimate against the anchor second, full
+ // credit when intensity is unknowable (rings, load-less imports). Anchors come
+ // from the 90-day window ending at this session, never from its future.
+ function sessionEffSets(workout, anchors, opts = {}) {
+ const sums = emptyMuscleMap(0)
+ const score = (row, set, entry, weights, requireDone = true) => {
+ if (requireDone && row?.done !== true) return
- const count = rirWeightFor(resolveSetRir(row, set, entry, workout, anchors, opts)?.rir)
++ const resolved = resolveSetRir(row, set, entry, workout, anchors, opts)
++ const count = resolved?.source !== 'logged' && isWarmupRow(set)
++ ? FATIGUE_RIR_FLOOR_WEIGHT
++ : rirWeightFor(resolved?.rir)
+ for (const [slug, weight] of Object.entries(weights)) {
+ if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) sums[slug] += count * weight
+ }
+ }
for (const entry of workout?.entries || []) {
const ex = exerciseFor(entry)
+ const weights = musclesOf(ex)
for (const set of entry.sets || []) {
- const load = loadKgFor(ex, entry, set, workout, opts)
- if (set?.done !== true || !(load > 0) || !(set.r > 0)) continue
- // Weighted blend of onerm's formulas (unrounded). Beyond the rep ceiling the ensemble
- // refuses to guess — that set then drops out of the session anchor, like any high-rep set.
- const est = set.r > WEIGHTED_REP_CAP ? null : weightedEstimate(load, set.r)
- if (!best.has(entry.id) || est > best.get(entry.id)) best.set(entry.id, est)
+ score(set, set, entry, weights)
+ // Drop-set drops carry their own load against the same anchor - extra work at
+ // a discount, never double-counted. Drops carry no done flag of their own;
+ // performed as part of a done set, they count unconditionally.
+ if (set?.done === true) for (const drop of dropsOf(set)) score(drop, set, entry, weights, false)
}
}
- return best
- }
-
- // Extra tonnage from a drop-set's drops, weighted the same way as the row's own main set — a
- // drop taken near failure counts the same as any other hard rep for fatigue purposes, it just
- // carries its own (usually lighter) load.
- //
- // A rest-pause row's `clusters` are NOT extra here: the row's own `r` already is the total reps
- // across every burst (see applyIntensifierPlan/history.js), so the main tonnage term below
- // already covers it — adding clusters on top would double-count the same reps.
- function extraTonnage(ex, entry, set, workout, oneRm, opts = {}) {
- const drops = dropsOf(set)
- if (!drops.length) return 0
- const isBwEx = bodyweightConfigured(ex, entry, set, workout, opts)
- const weigh = (load, reps) => {
- if (!(load > 0) || !(reps > 0)) return 0
- const raw = load * reps
- return isBwEx || !(oneRm > 0) ? raw : raw * Math.min(1, load / oneRm) ** 1.5
- }
- return drops.reduce((sum, d) => sum + weigh(loadKgFor(ex, entry, d, workout, opts), Number(d?.r) || 0), 0)
+ for (const slug of MUSCLES) sums[slug] = Math.min(sums[slug], FATIGUE_MAX_SETS_PER_SESSION)
+ return sums
}
- // Intensity-weighted tonnage for one completed set: load x reps x (load / exercise 1RM)^1.5.
- // The exponent saturates the "hard set" effect - a set at 90% of your 1RM counts ~0.81 of its
- // raw tonnage, one at 50% only ~0.35. Cardio, timed holds, and sets whose exercise has no
- // 1RM history stay unweighted (duration proxies, or intensity 1 for the first sessions).
- function setTonnage(ex, entry, set, workout, oneRm, opts = {}) {
- if (ex?.bp === 'cardio') {
- return Math.max(set?.min || 0, (set?.sec || 0) / 60) * CARDIO_TONNAGE_PER_MIN
-// Best Epley estimate per exercise inside one session, in kg. Session-local, so a
++// Best Epley estimate per exercise inside one session, in kg (body mass included for
++// bodyweight work, see loadKgFor). Epley on purpose, not onerm's weighted blend: the RIR
++// estimate inverts this same formula, so the set that set the anchor reads RIR 0. Session-local, so a
+ // 90-day-old import can never reweight today's anchor - only sessions inside the
+ // anchor window ending at the scored session contribute. Assistance work has no
+ // 1RM (the load is help received) and stays out, matching onerm.js.
+ function sessionBests(workout, opts = {}) {
+ const best = new Map()
- const consider = (row, set, entry, exId) => {
- if (row?.done !== true) return
- const sides = isSideSet(row) ? [row.sides.L, row.sides.R].filter(s => s?.done === true) : [row]
++ const consider = (ex, set, entry, exId) => {
++ if (set?.done !== true) return
++ const sides = isSideSet(set) ? [set.sides.L, set.sides.R].filter(s => s?.done === true) : [set]
+ for (const side of sides) {
- const est = estimate1RM(rowWkg(side, set, entry, workout, opts), numeric(side?.r))
++ const est = estimate1RM(loadKgFor(ex, entry, set, workout, opts, side), numeric(side?.r))
+ if (est !== null && (!best.has(exId) || est > best.get(exId))) best.set(exId, est)
+ }
}
- if (set?.sec != null && set?.r == null) {
- return (set.sec / 60) * CARDIO_TONNAGE_PER_MIN
+ for (const entry of workout?.entries || []) {
+ if (isAssisted(entry?.id ? { id: entry.id } : entry)) continue
- for (const set of entry.sets || []) consider(set, set, entry, entry.id)
++ const ex = exerciseFor(entry)
++ for (const set of entry.sets || []) consider(ex, set, entry, entry.id)
}
- const reps = set?.r || 1
- const load = loadKgFor(ex, entry, set, workout, opts)
- const raw = load * reps
- const extra = extraTonnage(ex, entry, set, workout, oneRm, opts)
- // A bodyweight target is already an external-load-normalised total (body mass + any added
- // load). It has no meaningful barbell-style 1RM intensity ratio in the legacy data model, so
- // retain the monotonic total-load stimulus instead of letting a newly created low 1RM shrink
- // a weighted bodyweight set below the unloaded version.
- if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw + extra
- if (!(oneRm > 0) || !(load > 0)) return raw + extra
- return raw * Math.min(1, load / oneRm) ** 1.5 + extra
+ return best
}
- // One session's per-muscle stimulus, calculated only from that session. A completed zero-load
- // set gets the set-equivalent fallback instead of disappearing from fatigue.
- function sessionTonnages(workout, opts = {}) {
- const sums = emptyMuscleMap(0)
- const oneRms = session1RMs(workout, opts)
- for (const entry of workout?.entries || []) {
- const ex = exerciseFor(entry)
- const weights = musclesOf(ex)
- for (const set of entry.sets || []) {
- if (set?.done !== true) continue
- const measured = setTonnage(ex, entry, set, workout, oneRms.get(entry.id), opts)
- const tonnage = Number.isFinite(measured) && measured > 0 ? measured : ZERO_LOAD_SET_STIMULUS
- for (const [slug, weight] of Object.entries(weights)) {
- if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) sums[slug] += tonnage * weight
+ /**
+ * Capacity anchors per workout: the 90-day rolling best 1RM estimate per exercise,
+ * in kg, keyed by the workout object. One chronological pass - later sessions never
+ * leak into earlier anchors. Powers both fatigue scoring and estimated-effort stats;
+ * unrated histories without any estimable set simply get empty maps (full credit).
+ *
+ * @param {Array<object>} workouts Workout history.
- * @param {{unit?: string}} opts Profile unit for unit-stamped loads.
++ * @param {{unit?: string, bodyweightKg?: number}} opts Profile unit for unstamped loads and the
++ * profile bodyweight for bodyweight exercises (the same options fatigueOf takes).
+ * @returns {Map<object, Map<string, number>>} Workout -> exercise id -> anchor.
+ */
+ export function anchorsByWorkout(workouts, opts = {}) {
+ const ordered = (workouts || [])
+ .map((workout, index) => ({ workout, index, timestamp: workoutTimestamp(workout) }))
+ .filter(item => Number.isFinite(item.timestamp))
+ .sort((a, b) => a.timestamp - b.timestamp || a.index - b.index)
+ const bests = ordered.map(item => sessionBests(item.workout, opts))
+ const out = new Map()
+ ordered.forEach((item, i) => {
+ const anchors = new Map()
+ for (let j = 0; j <= i; j += 1) {
+ if (ordered[j].timestamp <= item.timestamp - FATIGUE_RIR_WINDOW_MS) continue
+ for (const [exId, est] of bests[j]) {
+ if (!anchors.has(exId) || est > anchors.get(exId)) anchors.set(exId, est)
}
}
- }
- return sums
+ out.set(item.workout, anchors)
+ })
+ return out
}
- // Build normalised stimuli in workout order. The reference seen by a session is strictly the
- // reference left by earlier in-window sessions; the session cannot dilute its own score. The
- // downward-only EWMA is deliberate: removing any earlier workout can only raise a later
- // denominator (and removes its own positive stimulus), so deletion can never increase fatigue.
- // Rebuilding from the bounded scan also makes imports older than the scan exactly irrelevant.
+ /**
+ * One set's RIR with its provenance: logged effort first, Epley-inverse estimate
+ * against the workout's anchors second, null when intensity is unknowable. The same
+ * precedence fatigue scoring uses, so stats and the map never disagree about a set.
+ */
+ export function resolveSetRir(row, set, entry, workout, anchors, opts = {}) {
+ const logged = rirOf(row)
+ if (logged != null) return { rir: logged, source: 'logged' }
- const unit = unitOf(row, set, entry?.target, entry, workout, opts)
- return estimateSetRir(row, anchors?.get(entry?.id), unit)
++ const anchor = anchors?.get(entry?.id)
++ if (!(anchor > 0)) return null
++ // Same load rule as the anchor: canonical kg, body mass included for bodyweight work.
++ const loadKg = loadKgFor(exerciseFor(entry), entry, set || row, workout, opts, row)
++ return estimateSetRir({ w: loadKg, r: row?.r }, anchor, 'kg')
+ }
+
+ // Build normalised stimuli in workout order. Each session is scored from its own
+ // quality-weighted sets against the fixed full-session unit, multiplied by the
+ // acute:chronic gain left by strictly earlier exposure: a session that doubles the
+ // recent weekly rate scores up to twice, a deload down to half, maintenance
+ // reproduces phase-1 values. Stimuli stay non-negative and every window is
+ // causal, so rest still never increases fatigue and out-of-scan imports stay
+ // irrelevant - but deleting a mid-history workout can now re-score later sessions
+ // through their anchors and gains (adaptation is history-dependent by design).
+ // Deleting the latest session still never increases anything: earlier windows end
+ // before it.
function fatigueStimuli(workouts, current, opts = {}) {
- const cutoff = current - FATIGUE_SCAN_MS
- const ordered = (workouts || [])
+ const scanCutoff = current - FATIGUE_SCAN_MS
+ // The pool covers every window a scored session can read: its anchor reaches 90d
+ // back from its own timestamp, and the oldest scored session is 30d old, so the
+ // pool spans 120d. Narrower would let sessions age out of anchors as `now' advances
+ // and fatigue would rise during rest.
+ const poolCutoff = current - (FATIGUE_SCAN_MS + FATIGUE_RIR_WINDOW_MS)
+ const pool = (workouts || [])
.map((workout, index) => ({ workout, index, timestamp: workoutTimestamp(workout) }))
- .filter(item => Number.isFinite(item.timestamp) && item.timestamp > cutoff)
+ .filter(item => Number.isFinite(item.timestamp) && item.timestamp > poolCutoff)
.sort((a, b) => a.timestamp - b.timestamp || a.index - b.index)
- const references = emptyMuscleMap(FATIGUE_REF_VOLUME)
+ const scored = pool.filter(item => item.timestamp > scanCutoff)
+ const byWorkout = anchorsByWorkout(pool.map(item => item.workout), opts)
+ const effSets = pool.map(item => sessionEffSets(item.workout, byWorkout.get(item.workout), opts))
const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []]))
- for (const { workout, timestamp } of ordered) {
- const sums = sessionTonnages(workout, opts)
+ for (const item of scored) {
+ const i = pool.indexOf(item)
+ const acute = emptyMuscleMap(0)
+ const chronic = emptyMuscleMap(0)
+ for (let j = 0; j <= i; j += 1) {
+ const age = item.timestamp - pool[j].timestamp
+ if (age < 0 || age > FATIGUE_CHRONIC_WINDOW_MS) continue
+ for (const slug of MUSCLES) {
+ if (age <= FATIGUE_ACUTE_WINDOW_MS) acute[slug] += effSets[j][slug]
+ chronic[slug] += effSets[j][slug]
+ }
+ }
for (const slug of MUSCLES) {
- const stimulus = sums[slug]
+ const stimulus = effSets[i][slug]
if (!(stimulus > 0)) continue
- byMuscle[slug].push({ slug, timestamp, stimulus: stimulus / references[slug] })
- const ewma = references[slug] + (stimulus - references[slug]) / FATIGUE_MIN_SESSIONS
- references[slug] = Math.min(references[slug], ewma)
+ const gain = Math.min(
+ FATIGUE_RATIO_MAX,
+ Math.max(
+ FATIGUE_RATIO_MIN,
+ (acute[slug] + FATIGUE_NOVICE_WEEKLY_SETS) / (chronic[slug] / 4 + FATIGUE_NOVICE_WEEKLY_SETS),
+ ),
+ )
+ byMuscle[slug].push({ slug, timestamp: item.timestamp, stimulus: stimulus / FATIGUE_SETS_PER_UNIT * gain })
}
}
return byMuscle
@@@ -291,18 -351,22 +428,24 @@@ function fatigueValue(events, now, slug
/**
* Calculate current per-muscle fatigue from completed sets in the recent window.
*
-- * Stimulus time is `workout.start`, falling back to the workout date `workout.d`. Each completed
- * set contributes the exercise's `musclesOf` weights; the scan is bounded to FATIGUE_SCAN_MS for
- * performance, not semantics. Stimuli are accumulated chronologically with a 36-hour half-life,
- * decayed to `now`, and normalised with the saturation curve 1 - exp(-v). Each session is scored
- * against a causal, downward-only EWMA left by strictly earlier in-window sessions. Session-local
- * intensity estimates and the causal reference make out-of-window imports irrelevant, while
- * deleting a workout can only remove stimulus and/or raise later references.
++ * Stimulus time is history.js `workoutAt`: `workout.start`, falling back to the workout date
++ * `workout.d` read as local noon. Each completed
+ * set contributes the exercise's `musclesOf` weights in quality-weighted effective-set units
+ * (logged RIR first, Epley-inverse estimate against the 90-day rolling best second, full
+ * credit when intensity is unknowable); a full session of ~8 hard sets scores 1.0, scaled by
+ * the acute:chronic gain (recent weekly rate vs 28-day exposure, novice prior of 4 sets/week,
+ * clamped 0.5-2). The scan is bounded to FATIGUE_SCAN_MS for performance, not semantics.
+ * Stimuli accumulate chronologically with a per-muscle half-life (24h arms/small,
+ * 30h torso, 48h legs/lower-back), decayed to `now`, and normalised with the saturation curve
+ * 1 - exp(-v). Every window is causal, so rest never increases fatigue and out-of-window
+ * imports stay irrelevant; deleting the latest session never increases anything, while
+ * deleting mid-history may re-score later sessions through their anchors and gains.
* The result always contains every drawable muscle slug.
*
* @param {Array<object>} workouts Workout history with `start`/`d` and entry set arrays.
* @param {number} now Current time in milliseconds; injected to keep this function deterministic.
-- * @param {{unit?: string}} options Reserved profile-level options; unit is supplied at the UI boundary.
++ * @param {{unit?: string, bodyweightKg?: number}} options Profile unit for unstamped loads and the
++ * profile bodyweight (kg) for bodyweight exercises; both are supplied at the UI boundary.
* @returns {Record<string, number>} Fatigue values keyed by every drawable muscle slug.
*/
export function fatigueOf(workouts, now, opts = {}) {
diff --cc frontend/src/lib/recovery.test.js
index a684a0972,cbf501135..13cfff804
--- a/frontend/src/lib/recovery.test.js
+++ b/frontend/src/lib/recovery.test.js
@@@ -1,12 -1,15 +1,15 @@@
import { describe, expect, it } from 'vitest'
import {
- FATIGUE_HALF_LIFE_MS,
- FATIGUE_MIN_SESSIONS,
- FATIGUE_REF_VOLUME,
- FATIGUE_ACUTE_WINDOW_MS,
++ BODYWEIGHT_REF_LOAD,
+ FATIGUE_CHRONIC_WINDOW_MS,
+ FATIGUE_MAX_SETS_PER_SESSION,
+ FATIGUE_NOVICE_WEEKLY_SETS,
+ FATIGUE_RATIO_MAX,
+ FATIGUE_RATIO_MIN,
+ FATIGUE_RIR_FLOOR_WEIGHT,
FATIGUE_SCAN_MS,
+ FATIGUE_SETS_PER_UNIT,
FATIGUE_STATES,
- BODYWEIGHT_REF_LOAD,
- CARDIO_TONNAGE_PER_MIN,
STRENGTH_FLOOR,
STRENGTH_FULL_MS,
STRENGTH_HALF_LIFE_MS,
@@@ -19,7 -27,6 +27,7 @@@
import { EXDB, registerCustom } from './exercises.js'
import { MUSCLES, exerciseMuscleSnapshot, musclesOf } from './muscles.js'
import { fatigueStateOf } from './recovery-view.js'
- import { weightedEstimate } from './onerm.js'
++import { estimate1RM } from './onerm.js'
const HOUR = 60 * 60 * 1000
const DAY = 24 * HOUR
@@@ -246,6 -231,21 +235,35 @@@ describe('fatigueOf and strengthOf', (
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
expect(detrainedMuscles(workouts, NOW)).toEqual(MUSCLES)
})
+
++ it('gives explicit zero snapshot weights no fatigue or retained-strength stimulus', () => {
++ const workouts = [workoutAt('deleted-zero-mapped', NOW, [{ done: true, w: 80, r: 8 }])]
++ workouts[0].entries[0].muscleSnapshot = {
++ n: 'Zero mapped', muscleWeights: { chest: 1, biceps: 0 },
++ }
++
++ const fatigue = fatigueOf(workouts, NOW)
++ const strength = strengthOf(workouts, NOW)
++ expect(fatigue.chest).toBeGreaterThan(0)
++ expect(fatigue.biceps).toBe(0)
++ expect(strength.chest).toBe(1)
++ expect(strength.biceps).toBe(STRENGTH_FLOOR)
++ })
++
+ it('discounts ramp-up rows through the RIR anchor instead of charging full sets', () => {
+ const ramped = workoutAt(SINGLE.id, NOW, [
+ { done: true, w: 40, r: 8 },
+ { done: true, w: 80, r: 8 },
+ ])
+ const plain = doneWorkoutAt(SINGLE.id, NOW, 2)
+ const rampedValue = fatigueOf([ramped], NOW)[SINGLE_SLUG]
+ const plainValue = fatigueOf([plain], NOW)[SINGLE_SLUG]
+ // The 80 kg top set anchors at ~101 kg, so the 40 kg row reads RIR 10 and costs
+ // the floor weight: 1 + 0.3 effective sets against 2 full ones.
+ expect(rampedValue).toBeCloseTo(expectedSets(1 + FATIGUE_RIR_FLOOR_WEIGHT, 1, SINGLE_SLUG), 10)
+ expect(rampedValue).toBeLessThan(plainValue)
+ expect(rampedValue).toBeGreaterThan(fatigueOf([doneWorkoutAt(SINGLE.id, NOW)], NOW)[SINGLE_SLUG])
+ })
})
describe('fatigue state boundaries', () => {
@@@ -350,31 -360,94 +378,102 @@@ describe('causal session scoring', () =
loadedWorkout(NOW, 120, 10),
]
const before = fatigueOf(workouts, NOW)
+ const after = fatigueOf(workouts.slice(0, -1), NOW)
+ for (const slug of MUSCLES) expect(after[slug]).toBeLessThanOrEqual(before[slug] + Number.EPSILON)
+ })
+
+ it('documents that deleting an old PR session can raise current fatigue', () => {
+ // A 100x5 PR ten days ago anchors today's 80x8 at RIR ~6 (discounted); without it
+ // the same session anchors at its own best (RIR 0, full). The old session itself
+ // has decayed to ~nothing, so removing history reads as harder training now.
+ const pr = loadedWorkout(NOW - 10 * DAY, 100, 1)
+ pr.entries[0].sets[0].r = 5
+ const today = loadedWorkout(NOW, 80, 1)
+ const withHistory = fatigueOf([pr, today], NOW).chest
+ const withoutHistory = fatigueOf([today], NOW).chest
+ expect(withHistory).toBeGreaterThan(0)
+ expect(withoutHistory).toBeGreaterThan(withHistory)
+ })
+
+ it('rates a back-off session below repeating the full load', () => {
+ // Same athlete, same exercise: 4 work sets + 4 half-weight back-offs costs less
+ // than 8 work sets. The 100x8 top set anchors at ~127 kg, so each 50x8 back-off
+ // reads RIR 10 and costs the floor weight - while absolute loads across sessions
+ // stay comparable only through anchors and gains, never through raw tonnage.
+ const backOff = workoutAt(SINGLE.id, NOW, [
+ ...Array.from({ length: 4 }, () => ({ done: true, w: 100, r: 8 })),
+ ...Array.from({ length: 4 }, () => ({ done: true, w: 50, r: 8 })),
+ ])
+ const repeated = doneWorkoutAt(SINGLE.id, NOW, 8)
+ // doneWorkoutAt uses w:80 for every set, so each set is its entry's best.
+ const fullLoad = workoutAt(SINGLE.id, NOW, Array.from({ length: 8 }, () => ({ done: true, w: 100, r: 8 })))
- workouts.forEach((_, deletedIndex) => {
- const after = fatigueOf(workouts.filter((__, index) => index !== deletedIndex), NOW)
- for (const slug of MUSCLES) expect(after[slug]).toBeLessThanOrEqual(before[slug] + Number.EPSILON)
- })
+ expect(fatigueOf([backOff], NOW)[SINGLE_SLUG]).toBeLessThan(fatigueOf([fullLoad], NOW)[SINGLE_SLUG])
+ expect(fatigueOf([repeated], NOW)[SINGLE_SLUG]).toBeCloseTo(fatigueOf([fullLoad], NOW)[SINGLE_SLUG], 10)
})
+ it('rates a lighter current week below repeating the established load', () => {
+ const prior = [-21, -14, -7].map(days => loadedWorkout(NOW + days * DAY, 100))
+ const lighter = fatigueOf([...prior, loadedWorkout(NOW, 50)], NOW).chest
+ const repeated = fatigueOf([...prior, loadedWorkout(NOW, 100)], NOW).chest
+
+ expect(lighter).toBeLessThan(repeated)
+ })
+
- it('uses the last registered bodyweight for bodyweight exercises', () => {
- const bwEx = EXDB.find(ex => ex.eq === 'body weight' && drawable(ex))
- if (!bwEx) throw new Error('test requires a bodyweight exercise fixture')
- const slug = Object.keys(musclesOf(bwEx))[0]
- const workout = { d: new Date(NOW).toISOString(), start: NOW, entries: [{ id: bwEx.id, sets: [{ done: true, r: 10 }] }] }
- const at80 = fatigueOf([workout], NOW, { bodyweightKg: 80 })[slug]
- const at90 = fatigueOf([workout], NOW, { bodyweightKg: 90 })[slug]
- expect(at80).toBeCloseTo(1 - Math.exp(-800 / FATIGUE_REF_VOLUME), 10)
- expect(at90).toBeCloseTo(1 - Math.exp(-900 / FATIGUE_REF_VOLUME), 10)
- expect(at90).toBeGreaterThan(at80)
+ it('scores identical structures at different absolute loads equally', () => {
+ // Session-local intensity is relative by design (see above): 8x50 and 8x100 with
+ // no RIR data are both "8 hard sets". kg/lb equivalence falls out for free.
+ const light = loadedWorkout(NOW, 50, 8)
+ const heavy = loadedWorkout(NOW, 100, 8)
+ expect(fatigueOf([light], NOW).chest).toBeCloseTo(fatigueOf([heavy], NOW).chest, 10)
+ })
+ })
+
+ describe('RIR quality weighting', () => {
+ it('maps RIR to set weights: full at failure, floor when far', () => {
+ expect(rirWeightFor(null)).toBe(1)
+ expect(rirWeightFor(0)).toBe(1)
+ expect(rirWeightFor(3)).toBe(1)
+ expect(rirWeightFor(4)).toBeCloseTo(1 - (1 - FATIGUE_RIR_FLOOR_WEIGHT) / 3, 10)
+ expect(rirWeightFor(6)).toBe(FATIGUE_RIR_FLOOR_WEIGHT)
+ expect(rirWeightFor(10)).toBe(FATIGUE_RIR_FLOOR_WEIGHT)
+ })
+
+ it('estimates RIR against the anchor via Epley inverse', () => {
+ // 80x8 against a 110 max: 30*(110/80-1)-8 = 3.25
+ expect(estimateSetRir({ w: 80, r: 8 }, 110)).toMatchObject({ rir: 3.25, source: 'estimated' })
+ // The same set against its own estimate reads failure, clamped at zero.
+ expect(estimateSetRir({ w: 80, r: 8 }, 80 * (1 + 8 / 30)).rir).toBe(0)
+ // Far above capacity still clamps: a 40x8 warm-up against 101 reads RIR 10.
+ expect(estimateSetRir({ w: 40, r: 8 }, 80 * (1 + 8 / 30)).rir).toBe(10)
+ // Mixed units anchor in kg: 176.37 lb ~= 80 kg reads ~failure against an 80 kg max.
+ expect(estimateSetRir({ w: 176.3696, r: 8, unit: 'lb' }, 80 * (1 + 8 / 30)).rir).toBeCloseTo(0, 4)
+ // Dishonest inputs stay null: no anchor, no load, no reps, above the rep cap.
+ expect(estimateSetRir({ w: 80, r: 8 }, null)).toBeNull()
+ expect(estimateSetRir({ w: 0, r: 8 }, 100)).toBeNull()
+ expect(estimateSetRir({ w: 80 }, 100)).toBeNull()
+ expect(estimateSetRir({ w: 50, r: 20 }, 100)).toBeNull()
+ })
+
+ it('prefers a logged RIR over any estimate', () => {
+ // A grinder logged at RIR 5 counts 0.53 even with a low anchor that would estimate 0.
+ const logged = workoutAt(SINGLE.id, NOW, [{ done: true, w: 80, r: 8, rir: 5 }])
+ expect(fatigueOf([logged], NOW)[SINGLE_SLUG]).toBeCloseTo(
+ expectedSets(rirWeightFor(5), 1, SINGLE_SLUG), 10,
+ )
+ })
+
+ it('scores a deload week below the work weeks that anchor it', () => {
+ // Three weeks of 8x100 anchor at ~127 kg; the 8x50 deload then reads RIR 10
+ // (floor weight) instead of 8 full sets - the case session-local intensity
+ // could never see, since every deload set is its own session's best.
+ const work = [-21, -14, -7].map(days => workoutAt(
+ SINGLE.id, NOW + days * DAY, Array.from({ length: 8 }, () => ({ done: true, w: 100, r: 8 })),
+ ))
+ const deload = workoutAt(SINGLE.id, NOW, Array.from({ length: 8 }, () => ({ done: true, w: 50, r: 8 })))
+ const repeat = workoutAt(SINGLE.id, NOW, Array.from({ length: 8 }, () => ({ done: true, w: 100, r: 8 })))
+ expect(fatigueOf([...work, deload], NOW)[SINGLE_SLUG])
+ .toBeLessThan(fatigueOf([...work, repeat], NOW)[SINGLE_SLUG])
})
})
@@@ -460,17 -526,16 +552,30 @@@ describe('warm-up flag in strength and
const fatigue = fatigueOf(workouts, now)
expect(fatigue.chest).toBeGreaterThan(0)
})
++
++ it('charges a flagged warm-up the floor weight even before any anchor exists', () => {
++ // First session ever: no anchor, so an unflagged row would count full. The flag says
++ // the row was a ramp, so it costs the floor, like an estimated far-from-failure set.
++ const warm = workoutAt(SINGLE.id, NOW, [
++ { done: true, warmup: true, w: 0, r: 10 },
++ { done: true, w: 80, r: 8 },
++ ])
++ expect(fatigueOf([warm], NOW)[SINGLE_SLUG])
++ .toBeCloseTo(expectedSets(1 + FATIGUE_RIR_FLOOR_WEIGHT, 1, SINGLE_SLUG), 10)
++ // A logged effort on the warm-up row still wins over the flag.
++ const rated = workoutAt(SINGLE.id, NOW, [{ done: true, warmup: true, w: 0, r: 10, rir: 2 }])
++ expect(fatigueOf([rated], NOW)[SINGLE_SLUG]).toBeCloseTo(expectedSets(1, 1, SINGLE_SLUG), 10)
++ })
})
- describe('drop-set drops add fatigue tonnage on top of the main set', () => {
- // Same within-session weighted-mean anchor setTonnage derives from the row's own w/r (8 reps),
- // so a drop is weighted against the same 1RM as the main set.
- const oneRm = ANCHOR_80x8
+ describe('drop-set drops add discounted fatigue sets on top of the main set', () => {
+ // The drop carries its own (lighter) load against the 90-day anchor: a 60 kg drop
+ // after an 80 kg top set reads RIR 10 and costs the floor weight on top of the full set.
+ const dropShare = FATIGUE_RIR_FLOOR_WEIGHT
- it('a drop-set drop adds its own intensity-weighted tonnage', () => {
+ it('a drop-set drop adds its own RIR-weighted sets', () => {
const dropRow = { done: true, type: 'dropset', w: 80, r: 8, drops: [{ w: 60, r: 6 }] }
- const dropTonnage = 60 * 6 * Math.min(1, 60 / oneRm) ** 1.5
- const expected = expectedFatigue([{ stimulus: V + dropTonnage }])
+ const expected = expectedSets(1 + dropShare, 1, SINGLE_SLUG)
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [dropRow])], NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 8)
// strictly more than the plain 80x8 set alone — the drop is real extra work
@@@ -503,13 -568,13 +608,13 @@@ describe('a rest-pause row\'s clusters
})
})
- describe('canonical loads and configured bodyweight', () => {
+ describe('loads are relative, units are irrelevant', () => {
const loaded = EXDB.find(ex => {
const weights = musclesOf(ex)
- return ex.bp !== 'cardio' && ex.eq !== 'body weight'
+ return drawable(ex) && ex.eq !== 'body weight'
&& Object.keys(weights).length === 1 && Object.values(weights)[0] === 1
})
- const bodyweight = EXDB.find(ex => ex.bp !== 'cardio' && ex.eq === 'body weight')
+ const bodyweight = EXDB.find(ex => drawable(ex) && ex.eq === 'body weight')
if (!loaded || !bodyweight) throw new Error('recovery tests require loaded and bodyweight fixtures')
const loadedSlug = Object.keys(musclesOf(loaded))[0]
const bodyweightSlug = Object.keys(musclesOf(bodyweight))[0]
@@@ -561,9 -628,9 +668,46 @@@
const added = { ...unloaded, entries: [{ ...unloaded.entries[0], sets: [loadedSet] }] }
expect(fatigueOf([added], NOW, { unit: 'kg' })[bodyweightSlug])
- .toBeGreaterThan(fatigueOf([unloaded], NOW, { unit: 'kg' })[bodyweightSlug])
+ .toBeCloseTo(fatigueOf([unloaded], NOW, { unit: 'kg' })[bodyweightSlug], 10)
+ })
+
++ // Relative intensity needs the load the body actually moved: for bodyweight work that is body
++ // mass plus the added load, never the added load alone.
++ it('estimates a weighted bodyweight back-off against the body-mass-inclusive anchor', () => {
++ const weight = musclesOf(bodyweight)[bodyweightSlug]
++ const workout = {
++ d: new Date(NOW).toISOString(), start: NOW, unit: 'kg', bw: 80,
++ entries: [{ id: bodyweight.id, sets: [{ done: true, w: 20, r: 8 }, { done: true, w: 10, r: 8 }] }],
++ }
++ // 100 kg x 8 anchors the session; the 90 kg back-off is RIR ~4.2, not RIR 10 against a
++ // "20 kg max" that would only see the plates.
++ const anchor = estimate1RM(100, 8)
++ const backOffRir = 30 * (anchor / 90 - 1) - 8
++ expect(backOffRir).toBeGreaterThan(4)
++ expect(backOffRir).toBeLessThan(5)
++ expect(fatigueOf([workout], NOW, { unit: 'kg' })[bodyweightSlug])
++ .toBeCloseTo(expectedSets(1 + rirWeightFor(backOffRir), weight, bodyweightSlug), 10)
++ expect(rirWeightFor(backOffRir)).toBeGreaterThan(FATIGUE_RIR_FLOOR_WEIGHT)
++ })
++
++ it('anchors bodyweight work on the stamped, then profile, then reference body mass', () => {
++ const at = (bw) => ({
++ d: new Date(NOW).toISOString(), start: NOW, unit: 'kg', bw,
++ entries: [{ id: bodyweight.id, sets: [{ done: true, w: 0, r: 10 }] }],
++ })
++ const stamped = at(90)
++ const unstamped = at(undefined)
++ expect(anchorsByWorkout([stamped], { bodyweightKg: 70 }).get(stamped).get(bodyweight.id))
++ .toBeCloseTo(estimate1RM(90, 10), 6)
++ expect(anchorsByWorkout([unstamped], { bodyweightKg: 70 }).get(unstamped).get(bodyweight.id))
++ .toBeCloseTo(estimate1RM(70, 10), 6)
++ expect(anchorsByWorkout([unstamped]).get(unstamped).get(bodyweight.id))
++ .toBeCloseTo(estimate1RM(BODYWEIGHT_REF_LOAD, 10), 6)
++ // A pound-stamped bodyweight is canonicalised like any other load.
++ const lb = { ...at(176.3696), unit: 'lb' }
++ expect(anchorsByWorkout([lb]).get(lb).get(bodyweight.id)).toBeCloseTo(estimate1RM(80, 10), 1)
+ })
+
it('lets explicitly configured custom bodyweight work reset strength', () => {
const id = 'recovery-custom-bodyweight'
registerCustom([{ id, n: 'Custom bodyweight', bp: 'chest', tg: 'chest', eq: 'custom', sm: [] }])
diff --cc frontend/src/views/Stats.jsx
index 8a3c3a744,35715d3f3..8a83be88d
--- a/frontend/src/views/Stats.jsx
+++ b/frontend/src/views/Stats.jsx
@@@ -15,13 -15,13 +15,14 @@@ import { loadOfWeeklyPlan, loadOfWorkou
import { fatigueOf, strengthOf, STRENGTH_FLOOR, LB_TO_KG } from '../lib/recovery.js'
import { strengthExerciseRowsForMuscle } from '../lib/strength-exercises.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
-import { e1rmSeries, best1RM } from '../lib/onerm.js'
+import { e1rmSeries, best1RM, formulaOf } from '../lib/onerm.js'
import { maxRepsSeries } from '../lib/pyramid.js'
+import { perSetSessions, perSetLines, dropOffSet } from '../lib/per-set.js'
import {
- hasEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks,
- effortHistogram, isHardSet, HARD_RIR
+ hasEffort, hasEstimableEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks,
+ effortHistogram, isHardSet, HARD_RIR, MIN_RATED
} from '../lib/effort.js'
+ import { anchorsByWorkout, resolveSetRir } from '../lib/recovery.js'
import { Button, Segmented, SelectRow } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { isWarmupRow } from '../lib/workout-model.js'
@@@ -103,6 -100,6 +104,16 @@@ function fatigueLabel(value)
return t(state === 'ready' ? 'Ready' : state === 'recovering' ? 'Recovering' : 'Fatigued')
}
++// The user's own last registered bodyweight, in kg: the body-mass part of a bodyweight
++// exercise's load for fatigue and for estimated effort, so both read the same set the same way.
++function profileBodyweightKg(S) {
++ const entries = S.bodyweight || []
++ if (!entries.length) return null
++ const last = entries.slice().sort((a, b) => String(a.d).localeCompare(String(b.d))).at(-1)
++ if (!last || !(last.w > 0)) return null
++ return S.unit === 'lb' ? last.w * LB_TO_KG : last.w
++}
++
function MuscleBalance({ S }) {
const [view, setView] = useState('balance')
const [win, setWin] = useState(7)
@@@ -113,14 -110,14 +124,7 @@@
const now = useNow()
const lang = getLang()
const workouts = S.workouts
-- // The user's own last registered bodyweight drives bodyweight-exercise tonnage.
-- const bodyweightKg = useMemo(() => {
-- const entries = S.bodyweight || []
-- if (!entries.length) return null
-- const last = entries.slice().sort((a, b) => String(a.d).localeCompare(String(b.d))).at(-1)
-- if (!last || !(last.w > 0)) return null
-- return S.unit === 'lb' ? last.w * LB_TO_KG : last.w
-- }, [S.bodyweight, S.unit])
++ const bodyweightKg = useMemo(() => profileBodyweightKg(S), [S.bodyweight, S.unit])
const fatigue = useMemo(() => fatigueOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit])
const strength = useMemo(() => strengthOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit])
const muscleExercises = useMemo(() => (sel ? strengthExerciseRowsForMuscle(S, now, sel) : []), [S, now, sel, lang])
@@@ -303,9 -300,21 +307,23 @@@ function EffortCard({ S })
const [win, setWin] = useState(90)
const kind = displayScale(S)
const hd = scaleName(kind)
- const sum = effortSummary(S, win)
- const weeks = effortWeeks(S, win)
- const hist = effortHistogram(S, win)
+ const logged = effortSummary(S, win)
+ // Thin or missing ratings fall back to estimates (same precedence fatigue scoring
+ // uses), so imported histories get an effort card too. Well-rated windows keep
+ // their logged numbers untouched - estimates never dilute a real average.
+ const blend = logged.rated < MIN_RATED
++ // Same options as the fatigue map (unit + profile bodyweight), so a bodyweight set is
++ // estimated against the same body-mass-inclusive anchor in both places.
++ const opts = useMemo(() => ({ unit: S.unit, bodyweightKg: profileBodyweightKg(S) }), [S.unit, S.bodyweight])
+ const anchors = useMemo(
- () => (blend ? anchorsByWorkout(S.workouts, { unit: S.unit }) : new Map()),
- [blend, S.workouts, S.unit],
++ () => (blend ? anchorsByWorkout(S.workouts, opts) : new Map()),
++ [blend, S.workouts, opts],
+ )
- const opts = useMemo(() => ({ unit: S.unit }), [S.unit])
+ const resolve = (s, w, e) => resolveSetRir(s, s, e, w, anchors.get(w), opts)
+ const sum = blend ? effortSummary(S, win, resolve) : logged
+ const weeks = blend ? effortWeeks(S, win, resolve) : effortWeeks(S, win)
+ const hist = blend ? effortHistogram(S, win, resolve) : effortHistogram(S, win)
+ const estimated = blend && sum.est > 0
const maxBin = Math.max(1, ...hist.map(b => b.n))
// The week's set count rides along in the tooltip, because the pair is the reading:
// volume up with effort up is fatigue piling up, volume up with effort flat is adaptation.
@@@ -615,19 -596,7 +635,19 @@@ export default function Stats()
<div className="muted small" style={{ marginTop: 4 }}>{t('See which lift is holding back the rest.')}</div></div>
<Button size="sm" variant="tinted" trailingIcon="chevronRight" style={{ flexShrink: 0 }} onClick={() => nav('/structural-balance')}>{t('Open')}</Button>
</div>}
+ {workouts.length > 0 && <div className="card row between" style={{ alignItems: 'center', gap: 12 }}>
+ <div style={{ minWidth: 0 }}><h2 style={{ margin: 0 }}>{t('Progress photos')}</h2>
+ <div className="muted small" style={{ marginTop: 4 }}>{t('Every photo you kept with a workout, lined up by date. Plus a before/after slider.')}</div></div>
+ <Button size="sm" variant="tinted" trailingIcon="chevronRight" style={{ flexShrink: 0 }} onClick={() => nav('/progress-photos')}>{t('Open')}</Button>
+ </div>}
+ <div className="card row between" style={{ alignItems: 'center', gap: 12 }}>
+ <div style={{ minWidth: 0 }}><h2 style={{ margin: 0 }}>{t('Body measurements')}</h2>
+ <div className="muted small" style={{ marginTop: 4 }}>{(S.measurements || []).length
+ ? t('Last check-in {0}', fmtDate(S.measurements[S.measurements.length - 1].d, true))
+ : t('Waist, arms, body fat and anything else you measure, each with its own curve.')}</div></div>
+ <Button size="sm" variant="tinted" trailingIcon="chevronRight" style={{ flexShrink: 0 }} onClick={() => nav('/measurements')}>{t('Open')}</Button>
+ </div>
- {hasEffort(S) && <EffortCard S={S} />}
+ {(hasEffort(S) || hasEstimableEffort(S)) && <EffortCard S={S} />}
<div className="cols">
<div className="card">