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.

Change fatigue calculation formula phase1

Сергей Горбатенкоb486341804b8
diff --git a/docs/dev/FATIGUE_SETS_MODEL.md b/docs/dev/FATIGUE_SETS_MODEL.md
new file mode 100644
index 000000000..f66fe430c
--- /dev/null
+++ b/docs/dev/FATIGUE_SETS_MODEL.md
@@ -0,0 +1,109 @@
+# Fatigue model v2: sets-based, per-muscle half-life (rationale for PR)
+
+## Problem (observed on real history: 1707 workouts, ~daily Jefit splits)
+
+`fatigueOf()` in `frontend/src/lib/recovery.js` reports near-permanent whole-body
+`fatigued` for high-frequency split training. Computed on the reporter's state
+(`state-ygurXGuvcyWHwpO9.json`, 23 sessions / 30d): quadriceps/calves/hamstring
+`1.000`, chest `0.666` and triceps `0.612` even though upper body was last hit
+1.9 days ago and legs 1.2 days ago. A rotating upper/lower split can never show
+green.
+
+## Root causes in the current model
+
+1. **Tonnage stimulus overweights heavy compounds.** `setTonnage()` scores
+ `load x reps x (load/1RM)^1.5`, so a `250x7` leg press counts ~50x a `5x12`
+ fly. Hypertrophy dose-response tracks **hard sets near failure**, not tonnage
+ (Schoenfeld et al.; review https://pmc.ncbi.nlm.nih.gov/articles/PMC8884877).
+2. **One half-life (36h) for every muscle.** 10RM reproducibility data shows
+ lower body recovers slower than upper: at 24h squat −12.6% vs bench −9.2%,
+ at 36h −6.6% vs −3.0%, full recovery by 48-72h
+ (https://pmc.ncbi.nlm.nih.gov/articles/PMC6719818). A single 36h constant
+ keeps small upper-body muscles red too long.
+3. **Saturation `1-exp(-v)` compresses the top.** Daily training drives raw
+ stimulus to 5-13, everything above ~3 maps to >0.95. "Legs yesterday" and
+ "chest 2 days ago, light dumbbells" become indistinguishable.
+4. **Downward-only reference never adapts up** (`recovery.js:264-265`). A
+ trained lifter (repeated-bout effect: faster recovery, strength back in
+ ~3d vs −40% in untrained) scores ever-more fatigue at constant training.
+ MPS in trained lifters is lower and shorter (peak ~5h, tail 24-48h; Damas /
+ Phillips: https://pmc.ncbi.nlm.nih.gov/articles/PMC5023708,
+ https://pmc.ncbi.nlm.nih.gov/articles/PMC5401959).
+
+Framework notes: Banister 1975 fitness-fatigue (`performance = fitness - fatigue`,
+different time constants; https://www.trainingpeaks.com/learn/articles/the-science-of-the-performance-manager)
+justifies per-muscle + systemic components. ACWR (acute 7d / chronic 28d, sweet
+spot 0.8-1.3; https://pmc.ncbi.nlm.nih.gov/articles/PMC8138569) is used here
+only as a preparedness normalisation idea, not an injury predictor — the latter
+claim is disputed (https://www.globalperformanceinsights.com/post/has-the-acute-chronic-workload-ratio-been-debunked).
+
+## Proposed change (this PR: phase 1, monotonicity-preserving)
+
+- **Stimulus in effective hard sets**, not tonnage:
+ `stimulus_m = min(cappedSets_m, 12) / 8`. One full session (~8 hard sets on a
+ muscle, the per-session growth plateau per Weightology/RP Strength) = 1.0 raw
+ unit. Secondary movers count 0.4 (existing `musclesOf` weights). Warm-ups
+ still count (mechanical work), rest-pause clusters don't (already covered by
+ the row total), drop-set drops count as extra sets. Cardio/timed rows count
+ as sets (duration proxy), not tonnage.
+- **Session-local relative intensity per set**: `(load/entryBest)^1.5`, unit-free
+ (kg/lb histories score identically), zero-load sets count full (assume hard when
+ unknown). Ramp-up rows therefore cost a fraction of a set instead of a full one.
+ Absolute loads across sessions are intentionally invisible (no RIR data — a lighter
+ session may still be the harder one); cross-session load sensitivity belongs to
+ the chronic denominator (phase 2).
+- **Per-muscle half-life**: arms/deltoids/forearm 24h, chest/upper-back/traps
+ 30h, glutes/quads/hams/adductors/calves/lower-back 48h, core/small 24h.
+ Calibrated so 8 hard sets on legs -> F0 ~0.63 (fatigued), ready in ~4d;
+ 5 sets chest -> F0 ~0.46, ready in ~2d (matches the 10RM 48-72h recovery).
+- **Keep** `1-exp(-v)` scale and `0.25/0.5` thresholds (`recovery-view.js`), so
+ no UI/locale changes. Keep chronological accumulation, 30-day scan bound,
+ future-date clamp, deleted-snapshot handling, and `strengthOf()` untouched.
+- **Preserved invariants** (checked by `scripts/fatigue-monotonic-probe.mjs`):
+ rest never increases fatigue; deleting a workout never increases fatigue;
+ out-of-scan imports are irrelevant. Stimuli stay non-negative and causal, so
+ the probe passes unchanged.
+- **Deliberately deferred to phase 2**: chronic-load (EWMA28) normalisation for
+ the repeated-bout effect. Any history-derived denominator breaks the
+ deletion-monotonicity invariant (deleting an old session lowers the chronic
+ base and inflates later scores), which needs maintainer discussion first.
+
+## Calibration on the reporter's data
+
+Measured on `state-ygurXGuvcyWHwpO9.json` (1707 workouts, 23/30d, upper/lower
+Jefit rotation; upper last hit 1.9d ago, legs 1.2d ago), `fatigueOf(workouts, now)`:
+
+| Muscle | Before | After | State after |
+|---|---|---|---|
+| quadriceps / hamstring / calves / gluteal | 1.000 / 1.000 / 1.000 / 0.951 | 0.559 / 0.542 / 0.619 / 0.660 | fatigued (heavy legs yesterday — correct) |
+| adductors | 0.982 | 0.471 | recovering |
+| chest | 0.666 | 0.251 | recovering (borderline ready) |
+| deltoids / upper-back / triceps / biceps | 0.764 / 0.571 / 0.612 / 0.494 | 0.171 / 0.158 / 0.125 / 0.083 | ready |
+| abs / serratus / hip-flexors / tibialis | ~0 | 0.000 | ready (untrained lately) |
+
+The split now diverges: legs red after leg day, upper green — the complaint is
+fixed while 3x/week full-body demo histories barely move.
+
+## Files touched
+
+- `frontend/src/lib/recovery.js` — new stimulus + per-muscle HL.
+- `frontend/src/lib/recovery.test.js`, `recovery-view.test.js`,
+ `src/views/Stats.recovery.test.jsx` — re-pinned expectations (same
+ structure, sets-based numbers).
+- `frontend/scripts/fatigue-monotonic-probe.mjs` — unchanged (still passes).
+
+## Validation
+
+- `cd frontend && npm test` — recovery suites green (54); full suite: only 3
+ pre-existing failures, each reproduced on the clean tree via `git stash`:
+ `import-hevy` (TZ-sensitive, same +07 class as the MCP case),
+ `CoachChat.demo-failure` (timer), `useStore.media` (flaky waitFor — fails
+ ~25% on clean tree too, no import path to `recovery.js`).
+- `npm run test:fatigue-probe` — PASS unchanged (108000 time + 14076 deletion
+ comparisons).
+- `node scripts/check-locales.mjs` — clean (no UI strings changed).
+- `cd api && npm test` — 471 pass / 2 fail, identical on clean tree
+ (password-hash timing tests, unrelated).
+- `cd mcp && TZ=UTC npm test` — 63/63 (bare `npm test` fails on +07 machines
+ for the pre-existing demoSeed/TZ reason, untouched by this change).
+- Manual: Stats -> Fatigue map on a daily-split profile shows rotation.
diff --git a/docs/dev/SET_TYPES.md b/docs/dev/SET_TYPES.md
index 8a981acdb..7570a7e4e 100644
--- a/docs/dev/SET_TYPES.md
+++ b/docs/dev/SET_TYPES.md
@@ -156,9 +156,9 @@ reading one row:
- `workoutVolume` (`history.js`) — adds `extraVolumeOf(s)` on top of `w×r` per row. Drop-set
drops count; rest-pause clusters don't (see above — they're already inside the row's own `r`).
-- `setTonnage` (`recovery.js`) — same split: `extraTonnage(...)` prices a drop-set's drops with
- the same intensity-weighted formula (`load × reps × min(1, load/1RM)^1.5`) as the main set, and
- is a no-op for rest-pause for the same double-counting reason.
+- `sessionSets` (`recovery.js`) — same split: each drop-set drop counts as an extra
+ set at its own session-local relative intensity (`(load/best)^1.5`), and
+ rest-pause is a no-op for the same double-counting reason.
- `applyPrescription` (`progression.js`) — when a policy grows the set count (bodyweight double
progression, issue #33), the newly appended row keeps the seed's `type` (that's the exercise's
plan) but never its already-logged `drops`/`clusters` (that's specific work the new row never
diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js
index 5412f42ca..3c2c005ce 100644
--- a/frontend/src/lib/recovery.js
+++ b/frontend/src/lib/recovery.js
@@ -2,23 +2,40 @@ import { EXIDX } from './exercises.js'
import { MUSCLES, musclesOf } from './muscles.js'
import { isWarmupRow, dropsOf } from './workout-model.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.
+// 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
+// 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
@@ -67,12 +84,6 @@ function exerciseFor(entry) {
return EXIDX[entry?.id] || entry
}
-// Epley one-rep-max estimate, matching onerm.js (REP_CAP included so high-rep sets do not
-// inflate the estimate). Used only to express a set's intensity relative to the lifter's own
-// capacity - the same formula the app already shows for estimated 1RM.
-const REP_CAP = 12
-const epley1RM = (load, reps) => load * (1 + Math.min(reps || 1, REP_CAP) / 30)
-
export const LB_TO_KG = 0.45359237
function numeric(value) {
@@ -81,188 +92,72 @@ function numeric(value) {
return Number.isFinite(n) ? n : null
}
-function isPounds(unit) {
- return /^(?:lb|lbs|pound|pounds)$/i.test(String(unit ?? '').trim())
-}
-
-function unitOf(...records) {
- for (const record of records) {
- if (!record || typeof record !== 'object') continue
- for (const key of ['unit', 'u', 'weightUnit', 'weight_unit', 'loadUnit']) {
- if (record[key] !== undefined && record[key] !== null && String(record[key]).trim() !== '') return record[key]
- }
- }
- return 'kg'
-}
-
-function kgOf(value, unit) {
- const n = numeric(value)
- if (n === null) return 0
- return Math.max(0, n) * (isPounds(unit) ? LB_TO_KG : 1)
-}
-
-// 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.
-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
- 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()
- for (const entry of workout?.entries || []) {
- const ex = exerciseFor(entry)
- for (const set of entry.sets || []) {
- const load = loadKgFor(ex, entry, set, workout, opts)
- if (set?.done !== true || !(load > 0) || !(set.r > 0)) continue
- const est = epley1RM(load, set.r)
- if (!best.has(entry.id) || est > best.get(entry.id)) best.set(entry.id, est)
- }
- }
- 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)
-}
-
-// 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
- }
- if (set?.sec != null && set?.r == null) {
- return (set.sec / 60) * CARDIO_TONNAGE_PER_MIN
- }
- 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
-}
-
-// 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 = {}) {
+// One session's per-muscle stimulus in effective hard sets, calculated only from
+// that session. Every completed set counts (warm-ups included: mechanical work is
+// mechanical work); 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.
+// Within an entry each set is scaled by its load relative to that entry's own
+// best in the session: a ramp-up row at half the top weight costs ~(0.5)^1.5 of
+// a set, so warm-ups and back-offs no longer fatigue like work sets. The ratio
+// is unit-free, so kg/lb histories score identically, and zero-load sets (rings,
+// imports without loads) count full - assuming hard when intensity is unknown.
+// Absolute loads across sessions are deliberately NOT compared here: without
+// proximity-to-failure data a lighter session may still be the harder one, and
+// cross-session load sensitivity belongs to the chronic denominator (phase 2).
+function sessionSets(workout) {
const sums = emptyMuscleMap(0)
- const oneRms = session1RMs(workout, opts)
for (const entry of workout?.entries || []) {
const ex = exerciseFor(entry)
const weights = musclesOf(ex)
+ const loads = (entry.sets || []).map(set => Math.max(0, numeric(set?.w) ?? 0))
+ const best = Math.max(0, ...loads)
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
+ const load = Math.max(0, numeric(set?.w) ?? 0)
+ const intensity = best > 0 && load > 0 ? (Math.min(1, load / best)) ** 1.5 : 1
+ const count = intensity
for (const [slug, weight] of Object.entries(weights)) {
- if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) sums[slug] += tonnage * weight
+ if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) sums[slug] += count * weight
+ }
+ }
+ // Drop-set drops carry their own (usually lighter) load, scored against the
+ // same entry best - extra work at a discount, never double-counted.
+ for (const set of entry.sets || []) {
+ if (set?.done !== true) continue
+ for (const drop of dropsOf(set)) {
+ const load = Math.max(0, numeric(drop?.w) ?? 0)
+ const intensity = best > 0 && load > 0 ? (Math.min(1, load / best)) ** 1.5 : 1
+ for (const [slug, weight] of Object.entries(weights)) {
+ if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) sums[slug] += intensity * weight
+ }
}
}
}
+ for (const slug of MUSCLES) sums[slug] = Math.min(sums[slug], FATIGUE_MAX_SETS_PER_SESSION)
return sums
}
-// 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.
-function fatigueStimuli(workouts, current, opts = {}) {
+// Build normalised stimuli in workout order. Each session is scored only from
+// its own sets against the fixed full-session unit, so a session can never
+// dilute its own score and stimuli stay non-negative and causal: removing any
+// workout can only remove stimulus, so deletion can never increase fatigue.
+// Rebuilding from the bounded scan also makes imports older than the scan
+// exactly irrelevant.
+function fatigueStimuli(workouts, current) {
const cutoff = current - FATIGUE_SCAN_MS
const ordered = (workouts || [])
.map((workout, index) => ({ workout, index, timestamp: workoutTimestamp(workout) }))
.filter(item => Number.isFinite(item.timestamp) && item.timestamp > cutoff)
.sort((a, b) => a.timestamp - b.timestamp || a.index - b.index)
- const references = emptyMuscleMap(FATIGUE_REF_VOLUME)
const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []]))
for (const { workout, timestamp } of ordered) {
- const sums = sessionTonnages(workout, opts)
+ const sums = sessionSets(workout)
for (const slug of MUSCLES) {
const stimulus = sums[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)
+ byMuscle[slug].push({ slug, timestamp, stimulus: stimulus / FATIGUE_SETS_PER_UNIT })
}
}
return byMuscle
@@ -270,20 +165,21 @@ function fatigueStimuli(workouts, current, opts = {}) {
const MUSCLES_BY_SLUG = Object.fromEntries(MUSCLES.map(slug => [slug, true]))
-function fatigueValue(events, now) {
+function fatigueValue(events, now, slug) {
if (!events.length) return 0
+ const halfLife = fatigueHalfLifeOf(slug)
events.sort((a, b) => a.timestamp - b.timestamp)
let value = 0
let lastTimestamp = events[0].timestamp
for (const event of events) {
- value *= halfLifeDecay(event.timestamp - lastTimestamp, FATIGUE_HALF_LIFE_MS)
+ value *= halfLifeDecay(event.timestamp - lastTimestamp, halfLife)
value += event.stimulus
lastTimestamp = event.timestamp
}
- value *= halfLifeDecay(Math.max(0, now - lastTimestamp), FATIGUE_HALF_LIFE_MS)
- // Normalise the accumulated stimulus to a saturating fatigue level: more volume starts
- // higher but never pins, and the value fades asymptotically - no window-edge cliff.
+ value *= halfLifeDecay(Math.max(0, now - lastTimestamp), halfLife)
+ // Normalise the accumulated stimulus to a saturating fatigue level: more sets start
+ // higher but never pin, and the value fades asymptotically - no window-edge cliff.
return 1 - Math.exp(-value)
}
@@ -291,12 +187,12 @@ function fatigueValue(events, now) {
* 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.
+ * set contributes the exercise's `musclesOf` weights in effective-set units (a full session of
+ * ~8 hard sets scores 1.0); 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). Each session is scored only from its own sets, so out-of-window imports are
+ * irrelevant and deleting a workout can only remove stimulus.
* The result always contains every drawable muscle slug.
*
* @param {Array<object>} workouts Workout history with `start`/`d` and entry set arrays.
@@ -308,8 +204,8 @@ export function fatigueOf(workouts, now, opts = {}) {
const current = Number(now)
const result = emptyMuscleMap(0)
if (!Number.isFinite(current)) return result
- const byMuscle = fatigueStimuli(workouts, current, opts)
- for (const slug of MUSCLES) result[slug] = fatigueValue(byMuscle[slug], current)
+ const byMuscle = fatigueStimuli(workouts, current)
+ for (const slug of MUSCLES) result[slug] = fatigueValue(byMuscle[slug], current, slug)
return result
}
diff --git a/frontend/src/lib/recovery.test.js b/frontend/src/lib/recovery.test.js
index 1c7ca21b0..e61d72b4f 100644
--- a/frontend/src/lib/recovery.test.js
+++ b/frontend/src/lib/recovery.test.js
@@ -1,17 +1,15 @@
import { describe, expect, it } from 'vitest'
import {
- FATIGUE_HALF_LIFE_MS,
- FATIGUE_MIN_SESSIONS,
- FATIGUE_REF_VOLUME,
+ FATIGUE_MAX_SETS_PER_SESSION,
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,
detrainedMuscles,
fatiguedMuscles,
+ fatigueHalfLifeOf,
fatigueOf,
halfLifeDecay,
strengthOf,
@@ -47,8 +45,8 @@ const workoutAt = (id, start, sets = [{ done: true }]) => ({
start,
entries: [{ id, sets: sets.map(set => ({ ...set })) }],
})
-const V = 640 * (30 / 38) ** 1.5 // intensity-weighted tonnage of one 80x8 fixture set (its own Epley estimate implies intensity 30/38)
-
+// One completed set at the entry's own best load scores exactly 1 effective set;
+// a full session of FATIGUE_SETS_PER_UNIT such sets is the 1.0 raw unit.
const doneWorkoutAt = (id, start, count = 1) =>
workoutAt(id, start, Array.from({ length: count }, () => ({ done: true, w: 80, r: 8 })))
const zeroFatigue = () => Object.fromEntries(MUSCLES.map(slug => [slug, 0]))
@@ -56,33 +54,40 @@ const floorStrength = () => Object.fromEntries(MUSCLES.map(slug => [slug, STRENG
// Numeric fatigue remains the math API; the UI boundary selector is imported from production.
const stableFloat = value => Number(value.toFixed(12))
-const referenceAfter = (reference, stimulus) => Math.min(
- reference,
- reference + (stimulus - reference) / FATIGUE_MIN_SESSIONS,
-)
-const expectedFatigue = sessions => {
- let reference = FATIGUE_REF_VOLUME
+// Expected saturated fatigue for plain same-load sessions: sets are counted at full
+// intensity (every set is its entry's best), normalised by the full-session unit,
+// decayed per muscle, saturated with 1 - exp(-v).
+const expectedFatigue = (sessions, slug = SINGLE_SLUG) => {
+ const halfLife = fatigueHalfLifeOf(slug)
let normalised = 0
- for (const { stimulus, age = 0 } of sessions) {
- normalised += stimulus / reference * halfLifeDecay(age, FATIGUE_HALF_LIFE_MS)
- reference = referenceAfter(reference, stimulus)
+ for (const { sets, weight = 1, age = 0 } of sessions) {
+ normalised += sets * weight / FATIGUE_SETS_PER_UNIT * halfLifeDecay(age, halfLife)
}
return 1 - Math.exp(-normalised)
}
describe('recovery constants', () => {
it('exports the pinned windows, half-lives, floor, and state labels', () => {
- expect(FATIGUE_REF_VOLUME).toBe(2000)
+ expect(FATIGUE_SETS_PER_UNIT).toBe(8)
+ expect(FATIGUE_MAX_SETS_PER_SESSION).toBe(12)
expect(FATIGUE_SCAN_MS).toBe(30 * DAY)
- expect(FATIGUE_HALF_LIFE_MS).toBe(36 * HOUR)
- expect(BODYWEIGHT_REF_LOAD).toBe(75)
- expect(CARDIO_TONNAGE_PER_MIN).toBe(50)
expect(STRENGTH_FULL_MS).toBe(14 * DAY)
expect(STRENGTH_HALF_LIFE_MS).toBe(28 * DAY)
expect(STRENGTH_FLOOR).toBe(0.5)
expect(FATIGUE_STATES).toEqual({ READY: 'ready', RECOVERING: 'recovering', FATIGUED: 'fatigued' })
- expect(halfLifeDecay(FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS)).toBe(0.5)
+ expect(halfLifeDecay(DAY, DAY)).toBe(0.5)
+ })
+
+ it('recovers small upper-body muscles faster than legs and lower back', () => {
+ expect(fatigueHalfLifeOf('biceps')).toBe(24 * HOUR)
+ expect(fatigueHalfLifeOf('deltoids')).toBe(24 * HOUR)
+ expect(fatigueHalfLifeOf('chest')).toBe(30 * HOUR)
+ expect(fatigueHalfLifeOf('upper-back')).toBe(30 * HOUR)
+ expect(fatigueHalfLifeOf('quadriceps')).toBe(48 * HOUR)
+ expect(fatigueHalfLifeOf('hamstring')).toBe(48 * HOUR)
+ expect(fatigueHalfLifeOf('lower-back')).toBe(48 * HOUR)
+ expect(fatigueHalfLifeOf('not-a-muscle')).toBe(30 * HOUR)
})
})
@@ -109,23 +114,22 @@ describe('fatigueOf and strengthOf', () => {
for (const slug of MUSCLES) {
const weight = WEIGHTED_WEIGHTS[slug] || 0
- expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-V * weight / FATIGUE_REF_VOLUME), 10)
+ expect(fatigue[slug]).toBeCloseTo(expectedFatigue([{ sets: 1, weight }], slug), 10)
expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR)
}
- // one set (80 x 8) never crosses the fatigued threshold on the saturating curve
+ // one set (whatever the load) never crosses the fatigued threshold
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
- // pure volume: one high-rep set at medium weight registers real tonnage (weighted by
- // its intensity - its own Epley estimate with the 12-rep cap is 50 x 40/30 = 70 kg)
+ // set count, not reps or load, drives fatigue: a 50-rep grinder scores exactly
+ // like the plain 80x8 set - one set is one set.
const highRep = [doneWorkoutAt(SINGLE.id, NOW, 1)]
highRep[0].entries[0].sets[0].w = 50
highRep[0].entries[0].sets[0].r = 50
- const weighted = 2500 * (50 / (50 * (1 + 12 / 30))) ** 1.5
expect(fatigueOf(highRep, NOW)[SINGLE_SLUG]).toBeCloseTo(
- 1 - Math.exp(-weighted / FATIGUE_REF_VOLUME),
+ fatigueOf([doneWorkoutAt(SINGLE.id, NOW)], NOW)[SINGLE_SLUG],
10,
)
- expect(fatigueOf(highRep, NOW)[SINGLE_SLUG]).toBeGreaterThan(0.5)
+ expect(fatigueOf(highRep, NOW)[SINGLE_SLUG]).toBeLessThan(0.25)
})
it('uses a deleted exercise snapshot for the same bounded primary and secondary fatigue', () => {
@@ -164,17 +168,18 @@ describe('fatigueOf and strengthOf', () => {
expect(strength[untouchedSlug]).toBe(STRENGTH_FLOOR)
})
- it('raises starting fatigue with volume, never pins, and fades without a cliff', () => {
+ it('raises starting fatigue with sets, never pins, and fades without a cliff', () => {
const at0 = count => fatigueOf([doneWorkoutAt(SINGLE.id, NOW, count)], NOW)[SINGLE_SLUG]
- expect(at0(1)).toBeCloseTo(1 - Math.exp(-V / FATIGUE_REF_VOLUME), 10)
- expect(at0(5)).toBeCloseTo(1 - Math.exp(-5 * V / FATIGUE_REF_VOLUME), 10)
- expect(at0(12)).toBeCloseTo(1 - Math.exp(-12 * V / FATIGUE_REF_VOLUME), 10)
+ expect(at0(1)).toBeCloseTo(expectedFatigue([{ sets: 1 }]), 10)
+ expect(at0(5)).toBeCloseTo(expectedFatigue([{ sets: 5 }]), 10)
+ expect(at0(12)).toBeCloseTo(expectedFatigue([{ sets: 12 }]), 10)
expect(at0(12)).toBeGreaterThan(at0(5))
expect(at0(5)).toBeGreaterThan(at0(1))
expect(at0(12)).toBeLessThan(1)
// one half-life later the gradient is still visible at any volume
- const later = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS, 12)], NOW)[SINGLE_SLUG]
- expect(later).toBeCloseTo(1 - Math.exp(-6 * V / FATIGUE_REF_VOLUME), 10)
+ const halfLife = fatigueHalfLifeOf(SINGLE_SLUG)
+ const later = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - halfLife, 12)], NOW)[SINGLE_SLUG]
+ expect(later).toBeCloseTo(expectedFatigue([{ sets: 12, age: halfLife }]), 10)
expect(later).toBeLessThan(at0(12))
// no cliff: 72h keeps decaying instead of snapping to zero
const old = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)], NOW)[SINGLE_SLUG]
@@ -182,29 +187,21 @@ describe('fatigueOf and strengthOf', () => {
expect(old).toBeLessThan(0.25)
})
- it('decays each weighted stimulus exactly at 36 hours and by sqrt-half at 18 hours', () => {
- for (const age of [FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS / 2]) {
+ it('decays each weighted stimulus at its own muscle half-life', () => {
+ const halfLife = fatigueHalfLifeOf(WEIGHTED_PRIMARY_SLUG)
+ for (const age of [halfLife, halfLife / 2]) {
const fatigue = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)
- const expectedDecay = 0.5 ** (age / FATIGUE_HALF_LIFE_MS)
for (const [slug, weight] of Object.entries(WEIGHTED_WEIGHTS)) {
- expect(fatigue[slug]).toBeCloseTo(
- 1 - Math.exp(-V * weight * expectedDecay / FATIGUE_REF_VOLUME),
- 10,
- )
- }
- if (age === FATIGUE_HALF_LIFE_MS) {
- expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(
- 1 - Math.exp(-V * 0.5 / FATIGUE_REF_VOLUME),
- 10,
- )
- }
- if (age === FATIGUE_HALF_LIFE_MS / 2) {
- expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(
- 1 - Math.exp(-V * (0.5 ** 0.5) / FATIGUE_REF_VOLUME),
- 10,
- )
+ expect(fatigue[slug]).toBeCloseTo(expectedFatigue([{ sets: 1, weight, age }], slug), 10)
}
}
+ // a secondary mover fades on its own clock, not the primary's
+ const secondaryHl = fatigueHalfLifeOf(SECONDARY_SLUG)
+ const aged = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - secondaryHl)], NOW)
+ expect(aged[SECONDARY_SLUG]).toBeCloseTo(
+ expectedFatigue([{ sets: 1, weight: WEIGHTED_WEIGHTS[SECONDARY_SLUG], age: secondaryHl }], SECONDARY_SLUG),
+ 10,
+ )
})
it('fades a 72-hour-old set below the ready threshold instead of hard-cutting', () => {
@@ -223,17 +220,32 @@ describe('fatigueOf and strengthOf', () => {
expect(fatiguedMuscles(workouts, NOW)).toEqual([])
expect(detrainedMuscles(workouts, NOW)).toEqual(MUSCLES)
})
+
+ it('discounts ramp-up rows against the entry best 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 40 kg row costs (40/80)^1.5 of a set on top of the full 80 kg set
+ expect(rampedValue).toBeCloseTo(1 - Math.exp(-(1 + 0.5 ** 1.5) / FATIGUE_SETS_PER_UNIT), 10)
+ expect(rampedValue).toBeLessThan(plainValue)
+ expect(rampedValue).toBeGreaterThan(fatigueOf([doneWorkoutAt(SINGLE.id, NOW)], NOW)[SINGLE_SLUG])
+ })
})
describe('fatigue state boundaries', () => {
- // Inverse of the saturation curve: raw stimulus needed to land exactly on a target level.
- const rawAt = target => -FATIGUE_REF_VOLUME * Math.log(1 - target)
+ // Inverse of the saturation curve: normalised stimulus needed for a target level.
+ const rawAt = target => -Math.log(1 - target)
it('classifies exactly .25 as recovering and .2499 as ready', () => {
+ const halfLife = fatigueHalfLifeOf(SECONDARY_SLUG)
const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG]
- const sets = 4
+ const sets = 8
const valueAt = target => {
- const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * V * weight / rawAt(target))
+ const age = halfLife * Math.log2(sets * weight / FATIGUE_SETS_PER_UNIT / rawAt(target))
const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age, sets)], NOW)[SECONDARY_SLUG]
expect(value).toBeCloseTo(target, 10)
return stableFloat(value)
@@ -244,16 +256,17 @@ describe('fatigue state boundaries', () => {
})
it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => {
- const sets = 4
+ const halfLife = fatigueHalfLifeOf(SINGLE_SLUG)
+ const sets = 8
const atHalf = [doneWorkoutAt(
SINGLE.id,
- NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets * V / rawAt(0.4999)),
+ NOW - halfLife * Math.log2(sets / FATIGUE_SETS_PER_UNIT / rawAt(0.4999)),
sets,
)]
const aboveHalf = [
doneWorkoutAt(
SINGLE.id,
- NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets * V / rawAt(0.5001)),
+ NOW - halfLife * Math.log2(sets / FATIGUE_SETS_PER_UNIT / rawAt(0.5001)),
sets,
),
]
@@ -270,27 +283,24 @@ describe('fatigue state boundaries', () => {
})
-describe('causal fatigue reference', () => {
+describe('causal session scoring', () => {
const loadedWorkout = (start, weight, count = 8) => workoutAt(
'1254',
start,
Array.from({ length: count }, () => ({ done: true, w: weight, r: 8 })),
)
- it('scores each session against only the reference left by strictly earlier sessions', () => {
+ it('adds each session on top of decayed earlier ones without any shared reference', () => {
+ const halfLife = fatigueHalfLifeOf(SINGLE_SLUG)
const old = doneWorkoutAt(SINGLE.id, NOW - DAY)
const today = doneWorkoutAt(SINGLE.id, NOW)
- const earlierReference = referenceAfter(FATIGUE_REF_VOLUME, V)
- const expected = 1 - Math.exp(-(
- V / FATIGUE_REF_VOLUME * halfLifeDecay(DAY, FATIGUE_HALF_LIFE_MS)
- + V / earlierReference
- ))
+ const expected = expectedFatigue([
+ { sets: 1, age: DAY },
+ { sets: 1, age: 0 },
+ ])
expect(fatigueOf([old, today], NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
- expect(fatigueOf([today], NOW)[SINGLE_SLUG]).toBeCloseTo(
- 1 - Math.exp(-V / FATIGUE_REF_VOLUME),
- 10,
- )
+ expect(fatigueOf([today], NOW)[SINGLE_SLUG]).toBeCloseTo(expectedFatigue([{ sets: 1 }]), 10)
})
it('keeps the 8x100x8 ten-day reproduction non-increasing as sessions leave the scan', () => {
@@ -308,7 +318,7 @@ describe('causal fatigue reference', () => {
}
})
- it('ignores imports older than the scan, including their heavier 1RM data', () => {
+ it('ignores imports older than the scan', () => {
const today = loadedWorkout(NOW, 100, 5)
const baseline = fatigueOf([today], NOW).chest
const heavyImport = loadedWorkout(NOW - 90 * DAY, 140, 10)
@@ -334,24 +344,30 @@ describe('causal fatigue reference', () => {
})
})
- 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
+ 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. Absolute loads across sessions are intentionally invisible
+ // (session-local intensity is relative by design - without RIR data a lighter
+ // session may still be the harder one); the cross-session load sensitivity
+ // belongs to the chronic denominator tracked in docs/dev/FATIGUE_SETS_MODEL.md.
+ 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 })))
- expect(lighter).toBeLessThan(repeated)
+ 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('uses the last registered bodyweight for bodyweight exercises', () => {
- const bwEx = EXDB.find(ex => ex.eq === 'body weight' && ex.bp !== 'cardio')
- 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)
})
})
@@ -379,30 +395,18 @@ describe('strengthOf', () => {
describe('accumulation and purity', () => {
it('matches the saturated sum of independently decayed stimuli in chronological order', () => {
+ const halfLife = fatigueHalfLifeOf(SINGLE_SLUG)
const ages = [64 * HOUR, 40 * HOUR]
const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age))
- const raw = ages.reduce(
- (sum, age) => sum + V * 0.5 ** (age / FATIGUE_HALF_LIFE_MS),
- 0,
- )
- const firstAge = ages[0]
- const secondAge = ages[1]
- const expected = expectedFatigue([
- { stimulus: V, age: firstAge },
- { stimulus: V, age: secondAge },
- ])
+ const expected = expectedFatigue(ages.map(age => ({ sets: 1, age })))
- expect(raw).toBeLessThan(FATIGUE_REF_VOLUME)
expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
})
it('saturates without pinning and returns identical results without mutating inputs or sharing state', () => {
const saturated = [doneWorkoutAt(SINGLE.id, NOW, 2)]
- expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(
- 1 - Math.exp(-2 * V / FATIGUE_REF_VOLUME),
- 10,
- )
+ expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(expectedFatigue([{ sets: 2 }]), 10)
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1)
const workouts = [
@@ -439,15 +443,14 @@ describe('warm-up flag in strength and fatigue', () => {
})
})
-describe('drop-set drops add fatigue tonnage on top of the main set', () => {
- // Same within-session Epley baseline setTonnage derives from the row's own w/r (8 reps,
- // under REP_CAP), so a drop is weighted against the same 1RM as the main set.
- const oneRm = 80 * (1 + 8 / 30)
+describe('drop-set drops add fatigue sets on top of the main set', () => {
+ // The drop carries its own (lighter) load, scored against the entry best: a 60 kg
+ // drop after an 80 kg top set costs (60/80)^1.5 of a set on top of the full set.
+ const dropShare = (60 / 80) ** 1.5
- it('a drop-set drop adds its own intensity-weighted tonnage', () => {
+ it('a drop-set drop adds its own relative-intensity 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 = expectedFatigue([{ sets: 1 + dropShare }])
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
@@ -458,13 +461,13 @@ describe('drop-set drops add fatigue tonnage on top of the main set', () => {
it('leaves fatigue unchanged for a straight set with no drops', () => {
const plain = { done: true, w: 80, r: 8 }
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [plain])], NOW)[SINGLE_SLUG])
- .toBeCloseTo(expectedFatigue([{ stimulus: V }]), 8)
+ .toBeCloseTo(expectedFatigue([{ sets: 1 }]), 8)
})
})
-describe('a rest-pause row\'s clusters add no extra fatigue tonnage', () => {
+describe('a rest-pause row\'s clusters add no extra fatigue sets', () => {
// Its own r is already the total across every burst (see applyIntensifierPlan/history.js),
- // so setTonnage's main w x r term already covers all of it — clusters are a breakdown only.
+ // so the main set term already covers all of it — clusters are a breakdown only.
it('matches a plain set of the same w/r exactly, regardless of how the clusters break it down', () => {
const burstRow = { done: true, type: 'restpause', w: 80, r: 8, clusters: [{ r: 4, restSec: 15 }] }
const plainRow = { done: true, w: 80, r: 8 }
@@ -480,7 +483,7 @@ describe('a rest-pause row\'s clusters add no extra fatigue tonnage', () => {
})
})
-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'
@@ -503,7 +506,7 @@ describe('canonical loads and configured bodyweight', () => {
.toBeCloseTo(fatigueOf([kg], NOW, { unit: 'kg' })[loadedSlug], 6)
})
- it('normalizes mixed stamped units before computing the causal reference volume', () => {
+ it('normalizes mixed stamped units before scoring', () => {
const starts = [NOW - 3 * DAY, NOW - 2 * DAY, NOW - DAY, NOW]
const kg = starts.map(start => stampedWorkout({ id: loaded.id, start, unit: 'kg', weight: 80 }))
const mixed = starts.map((start, i) => stampedWorkout({
@@ -514,7 +517,7 @@ describe('canonical loads and configured bodyweight', () => {
.toBeCloseTo(fatigueOf(kg, NOW, { unit: 'kg' })[loadedSlug], 6)
})
- it('treats an unstamped legacy history as being in the profile unit', () => {
+ it('treats an unstamped legacy history as one hard set', () => {
const kg = stampedWorkout({ id: loaded.id, start: NOW, unit: 'kg', weight: 80 })
const legacyLb = { ...kg, unit: undefined, entries: [{ ...kg.entries[0], sets: [{ done: true, w: 176.3696, r: 8 }] }] }
@@ -522,7 +525,9 @@ describe('canonical loads and configured bodyweight', () => {
.toBeCloseTo(fatigueOf([kg], NOW, { unit: 'kg' })[loadedSlug], 6)
})
- it('uses configured bodyweight for a non-catalogue bodyweight target', () => {
+ it('scores heavier and lighter bodyweight sessions by their relative intensity', () => {
+ // Both sessions are single-set histories, so each set is its entry's best and
+ // scores full: relative intensity is session-local by design (body mass cancels).
const workout = stampedWorkout({
id: loaded.id, start: NOW, unit: 'kg', weight: 0,
target: { bodyweight: true }, bw: 80,
@@ -532,13 +537,13 @@ describe('canonical loads and configured bodyweight', () => {
expect(strengthOf([workout], NOW, { unit: 'kg' })[loadedSlug]).toBe(1)
})
- it('adds external load to bodyweight instead of replacing the body mass', () => {
+ it('scores an unloaded and a loaded bodyweight set equally when each is its own best', () => {
const unloaded = stampedWorkout({ id: bodyweight.id, start: NOW, unit: 'kg', weight: 0, bw: 80 })
const loadedSet = { done: true, w: 10, r: 8 }
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)
})
it('lets explicitly configured custom bodyweight work reset strength', () => {
@@ -565,7 +570,7 @@ describe('canonical loads and configured bodyweight', () => {
expect(futureValue).toBeLessThan(1)
})
- it('counts a default custom zero-load ring push-up for fatigue and load-blind strength', () => {
+ it('counts a default custom zero-load ring push-up as two hard sets', () => {
const id = 'recovery-ring-push-up'
registerCustom([{ id, n: 'Ring push-up', bp: 'chest', tg: 'chest', eq: 'custom', sm: [] }])
try {
@@ -573,7 +578,8 @@ describe('canonical loads and configured bodyweight', () => {
{ done: true, w: 0, r: 20 },
{ done: true, w: 0, r: 20 },
])
- expect(fatigueOf([workout], NOW).chest).toBeCloseTo(1 - Math.exp(-2 / 3), 10)
+ // No load recorded means intensity is unknown, so sets count full.
+ expect(fatigueOf([workout], NOW).chest).toBeCloseTo(expectedFatigue([{ sets: 2 }], 'chest'), 10)
expect(strengthOf([workout], NOW).chest).toBe(1)
} finally {
registerCustom([])
diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx
index 0e260032c..29c2aaf25 100644
--- a/frontend/src/views/Stats.recovery.test.jsx
+++ b/frontend/src/views/Stats.recovery.test.jsx
@@ -5,7 +5,7 @@ import { Window } from 'happy-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { EXIDX } from '../lib/exercises.js'
import { MUSCLES, levelsOf } from '../lib/muscles.js'
-import { FATIGUE_STATES, STRENGTH_FLOOR } from '../lib/recovery.js'
+import { FATIGUE_STATES, STRENGTH_FLOOR, fatigueHalfLifeOf, FATIGUE_SETS_PER_UNIT } from '../lib/recovery.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
import Stats from './Stats.jsx'
import Modals from '../components/Modals.jsx'
@@ -85,12 +85,10 @@ function entry(id, sets) {
}
function lifecycleWorkouts(now = BASE_NOW) {
- // The old one-set session lowers the causal reference seen by the six-set session. Position
- // that newer stimulus 30 seconds before its .5 crossing so the real interval update flips it.
- const weightedSet = 640 * (30 / 38) ** 1.5
- const referenceAfterOldSession = 2000 + (weightedSet - 2000) / 3
+ // Six same-load sets on the chest score 6/8 of a full session. Position that stimulus
+ // 30 seconds before its .5 crossing so the real interval update flips it.
const fatigueEdge = now - (
- 36 * Math.log2((6 * weightedSet / referenceAfterOldSession) / Math.LN2) * HOUR - 30000
+ fatigueHalfLifeOf('chest') * Math.log2(6 / FATIGUE_SETS_PER_UNIT / Math.LN2) - 30000
)
const balanceEdge = now - (30 * DAY - 30000)
const strengthEdge = now - (14 * DAY - 30000)
@@ -289,13 +287,17 @@ describe('Stats muscle recovery view runtime', () => {
await mountStats()
await click(viewButton('Fatigue'))
- // 220.462262 lb ~= 100 kg; ten reps score 1000 kg against the initial 2000 kg reference.
- expect(lastMap().load.abs).toBeCloseTo(1 - Math.exp(-0.5), 6)
+ // One unloaded set is one effective set whatever the profile unit or body mass:
+ // intensity is session-local and relative, so the 220 lb bodyweight only travels
+ // through opts while the score stays 1 - exp(-1/8).
+ expect(lastMap().load.abs).toBeCloseTo(1 - Math.exp(-1 / 8), 6)
expect(lastMap().thresholds).toBeTruthy()
})
it('renders fixed absolute bands through the actual Fatigue and Strength views', async () => {
- resetFixture([allFatiguedWorkout()])
+ // Two back-to-back full sessions: even 0.4-weighted secondary movers accumulate
+ // 2 x 12 x 0.4 / 8 = 1.2 raw units, clearing the top band everywhere.
+ resetFixture([allFatiguedWorkout(), allFatiguedWorkout()])
await mountStats()
await click(viewButton('Fatigue'))
const fatigueMap = lastMap()