fix: fatigue round-4 (zero-load strength, history-stable reference, real Stats view tests + committed probe)
This commit is contained in:
1 parent
528cb70a79
commit
ed666df237
7 files changed
+759
-455
No files matched your search
+204
-38
@@ -1,14 +1,20 @@
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
|
||||
/** Completed-workout window used when calculating current fatigue. */
|
||||
// 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 = 3
|
||||
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.
|
||||
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. */
|
||||
export const FATIGUE_HALF_LIFE_MS = 129600000
|
||||
@@ -54,31 +60,184 @@ function emptyMuscleMap(value) {
|
||||
return Object.fromEntries(MUSCLES.map(slug => [slug, value]))
|
||||
}
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.min(max, Math.max(min, value))
|
||||
// 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)
|
||||
|
||||
const LB_TO_KG = 0.45359237
|
||||
|
||||
function numeric(value) {
|
||||
if (value === null || value === undefined || value === '' || typeof value === 'boolean') return null
|
||||
const n = Number(value)
|
||||
return Number.isFinite(n) ? n : null
|
||||
}
|
||||
|
||||
// Yield one weighted stimulus per completed set. Repeating the exercise's muscle weights for
|
||||
// every done set is equivalent to multiplying musclesOf(ex) by the completed-set count while
|
||||
// preserving the workout/set shape already used by the app.
|
||||
function completedStimuli(workouts, include) {
|
||||
const stimuli = []
|
||||
for (const workout of workouts || []) {
|
||||
const timestamp = workoutTimestamp(workout)
|
||||
if (!Number.isFinite(timestamp) || !include(timestamp)) continue
|
||||
for (const entry of workout.entries || []) {
|
||||
const weights = musclesOf(EXIDX[entry.id])
|
||||
for (const set of entry.sets || []) {
|
||||
if (set?.done !== true) continue
|
||||
for (const [slug, weight] of Object.entries(weights)) {
|
||||
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) {
|
||||
stimuli.push({ slug, timestamp, stimulus: weight })
|
||||
}
|
||||
}
|
||||
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
|
||||
|| Object.prototype.hasOwnProperty.call(opts, 'bodyweightKg')
|
||||
|| 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 = EXIDX[entry.id]
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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
|
||||
if (!(oneRm > 0) || !(load > 0)) return raw
|
||||
return raw * Math.min(1, load / oneRm) ** 1.5
|
||||
}
|
||||
|
||||
// One session's per-muscle stimulus, calculated only from that session. A completed zero-load
|
||||
// set gets the set-equivalent fallback instead of disappearing from fatigue.
|
||||
function sessionTonnages(workout, opts = {}) {
|
||||
const sums = emptyMuscleMap(0)
|
||||
const oneRms = session1RMs(workout, opts)
|
||||
for (const entry of workout?.entries || []) {
|
||||
const weights = musclesOf(EXIDX[entry.id])
|
||||
for (const set of entry.sets || []) {
|
||||
if (set?.done !== true) continue
|
||||
const measured = setTonnage(EXIDX[entry.id], entry, set, workout, oneRms.get(entry.id), opts)
|
||||
const tonnage = Number.isFinite(measured) && measured > 0 ? measured : ZERO_LOAD_SET_STIMULUS
|
||||
for (const [slug, weight] of Object.entries(weights)) {
|
||||
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) sums[slug] += tonnage * weight
|
||||
}
|
||||
}
|
||||
}
|
||||
return stimuli
|
||||
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 = {}) {
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
return byMuscle
|
||||
}
|
||||
|
||||
const MUSCLES_BY_SLUG = Object.fromEntries(MUSCLES.map(slug => [slug, true]))
|
||||
@@ -97,7 +256,7 @@ function fatigueValue(events, now) {
|
||||
value *= halfLifeDecay(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.
|
||||
return 1 - Math.exp(-value / FATIGUE_REF_VOLUME)
|
||||
return 1 - Math.exp(-value)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,22 +265,21 @@ function fatigueValue(events, now) {
|
||||
* 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 / FATIGUE_REF_VOLUME).
|
||||
* 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.
|
||||
* The result always contains every drawable muscle slug.
|
||||
*
|
||||
* @param {Array<object>} workouts Workout history with `start`/`d` and entry set arrays.
|
||||
* @param {number} now Current time in milliseconds; injected to keep this function deterministic.
|
||||
* @returns {Record<string, number>} Fatigue values keyed by every drawable muscle slug.
|
||||
*/
|
||||
export function fatigueOf(workouts, now) {
|
||||
export function fatigueOf(workouts, now, opts = {}) {
|
||||
const current = Number(now)
|
||||
const cutoff = current - FATIGUE_SCAN_MS
|
||||
const stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff)
|
||||
const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []]))
|
||||
for (const stimulus of stimuli) byMuscle[stimulus.slug].push(stimulus)
|
||||
|
||||
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)
|
||||
return result
|
||||
}
|
||||
@@ -138,12 +296,20 @@ export function fatigueOf(workouts, now) {
|
||||
* @param {number} now Current time in milliseconds; injected to keep this function deterministic.
|
||||
* @returns {Record<string, number>} Retained-strength values keyed by every drawable muscle slug.
|
||||
*/
|
||||
export function strengthOf(workouts, now) {
|
||||
export function strengthOf(workouts, now, opts = {}) {
|
||||
const current = Number(now)
|
||||
const latest = Object.fromEntries(MUSCLES.map(slug => [slug, -Infinity]))
|
||||
const stimuli = completedStimuli(workouts, () => true)
|
||||
for (const stimulus of stimuli) {
|
||||
if (stimulus.timestamp > latest[stimulus.slug]) latest[stimulus.slug] = stimulus.timestamp
|
||||
for (const workout of workouts || []) {
|
||||
const timestamp = workoutTimestamp(workout)
|
||||
if (!Number.isFinite(timestamp)) continue
|
||||
for (const entry of workout.entries || []) {
|
||||
if (!(entry.sets || []).some(set => set?.done === true && !set?.warmup)) continue
|
||||
for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) {
|
||||
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug) && timestamp > latest[slug]) {
|
||||
latest[slug] = timestamp
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = emptyMuscleMap(STRENGTH_FLOOR)
|
||||
@@ -174,8 +340,8 @@ export function strengthOf(workouts, now) {
|
||||
* @example
|
||||
* const avoid = fatiguedMuscles(workouts, now)
|
||||
*/
|
||||
export function fatiguedMuscles(workouts, now) {
|
||||
return Object.entries(fatigueOf(workouts, now))
|
||||
export function fatiguedMuscles(workouts, now, opts = {}) {
|
||||
return Object.entries(fatigueOf(workouts, now, opts))
|
||||
.filter(([, value]) => value > 0.5)
|
||||
.map(([slug]) => slug)
|
||||
}
|
||||
@@ -190,8 +356,8 @@ export function fatiguedMuscles(workouts, now) {
|
||||
* @example
|
||||
* const targets = detrainedMuscles(workouts, now)
|
||||
*/
|
||||
export function detrainedMuscles(workouts, now) {
|
||||
return Object.entries(strengthOf(workouts, now))
|
||||
export function detrainedMuscles(workouts, now, opts = {}) {
|
||||
return Object.entries(strengthOf(workouts, now, opts))
|
||||
.filter(([, value]) => value < 1)
|
||||
.map(([slug]) => slug)
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
FATIGUE_HALF_LIFE_MS,
|
||||
FATIGUE_MIN_SESSIONS,
|
||||
FATIGUE_REF_VOLUME,
|
||||
FATIGUE_SCAN_MS,
|
||||
FATIGUE_STATES,
|
||||
BODYWEIGHT_REF_LOAD,
|
||||
CARDIO_TONNAGE_PER_MIN,
|
||||
STRENGTH_FLOOR,
|
||||
STRENGTH_FULL_MS,
|
||||
STRENGTH_HALF_LIFE_MS,
|
||||
@@ -13,7 +16,7 @@ import {
|
||||
halfLifeDecay,
|
||||
strengthOf,
|
||||
} from './recovery.js'
|
||||
import { EXDB } from './exercises.js'
|
||||
import { EXDB, registerCustom } from './exercises.js'
|
||||
import { MUSCLES, musclesOf } from './muscles.js'
|
||||
import { fatigueStateOf } from './recovery-view.js'
|
||||
|
||||
@@ -44,19 +47,37 @@ 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)
|
||||
|
||||
const doneWorkoutAt = (id, start, count = 1) =>
|
||||
workoutAt(id, start, Array.from({ length: count }, () => ({ done: true })))
|
||||
workoutAt(id, start, Array.from({ length: count }, () => ({ done: true, w: 80, r: 8 })))
|
||||
const zeroFatigue = () => Object.fromEntries(MUSCLES.map(slug => [slug, 0]))
|
||||
const floorStrength = () => Object.fromEntries(MUSCLES.map(slug => [slug, STRENGTH_FLOOR]))
|
||||
|
||||
// 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
|
||||
let normalised = 0
|
||||
for (const { stimulus, age = 0 } of sessions) {
|
||||
normalised += stimulus / reference * halfLifeDecay(age, FATIGUE_HALF_LIFE_MS)
|
||||
reference = referenceAfter(reference, stimulus)
|
||||
}
|
||||
return 1 - Math.exp(-normalised)
|
||||
}
|
||||
|
||||
describe('recovery constants', () => {
|
||||
it('exports the pinned windows, half-lives, floor, and state labels', () => {
|
||||
expect(FATIGUE_REF_VOLUME).toBe(3)
|
||||
expect(FATIGUE_REF_VOLUME).toBe(2000)
|
||||
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)
|
||||
@@ -88,24 +109,36 @@ describe('fatigueOf and strengthOf', () => {
|
||||
|
||||
for (const slug of MUSCLES) {
|
||||
const weight = WEIGHTED_WEIGHTS[slug] || 0
|
||||
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight / FATIGUE_REF_VOLUME), 10)
|
||||
expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-V * weight / FATIGUE_REF_VOLUME), 10)
|
||||
expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR)
|
||||
}
|
||||
// one set never crosses the fatigued threshold on the saturating curve
|
||||
// one set (80 x 8) never crosses the fatigued threshold on the saturating curve
|
||||
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)
|
||||
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),
|
||||
10,
|
||||
)
|
||||
expect(fatigueOf(highRep, NOW)[SINGLE_SLUG]).toBeGreaterThan(0.5)
|
||||
})
|
||||
|
||||
it('raises starting fatigue with volume, 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(-1 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at0(5)).toBeCloseTo(1 - Math.exp(-5 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(at0(12)).toBeCloseTo(1 - Math.exp(-12 / FATIGUE_REF_VOLUME), 10)
|
||||
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(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 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(later).toBeCloseTo(1 - Math.exp(-6 * V / FATIGUE_REF_VOLUME), 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]
|
||||
@@ -118,13 +151,22 @@ describe('fatigueOf and strengthOf', () => {
|
||||
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(-weight * expectedDecay / FATIGUE_REF_VOLUME), 10)
|
||||
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(-0.5 / FATIGUE_REF_VOLUME), 10)
|
||||
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(-(0.5 ** 0.5) / FATIGUE_REF_VOLUME), 10)
|
||||
expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(
|
||||
1 - Math.exp(-V * (0.5 ** 0.5) / FATIGUE_REF_VOLUME),
|
||||
10,
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -153,9 +195,9 @@ describe('fatigue state boundaries', () => {
|
||||
|
||||
it('classifies exactly .25 as recovering and .2499 as ready', () => {
|
||||
const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG]
|
||||
const sets = 3
|
||||
const sets = 4
|
||||
const valueAt = target => {
|
||||
const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * weight / rawAt(target))
|
||||
const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * V * weight / rawAt(target))
|
||||
const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age, sets)], NOW)[SECONDARY_SLUG]
|
||||
expect(value).toBeCloseTo(target, 10)
|
||||
return stableFloat(value)
|
||||
@@ -166,10 +208,18 @@ describe('fatigue state boundaries', () => {
|
||||
})
|
||||
|
||||
it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => {
|
||||
const sets = 3
|
||||
const atHalf = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.4999)), sets)]
|
||||
const sets = 4
|
||||
const atHalf = [doneWorkoutAt(
|
||||
SINGLE.id,
|
||||
NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets * V / rawAt(0.4999)),
|
||||
sets,
|
||||
)]
|
||||
const aboveHalf = [
|
||||
doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.5001)), sets),
|
||||
doneWorkoutAt(
|
||||
SINGLE.id,
|
||||
NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets * V / rawAt(0.5001)),
|
||||
sets,
|
||||
),
|
||||
]
|
||||
const half = fatigueOf(atHalf, NOW)[SINGLE_SLUG]
|
||||
const above = fatigueOf(aboveHalf, NOW)[SINGLE_SLUG]
|
||||
@@ -183,6 +233,92 @@ describe('fatigue state boundaries', () => {
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('causal fatigue reference', () => {
|
||||
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', () => {
|
||||
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
|
||||
))
|
||||
|
||||
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,
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps the 8x100x8 ten-day reproduction non-increasing as sessions leave the scan', () => {
|
||||
const base = Date.UTC(2026, 0, 31, 12)
|
||||
const workouts = [-20, -10, 0].map(days => loadedWorkout(base + days * DAY, 100))
|
||||
const observed = Array.from(
|
||||
{ length: 31 * 24 + 1 },
|
||||
(_, hour) => fatigueOf(workouts, base + hour * HOUR).chest,
|
||||
)
|
||||
|
||||
expect(observed[0]).toBeGreaterThan(0.5)
|
||||
expect(observed.at(-1)).toBe(0)
|
||||
for (let index = 1; index < observed.length; index += 1) {
|
||||
expect(observed[index]).toBeLessThanOrEqual(observed[index - 1] + Number.EPSILON)
|
||||
}
|
||||
})
|
||||
|
||||
it('ignores imports older than the scan, including their heavier 1RM data', () => {
|
||||
const today = loadedWorkout(NOW, 100, 5)
|
||||
const baseline = fatigueOf([today], NOW).chest
|
||||
const heavyImport = loadedWorkout(NOW - 90 * DAY, 140, 10)
|
||||
const highVolumeImport = loadedWorkout(NOW - 90 * DAY, 100, 20)
|
||||
|
||||
expect(fatigueOf([heavyImport, today], NOW).chest).toBe(baseline)
|
||||
expect(fatigueOf([highVolumeImport, today], NOW).chest).toBe(baseline)
|
||||
})
|
||||
|
||||
it('never increases fatigue when any one workout is deleted', () => {
|
||||
const workouts = [
|
||||
loadedWorkout(NOW - 40 * DAY, 100, 15),
|
||||
loadedWorkout(NOW - 3 * DAY, 100, 8),
|
||||
loadedWorkout(NOW - 2 * DAY, 100, 8),
|
||||
loadedWorkout(NOW - DAY, 60, 4),
|
||||
loadedWorkout(NOW, 120, 10),
|
||||
]
|
||||
const before = fatigueOf(workouts, NOW)
|
||||
|
||||
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('rates a lighter current week below repeating the established load', () => {
|
||||
const prior = [-21, -14, -7].map(days => loadedWorkout(NOW + days * DAY, 100))
|
||||
const lighter = fatigueOf([...prior, loadedWorkout(NOW, 50)], NOW).chest
|
||||
const repeated = fatigueOf([...prior, loadedWorkout(NOW, 100)], NOW).chest
|
||||
|
||||
expect(lighter).toBeLessThan(repeated)
|
||||
})
|
||||
|
||||
it('uses the last registered bodyweight for bodyweight exercises', () => {
|
||||
const bwEx = EXDB.find(ex => ex.eq === 'body weight' && 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)
|
||||
})
|
||||
})
|
||||
|
||||
describe('strengthOf', () => {
|
||||
const strengthAt = age => strengthOf([doneWorkoutAt(SINGLE.id, NOW - age)], NOW)[SINGLE_SLUG]
|
||||
|
||||
@@ -210,10 +346,15 @@ describe('accumulation and purity', () => {
|
||||
const ages = [64 * HOUR, 40 * HOUR]
|
||||
const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age))
|
||||
const raw = ages.reduce(
|
||||
(sum, age) => sum + 0.5 ** (age / FATIGUE_HALF_LIFE_MS),
|
||||
(sum, age) => sum + V * 0.5 ** (age / FATIGUE_HALF_LIFE_MS),
|
||||
0,
|
||||
)
|
||||
const expected = 1 - Math.exp(-raw / FATIGUE_REF_VOLUME)
|
||||
const firstAge = ages[0]
|
||||
const secondAge = ages[1]
|
||||
const expected = expectedFatigue([
|
||||
{ stimulus: V, age: firstAge },
|
||||
{ stimulus: V, age: secondAge },
|
||||
])
|
||||
|
||||
expect(raw).toBeLessThan(FATIGUE_REF_VOLUME)
|
||||
expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10)
|
||||
@@ -222,7 +363,10 @@ 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(1 - Math.exp(-2 / FATIGUE_REF_VOLUME), 10)
|
||||
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(
|
||||
1 - Math.exp(-2 * V / FATIGUE_REF_VOLUME),
|
||||
10,
|
||||
)
|
||||
expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1)
|
||||
|
||||
const workouts = [
|
||||
@@ -240,3 +384,110 @@ describe('accumulation and purity', () => {
|
||||
expect(workouts).toEqual(before)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
describe('warm-up flag in strength and fatigue', () => {
|
||||
it('a warm-up set does not reset strength but still adds fatigue volume', () => {
|
||||
const now = Date.UTC(2026, 7, 1, 12)
|
||||
const oldWork = { id: 'w1', d: '2026-07-10', start: now - 20 * 86400000, unit: 'kg',
|
||||
entries: [{ id: '1254', sets: [{ done: true, w: 80, r: 8 }] }] }
|
||||
const warm = { id: 'w2', d: '2026-08-01', start: now - 3600000, unit: 'kg',
|
||||
entries: [{ id: '1254', sets: [{ done: true, warmup: true, w: 20, r: 8 }] }] }
|
||||
const workouts = [oldWork, warm]
|
||||
const strength = strengthOf(workouts, now)
|
||||
// the strength edge is 20 days old: the fresh warm-up must NOT be the latest training event
|
||||
expect(strength.chest).toBeLessThan(1)
|
||||
// but the warm-up still contributes to the fatigue stimulus (real mechanical work)
|
||||
const fatigue = fatigueOf(workouts, now)
|
||||
expect(fatigue.chest).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('canonical loads and configured bodyweight', () => {
|
||||
const loaded = EXDB.find(ex => {
|
||||
const weights = musclesOf(ex)
|
||||
return ex.bp !== 'cardio' && ex.eq !== 'body weight'
|
||||
&& Object.keys(weights).length === 1 && Object.values(weights)[0] === 1
|
||||
})
|
||||
const bodyweight = EXDB.find(ex => ex.bp !== 'cardio' && ex.eq === 'body weight')
|
||||
if (!loaded || !bodyweight) throw new Error('recovery tests require loaded and bodyweight fixtures')
|
||||
const loadedSlug = Object.keys(musclesOf(loaded))[0]
|
||||
const bodyweightSlug = Object.keys(musclesOf(bodyweight))[0]
|
||||
const stampedWorkout = ({ id, start, unit, weight, target, bw }) => ({
|
||||
d: new Date(start).toISOString(), start, unit, bw,
|
||||
entries: [{ id, target, sets: [{ done: true, w: weight, r: 8 }] }],
|
||||
})
|
||||
|
||||
it('gives kg and physically equivalent stamped-pound histories the same fatigue', () => {
|
||||
const kg = stampedWorkout({ id: loaded.id, start: NOW, unit: 'kg', weight: 80 })
|
||||
const lb = stampedWorkout({ id: loaded.id, start: NOW, unit: 'lb', weight: 176.3696 })
|
||||
|
||||
expect(fatigueOf([lb], NOW, { unit: 'kg' })[loadedSlug])
|
||||
.toBeCloseTo(fatigueOf([kg], NOW, { unit: 'kg' })[loadedSlug], 6)
|
||||
})
|
||||
|
||||
it('normalizes mixed stamped units before computing the causal reference volume', () => {
|
||||
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({
|
||||
id: loaded.id, start, unit: i % 2 ? 'lb' : 'kg', weight: i % 2 ? 176.3696 : 80,
|
||||
}))
|
||||
|
||||
expect(fatigueOf(mixed, NOW, { unit: 'kg' })[loadedSlug])
|
||||
.toBeCloseTo(fatigueOf(kg, NOW, { unit: 'kg' })[loadedSlug], 6)
|
||||
})
|
||||
|
||||
it('treats an unstamped legacy history as being in the profile unit', () => {
|
||||
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 }] }] }
|
||||
|
||||
expect(fatigueOf([legacyLb], NOW, { unit: 'lb' })[loadedSlug])
|
||||
.toBeCloseTo(fatigueOf([kg], NOW, { unit: 'kg' })[loadedSlug], 6)
|
||||
})
|
||||
|
||||
it('uses configured bodyweight for a non-catalogue bodyweight target', () => {
|
||||
const workout = stampedWorkout({
|
||||
id: loaded.id, start: NOW, unit: 'kg', weight: 0,
|
||||
target: { bodyweight: true }, bw: 80,
|
||||
})
|
||||
|
||||
expect(fatigueOf([workout], NOW, { unit: 'kg' })[loadedSlug]).toBeGreaterThan(0)
|
||||
expect(strengthOf([workout], NOW, { unit: 'kg' })[loadedSlug]).toBe(1)
|
||||
})
|
||||
|
||||
it('adds external load to bodyweight instead of replacing the body mass', () => {
|
||||
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])
|
||||
})
|
||||
|
||||
it('lets explicitly configured custom bodyweight work reset strength', () => {
|
||||
const id = 'recovery-custom-bodyweight'
|
||||
registerCustom([{ id, n: 'Custom bodyweight', bp: 'chest', tg: 'chest', eq: 'custom', sm: [] }])
|
||||
try {
|
||||
const workout = stampedWorkout({ id, start: NOW, unit: 'kg', weight: 0, bw: 80, target: { bodyweight: true } })
|
||||
expect(fatigueOf([workout], NOW, { unit: 'kg' }).chest).toBeGreaterThan(0)
|
||||
expect(strengthOf([workout], NOW, { unit: 'kg' }).chest).toBe(1)
|
||||
} finally {
|
||||
registerCustom([])
|
||||
}
|
||||
})
|
||||
|
||||
it('counts a default custom zero-load ring push-up for fatigue and load-blind strength', () => {
|
||||
const id = 'recovery-ring-push-up'
|
||||
registerCustom([{ id, n: 'Ring push-up', bp: 'chest', tg: 'chest', eq: 'custom', sm: [] }])
|
||||
try {
|
||||
const workout = workoutAt(id, NOW, [
|
||||
{ done: true, w: 0, r: 20 },
|
||||
{ done: true, w: 0, r: 20 },
|
||||
])
|
||||
expect(fatigueOf([workout], NOW).chest).toBeCloseTo(1 - Math.exp(-2 / 3), 10)
|
||||
expect(strengthOf([workout], NOW).chest).toBe(1)
|
||||
} finally {
|
||||
registerCustom([])
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -37,7 +37,7 @@ function latestMuscleTraining(workouts) {
|
||||
return latest
|
||||
}
|
||||
|
||||
const FATIGUE_LEVELS = [
|
||||
export const FATIGUE_LEVELS = [
|
||||
{ at: 0, level: 0 },
|
||||
{ at: 0.15, level: 1 },
|
||||
{ at: 0.25, level: 2 },
|
||||
@@ -45,7 +45,7 @@ const FATIGUE_LEVELS = [
|
||||
{ at: 0.55, level: 4, exclusive: true },
|
||||
]
|
||||
|
||||
const STRENGTH_LEVELS = [
|
||||
export const STRENGTH_LEVELS = [
|
||||
{ at: STRENGTH_FLOOR, level: 0 },
|
||||
{ at: 0.625, level: 1 },
|
||||
{ at: 0.75, level: 2 },
|
||||
@@ -100,8 +100,16 @@ function MuscleBalance({ S }) {
|
||||
const [sel, setSel] = useState(null)
|
||||
const now = useNow()
|
||||
const workouts = S.workouts
|
||||
const fatigue = useMemo(() => fatigueOf(workouts, now), [workouts, now])
|
||||
const strength = useMemo(() => strengthOf(workouts, now), [workouts, now])
|
||||
// The user's own last registered bodyweight drives bodyweight-exercise tonnage.
|
||||
const bodyweightKg = useMemo(() => {
|
||||
const entries = S.bodyweight || []
|
||||
if (!entries.length) return null
|
||||
const last = entries.slice().sort((a, b) => String(a.d).localeCompare(String(b.d))).at(-1)
|
||||
if (!last || !(last.w > 0)) return null
|
||||
return S.unit === 'lb' ? last.w * 0.45359237 : last.w
|
||||
}, [S.bodyweight, S.unit])
|
||||
const fatigue = useMemo(() => fatigueOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit])
|
||||
const strength = useMemo(() => strengthOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit])
|
||||
const lastTrained = useMemo(() => latestMuscleTraining(workouts), [workouts])
|
||||
const { worked: strengthOrder } = rankOf(strength)
|
||||
const detrained = strengthOrder.filter(slug => strength[slug] < 1)
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { parseHTML } from 'linkedom'
|
||||
import { Window } from 'happy-dom'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MUSCLES, MUSCLE_NAME, levelsOf, rankOf } from '../lib/muscles.js'
|
||||
import { MUSCLES, levelsOf } from '../lib/muscles.js'
|
||||
import { FATIGUE_STATES, STRENGTH_FLOOR } from '../lib/recovery.js'
|
||||
import { fatigueStateOf } from '../lib/recovery-view.js'
|
||||
import Stats, { weeksSinceTraining } from './Stats.jsx'
|
||||
import Stats from './Stats.jsx'
|
||||
|
||||
const DAY = 86400000
|
||||
const HOUR = 3600000
|
||||
@@ -35,7 +35,7 @@ vi.mock('../components/BodyMap.jsx', () => ({
|
||||
default: props => {
|
||||
mocks.maps.push(props)
|
||||
React.useEffect(() => {
|
||||
mocks.mapMounts++
|
||||
mocks.mapMounts += 1
|
||||
return () => {}
|
||||
}, [])
|
||||
return React.createElement(
|
||||
@@ -59,7 +59,7 @@ function iso(timestamp) {
|
||||
}
|
||||
|
||||
function set(done, extra = {}) {
|
||||
return { done, w: 10, r: 8, unit: 'kg', ...extra }
|
||||
return { done, w: 80, r: 8, unit: 'kg', ...extra }
|
||||
}
|
||||
|
||||
function workout(id, start, entries) {
|
||||
@@ -71,49 +71,34 @@ function entry(id, sets) {
|
||||
}
|
||||
|
||||
function lifecycleWorkouts(now = BASE_NOW) {
|
||||
// A 6-set chest day on the saturating curve crosses .5 at ~55.05 hours, so the edge
|
||||
// flips fatigued -> recovering after one 60-second interval tick.
|
||||
const fatigueEdge = now - (36 * Math.log2(6 / (3 * Math.LN2)) * HOUR - 30000)
|
||||
// This completed set is in the initial 30-day Balance window, then ages out after one tick.
|
||||
// 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
|
||||
const fatigueEdge = now - (
|
||||
36 * Math.log2((6 * weightedSet / referenceAfterOldSession) / Math.LN2) * HOUR - 30000
|
||||
)
|
||||
const balanceEdge = now - (30 * DAY - 30000)
|
||||
// The 14-day strength edge becomes sub-full after one tick.
|
||||
const strengthEdge = now - (14 * DAY - 30000)
|
||||
// This completed event must remain the latest training event for abs: the newer set is undone.
|
||||
const absCompleted = now - 20 * DAY
|
||||
const absUndone = now - DAY
|
||||
return [
|
||||
workout('fatigue-edge', fatigueEdge, [entry('1254', Array.from({ length: 6 }, () => set(true, { rir: 0 })))]),
|
||||
workout('balance-edge', balanceEdge, [entry('1254', [set(true, { rir: 2 })])]),
|
||||
workout('strength-edge', strengthEdge, [entry('1001', [set(true, { rir: 2 })])]),
|
||||
workout('abs-completed', absCompleted, [entry('1002', [set(true, { rir: 2 })])]),
|
||||
workout('abs-undone', absUndone, [entry('1002', [set(false, { rir: 0 })])]),
|
||||
workout('abs-completed', now - 20 * DAY, [entry('1002', [set(true, { rir: 2 })])]),
|
||||
workout('abs-undone', now - DAY, [entry('1002', [set(false, { rir: 0 })])]),
|
||||
]
|
||||
}
|
||||
|
||||
function allFatiguedWorkout(now = BASE_NOW) {
|
||||
// Eight completed sets per exercise: on the saturating curve every involved muscle gets
|
||||
// raw >= 3.2 (0.4 x 8), i.e. a fatigue value above the .55 top band regardless of the
|
||||
// catalogue's secondary-muscle metadata.
|
||||
const ids = [
|
||||
['1018', 1], // trapezius
|
||||
['1012', 1], // deltoids
|
||||
['1167', 1], // chest
|
||||
['1013', 1], // upper-back
|
||||
['3011', 1], // serratus
|
||||
['1413', 1], // biceps
|
||||
['1399', 1], // triceps
|
||||
['1016', 1], // forearm
|
||||
['1005', 2], // abs + obliques
|
||||
['1010', 1], // lower-back
|
||||
['1003', 1], // gluteal
|
||||
['1001', 1], // quadriceps
|
||||
['1511', 1], // hamstring
|
||||
['1494', 1], // adductors
|
||||
['1002', 2], // abs + hip-flexors
|
||||
['1000', 1], // calves
|
||||
['1396', 2], // calves + tibialis
|
||||
'1018', '1012', '1167', '1013', '3011', '1413', '1399', '1016', '1005',
|
||||
'1010', '1003', '1001', '1511', '1494', '1002', '1000', '1396',
|
||||
]
|
||||
return workout('all-fatigued', now, ids.map(([id]) => entry(id, Array.from({ length: 8 }, () => set(true)))))
|
||||
return workout(
|
||||
'all-fatigued',
|
||||
now,
|
||||
ids.map(id => entry(id, Array.from({ length: 12 }, () => set(true)))),
|
||||
)
|
||||
}
|
||||
|
||||
function allSubfullWorkout(now = BASE_NOW) {
|
||||
@@ -121,20 +106,24 @@ function allSubfullWorkout(now = BASE_NOW) {
|
||||
}
|
||||
|
||||
function resetFixture(workouts = lifecycleWorkouts()) {
|
||||
mocks.S.unit = 'kg'
|
||||
mocks.S.bodyweight = []
|
||||
mocks.S.workouts = workouts
|
||||
mocks.maps.length = 0
|
||||
mocks.mapMounts = 0
|
||||
}
|
||||
|
||||
function installDom() {
|
||||
const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')
|
||||
dom = parsed.window
|
||||
dom = new Window({ url: 'http://localhost/' })
|
||||
globalThis.window = dom
|
||||
globalThis.document = dom.document
|
||||
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
|
||||
for (const key of ['HTMLElement', 'Node', 'Element', 'Event']) globalThis[key] = dom[key]
|
||||
for (const key of ['HTMLElement', 'HTMLIFrameElement', 'Node', 'Element', 'Event', 'MouseEvent']) {
|
||||
globalThis[key] = dom[key]
|
||||
}
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
container = document.getElementById('root')
|
||||
container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
root = createRoot(container)
|
||||
}
|
||||
|
||||
@@ -148,6 +137,7 @@ async function unmountStats() {
|
||||
await act(async () => { root.unmount() })
|
||||
root = null
|
||||
container = null
|
||||
dom.close()
|
||||
dom = null
|
||||
}
|
||||
|
||||
@@ -166,36 +156,20 @@ function viewButton(text) {
|
||||
}
|
||||
|
||||
function balanceRangeButton(text) {
|
||||
const segments = muscleCard().querySelectorAll('.seg')
|
||||
return buttonWithText(segments[1], text)
|
||||
return buttonWithText(muscleCard().querySelectorAll('.seg')[1], text)
|
||||
}
|
||||
|
||||
async function click(button) {
|
||||
expect(button, `expected a button named ${button?.textContent || 'unknown'}`).toBeTruthy()
|
||||
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
|
||||
await act(async () => { button.dispatchEvent(new dom.MouseEvent('click', { bubbles: true })) })
|
||||
}
|
||||
|
||||
async function tick(milliseconds) {
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(milliseconds) })
|
||||
}
|
||||
|
||||
function lastMap() {
|
||||
return mocks.maps.at(-1)
|
||||
}
|
||||
|
||||
function expectPressed(button) {
|
||||
expect(button?.getAttribute('aria-pressed')).toBe('true')
|
||||
}
|
||||
|
||||
function strengthRows() {
|
||||
return [...muscleCard().querySelectorAll('.mrow .nm')].map(node => node.textContent.trim())
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await unmountStats()
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
const lastMap = () => mocks.maps.at(-1)
|
||||
const expectPressed = button => expect(button?.getAttribute('aria-pressed')).toBe('true')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
@@ -203,41 +177,48 @@ beforeEach(() => {
|
||||
resetFixture()
|
||||
})
|
||||
|
||||
describe('Stats muscle recovery view runtime', () => {
|
||||
it('starts in Balance and preserves range, hard filter, and selected muscle through every real view transition', async () => {
|
||||
await mountStats()
|
||||
const card = muscleCard()
|
||||
afterEach(async () => {
|
||||
await unmountStats()
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
expectPressed(buttonWithText(card, 'Muscle balance'))
|
||||
expectPressed(buttonWithText(card, 'Week'))
|
||||
describe('Stats muscle recovery view runtime', () => {
|
||||
it('dispatches real clicks through Balance, Fatigue, and Strength and preserves selection', async () => {
|
||||
await mountStats()
|
||||
expectPressed(viewButton('Muscle balance'))
|
||||
expectPressed(balanceRangeButton('Week'))
|
||||
|
||||
await click(balanceRangeButton('30d'))
|
||||
await click(buttonWithText(card, 'All'))
|
||||
await click(card.querySelector('[data-muscle="chest"]'))
|
||||
expectPressed(balanceRangeButton('30d'))
|
||||
await click(buttonWithText(muscleCard(), 'All'))
|
||||
await click(muscleCard().querySelector('[data-muscle="chest"]'))
|
||||
expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy()
|
||||
expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
|
||||
|
||||
await click(viewButton('Fatigue'))
|
||||
expectPressed(viewButton('Fatigue'))
|
||||
expect(lastMap().thresholds).toBeTruthy()
|
||||
expect(container.textContent).toContain('Fatigue shows how recently each muscle was trained. High means rest.')
|
||||
await click(viewButton('Strength'))
|
||||
expect(container.textContent).toContain('Strength shows retained muscle strength. Train again to reset it.')
|
||||
await click(viewButton('Muscle balance'))
|
||||
expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
|
||||
|
||||
await click(viewButton('Strength'))
|
||||
expectPressed(viewButton('Strength'))
|
||||
expect(lastMap().thresholds.at(-1)).toEqual({ at: 1, level: 4 })
|
||||
expect(container.textContent).toContain('Strength shows retained muscle strength. Train again to reset it.')
|
||||
|
||||
await click(viewButton('Muscle balance'))
|
||||
expectPressed(balanceRangeButton('30d'))
|
||||
expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy()
|
||||
expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy()
|
||||
expect(lastMap().selected).toBe('chest')
|
||||
expect(lastMap().load.chest).toBe(7)
|
||||
})
|
||||
|
||||
it('refreshes fatigue presentation, Balance 30-day filtering, and the mounted tree on the 60-second tick', async () => {
|
||||
it('updates the rendered Fatigue map and Balance window on the real 60-second interval', async () => {
|
||||
await mountStats()
|
||||
await click(balanceRangeButton('30d'))
|
||||
await click(viewButton('Fatigue'))
|
||||
await click(muscleCard().querySelector('[data-muscle="chest"]'))
|
||||
|
||||
const beforeTickMounts = mocks.mapMounts
|
||||
const mountsBeforeTick = mocks.mapMounts
|
||||
const beforeTick = lastMap().load.chest
|
||||
expect(fatigueStateOf(beforeTick)).toBe(FATIGUE_STATES.FATIGUED)
|
||||
expect(container.textContent).toContain('Fatigued')
|
||||
@@ -245,43 +226,34 @@ describe('Stats muscle recovery view runtime', () => {
|
||||
await tick(60000)
|
||||
|
||||
const afterTick = lastMap().load.chest
|
||||
expect(mocks.mapMounts).toBe(beforeTickMounts)
|
||||
expect(afterTick).toBeLessThan(0.5)
|
||||
expect(mocks.mapMounts).toBe(mountsBeforeTick)
|
||||
expect(afterTick).toBeLessThan(beforeTick)
|
||||
expect(fatigueStateOf(afterTick)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(container.textContent).toContain('Recovering')
|
||||
|
||||
await click(viewButton('Strength'))
|
||||
expect(lastMap().load.quadriceps).toBeLessThan(1)
|
||||
expect(strengthRows()).toContain('Quads')
|
||||
|
||||
await click(viewButton('Muscle balance'))
|
||||
expect(lastMap().load.chest).toBe(6)
|
||||
expectPressed(balanceRangeButton('30d'))
|
||||
})
|
||||
|
||||
it('ignores an undone latest set, floors rendered training age, and follows production rankOf ordering', async () => {
|
||||
it('derives a pound-profile bodyweight in kg and passes it into the rendered Fatigue map', async () => {
|
||||
const bodyweightWorkout = workout('bodyweight', BASE_NOW, [
|
||||
entry('0001', [{ done: true, w: 0, r: 10 }]),
|
||||
])
|
||||
resetFixture([bodyweightWorkout])
|
||||
mocks.S.unit = 'lb'
|
||||
mocks.S.bodyweight = [{ d: '2026-01-20', w: 180 }, { d: '2026-01-22', w: 220.462262 }]
|
||||
|
||||
await mountStats()
|
||||
await click(viewButton('Strength'))
|
||||
await click(viewButton('Fatigue'))
|
||||
|
||||
const load = lastMap().load
|
||||
const expectedRows = rankOf(load).worked
|
||||
.filter(slug => load[slug] < 1)
|
||||
.map(slug => MUSCLE_NAME[slug])
|
||||
expect(strengthRows()).toEqual(expectedRows)
|
||||
|
||||
// The newer abs row is undone, so the rendered hint uses the completed event from 20 days ago.
|
||||
expect(container.textContent).toContain('1 sets')
|
||||
|
||||
// The production helper used by Stats' rendered strength hint floors six elapsed days to zero.
|
||||
expect(weeksSinceTraining(BASE_NOW, BASE_NOW - 6 * DAY)).toBe(0)
|
||||
// 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)
|
||||
expect(lastMap().thresholds).toBeTruthy()
|
||||
})
|
||||
|
||||
it('uses production boundaries and fixed absolute bands for all-fatigued and all-subfull maps', async () => {
|
||||
expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY)
|
||||
expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING)
|
||||
expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED)
|
||||
|
||||
it('renders fixed absolute bands through the actual Fatigue and Strength views', async () => {
|
||||
resetFixture([allFatiguedWorkout()])
|
||||
await mountStats()
|
||||
await click(viewButton('Fatigue'))
|
||||
|
||||
Reference in new issue
Block a user