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.

Implement fatigue calculation phase2

Сергей Горбатенкоe71514b4355e
diff --git a/docs/dev/FATIGUE_SETS_MODEL.md b/docs/dev/FATIGUE_SETS_MODEL.md
index f66fe430c..b8b3c275f 100644
--- a/docs/dev/FATIGUE_SETS_MODEL.md
+++ b/docs/dev/FATIGUE_SETS_MODEL.md
@@ -84,23 +84,57 @@ Jefit rotation; upper last hit 1.9d ago, legs 1.2d ago), `fatigueOf(workouts, no
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
+## Phase 2 (this change): RIR quality + acute:chronic gain
-- `frontend/src/lib/recovery.js` — new stimulus + per-muscle HL.
+Two orthogonal multipliers on top of the phase-1 sets, both causal and bounded:
+
+- **RIR weight per set** (`rirWeightFor`, `estimateSetRir`): logged `rir`/`rpe`
+ (via `effort.js`, `HARD_RIR = 3`) always wins; otherwise RIR is estimated by
+ Epley inverse against the exercise's 90-day rolling best anchor
+ (`30*(anchor/w-1)-r`, clamped 0..10, null above `REP_CAP = 12`, for
+ load-less rows, or assisted work). Weight is 1.0 at RIR <= 3, linear down to
+ the 0.3 floor at RIR >= 6. Loads canonicalise to kg through the
+ set -> target -> entry -> workout -> opts chain, so mixed-unit imports anchor
+ correctly (176 lb anchors like 80 kg). A ramp-up row therefore costs a
+ fraction of a set; a deload week of half-weight work reads RIR 10 instead of
+ 8 phantom hard sets (the case session-local intensity could never see).
+- **Acute:chronic gain per session and muscle**: `clamp((acute7+4)/(chronicW+4),
+ 0.5, 2)` with a 4-sets/week novice prior (repeated-bout effect as arithmetic:
+ first sessions score amplified, maintained veterans ~1.0 reproduce phase 1).
+ Maintenance preserves the phase-1 calibration by construction.
+
+**Contract change (deliberate, probe updated):** anchors and gains are
+history-dependent, so deleting a mid-history workout may re-score later sessions
+(removing a PR lowers their anchors). What still holds, and is now probed:
+rest never increases fatigue, out-of-pool imports stay irrelevant, and deleting
+the *chronologically latest* session never increases anything. A subtle
+correctness point the probe caught twice during development: the info pool must
+span scan + anchor window (120d), otherwise sessions age out of anchors as `now`
+advances and rest would raise fatigue; and "latest" means max timestamp, not
+array order.
+
+Measured on the same state: gluteal 0.533 fatigued, hamstring/quads/calves
+0.31-0.46 recovering (heavy legs 1.2d ago - pyramid ramp sets now correctly
+discounted), chest 0.156 ready (upper 1.9d ago). Phase 1 read 0.54-0.66/0.251
+on the same day; the direction is the same, the magnitudes now respect quality.
+
+## Files touched (phase 2 adds)
+
+- `frontend/src/lib/recovery.js` — phase 1: sets stimulus + per-muscle HL; phase 2:
+ RIR weighting, 90-day anchors (kg-canonical), acute:chronic gain, 120d info pool.
- `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).
+ structure, sets-based numbers) + RIR/deload/deletion-contract tests.
+- `frontend/scripts/fatigue-monotonic-probe.mjs` — latest-session (max timestamp)
+ deletion contract (mid-history rescoring is intended, not a violation).
## 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).
+- `cd frontend && npm test` — recovery suites green (59); full suite: only 2-3
+ pre-existing failures (see phase-1 notes; `useStore.media` is flaky on clean
+ tree too).
+- `npm run test:fatigue-probe` — PASS (108000 time + 1800 latest-deletion
+ comparisons; contract changed, see above).
- `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).
diff --git a/docs/dev/SET_TYPES.md b/docs/dev/SET_TYPES.md
index 7570a7e4e..771b9cc0f 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`).
-- `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.
+- `sessionEffSets` (`recovery.js`) — same split: each drop-set drop counts as an extra
+ set at its own RIR weight against the 90-day anchor, 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/scripts/fatigue-monotonic-probe.mjs b/frontend/scripts/fatigue-monotonic-probe.mjs
index 89aec6264..bcd68863a 100644
--- a/frontend/scripts/fatigue-monotonic-probe.mjs
+++ b/frontend/scripts/fatigue-monotonic-probe.mjs
@@ -48,17 +48,20 @@ for (let historyIndex = 0; historyIndex < 100; historyIndex += 1) {
}
const beforeDeletion = fatigueOf(history, BASE)
- for (let deleted = 0; deleted < history.length; deleted += 1) {
- const afterDeletion = fatigueOf(history.filter((_, index) => index !== deleted), BASE)
- for (const [slug, before] of Object.entries(beforeDeletion)) {
- if (afterDeletion[slug] > before + Number.EPSILON) {
- throw new Error(
- `deleting workout ${deleted} in history ${historyIndex} increased ${slug}: `
- + `${before} -> ${afterDeletion[slug]}`,
- )
- }
- deletionComparisons += 1
+ // Phase-2 contract: only the chronologically latest session's deletion is monotonic.
+ // Anchors and acute:chronic gains are history-dependent, so removing a mid-history
+ // workout may re-score later sessions (a removed PR lowers their anchors). Deleting
+ // the latest session touches no earlier window and can only remove stimulus.
+ const latestIndex = history.reduce((best, w, i) => (w.start > history[best].start ? i : best), 0)
+ const afterLatestDeletion = fatigueOf(history.filter((_, index) => index !== latestIndex), BASE)
+ for (const [slug, before] of Object.entries(beforeDeletion)) {
+ if (afterLatestDeletion[slug] > before + Number.EPSILON) {
+ throw new Error(
+ `deleting the latest workout in history ${historyIndex} increased ${slug}: `
+ + `${before} -> ${afterLatestDeletion[slug]}`,
+ )
}
+ deletionComparisons += 1
}
}
@@ -81,20 +84,16 @@ const deletionHistory = [
workout(BASE, 120, 10),
]
const beforePinnedDeletion = fatigueOf(deletionHistory, BASE)
-for (let deleted = 0; deleted < deletionHistory.length; deleted += 1) {
- const afterDeletion = fatigueOf(
- deletionHistory.filter((_, index) => index !== deleted),
- BASE,
- )
- for (const [slug, before] of Object.entries(beforePinnedDeletion)) {
- if (afterDeletion[slug] > before + Number.EPSILON) {
- throw new Error(`deleting workout ${deleted} increased ${slug}: ${before} -> ${afterDeletion[slug]}`)
- }
+// Pinned latest-deletion case: removing the newest session never increases fatigue.
+const afterPinnedDeletion = fatigueOf(deletionHistory.slice(0, -1), BASE)
+for (const [slug, before] of Object.entries(beforePinnedDeletion)) {
+ if (afterPinnedDeletion[slug] > before + Number.EPSILON) {
+ throw new Error(`deleting the latest workout increased ${slug}: ${before} -> ${afterPinnedDeletion[slug]}`)
}
}
console.log(`monotonic probe: ${comparisons} comparisons, largest increase ${largestIncrease}, PASS`)
console.log(
`history-edit probe: out-of-scan imports stable; ${deletionComparisons} randomized `
- + 'single-workout deletion comparisons non-increasing, PASS',
+ + 'latest-workout deletion comparisons non-increasing, PASS',
)
diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js
index 3c2c005ce..f6ec2f7e8 100644
--- a/frontend/src/lib/recovery.js
+++ b/frontend/src/lib/recovery.js
@@ -1,6 +1,8 @@
-import { EXIDX } from './exercises.js'
+import { EXIDX, isAssisted } from './exercises.js'
import { MUSCLES, musclesOf } from './muscles.js'
-import { isWarmupRow, dropsOf } from './workout-model.js'
+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
@@ -14,6 +16,24 @@ 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
+// 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
// Exponential half-life for fatigue stimulus, per muscle. Lower body (heavier
// absolute loads, more damage) recovers slower than upper body: 10RM
@@ -92,72 +112,188 @@ function numeric(value) {
return Number.isFinite(n) ? n : null
}
-// 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) {
+// Unit stamps live on the set, the target, the entry, or the workout; profile unit
+// comes through opts. The anchor compares loads across sessions (and mixed-unit
+// imports alternate kg/lb rows), so every load is canonicalised to kg first -
+// 176 lb must anchor like 80 kg, not like 176 kg.
+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 isPounds(unit) {
+ return /^(?:lb|lbs|pound|pounds)$/i.test(String(unit ?? '').trim())
+}
+
+function kgOf(value, unit) {
+ const n = numeric(value)
+ if (n === null) return 0
+ 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))
+}
+
+/**
+ * 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);
+// 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, anchorKg, requireDone = true) => {
+ if (requireDone && row?.done !== true) return
+ const unit = unitOf(row, set, entry?.target, entry, workout, opts)
+ const logged = rirOf(row)
+ const estimated = logged == null ? estimateSetRir(row, anchorKg, unit) : null
+ const count = rirWeightFor(logged ?? estimated?.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)
- 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 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] += 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.
+ const anchorKg = anchors?.get(entry.id)
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
- }
- }
+ score(set, set, entry, weights, anchorKg)
+ // 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, anchorKg, false)
}
}
for (const slug of MUSCLES) sums[slug] = Math.min(sums[slug], FATIGUE_MAX_SETS_PER_SESSION)
return sums
}
-// 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 || [])
+// Best Epley estimate per exercise inside one session, in kg. 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]
+ for (const side of sides) {
+ const est = estimate1RM(rowWkg(side, set, entry, workout, opts), numeric(side?.r))
+ if (est !== null && (!best.has(exId) || est > best.get(exId))) best.set(exId, est)
+ }
+ }
+ 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)
+ }
+ return best
+}
+
+// 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 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 scored = pool.filter(item => item.timestamp > scanCutoff)
+ const bests = pool.map(item => sessionBests(item.workout, opts))
+ const effSets = pool.map((item, i) => {
+ const anchors = new Map()
+ for (let j = 0; j <= i; j += 1) {
+ if (pool[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 sessionEffSets(item.workout, anchors, opts)
+ })
const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []]))
- for (const { workout, timestamp } of ordered) {
- const sums = sessionSets(workout)
+ 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 / FATIGUE_SETS_PER_UNIT })
+ 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
@@ -187,12 +323,16 @@ 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 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,
+ * 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). Each session is scored only from its own sets, so out-of-window imports are
- * irrelevant and deleting a workout can only remove stimulus.
+ * 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.
@@ -204,7 +344,7 @@ 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)
+ const byMuscle = fatigueStimuli(workouts, current, opts)
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 e61d72b4f..cc91ec388 100644
--- a/frontend/src/lib/recovery.test.js
+++ b/frontend/src/lib/recovery.test.js
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'vitest'
import {
+ FATIGUE_ACUTE_WINDOW_MS,
+ 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,
@@ -8,10 +14,12 @@ import {
STRENGTH_FULL_MS,
STRENGTH_HALF_LIFE_MS,
detrainedMuscles,
+ estimateSetRir,
fatiguedMuscles,
fatigueHalfLifeOf,
fatigueOf,
halfLifeDecay,
+ rirWeightFor,
strengthOf,
} from './recovery.js'
import { EXDB, registerCustom } from './exercises.js'
@@ -55,17 +63,18 @@ 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))
-// 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 { sets, weight = 1, age = 0 } of sessions) {
- normalised += sets * weight / FATIGUE_SETS_PER_UNIT * halfLifeDecay(age, halfLife)
- }
- return 1 - Math.exp(-normalised)
-}
+// Expected saturated fatigue for uniform-load sessions (every set its entry's best,
+// so RIR is 0 and sets count full). Mirrors the production gain: the acute:chronic
+// ratio over the same session list, novice prior included, clamped like production.
+const effGain = eff => Math.min(
+ FATIGUE_RATIO_MAX,
+ Math.max(FATIGUE_RATIO_MIN, (eff + FATIGUE_NOVICE_WEEKLY_SETS) / (eff / 4 + FATIGUE_NOVICE_WEEKLY_SETS)),
+);
+const expectedSets = (sets, weight, slug, age = 0, gainEff = null) => {
+ const eff = Math.min(sets * weight, FATIGUE_MAX_SETS_PER_SESSION)
+ const gain = gainEff === null ? effGain(eff) : gainEff
+ return 1 - Math.exp(-eff / FATIGUE_SETS_PER_UNIT * gain * halfLifeDecay(age, fatigueHalfLifeOf(slug)))
+};
describe('recovery constants', () => {
it('exports the pinned windows, half-lives, floor, and state labels', () => {
@@ -114,7 +123,7 @@ describe('fatigueOf and strengthOf', () => {
for (const slug of MUSCLES) {
const weight = WEIGHTED_WEIGHTS[slug] || 0
- expect(fatigue[slug]).toBeCloseTo(expectedFatigue([{ sets: 1, weight }], slug), 10)
+ expect(fatigue[slug]).toBeCloseTo(expectedSets(1, weight, slug), 10)
expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR)
}
// one set (whatever the load) never crosses the fatigued threshold
@@ -170,16 +179,16 @@ describe('fatigueOf and strengthOf', () => {
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(expectedFatigue([{ sets: 1 }]), 10)
- expect(at0(5)).toBeCloseTo(expectedFatigue([{ sets: 5 }]), 10)
- expect(at0(12)).toBeCloseTo(expectedFatigue([{ sets: 12 }]), 10)
+ expect(at0(1)).toBeCloseTo(expectedSets(1, 1, SINGLE_SLUG), 10)
+ expect(at0(5)).toBeCloseTo(expectedSets(5, 1, SINGLE_SLUG), 10)
+ expect(at0(12)).toBeCloseTo(expectedSets(12, 1, SINGLE_SLUG), 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 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).toBeCloseTo(expectedSets(12, 1, SINGLE_SLUG, 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]
@@ -192,14 +201,14 @@ describe('fatigueOf and strengthOf', () => {
for (const age of [halfLife, halfLife / 2]) {
const fatigue = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)
for (const [slug, weight] of Object.entries(WEIGHTED_WEIGHTS)) {
- expect(fatigue[slug]).toBeCloseTo(expectedFatigue([{ sets: 1, weight, age }], slug), 10)
+ expect(fatigue[slug]).toBeCloseTo(expectedSets(1, weight, slug, age), 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),
+ expectedSets(1, WEIGHTED_WEIGHTS[SECONDARY_SLUG], SECONDARY_SLUG, secondaryHl),
10,
)
})
@@ -221,7 +230,7 @@ describe('fatigueOf and strengthOf', () => {
expect(detrainedMuscles(workouts, NOW)).toEqual(MUSCLES)
})
- it('discounts ramp-up rows against the entry best instead of charging full sets', () => {
+ 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 },
@@ -229,8 +238,9 @@ describe('fatigueOf and strengthOf', () => {
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)
+ // 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])
})
@@ -244,8 +254,10 @@ describe('fatigue state boundaries', () => {
const halfLife = fatigueHalfLifeOf(SECONDARY_SLUG)
const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG]
const sets = 8
+ const eff = sets * weight
+ const gain = effGain(eff)
const valueAt = target => {
- const age = halfLife * Math.log2(sets * weight / FATIGUE_SETS_PER_UNIT / rawAt(target))
+ const age = halfLife * Math.log2(eff / FATIGUE_SETS_PER_UNIT * gain / rawAt(target))
const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age, sets)], NOW)[SECONDARY_SLUG]
expect(value).toBeCloseTo(target, 10)
return stableFloat(value)
@@ -258,15 +270,16 @@ describe('fatigue state boundaries', () => {
it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => {
const halfLife = fatigueHalfLifeOf(SINGLE_SLUG)
const sets = 8
+ const gain = effGain(sets)
const atHalf = [doneWorkoutAt(
SINGLE.id,
- NOW - halfLife * Math.log2(sets / FATIGUE_SETS_PER_UNIT / rawAt(0.4999)),
+ NOW - halfLife * Math.log2(sets / FATIGUE_SETS_PER_UNIT * gain / rawAt(0.4999)),
sets,
)]
const aboveHalf = [
doneWorkoutAt(
SINGLE.id,
- NOW - halfLife * Math.log2(sets / FATIGUE_SETS_PER_UNIT / rawAt(0.5001)),
+ NOW - halfLife * Math.log2(sets / FATIGUE_SETS_PER_UNIT * gain / rawAt(0.5001)),
sets,
),
]
@@ -290,17 +303,21 @@ describe('causal session scoring', () => {
Array.from({ length: count }, () => ({ done: true, w: weight, r: 8 })),
)
- it('adds each session on top of decayed earlier ones without any shared reference', () => {
+ it('adds each session on top of decayed earlier ones, each with its own acute:chronic gain', () => {
const halfLife = fatigueHalfLifeOf(SINGLE_SLUG)
const old = doneWorkoutAt(SINGLE.id, NOW - DAY)
const today = doneWorkoutAt(SINGLE.id, NOW)
- const expected = expectedFatigue([
- { sets: 1, age: DAY },
- { sets: 1, age: 0 },
- ])
+ // The old session trained alone (gain over its own single set); today sees both
+ // sets in its acute window, hence the higher gain: adaptation is history-dependent.
+ const oldGain = effGain(1)
+ const todayGain = (2 + FATIGUE_NOVICE_WEEKLY_SETS) / (0.5 + FATIGUE_NOVICE_WEEKLY_SETS)
+ const expected = 1 - Math.exp(-(
+ 1 / FATIGUE_SETS_PER_UNIT * oldGain * halfLifeDecay(DAY, halfLife)
+ + 1 / FATIGUE_SETS_PER_UNIT * todayGain
+ ))
expect(fatigueOf([old, today], NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
- expect(fatigueOf([today], NOW)[SINGLE_SLUG]).toBeCloseTo(expectedFatigue([{ sets: 1 }]), 10)
+ expect(fatigueOf([today], NOW)[SINGLE_SLUG]).toBeCloseTo(expectedSets(1, 1, SINGLE_SLUG), 10)
})
it('keeps the 8x100x8 ten-day reproduction non-increasing as sessions leave the scan', () => {
@@ -328,7 +345,11 @@ describe('causal session scoring', () => {
expect(fatigueOf([highVolumeImport, today], NOW).chest).toBe(baseline)
})
- it('never increases fatigue when any one workout is deleted', () => {
+ // Phase-2 contract: anchors and gains are history-dependent by design, so only the
+ // latest session's deletion is monotonic. Deleting mid-history may re-score later
+ // sessions (a removed PR lowers their anchors and raises their gains) - documented
+ // in docs/dev/FATIGUE_SETS_MODEL.md rather than forbidden.
+ it('never increases fatigue when the latest workout is deleted', () => {
const workouts = [
loadedWorkout(NOW - 40 * DAY, 100, 15),
loadedWorkout(NOW - 3 * DAY, 100, 8),
@@ -337,19 +358,28 @@ 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)
+ })
- 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)
- })
+ 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. 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.
+ // 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 })),
@@ -371,6 +401,54 @@ describe('causal session scoring', () => {
})
})
+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])
+ })
+})
+
describe('strengthOf', () => {
const strengthAt = age => strengthOf([doneWorkoutAt(SINGLE.id, NOW - age)], NOW)[SINGLE_SLUG]
@@ -398,7 +476,12 @@ describe('accumulation and purity', () => {
const halfLife = fatigueHalfLifeOf(SINGLE_SLUG)
const ages = [64 * HOUR, 40 * HOUR]
const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age))
- const expected = expectedFatigue(ages.map(age => ({ sets: 1, age })))
+ // The older session trained alone; the newer one sees both sets in its windows.
+ const firstGain = effGain(1)
+ const secondGain = (2 + FATIGUE_NOVICE_WEEKLY_SETS) / (0.5 + FATIGUE_NOVICE_WEEKLY_SETS)
+ const raw = 1 / FATIGUE_SETS_PER_UNIT * firstGain * halfLifeDecay(ages[0], halfLife)
+ + 1 / FATIGUE_SETS_PER_UNIT * secondGain * halfLifeDecay(ages[1], halfLife)
+ const expected = 1 - Math.exp(-raw)
expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
@@ -406,7 +489,7 @@ describe('accumulation and purity', () => {
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(expectedFatigue([{ sets: 2 }]), 10)
+ expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(expectedSets(2, 1, SINGLE_SLUG), 10)
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1)
const workouts = [
@@ -443,14 +526,14 @@ describe('warm-up flag in strength and fatigue', () => {
})
})
-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
+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 relative-intensity sets', () => {
+ 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 expected = expectedFatigue([{ sets: 1 + dropShare }])
+ 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
@@ -461,7 +544,7 @@ describe('drop-set drops add fatigue sets 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([{ sets: 1 }]), 8)
+ .toBeCloseTo(expectedSets(1, 1, SINGLE_SLUG), 8)
})
})
@@ -579,7 +662,7 @@ describe('loads are relative, units are irrelevant', () => {
{ done: true, w: 0, r: 20 },
])
// No load recorded means intensity is unknown, so sets count full.
- expect(fatigueOf([workout], NOW).chest).toBeCloseTo(expectedFatigue([{ sets: 2 }], 'chest'), 10)
+ expect(fatigueOf([workout], NOW).chest).toBeCloseTo(expectedSets(2, 1, '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 29c2aaf25..ca837dfe8 100644
--- a/frontend/src/views/Stats.recovery.test.jsx
+++ b/frontend/src/views/Stats.recovery.test.jsx
@@ -85,10 +85,13 @@ function entry(id, sets) {
}
function lifecycleWorkouts(now = BASE_NOW) {
- // 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.
+ // Six same-load sets on the chest score 6/8 of a full session, amplified by the
+ // acute:chronic gain of a lone recent session ((6+4)/(1.5+4)). Position that
+ // stimulus 30 seconds before its .5 crossing so the real interval update flips it.
+ // (The 30-day-old balance session sits outside the 28-day chronic window.)
+ const loneGain = (6 + 4) / (6 / 4 + 4)
const fatigueEdge = now - (
- fatigueHalfLifeOf('chest') * Math.log2(6 / FATIGUE_SETS_PER_UNIT / Math.LN2) - 30000
+ fatigueHalfLifeOf('chest') * Math.log2(6 / FATIGUE_SETS_PER_UNIT * loneGain / Math.LN2) - 30000
)
const balanceEdge = now - (30 * DAY - 30000)
const strengthEdge = now - (14 * DAY - 30000)
@@ -289,8 +292,8 @@ describe('Stats muscle recovery view runtime', () => {
// 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)
+ // through opts while the score stays 1 - exp(-1/8 x novice gain of 5/4.25).
+ expect(lastMap().load.abs).toBeCloseTo(1 - Math.exp(-5 / 34), 6)
expect(lastMap().thresholds).toBeTruthy()
})