diff --git a/frontend/package-lock.json b/frontend/package-lock.json index fbdf56d..d923859 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "opengym-frontend", - "version": "1.2.5", + "version": "1.2.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opengym-frontend", - "version": "1.2.5", + "version": "1.2.6", "license": "AGPL-3.0-or-later", "dependencies": { "@capacitor/core": "^7.6.8", @@ -24,7 +24,7 @@ "@capacitor/cli": "^7.6.8", "@capacitor/ios": "^7.6.8", "@vitejs/plugin-react": "^6.0.3", - "linkedom": "^0.18.13", + "happy-dom": "^20.11.2", "vite": "^8.1.5", "vitest": "^4.1.10" } @@ -1265,6 +1265,23 @@ "integrity": "sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==", "dev": true }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -2071,6 +2088,19 @@ "node": "*" } }, + "node_modules/buffer-image-size": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", + "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + }, + "engines": { + "node": ">=4.0" + } + }, "node_modules/camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -2595,13 +2625,6 @@ "url": "https://github.com/sponsors/fb55" } }, - "node_modules/cssom": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz", - "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==", - "dev": true, - "license": "MIT" - }, "node_modules/dargs": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/dargs/-/dargs-7.0.0.tgz", @@ -3276,6 +3299,38 @@ "uglify-js": "^3.1.4" } }, + "node_modules/happy-dom": { + "version": "20.11.2", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.11.2.tgz", + "integrity": "sha512-7MB+bJLkxu3SowAfBJbjW+c55kNz5tkR45gu2qzrxznezhLeN5YIlJbwUgSzlGc+qWoZ8Ykg71H5ezz69xixrw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": ">=20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "@types/ws": "^8.18.1", + "buffer-image-size": "^0.6.4", + "entities": "^7.0.1", + "whatwg-mimetype": "^3.0.0", + "ws": "^8.21.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/happy-dom/node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/hard-rejection": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/hard-rejection/-/hard-rejection-2.1.0.tgz", @@ -3345,105 +3400,6 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, - "node_modules/html-escaper": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz", - "integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/htmlparser2": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz", - "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==", - "dev": true, - "funding": [ - "https://github.com/fb55/htmlparser2?sponsor=1", - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "MIT", - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.2.2", - "entities": "^7.0.1" - } - }, - "node_modules/htmlparser2/node_modules/dom-serializer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", - "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", - "dev": true, - "license": "MIT", - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.2", - "entities": "^4.2.0" - }, - "funding": { - "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" - } - }, - "node_modules/htmlparser2/node_modules/dom-serializer/node_modules/entities": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/htmlparser2/node_modules/domhandler": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", - "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "domelementtype": "^2.3.0" - }, - "engines": { - "node": ">= 4" - }, - "funding": { - "url": "https://github.com/fb55/domhandler?sponsor=1" - } - }, - "node_modules/htmlparser2/node_modules/domutils": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", - "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "dom-serializer": "^2.0.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3" - }, - "funding": { - "url": "https://github.com/fb55/domutils?sponsor=1" - } - }, - "node_modules/htmlparser2/node_modules/entities": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", - "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, "node_modules/ieee754": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", @@ -3933,181 +3889,6 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true }, - "node_modules/linkedom": { - "version": "0.18.13", - "resolved": "https://registry.npmjs.org/linkedom/-/linkedom-0.18.13.tgz", - "integrity": "sha512-ES/o9qotMpzpN2MHs+Iq/JcVoOj8Fa5wiQYrTdFpvAnwXL0g66XHHUc9WUMk6nAlBtGsFQ24ne+SYnvnaQ2FSw==", - "dev": true, - "license": "ISC", - "dependencies": { - "css-select": "^7.0.0", - "cssom": "^0.5.0", - "html-escaper": "^3.0.3", - "htmlparser2": "^10.1.0", - "uhyphen": "^0.2.0" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "canvas": ">= 2" - }, - "peerDependenciesMeta": { - "canvas": { - "optional": true - } - } - }, - "node_modules/linkedom/node_modules/boolbase": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz", - "integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - }, - "node_modules/linkedom/node_modules/css-select": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/css-select/-/css-select-7.0.0.tgz", - "integrity": "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "boolbase": "^2.0.0", - "css-what": "^8.0.0", - "domhandler": "^6.0.1", - "domutils": "^4.0.2", - "nth-check": "^3.0.1" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - }, - "node_modules/linkedom/node_modules/css-what": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/css-what/-/css-what-8.0.0.tgz", - "integrity": "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - }, - "node_modules/linkedom/node_modules/dom-serializer": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz", - "integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==", - "dev": true, - "license": "MIT", - "dependencies": { - "domelementtype": "^3.0.0", - "domhandler": "^6.0.0", - "entities": "^8.0.0" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" - } - }, - "node_modules/linkedom/node_modules/domelementtype": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz", - "integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "BSD-2-Clause", - "engines": { - "node": ">=20.19.0" - } - }, - "node_modules/linkedom/node_modules/domhandler": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz", - "integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "domelementtype": "^3.0.0" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/fb55/domhandler?sponsor=1" - } - }, - "node_modules/linkedom/node_modules/domutils": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz", - "integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "dom-serializer": "^3.0.0", - "domelementtype": "^3.0.0", - "domhandler": "^6.0.0" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/fb55/domutils?sponsor=1" - } - }, - "node_modules/linkedom/node_modules/entities": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz", - "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/linkedom/node_modules/nth-check": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-3.0.1.tgz", - "integrity": "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "boolbase": "^2.0.0" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/fb55/nth-check?sponsor=1" - } - }, "node_modules/load-json-file": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", @@ -6168,13 +5949,6 @@ "node": ">=0.8.0" } }, - "node_modules/uhyphen": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz", - "integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==", - "dev": true, - "license": "ISC" - }, "node_modules/undici-types": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", @@ -6418,6 +6192,16 @@ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", "dev": true }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", @@ -6494,6 +6278,28 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "dev": true }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/xcode": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/xcode/-/xcode-3.0.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index cca5e4f..adb365e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -9,7 +9,8 @@ "build:mobile": "VITE_MOBILE=1 VITE_IMG_BASE=https://cdn.jsdelivr.net/gh/hasaneyldrm/exercises-dataset@7455efae41b330c265e7cd4b78dfa848e7ce5ebd/images/ VITE_GIF_BASE=https://cdn.jsdelivr.net/gh/hasaneyldrm/exercises-dataset@7455efae41b330c265e7cd4b78dfa848e7ce5ebd/videos/ vite build && cap sync", "preview": "vite preview", "test": "vitest run", - "test:watch": "vitest" + "test:watch": "vitest", + "test:fatigue-probe": "node scripts/fatigue-monotonic-probe.mjs" }, "license": "AGPL-3.0-or-later", "dependencies": { @@ -28,7 +29,7 @@ "@capacitor/cli": "^7.6.8", "@capacitor/ios": "^7.6.8", "@vitejs/plugin-react": "^6.0.3", - "linkedom": "^0.18.13", + "happy-dom": "^20.11.2", "vite": "^8.1.5", "vitest": "^4.1.10" } diff --git a/frontend/scripts/fatigue-monotonic-probe.mjs b/frontend/scripts/fatigue-monotonic-probe.mjs new file mode 100644 index 0000000..89aec62 --- /dev/null +++ b/frontend/scripts/fatigue-monotonic-probe.mjs @@ -0,0 +1,100 @@ +import { FATIGUE_SCAN_MS, fatigueOf } from '../src/lib/recovery.js' + +const HOUR = 60 * 60 * 1000 +const DAY = 24 * HOUR +const BASE = Date.UTC(2026, 0, 31, 12) +const ID = '1254' + +const workout = (start, weight, count = 8) => ({ + d: new Date(start).toISOString(), + start, + entries: [{ + id: ID, + sets: Array.from({ length: count }, () => ({ done: true, w: weight, r: 8 })), + }], +}) + +// Deterministic LCG: failures reproduce exactly without an external property-testing dependency. +let seed = 0x5eed1234 +const random = () => { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0 + return seed / 0x100000000 +} + +let comparisons = 0 +let deletionComparisons = 0 +let largestIncrease = -Infinity +for (let historyIndex = 0; historyIndex < 100; historyIndex += 1) { + const sessionCount = 3 + Math.floor(random() * 10) + const history = Array.from({ length: sessionCount }, () => { + const ageHours = Math.floor(random() * 120 * 24) + const weight = 40 + Math.floor(random() * 141) + const count = 1 + Math.floor(random() * 12) + return workout(BASE - ageHours * HOUR, weight, count) + }) + + let previous = fatigueOf(history, BASE).chest + for (let hour = 1; hour <= 1080; hour += 1) { + const current = fatigueOf(history, BASE + hour * HOUR).chest + const increase = current - previous + largestIncrease = Math.max(largestIncrease, increase) + if (increase > 1e-12) { + throw new Error( + `fatigue increased in history ${historyIndex} at hour ${hour}: ${previous} -> ${current}`, + ) + } + previous = current + comparisons += 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 + } + } +} + +if (comparisons !== 108000) throw new Error(`expected 108000 comparisons, got ${comparisons}`) + +// Pin the two history-edit invariants alongside the randomized property probes. +const today = workout(BASE, 100, 5) +const baseline = fatigueOf([today], BASE).chest +for (const oldImport of [workout(BASE - 90 * DAY, 140, 10), workout(BASE - 90 * DAY, 100, 20)]) { + if (fatigueOf([oldImport, today], BASE).chest !== baseline) { + throw new Error('an import older than the scan changed current fatigue') + } +} + +const deletionHistory = [ + workout(BASE - FATIGUE_SCAN_MS - DAY, 100, 15), + workout(BASE - 3 * DAY, 100, 8), + workout(BASE - 2 * DAY, 100, 8), + workout(BASE - DAY, 60, 4), + 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]}`) + } + } +} + +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', +) diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js index ebc8020..5d63f00 100644 --- a/frontend/src/lib/recovery.js +++ b/frontend/src/lib/recovery.js @@ -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) + +export 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 + || numeric(opts.bodyweightKg) !== null + || numeric(opts.bodyweight) !== null + || hasUnitStamp(set, entry?.target, entry, workout) + return ex?.eq === 'body weight' && (added === 0 || hasBodyweightContext) +} + +function loadKgFor(ex, entry, set, workout, opts = {}) { + const setUnit = unitOf(set, entry?.target, entry, workout, opts) + const addedKg = kgOf(set?.w, setUnit) + const loadUnit = hasUnitStamp(set, entry?.target, entry) ? setUnit : undefined + return bodyweightConfigured(ex, entry, set, workout, opts) + ? bodyweightKgFor(workout, opts, loadUnit) + addedKg + : addedKg +} + +// Best Epley estimate inside one session. Keeping intensity context on the session makes a +// scored stimulus independent of later imports/deletes; unlike an all-history maximum, a +// 90-day-old CSV row cannot retroactively reweight today's sets. +function session1RMs(workout, opts = {}) { + const best = new Map() + for (const entry of workout?.entries || []) { + const ex = 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])) @@ -94,10 +253,10 @@ function fatigueValue(events, now) { value += event.stimulus lastTimestamp = event.timestamp } - value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS) + value *= halfLifeDecay(Math.max(0, now - lastTimestamp), FATIGUE_HALF_LIFE_MS) // Normalise the accumulated stimulus to a saturating fatigue level: more volume starts // higher but never pins, and the value fades asymptotically - no window-edge cliff. - 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} 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} 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} 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) } diff --git a/frontend/src/lib/recovery.test.js b/frontend/src/lib/recovery.test.js index 0f0d35a..884f814 100644 --- a/frontend/src/lib/recovery.test.js +++ b/frontend/src/lib/recovery.test.js @@ -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,122 @@ 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('treats a future-dated workout as its own timestamp, never amplified', () => { + // A CSV import with a bad timezone can date a workout 10 days in the future. The final + // decay clamps the age to zero instead of exponentiating, so the session counts exactly + // like the same workout dated now - no 2^(10d/36h) ~ 102x amplification. + const future = doneWorkoutAt(SINGLE.id, NOW + 10 * DAY, 5) + const now = doneWorkoutAt(SINGLE.id, NOW, 5) + const futureValue = fatigueOf([future], NOW)[SINGLE_SLUG] + const nowValue = fatigueOf([now], NOW)[SINGLE_SLUG] + expect(futureValue).toBeCloseTo(nowValue, 10) + expect(futureValue).toBeLessThan(1) + }) + + 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([]) + } + }) +}) diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index af08fba..14ef77b 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -11,7 +11,7 @@ import Heatmap from '../components/Heatmap.jsx' import Icon from '../components/Icon.jsx' import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx' import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js' -import { fatigueOf, strengthOf, STRENGTH_FLOOR } from '../lib/recovery.js' +import { fatigueOf, strengthOf, STRENGTH_FLOOR, LB_TO_KG } from '../lib/recovery.js' import { fatigueStateOf } from '../lib/recovery-view.js' import { e1rmSeries, best1RM } from '../lib/onerm.js' import { @@ -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 * LB_TO_KG : 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) diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx index bf06701..70d1e0a 100644 --- a/frontend/src/views/Stats.recovery.test.jsx +++ b/frontend/src/views/Stats.recovery.test.jsx @@ -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('
') - 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'))