Compare commits

...
11 Commits
Author SHA1 Message Date
Duarte Santos 551b072c54 MCP: die zweite Einheit an einem Tag ist erreichbar, und ein leeres 1RM sagt warum
Zwei Befunde aus dem Parity-Durchlauf gegen echte Daten. Die Arithmetik stimmte
ueberall (rund 120 Werte gegen eine unabhaengige Nachrechnung, null Abweichung)
— diese beiden nicht.

get_workout nahm `.find(x => x.d === date)`. Wer morgens hebt und abends laeuft,
hat zwei Einheiten am selben Datum, und die zweite war ueber gar keinen Weg
erreichbar: es gab nirgends eine id, und die Frage nach dem Lauf bekam die
Zahlen des Zugtrainings — vollkommen selbstbewusst vorgetragen. list_workouts
liefert jetzt `id`, get_workout nimmt `workout_id` oder `date`, und bei zwei
Treffern am selben Tag antwortet es mit beiden zur Auswahl statt zu raten.

Und `best: null` hatte zwei gegensaetzliche Ursachen in einer Form: nie
trainiert, oder immer ueber der 12-Wiederholungs-Grenze. Eine Wade, die seit
Monaten mit 15ern im Log steht, las sich damit als "keine Aufzeichnungen".
no_estimate_reason unterscheidet die beiden, und formula_note steht jetzt auch
auf diesem Zweig — bisher gab es die Erklaerung nur in der PR-Tabelle.

Drei Regressionstests dazu (36 statt 33), mcp/README zu get_workout nachgezogen.
2026-08-04 17:48:52 +02:00
Duarte Santos e007f76d43 MCP: CI laeuft ueberhaupt erstmal, und der Server ueberlebt seinen Client nicht
Fuer mcp/ gab es keinen CI-Job — weder die 33 Tests noch sonst irgendwas lief je
auf GitHub. Jetzt laeuft beides bei jedem PR, der mcp/ oder frontend/ anfasst.

Dazu der Check, den die Testsuite prinzipiell nicht machen kann: vitest loest
ueber Vite auf, also gehen dort import.meta.glob, ?raw und .jsx anstandslos
durch. Genau so kam ein Vite-only-Import in ein gemeinsames Lib-Modul und liess
33 gruene Tests ueber einem Server stehen, der beim Start starb.
check-node-loadable.mjs laeuft deshalb unter nacktem node — dass es ausserhalb
von vitest laeuft, IST der Test. Gegengeprueft: Bug wieder eingebaut → Exit 1
und history.js/progression.js/tools.js namentlich gemeldet; sauber → Exit 0.

Und der fs.watch-Handle haelt die Event-Loop offen, sobald es eine State-Datei
zu beobachten gibt — der Prozess ueberlebt damit den Client, der ihn gestartet
hat, obwohl die mcp/README genau das Gegenteil verspricht. Ein unref() reicht;
nachgemessen: mit State-Datei vorher Exit 124 (haengt), jetzt Exit 0, und der
Watcher invalidiert den Cache unveraendert weiter.
2026-08-04 16:40:03 +02:00
Duarte Santos e28345dd13 Release v1.2.5: der MCP-Server, und sonst nichts an der App
Letztes publiziertes Release war v1.2.4, also ist das hier v1.2.5 — alles seit
dem Release in EINE Nummer. Inhalt ist genau eine Sache: der optionale
MCP-Server aus PR #19 nebst dem i18n-Kern-Split, der ihn ueberhaupt erst unter
reinem Node ladbar macht.

An der App selbst aendert sich nichts. Wer keinen KI-Client benutzt, merkt von
diesem Release ueberhaupt nichts: nichts wandert in den Docker-Build, die
docker-compose.yml bleibt unberuehrt.

Kein neues APK — der Bundle-Hash bewegt sich zwar (der Modulgraph haengt jetzt
direkt am i18n-Kern), aber verhalten tut sich die App identisch. Die
Download-Zeile auf der Website bleibt deshalb bei v1.2.4.
2026-08-04 16:35:34 +02:00
Duarte Santos ba412cb36d MCP: die Lib bleibt unter reinem Node ladbar, und die Testwerte stimmen wieder
Der MCP-Server ist ein nacktes `node src/index.js` — kein Vite, kein React. PR 19
hatte dafuer den reinen Kern nach i18n-core.js gezogen; v1.2.4 hat danach in
history.js `t` wieder aus i18n.js geholt, und damit import.meta.glob ueber die
Locale-Packs plus useSyncExternalStore in einen Prozess, der beides nicht hat.
Der Server starb beim Import:

  TypeError: (intermediate value).glob is not a function

Die Testsuite konnte das nicht sehen: vitest transformiert import.meta.glob, also
liefen 33 gruene Tests gegen ein Binary, das nie startet. i18n.js re-exportiert
ohnehin genau dieses `t` aus dem Kern — history.js, mobile.js und plan-share.js
holen es jetzt direkt von dort, und mitgeschleppt wird nichts mehr.

Dazu die Werte, die der v1.2.4-Seed verschoben hat: Volumen 18500 → 18412.5
(Handsumme w×r ueber die zwanzig erledigten Saetze), Koerpergewicht 78.6 → 78.4,
Wiegung 78.5/1.5 → 78.3/1.3, Dauer 51 min → 1h 11m — samt der Zusicherung, die
sich das "N min"-Format noch fest verdrahtet hatte. Jeder Wert nachgerechnet,
nicht aus einem roten Lauf abgeschrieben.

Und das FORMULAS aus Punkt 2 des Reviews, das als einziges stehengeblieben war.
2026-08-04 16:30:34 +02:00
Duarte Santos f554b6b004 Merge pull request #19 from Pengboi/feat/mcp-server
MCP: read-only stdio server for LLM apps to query workout history

Ein Node-Prozess, den der LLM-Client selbst startet und der dieselben reinen
Helfer aus frontend/src/lib benutzt wie die Stats-Seite — also stehen dort
dieselben Zahlen. Read-only, kein Container, kein zusaetzliches Auth, nichts
verlaesst die Box. Wer keinen KI-Client benutzt, merkt nichts davon.
2026-08-04 16:30:14 +02:00
Pengboi 09949686c2 MCP: fixes from review (cardio mode, dead code, Stryker drop, docs)
· entryView was passing `e.target || { id: e.id }` to modeOf, which
   doesn't put id on the target when target exists — so a cardio config
   saved as {sets, min, speed} (no mode, no id) fell through to 'reps'
   and the label came back as "0×0". Now uses the same pattern every
   app call site uses (Workout.jsx, Stats.jsx, progression.js):
   modeOf({ ...(e.target || {}), id: e.id }). Same fix applied to the
   setLabel call right below. Added a regression test using a real
   cardio exercise id with a target that has no mode key — would have
   caught the original bug.

 · requireIso/ISO/fmt/friendlyDate/MUSCLES were unused (zod regexes
   cover ISO validation at the SDK layer). Removed, along with the
   misplaced comment that described requireIso but sat above entryView.

 · estimate_1rm's exercise_id schema description referenced
   search_exercises (v1.5) which doesn't exist yet — an LLM reading
   the schema would try to call it. Dropped the reference; the
   Roadmap section in mcp/README.md drops the same mention.

 · resolveUid threw "set OPENGYM_UID to one of: " (empty list) when
   there were zero state files but multiple users in db.json — the
   files array was empty so files.join(', ') rendered nothing. Now
   falls back to the db.json user ids in that branch.

 · Dropped Stryker entirely. The MCP SDK's 93 transitive runtime
   packages are tolerable since mcp/ is opt-in and never enters
   Docker, but a second test toolchain for a 39% mutation score
   wasn't carrying its weight next to the plain vitest suite.
   Removed .stryker.conf.json, the two Stryker devDeps, the
   mutation:test script, the .gitignore entries, and the README
   section. mcp/ now has a single devDep (vitest); 0 vulnerabilities
   (was 2 moderate).

 · CONTRIBUTING.md layout block + a one-line cross-reference in
   README.md's Tech section pointing at mcp/README.md, so people can
   actually find it.

92 frontend + 33 MCP tests pass.
2026-08-02 19:42:36 +01:00
Duarte Santos 7c69e57b4f Website: the download is v1.2.4
The APK on opengym.duarte-santos.ch is the 1.2.4 build (versionCode 5, same
signing key, so it installs over 1.2.3). The meta line said 1.2.3.
2026-08-01 17:09:28 +02:00
Pengboi 6aaf2a3eea Comments: trim to the established cadence
The MCP code came in with 5–8 line file headers, JSDoc on every
one-line wrapper, and inline explanations that referenced the PR
itself ("so the MCP server can reuse it") — none of which matches
api/server.js or frontend/src/lib/, where comments are one-line,
fact-shaped and never mention the change that introduced them.

Trimmed across mcp/src/*.js, i18n-core.js, i18n.js, exercises.js,
format.js, mcp/test/tools.test.js, mcp/vitest.config.js and
mcp/README.md. Tool prefaces lost their numbers; duplicate fs.watch
rationale folded into one; the ASCII import diagram in the README
replaced with a paragraph; the cross-references and self-references
removed. Also fixed two real defects: a corrupted Cyrillic word in a
state.js comment and a missing space in a tools.test.js comment.

No code changes; 92 frontend + 32 MCP tests still pass.
2026-07-26 19:47:52 +01:00
Pengboi 4143ab8676 Tests: Stryker mutation testing on the MCP handlers
Adds Stryker 9.6.1 as a devDep and a .stryker.conf.json scoped to the three MCP-only
modules (src/state.js, src/labels.js, src/tools.js). The reused pure lib in
frontend/src/lib/ is deliberately excluded — it has its own 92-test vitest suite, and
mutating it here would just re-test it under a different label.

Two non-obvious config choices, both learned the hard way:
 · inPlace: true. Stryker's default copies the project to a sandbox, but the MCP test
   file imports "../../frontend/src/lib/*.js" — a relative path that breaks the moment
   the source is moved. inPlace mutates files where they live, keeps a backup in
   .stryker-tmp/backup-*/ during the run, and restores on exit. Verified: after the
   run, `git diff` shows no changes and all 92+32 tests still pass.
 · vitest.related: false. The vitest runner's related-files mode uses static import
   analysis to pick which tests to run per mutant; it can't see the cross-directory
   imports and reported "no tests were found". Disabling it means every mutant runs
   the full suite — slower (~54s for 847 mutants) but accurate.

Baseline first run: 39.32% mutation score (333 killed, 330 survived, 184 no-coverage).
Most of the survivors are zod schema string literals (the unit suite bypasses the SDK's
validation by calling handlers directly), and the bulk of the no-coverage debt lives in
state.js — file watching, multi-user resolution and the mtime fallback paths. The HTML
report at mcp/reports/mutation/mutation.html (gitignored, regenerated per run) shows
each survived mutant inline.

Run with `npm run mutation:test` from mcp/.
2026-07-26 19:34:15 +01:00
Pengboi 92914dea43 MCP: read-only stdio server for LLM apps to query workout history
A Model Context Protocol bridge that lets an external LLM application (Claude Desktop,
Cursor, Cline, Continue, …) read a user's openGym profile directly from ./data — no new
container, no extra auth, no third-party service. The LLM client spawns the server
locally as a stdio process (per the official MCP model); reads the same state-<uid>.json
the api server writes; reuses the pure training helpers from frontend/src/lib/*.js so
the numbers it answers with match what the Stats screen shows exactly.

Eight tools in v1, all read-only:
 · list_routines, get_routine — names + exercise counts + per-exercise targets
 · get_week_plan — Mo/We/Fr assignments and today's routine, accounting for any
   date-specific overrides (a "rest" override cancels the day)
 · list_workouts, get_workout — newest-first session summaries + per-set breakdown
 · get_bodyweight — weigh-ins with the goal line and signed deltas vs goal
 · estimate_1rm — Epley/Brzycki/Lombardi formulas, all-time best + trend per exercise,
   or a PR table across all reps-mode exercises
 · muscle_balance — which muscles are trained vs neglected over a week/month/all window

State is read with fs.watch (mtime fallback for platforms where watchers are flaky) so
the server reflects a session the web UI just finished without a restart. No passkey
material, VAPID keys, or session secrets ever cross the boundary — handlers only ever
serialize fields from the state object plus the user's name from db.json.

The MCP server has exactly one runtime dependency beyond the SDK: none. zod is the SDK's
transitive; vitest and Stryker are devDeps only. Tests run against the demo seed fixture
(demoSeed.js) — 32 cases pinning the JSON shape and the most user-facing edge cases
(empty state, missing routine, rest-day override, zero-workout muscle_balance, three
1RM formulas, superset links, timed/cardio set labels).
2026-07-26 19:34:09 +01:00
Pengboi fadeb17b6c i18n: split the pure core out so the lib is Node-loadable
The pure training helpers (history, progression, onerm, muscles, format, exercises) are
deliberately self-contained — that is what lets them ship with their own vitest suites and
got them reused across the React and mobile builds. They were one Vite-only call away from
being loadable from plain Node too: `import.meta.glob` for the lazy locale packs, run at the
top of i18n.js. Anything that imported `t` or `dateLocale` via the chain (i.e. every helper
in src/lib) inherited the dependency.

Splitting the runtime-agnostic state, constants and readers (t, dateLocale, instrFor, getLang,
LANGS, INSTR_LANGS, DATE_LOCALES) into i18n-core.js lets plain Node require them. i18n.js
keeps the Vite-only bits (the async setLang that lazy-loads locale packs via import.meta.glob
and the React subscription hook useLang) and re-exports everything from core, so none of the
23 existing import sites change.

exercises.js had one direct `import.meta.env` access for IMG_BASE/GIF_BASE — guarded with
`?.` so the module resolves without Vite present. format.js and exercises.js import i18n-core
directly; everything else still imports i18n.js.

No public exports changed. 92/92 vitest tests pass; vite build still code-splits the locale
packs the same way.
2026-07-26 19:34:01 +01:00
26 changed files with 4005 additions and 51 deletions

No files matched your search

+22
View File
@@ -6,11 +6,13 @@ on:
pull_request:
paths:
- 'frontend/**'
- 'mcp/**'
- '.github/workflows/test.yml'
push:
branches: [main]
paths:
- 'frontend/**'
- 'mcp/**'
- '.github/workflows/test.yml'
workflow_dispatch:
@@ -41,3 +43,23 @@ jobs:
working-directory: frontend
- run: node scripts/check-locales.mjs
working-directory: frontend
mcp:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
cache-dependency-path: mcp/package-lock.json
- run: npm ci
working-directory: mcp
- run: npm test
working-directory: mcp
# The one check the vitest suite structurally cannot make. The MCP server is a bare node
# process, but vitest runs its tests through Vite — import.meta.glob, .jsx imports and
# ?raw all resolve happily there. That is how a Vite-only import reached a shared lib
# module with 33 green tests standing over a server that died on startup.
- run: npm run check:node-loadable
working-directory: mcp
+42
View File
@@ -1,5 +1,47 @@
# Changelog
## v1.2.5 — 2026-08-04
Nothing in the app itself changed. This release adds an optional side door: a small server that
lets an AI assistant you already run — Claude Desktop, Cursor, Cline — answer questions about
your own training, off the same files your instance already writes. If you don't use one, this
release is invisible to you.
### Ask an AI about your training, without the data leaving your box (#19)
- 🤖 **An MCP server (`mcp/`)** — opt-in, read-only, and not part of the Docker build. Your LLM
client spawns it as a local process, it reads `./data` directly, and it exits when the client
disconnects. No new container, no extra auth on the api, no third-party service, nothing over
the network. *"What did I bench last week?", "what's my estimated 1RM on deadlift?", "which
muscles have I been neglecting?"*
- **The answers match the Stats screen because they are the same numbers.** The server calls the
very functions in `frontend/src/lib/` the app already computes with, rather than reimplementing
them. Eight tools: routines, the week plan, workouts, one session in detail, body weight,
estimated 1RM and muscle balance.
- **Read-only on purpose.** Logging a workout from an assistant needs a long-lived token the api
does not have yet, plus a lock against the web UI's read-modify-write. Until both exist, the
server answers questions and does nothing else. It never reads passkey material, VAPID keys or
session state — only the profile it was pointed at.
- `docker-compose.yml` is untouched and nothing new enters the image, so an instance that ignores
this ships exactly what it shipped before. Setup is in [mcp/README.md](mcp/README.md).
### Under the hood
- The pure half of `i18n.js` — the language state, the constants, the readers — moved into
`i18n-core.js`, so the helpers under `frontend/src/lib/` can be loaded by a plain Node process
and not only by Vite. `i18n.js` keeps the Vite-only parts (the locale-pack loader, the React
hook) and re-exports the rest, so nothing that imports it had to change.
- The shared lib modules that only need `t` now take it from the core directly. A Vite-only
import inside a shared module is invisible under vitest, which transforms it, and fatal to the
MCP server, which does not — so the shared half stays clear of the bundler half by
construction rather than by remembering to.
- `npm run check:node-loadable` in `mcp/` walks the server's import graph under a bare `node`,
which is the one thing the test suite cannot do from inside Vite. CI runs it, alongside the
MCP tests — neither had ever run there before.
The MCP server was contributed by [@Pengboi](https://github.com/Pengboi) — the first feature in
openGym written by someone other than me. Thank you.
## v1.2.4 — 2026-08-01
The effort ratings you have been recording since v1.2.3 now answer questions, and bodyweight
+3
View File
@@ -12,6 +12,9 @@ api/ backend — server.js (Node, no framework), one dependency (@simplewe
web/ multi-stage Dockerfile (builds frontend → nginx) + nginx.conf (serves app, proxies /api).
media/ exercise img/gif (gitignored, fetched at runtime).
docs/ self-hosting guide.
mcp/ optional Model Context Protocol server — read-only stdio bridge for LLM apps
(Claude Desktop, Cursor, …) to query a user's workouts/1RM/muscle balance. Not in
the Docker build; only runs when an LLM client spawns it. See mcp/README.md.
```
## Running for development
+5
View File
@@ -81,6 +81,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- 🌍 **12 languages** — full UI translation (EN, DE, ES, FR, IT, PT, PL, TR, RU, ZH, KO, HI); exercise instructions localized in 10 of them, loaded on demand so the app stays fast
- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy**, or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped
- 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry**
- 🤖 **Ask an AI about your training** (optional) — an [MCP server](mcp/README.md) lets a client like Claude Desktop or Cursor read your history in your own words: *"what did I bench last week?"*. Read-only, spawned locally by the client, nothing leaves your box. Not in the Docker build — if you don't use an AI assistant, it isn't there
- 📱 **Standalone Android app** — the whole tracker as a sideloadable APK: no account, no server, data on the phone, native workout reminders ([download](https://opengym.duarte-santos.ch))
## Quick start (self-host)
@@ -184,6 +185,10 @@ lives in pure functions under `frontend/src/lib/` with tests next to them: `npm
`frontend/`. Vitest is a dev dependency; the app itself ships no runtime dependencies beyond
React, the router and Zustand.
The same pure helpers power an optional MCP server (`mcp/`) that lets an LLM client like
Claude Desktop read your data over stdio — see [mcp/README.md](mcp/README.md). Opt-in, not
in the Docker build.
## Community
- **[Q&A](https://github.com/DuarteSantos8/openGym/discussions/categories/q-a)** — self-hosting
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gym-api",
"version": "1.2.4",
"version": "1.2.5",
"private": true,
"type": "module",
"main": "server.js",
+2 -2
View File
@@ -7,8 +7,8 @@ android {
applicationId "ch.duartesantos.opengym"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 5
versionName "1.2.4"
versionCode 6
versionName "1.2.5"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "opengym-frontend",
"version": "1.2.4",
"version": "1.2.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opengym-frontend",
"version": "1.2.4",
"version": "1.2.5",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/core": "^7.6.8",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "opengym-frontend",
"private": true,
"version": "1.2.4",
"version": "1.2.5",
"type": "module",
"scripts": {
"dev": "vite",
+6 -4
View File
@@ -1,5 +1,5 @@
import { EXDB } from './exercises-data.js'
import { t } from './i18n.js'
import { t } from './i18n-core.js'
export { EXDB }
export const EXIDX = {}
@@ -28,9 +28,11 @@ export const allExercises = st => [...(st.customEx || []), ...EXDB]
// Media normally sits next to the app (img/ and gif/, mounted into the web container).
// A build can point them somewhere else — the demo build pulls them off a CDN instead of
// shipping ~140 MB of images into the deployment.
const IMG_BASE = import.meta.env.VITE_IMG_BASE || 'img/'
const GIF_BASE = import.meta.env.VITE_GIF_BASE || 'gif/'
// shipping ~140 MB of images into the deployment. `import.meta.env` is undefined in plain
// Node; the guard keeps this module loadable without Vite.
const ENV = import.meta.env || {}
const IMG_BASE = ENV.VITE_IMG_BASE || 'img/'
const GIF_BASE = ENV.VITE_GIF_BASE || 'gif/'
export const imgSrc = ex => IMG_BASE + ex.img
export const gifSrc = ex => GIF_BASE + ex.gif
+1 -1
View File
@@ -1,5 +1,5 @@
// Formatting + date helpers (ported from the vanilla app, unit taken from the store where needed).
import { dateLocale, t } from './i18n.js'
import { dateLocale, t } from './i18n-core.js'
export const todayISO = () => {
const d = new Date()
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0')
+5 -1
View File
@@ -1,7 +1,11 @@
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
import { isCardio, isBodyweightEq } from './exercises.js'
import { t } from './i18n.js'
// i18n-core, not i18n: this file is imported by mcp/, which is plain Node with no Vite and no
// React. i18n.js is the Vite half — import.meta.glob over the locale packs, useSyncExternalStore
// for the hook — and it re-exports this very `t` from core, so nothing changes here except what
// gets dragged along behind it.
import { t } from './i18n-core.js'
// How an exercise is logged (issue #16). This used to be derived from the body part alone,
// which meant a plank or a farmer's carry could only be timed by filing it under cardio.
+44
View File
@@ -0,0 +1,44 @@
// Runtime-agnostic core of the i18n module: state, constants and readers (t, dateLocale,
// instrFor, getLang). Plain Node-loadable — the browser-only pieces (import.meta.glob lazy
// loads, the React subscription hook) live in i18n.js and re-export from here.
export const LANGS = {
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
pt: 'Português', pl: 'Polski', tr: 'Türkçe', ru: 'Русский', zh: '中文',
ko: '한국어', hi: 'हिन्दी'
}
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko']
export const DATE_LOCALES = {
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT',
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
}
let lang = 'en' // set only by _setLangState, called from i18n.js setLang
let dict = {} // current locale pack (empty = English fallback)
let instr = null // { exId: [steps] } for the current language, null = English
let version = 0 // bumped on every setLang; drives the React subscription selector
export const getLang = () => lang
export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB'
export const getVersion = () => version
// Translate a source string; {0},{1}… are replaced with args (also on the English fallback).
export function t(s, ...args) {
let v = dict[s] || s
for (let i = 0; i < args.length; i++) v = v.replaceAll('{' + i + '}', args[i])
return v
}
// Instructions for an exercise in the current language (English steps as fallback).
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
// Called by i18n.js's setLang once the locale pack has been loaded — kept here rather than
// exported as setLang because loading packs requires import.meta.glob, which is Vite-only.
// Both `dict` and `instr` may be null to reset to English.
export function _setLangState(newLang, newDict, newInstr) {
lang = LANGS[newLang] ? newLang : 'en'
dict = lang === 'en' ? {} : (newDict || {})
instr = lang === 'en' || !INSTR_LANGS.includes(lang) ? null : (newInstr || null)
version++
return version
}
+18 -36
View File
@@ -1,56 +1,38 @@
// Tiny dependency-free i18n. English source strings are the keys; locale files in
// src/locales/ map them to translations and are lazy-loaded (Vite code-splits each
// import.meta.glob entry), so the initial bundle stays English-only.
// Exercise instructions come from separately generated packs in src/instr/ (one per
// language, from the upstream dataset) — also lazy-loaded on language switch.
// Browser-only shell of the i18n module. The runtime-agnostic state and readers live
// in i18n-core.js (plain Node-loadable); this file adds the two pieces that genuinely need
// the browser: `setLang` (which lazy-loads locale packs via import.meta.glob) and the React
// subscription hook `useLang`.
import { useSyncExternalStore } from 'react'
import {
LANGS, INSTR_LANGS, DATE_LOCALES,
getLang, dateLocale, t, instrFor, getVersion, _setLangState
} from './i18n-core.js'
// UI languages. de/pt have no instruction pack upstream — instructions fall back to English.
export const LANGS = {
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
pt: 'Português', pl: 'Polski', tr: 'Türkçe', ru: 'Русский', zh: '中文',
ko: '한국어', hi: 'हिन्दी'
}
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko']
const DATE_LOCALES = {
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT',
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
}
export { LANGS, INSTR_LANGS, DATE_LOCALES, getLang, dateLocale, t, instrFor }
// Vite code-splits each locale pack into its own chunk via import.meta.glob; instructions use
// the same mechanism in src/instr/. Both are lazy, so the production bundle ships English only.
const localePacks = import.meta.glob('../locales/*.js')
const instrPacks = import.meta.glob('../instr/*.js')
let lang = 'en'
let dict = {}
let instr = null // { exId: [steps] } for the current language, null = English
let version = 0
// React subscription bookkeeping — kept here, not in core, so core has zero React coupling.
const subs = new Set()
const notify = () => { version++; subs.forEach(f => f()) }
export const getLang = () => lang
export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB'
// Translate a source string; {0},{1}… are replaced with args (also on the English fallback).
export function t(s, ...args) {
let v = dict[s] || s
for (let i = 0; i < args.length; i++) v = v.replaceAll('{' + i + '}', args[i])
return v
}
// Instructions for an exercise in the current language (English steps as fallback).
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
const notify = () => { subs.forEach(f => f()) }
export async function setLang(l) {
if (!LANGS[l]) l = 'en'
if (l === lang && version > 0) return
lang = l
if (l === getLang() && getVersion() > 0) return
let dict = {}, instr = null
try {
dict = l === 'en' ? {} : (await localePacks['../locales/' + l + '.js']()).default
instr = l === 'en' || !INSTR_LANGS.includes(l) ? null : (await instrPacks['../instr/' + l + '.js']()).default
} catch (e) { dict = {}; instr = null }
_setLangState(l, dict, instr)
notify()
}
// Re-renders the subscribing component (and its children) whenever the language changes.
export function useLang() {
return useSyncExternalStore(fn => { subs.add(fn); return () => subs.delete(fn) }, () => version)
return useSyncExternalStore(fn => { subs.add(fn); return () => subs.delete(fn) }, getVersion)
}
+1 -1
View File
@@ -9,7 +9,7 @@
//
// Like the demo build, MOBILE is replaced at build time, so all of this folds away in
// web bundles; the Capacitor plugins are only ever imported behind it.
import { t } from './i18n.js'
import { t } from './i18n-core.js'
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
+1 -1
View File
@@ -11,7 +11,7 @@
import { EXIDX, isBodyweightEq } from './exercises.js'
import { modeOf, fmtSec, isBw, isPerSide, sideReps } from './history.js'
import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'
import { t } from './i18n.js'
import { t } from './i18n-core.js'
const PLAN_FMT = 1
const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] // Mon-first, matching the Plan screen
+136
View File
@@ -0,0 +1,136 @@
# openGym MCP server
A [Model Context Protocol](https://modelcontextprotocol.io) bridge that lets an external LLM
application (Claude Desktop, Cursor, Cline, Continue, etc.) read your openGym profile —
routines, workouts, body-weight log, estimated 1RMs, and muscle balance — directly from your
self-hosted `./data` directory.
It is read-only, runs locally as a stdio process spawned by the LLM client, adds no new
container, and requires no extra authentication. The LLM never sees passkeys, VAPID keys, or
session secrets — it can only read the same `state-<uid>.json` files the openGym api already
writes.
The numbers it answers with are computed by the **same pure functions the React UI uses**
(`frontend/src/lib/*.js`) — `estimate1RM`, `loadOfWorkouts`, `effectiveRoutine`, etc. — so a
"what's my bench 1RM?" answer matches the Stats screen exactly.
> Phase 1 of a multi-phase plan. Read-only today; long-lived token auth + write tools are
> planned but not shipped yet. See **Roadmap** below.
## Quick start
### 1. Install
```bash
cd mcp
npm install
```
### 2. Point it at your data
The MCP server reads the same `./data` directory `docker compose up` creates. Pick the profile
to answer for — its user id is in `./data/db.json` under `users[].id`:
```bash
# single-user instance (the common self-hosted case) — auto-detected:
node src/index.js
# multi-user instance, or just to be explicit:
OPENGYM_UID=<your-uid> OPENGYM_DATA=/path/to/openGym/data node src/index.js
```
### 3. Register with your LLM client
Add the server to your LLM client's MCP config. For Claude Desktop, edit
`claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`):
```jsonc
{
"mcpServers": {
"opengym": {
"command": "node",
"args": ["/absolute/path/to/openGym/mcp/src/index.js"],
"env": {
"OPENGYM_DATA": "/absolute/path/to/openGym/data",
"OPENGYM_UID": "<your-uid>" // optional — auto-detected if you have one profile
}
}
}
}
```
For Cursor and other MCP-compatible clients, see the client's MCP docs — the same `command` +
`args` + `env` shape is what every stdio MCP server expects.
Restart the client; you should see the openGym tools appear with "serving profile \<name\>" on
the server's stderr.
## Tools
Eight read-only tools in v1:
| Tool | What it answers |
|---|---|
| `list_routines` | What routines are saved in my profile? (names + exercise counts) |
| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) |
| `get_week_plan` | What's on my plan this week, including today with any date-specific override? |
| `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. |
| `get_workout` | Full set-by-set breakdown of one session, by `workout_id` or by date. On a day with two sessions the date alone returns both ids to pick from rather than guessing at one. |
| `get_bodyweight` | Weigh-ins with the latest weight, the goal line, and deltas vs goal. |
| `estimate_1rm` | All-time best 1RM for an exercise + the trend, or a PR table across all exercises. |
| `muscle_balance` | Which muscles I've trained this week/month/all-time, ranked + which I've neglected. |
Each tool returns JSON the LLM can format as it likes; structured fields (sets, dates, levels)
are pre-formatted into human-readable labels in `src/labels.js` so the LLM doesn't need to
re-interpret them.
## How it reuses the training logic
The MCP server imports the training helpers under `frontend/src/lib/` directly as Node ESM
and calls the same functions the React UI does (`history.js`, `onerm.js`, `muscles.js`,
`exercises.js`). The numbers it returns match what the Stats screen shows, because they are
the same code.
The one lib file that wasn't Node-safe was `i18n.js` (Vite's `import.meta.glob` at module
top level) — split into `i18n-core.js` (pure, Node-safe) + `i18n.js` (Vite/React bits,
re-exports from core). `exercises.js` got a one-line `import.meta.env || {}` guard. No new
dependencies landed in `frontend/`, no public exports changed.
## Design constraints honoured
- **One runtime dependency beyond the MCP SDK:** none. No database driver, no HTTP framework.
- **No new container.** stdio transport is spawned by the LLM client; nothing to add to
`docker-compose.yml`.
- **No new auth.** The filesystem is the boundary — same as `docker compose` running on the
user's box. No passkey material, VAPID keys, or session secrets ever cross it.
- **No telemetry, no network.** Reads `./data/*.json` and exits when the LLM client
disconnects.
## Tests
```bash
cd mcp && npm test
```
32 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture
the public demo runs on). Pins JSON shape and the user-facing edge cases: rest-day override,
missing routine, zero-workout history, no synced state, superset links, three 1RM formulas.
"Today" is pinned via `vi.useFakeTimers({ now: ..., toFake: ['Date'] })` so date-dependent
tools see consistent values regardless of when the suite runs. The pure lib functions have
their own 92 tests in `frontend/src/lib/*.test.js`.
## Roadmap
- **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access.
- **Phase 1.5:** a `progression_next` tool (what does the policy prescribe next?). No new
deps; small surface area.
- **Phase 2:** read+write over stdio. Requires a long-lived token auth path minted from the
admin dashboard (new `./data/tokens.json`) and a write-lock against the web UI's read-modify-
write of `state-<uid>.json`. Tools: `log_workout`, `add_bodyweight`, `edit_routine`,
`assign_weekday`, `override_day`.
- **Phase 3:** Streamable HTTP transport, opt-in 4th container in `docker-compose.yml`. Same
tool implementations, second transport — the MCP SDK supports both behind one tool registration.
## License
AGPL-3.0-or-later, same as openGym.
+2465
View File
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
{
"name": "opengym-mcp",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "MCP (Model Context Protocol) bridge for openGym \u2014 lets an external LLM read your routines, workouts, body-weight log, estimated 1RMs and muscle balance from your self-hosted data. Read-only, stdio transport; no extra container.",
"license": "AGPL-3.0-or-later",
"main": "src/index.js",
"bin": {
"opengym-mcp": "src/index.js"
},
"scripts": {
"start": "node src/index.js",
"test": "vitest run",
"check:node-loadable": "node scripts/check-node-loadable.mjs"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.4",
"zod": "^3.23.8"
},
"devDependencies": {
"vitest": "^4.1.10"
}
}
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env node
/* Does the server's import graph still load under plain node?
*
* This exists because the test suite cannot answer that question. `npm test` runs vitest, and
* vitest resolves modules through Vite — `import.meta.glob`, `?raw`, a stray `.jsx` import all
* work there. The server does not run under Vite. So a Vite-only import can land in a shared
* lib module, leave all 33 tests green, and still kill the server at startup. That is exactly
* what happened once: `history.js` began importing `t` from `i18n.js` (import.meta.glob over
* the locale packs, plus React), and the server died on `import` with the suite none the wiser.
*
* Run by bare `node` on purpose — being outside vitest IS the check. Do not port this to a
* vitest test file; that would make it pass unconditionally.
*
* Importing the two entry modules is enough on its own: everything the server touches hangs off
* them, so a lib module that grows a browser-only dependency next year fails here without this
* list being updated. The named list below only exists to point at the culprit instead of at a
* stack trace ten frames deep.
*/
const LIB = new URL('../../frontend/src/lib/', import.meta.url)
// Every frontend/src/lib module the server reaches today. Named individually so a failure says
// which one, rather than which import chain.
const MODULES = [
'i18n-core.js', 'format.js', 'exercises.js', 'exercises-data.js',
'history.js', 'muscles.js', 'onerm.js', 'progression.js'
]
let failed = 0
for (const m of MODULES) {
try {
await import(new URL(m, LIB))
console.log(` ok ${m}`)
} catch (e) {
failed++
console.error(` FAIL ${m} — ${e.message}`)
}
}
// The real assertion: the server's own entry points, which pull the whole graph transitively.
// A module added to the graph later is covered by this even if the list above never learns it.
for (const entry of ['../src/state.js', '../src/tools.js']) {
try {
await import(new URL(entry, import.meta.url))
console.log(` ok mcp/${entry.replace('../', '')}`)
} catch (e) {
failed++
console.error(` FAIL mcp/${entry.replace('../', '')} — ${e.message}`)
}
}
if (failed) {
console.error(`\n${failed} module(s) do not load under plain node — the MCP server would not start.`)
process.exit(1)
}
console.log('\nthe whole MCP import graph loads under plain node.')
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env node
/* openGym MCP server — stdio transport. The LLM client (Claude Desktop, Cursor, …) spawns
this process locally, talks JSON-RPC over stdin/stdout, tears it down when the session ends.
No extra container, no new outbound network — your data stays in a folder you control. */
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { TOOLS } from './tools.js'
import { init, getUser } from './state.js'
const server = new McpServer({
name: 'opengym',
version: '0.1.0'
})
// Fail fast on bad config so a misnamed OPENGYM_DATA doesn't silently answer every call with
// the no-state sentinel. Always register every tool so the LLM sees the full list at
// handshake, even when state didn't resolve.
try {
init()
const u = getUser()
console.error(`[opengym-mcp] serving profile ${u.name} (${u.id})`)
} catch (e) {
console.error(`[opengym-mcp] ${e.message}`)
// Don't exit — keep the tool listings up so the user sees a useful error after fixing their
// env and restarting.
}
for (const t of TOOLS) {
server.tool(
t.name,
t.description,
t.schema,
async (params) => {
try {
const result = t.handler(params || {})
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] }
} catch (err) {
const code = err.code || 'ERROR'
return {
isError: true,
content: [{ type: 'text', text: `${code}: ${err.message}` }]
}
}
}
)
}
const transport = new StdioServerTransport()
await server.connect(transport)
// Process stays alive serving JSON-RPC over stdio until the LLM client disconnects.
+47
View File
@@ -0,0 +1,47 @@
// Formatting glue between lib helpers (which speak {0}/{1} templates) and the JSON returned
// to the LLM.
import { MUSCLE_NAME, MUSCLES } from '../../frontend/src/lib/muscles.js'
import { modeOf, fmtSec, setLabel } from '../../frontend/src/lib/history.js'
import { POLICY_NAME } from '../../frontend/src/lib/progression.js'
import { fmtDate, fmtNum, fmtDur } from '../../frontend/src/lib/format.js'
// Apply {0},{1},… substitutions to the template strings the lib returns.
export function fmt(template, args) {
let v = template
for (let i = 0; i < (args || []).length; i++) v = v.replaceAll('{' + i + '}', String(args[i]))
return v
}
export { setLabel }
export function exLine(cfg, unit) {
const mode = modeOf(cfg)
const n = cfg.sets || 1
const load = cfg.weight ? ' · ' + fmtNum(cfg.weight) + ' ' + unit : ''
if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtNum(cfg.speed || 8)} km/h`
if (mode === 'time') return `${n} × ${fmtSec(cfg.sec || 45)}${load}`
return `${n} × ${cfg.reps}${load}`
}
export function muscleName(slug) {
return MUSCLE_NAME[slug] || slug
}
export function policyName(policy) {
return POLICY_NAME[policy] || policy
}
export function friendlyDate(iso) {
if (!iso) return null
return fmtDate(iso)
}
export function friendlyDuration(ms) {
return ms ? fmtDur(ms) : null
}
export function ratio(done, total) {
return `${done}/${total}`
}
export function muscleOrder() { return MUSCLES.slice() }
+137
View File
@@ -0,0 +1,137 @@
/* opengym-mcp state — reads ./data/state-<uid>.json + db.json (read-only). Cached with an
fs.watch + mtime fallback so a session the api server just wrote is visible on the next
tool call without a restart. */
import fs from 'node:fs'
import path from 'node:path'
const DATA_DIR = process.env.OPENGYM_DATA || path.join(process.cwd(), 'data')
// null = no state file (brand-new account); undefined = not yet loaded.
let _state = undefined
let _db = undefined
let _uid = null
let _watcher = null
let _loadedMtime = 0 // mtimeMs we last read at — used to catch watcher omissions
function readJsonOrNull(file) {
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
}
function reloadDb() { _db = readJsonOrNull(path.join(DATA_DIR, 'db.json')) || { users: [], creds: [], subs: [], invites: [] } }
function stateFile(uid) {
return path.join(DATA_DIR, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json')
}
// Pick the uid: OPENGYM_UID env, else the only state-* file, else the only user in db.json.
// Throws listing the options if ambiguous. The sanitiser on stateFile() keeps a sneaky
// '..' in OPENGYM_UID harmless.
function resolveUid() {
const envUid = (process.env.OPENGYM_UID || '').trim()
if (envUid) {
if (!/^[a-zA-Z0-9_-]+$/.test(envUid)) throw new Error(`OPENGYM_UID contains characters that aren't safe in a filename: ${JSON.stringify(envUid)}`)
return envUid
}
const files = fs.readdirSync(DATA_DIR)
.filter(f => /^state-[a-zA-Z0-9_-]+\.json$/.test(f))
.map(f => f.replace(/^state-/, '').replace(/\.json$/, ''))
if (files.length === 1) return files[0]
if (files.length === 0) {
reloadDb()
if (_db.users.length === 1) return _db.users[0].id
if (_db.users.length === 0) throw new Error(`no openGym users found in ${path.join(DATA_DIR, 'db.json')} — sign in at least once on a device`)
// Multiple users in db.json but no state files yet — list their ids, not the (empty)
// files list. Hit when accounts exist but none has signed in on a device.
throw new Error(
`multiple openGym users found — set OPENGYM_UID to one of: ${_db.users.map(u => u.id).join(', ')}\n` +
` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)`
)
}
throw new Error(
`multiple openGym users found — set OPENGYM_UID to one of: ${files.join(', ')}\n` +
` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)`
)
}
// Idempotent. Picks the uid, loads db.json, attaches the watcher, primes state.
export function init() {
if (_uid !== null) return
if (!fs.existsSync(DATA_DIR)) throw new Error(`OPENGYM_DATA dir does not exist: ${DATA_DIR}`)
_uid = resolveUid()
reloadDb()
const file = stateFile(_uid)
if (fs.existsSync(file)) {
_state = readJsonOrNull(file)
if (_state) _state = Object.assign({}, defaultsShape(), _state)
try { _loadedMtime = fs.statSync(file).mtimeMs } catch {}
}
if (_watcher) _watcher.close()
// fs.watch is best-effort: the api server's atomic write at PUT /api/data is the source of
// truth, and a stale read just gets corrected on the next change or the next tool call.
try {
_watcher = fs.watch(file, () => {
// On change, simply clear the cache — the next getState() will re-read. Avoids reading
// twice if the watcher fires multiple events for one atomic-write (rename + create).
_state = undefined
_loadedMtime = 0
})
// Unref'd, or the watcher alone holds the event loop open and the process outlives the
// client that spawned it — "exits when the LLM client disconnects" stops being true the
// moment there is a state file to watch. Most clients kill the child anyway, but one that
// merely closes the pipe would leak a process per session. Watching is unaffected: the
// stdio transport is what keeps the loop alive while a client is actually attached.
_watcher.unref()
} catch { /* fs.watch unsupported on this platform; tools will re-read on mtime change */ }
}
// Returns the state object, or null for a fresh account that never signed in on a device.
export function getState() {
init()
const file = stateFile(_uid)
// Re-read if the file's mtime changed since our last load — covers watcher omissions and
// platforms with no fs.watch.
let mtime
try { mtime = fs.statSync(file).mtimeMs } catch {
return _state === undefined ? null : _state
}
if (_state === undefined || mtime !== _loadedMtime) {
const fresh = readJsonOrNull(file)
if (fresh) {
// Same shape the frontend builds on pullState — defaults merged with stored state so any
// field the app added since the snapshot was last saved shows up undefined-safe.
_state = Object.assign({}, defaultsShape(), fresh)
_loadedMtime = mtime
} else if (_state === undefined) {
_state = null // no state file at all — never signed in on a device
}
}
return _state
}
// Returns the user record (id + name). No passkey material, no VAPID keys, no push subs.
export function getUser() {
init()
const u = _db.users.find(x => x.id === _uid) || { id: _uid, name: 'Profile', created: null }
return { id: u.id, name: u.name, created: u.created || null }
}
export const dataDir = () => DATA_DIR
// Test-only: work against a passed-in state, not the disk.
export function _seedStateForTests(state) {
_uid = 'test-uid'
_db = { users: [{ id: _uid, name: 'Test', created: '2026-07-26T00:00:00.000Z' }], creds: [], subs: [], invites: [] }
_state = state
_loadedMtime = Number.MAX_SAFE_INTEGER // never re-read from disk in a test
if (_watcher) { _watcher.close(); _watcher = null }
}
function defaultsShape() {
return {
unit: 'kg', restSec: 90, sound: true, lang: 'en',
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], customEx: [], gifSize: 'full',
reminder: { on: false, time: '08:00', tz: null }
}
}
+389
View File
@@ -0,0 +1,389 @@
/* The eight read-only tools. Each handler returns JSON; labels.js pre-substitutes any
{0}/{1} template the lib returns so the LLM gets final text, not template strings.
ISO dates are validated on the way in; the handlers never see 'yesterday'. */
import { z } from 'zod'
import { getState, getUser } from './state.js'
import {
setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder
} from './labels.js'
import {
modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId
} from '../../frontend/src/lib/history.js'
import { EXIDX, exOr } from '../../frontend/src/lib/exercises.js'
import {
estimate1RM, best1RM, e1rmSeries, DEFAULT_FORMULA, REP_CAP
} from '../../frontend/src/lib/onerm.js'
import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js'
/* ---------- helpers ---------- */
function entryView(e, S) {
const ex = exOr(e.id)
// Spread id into the cfg the way every call site in the app does (Workout.jsx, Stats.jsx,
// progression.js) — the sheet saves a cardio target as {sets, min, speed} with no id and no
// mode, so modeOf needs the id to fall through to isCardio(id).
const cfg = { ...(e.target || {}), id: e.id }
const mode = modeOf(cfg)
return {
id: e.id,
name: ex.n,
body_part: ex.bp || null,
mode,
target: e.target || null,
sets: (e.sets || []).map(s => ({
done: !!s.done,
label: setLabel(e.id, { ...s, done: undefined }, cfg),
w: Number(s.w) || 0,
r: Number(s.r) || 0,
sec: Number(s.sec) || 0,
min: Number(s.min) || 0,
speed: Number(s.speed) || 0
}))
}
}
// Best estimate per exercise, mirroring the UI's PR table: every eligible set across history, biggest wins.
function prTable(S, formula) {
const byId = new Map()
for (const w of (S.workouts || [])) {
for (const e of (w.entries || [])) {
for (const s of (e.sets || [])) {
if (!s.done) continue
const est = estimate1RM(s.w, s.r, formula)
if (est == null) continue
const ex = exOr(e.id)
const prev = byId.get(e.id)
if (!prev || est > prev.est) {
// exId as well as exName: the consumer needs an id, not a name — exOr() treats any
// string as both, so passing exName where exId belongs would silently "work" wrong.
byId.set(e.id, { exId: e.id, exName: ex.n, bp: ex.bp || null, est, w: Number(s.w), r: Math.round(Number(s.r)), date: w.d })
}
}
}
}
return [...byId.values()].sort((a, b) => b.est - a.est)
}
/* ---------- the 8 tools ---------- */
/** list_routines — names + counts of each routine in the user's plan. */
export const listRoutines = {
name: 'list_routines',
description: 'List the workout routines saved in the user\'s openGym profile (the same list the Plan screen shows). Each routine is a named set of exercises with set/rep targets. Use this to discover the plan structure before diving into a specific routine or today\'s workout.',
schema: {},
handler: () => {
const S = getState()
if (!S) return noState()
return {
unit: S.unit || 'kg',
routines: (S.routines || []).map(r => ({
id: r.id,
name: r.name,
emoji: r.emoji || null,
exercise_count: (r.ex || []).length,
superset_groups: [...new Set((r.ex || []).map(e => e.sg).filter(Boolean))].length || 0,
policy: r.policy || 'off'
}))
}
}
}
/** get_routine — the full exercise list for one routine, including set/rep targets. */
export const getRoutine = {
name: 'get_routine',
description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, and any per-exercise custom increment you can override. Use routine_id from list_routines.',
schema: { routine_id: z.string().min(1) },
handler: ({ routine_id }) => {
const S = getState()
if (!S) return noState()
const r = (S.routines || []).find(x => x.id === routine_id)
if (!r) { const e = new Error(`no routine with id ${JSON.stringify(routine_id)}`); e.code = 'ENOENT'; throw e }
return {
id: r.id,
name: r.name,
emoji: r.emoji || null,
policy: r.policy || 'off',
policy_name: policyName(r.policy || 'off'),
unit: S.unit || 'kg',
exercises: (r.ex || []).map((cfg, i) => {
const ex = exOr(cfg.id)
const mode = modeOf(cfg)
return {
position: i + 1,
id: cfg.id,
name: ex.n,
body_part: ex.bp || null,
mode,
sets: cfg.sets || 1,
reps: mode === 'reps' ? (cfg.reps || 0) : undefined,
reps_min: mode === 'reps' && cfg.repsMin != null ? cfg.repsMin : undefined,
sec: mode === 'time' ? (cfg.sec || 0) : undefined,
min: mode === 'cardio' ? (cfg.min || 0) : undefined,
speed: mode === 'cardio' ? (cfg.speed || 0) : undefined,
weight: cfg.weight != null ? cfg.weight : undefined,
increment: cfg.inc != null ? cfg.inc : undefined,
policy_override: cfg.policy || null,
superset_group: cfg.sg || null,
summary: exLine(cfg, S.unit || 'kg')
}
})
}
}
}
/** get_week_plan — what's scheduled each weekday + today. */
export const getWeekPlan = {
name: 'get_week_plan',
description: 'Show the user\'s weekly plan: which routine (if any) is assigned to each weekday, keyed by JS getDay() (Sunday=0, Monday=1, … Saturday=6 — the same convention the openGym state file uses). Also reports today\'s date and what routine applies today, accounting for one-off overrides the user may have set for a specific date (a "rest" override cancels the day).',
schema: {},
handler: () => {
const S = getState()
if (!S) return noState()
const today = new Date()
const isoToday = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0')
const todayWd = today.getDay()
return {
today: isoToday,
weekdays: [0, 1, 2, 3, 4, 5, 6].map(d => {
const rid = S.week?.[d] || null
const r = rid ? (S.routines || []).find(x => x.id === rid) : null
// Surface today's override only (not the whole dayPlan dict — usually empty, but might
// have grown from repeated "move this day" actions).
const overrideForToday = d === todayWd ? (S.dayPlan?.[isoToday] ?? null) : null
return {
weekday: d,
weekday_name: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d],
routine_id: rid,
routine_name: r?.name || null,
routine_emoji: r?.emoji || null,
override_for_today_or_null: overrideForToday
}
}),
today_routine_id: effectiveRoutineId(S, isoToday),
today_routine_name: effectiveRoutine(S, isoToday)?.name || null
}
}
}
/** list_workouts — newest-first summary of recent sessions. */
export const listWorkouts = {
name: 'list_workouts',
description: 'List recent finished workouts, newest first. Each item summarises the date, exercise count, sets done / planned, total volume (in the user\'s unit), duration and whether PRs were set. Use this before drilling into a specific date with get_workout.',
schema: {
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive start date YYYY-MM-DD. Defaults to no lower bound (list most recent).'),
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive end date YYYY-MM-DD. Defaults to today.'),
limit: z.number().int().min(1).max(200).optional().describe('Max items to return. Defaults to 25.')
},
handler: ({ from, to, limit }) => {
const S = getState()
if (!S) return noState()
const lim = Math.min(Math.max(limit || 25, 1), 200)
const all = (S.workouts || []).slice().sort((a, b) => (b.d || '').localeCompare(a.d || ''))
const filtered = all.filter(w => {
if (from && w.d < from) return false
if (to && w.d > to) return false
return true
}).slice(0, lim)
return {
unit: S.unit || 'kg',
total_count: all.length,
returned_count: filtered.length,
workouts: filtered.map(w => ({
// The only thing that identifies a session uniquely. Two workouts on one day is
// ordinary — a lifting session and an evening run — and without an id here the second
// one cannot be asked about at all.
id: w.id || null,
date: w.d,
routine_id: w.routineId || null,
routine_name: w.name || null,
exercise_count: (w.entries || []).length,
sets_done: setsDone(w),
sets_planned: plannedSets(w),
sets_ratio: ratio(setsDone(w), plannedSets(w)),
volume: workoutVolume(w),
duration_ms: w.end && w.start ? (w.end - w.start) : null,
duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null,
prs: (w.prs || []).length,
bodyweight_at_workout: w.bw || null
}))
}
}
}
function plannedSets(w) {
let n = 0
;(w.entries || []).forEach(e => { n += (e.sets || []).length })
return n
}
/** get_workout — full entry/set breakdown for one date. */
export const getWorkout = {
name: 'get_workout',
description: 'Get the full breakdown of one workout: every exercise, its mode (reps/time/cardio), the target, and per-set labels (e.g. "5 @ 60 kg", "1:30 · 20 kg"). Identify it by workout_id (from list_workouts) or by date. Use list_workouts first if you don\'t know either.',
schema: {
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('The workout date as YYYY-MM-DD. If two sessions share that date, the answer lists them instead and asks for a workout_id.'),
workout_id: z.string().min(1).optional().describe('The id from list_workouts. Preferred: it names one session even on a day with two.')
},
handler: ({ date, workout_id }) => {
const S = getState()
if (!S) return noState()
const workouts = S.workouts || []
let w
if (workout_id) {
w = workouts.find(x => x.id === workout_id)
if (!w) { const e = new Error(`no workout with id ${workout_id}`); e.code = 'ENOENT'; throw e }
} else if (date) {
const sameDay = workouts.filter(x => x.d === date)
if (!sameDay.length) { const e = new Error(`no workout on ${date}`); e.code = 'ENOENT'; throw e }
// Answering with the first of two is how a question about the evening run gets the
// morning's lifting numbers, stated with total confidence. Say there are two instead.
if (sameDay.length > 1) {
return {
ambiguous: true,
date,
message: `${sameDay.length} workouts were logged on ${date} — call get_workout again with one of these workout_id values.`,
workouts: sameDay.map(x => ({
id: x.id || null,
routine_name: x.name || null,
sets_done: setsDone(x),
volume: workoutVolume(x),
duration: x.end && x.start ? friendlyDuration(x.end - x.start) : null
}))
}
}
w = sameDay[0]
} else {
const e = new Error('get_workout needs either workout_id or date'); e.code = 'EINVAL'; throw e
}
return {
id: w.id || null,
date: w.d,
routine_id: w.routineId || null,
routine_name: w.name || null,
unit: S.unit || 'kg',
bodyweight_at_workout: w.bw || null,
volume: workoutVolume(w),
sets_done: setsDone(w),
sets_planned: plannedSets(w),
duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null,
prs: (w.prs || []).map(id => EXIDX[id]?.n || id),
entries: (w.entries || []).map(e => entryView(e, S))
}
}
}
/** get_bodyweight — recent weigh-ins with the goal line. */
export const getBodyweight = {
name: 'get_bodyweight',
description: 'Get the body-weight log: chronological weigh-ins with weights, current goal, deltas vs goal (signed positive = above goal), and a latest summary. Useful for "am I trending toward my weight goal?" questions.',
schema: {
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive start date YYYY-MM-DD.'),
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive end date YYYY-MM-DD. Defaults to today.')
},
handler: ({ from, to }) => {
const S = getState()
if (!S) return noState()
const goal = S.targetW || null
const bw = (S.bodyweight || []).filter(b => {
if (from && b.d < from) return false
if (to && b.d > to) return false
return true
}).sort((a, b) => (a.d || '').localeCompare(b.d || ''))
const latest = bw.length ? bw[bw.length - 1] : null
return {
unit: S.unit || 'kg',
goal,
count: bw.length,
latest: latest ? { date: latest.d, weight: latest.w, delta_vs_goal: goal != null ? Math.round((latest.w - goal) * 10) / 10 : null } : null,
entries: bw.map(b => ({
date: b.d,
weight: b.w,
delta_vs_goal: goal != null ? Math.round((b.w - goal) * 10) / 10 : null
}))
}
}
}
/** estimate_1rm — best-ever 1RM for one exercise or a PR table across all reps-mode exercises. */
export const estimate1rm = {
name: 'estimate_1rm',
description: `Estimate one-rep max using Epley, Brzycki or Lombardi formulas. If an exercise_id is given, returns the all-time best estimate for that exercise with the source set (weight × reps + date) and the trend across history. If no exercise_id is given, returns a PR table across all reps-mode exercises (sorted highest first). Refuses to guess above ${REP_CAP} reps — above that, formulas diverge past 10% and "work capacity" is read instead of "maximal strength".`,
schema: {
exercise_id: z.string().optional().describe('An exercise id from list_routines or get_workout entries. If omitted, returns a full PR table.'),
formula: z.enum(['epley', 'brzycki', 'lombardi']).optional().describe(`Formula to use. Defaults to ${DEFAULT_FORMULA}.`)
},
handler: ({ exercise_id, formula }) => {
const S = getState()
if (!S) return noState()
const f = formula || DEFAULT_FORMULA
if (exercise_id) {
const ex = exOr(exercise_id)
const best = best1RM(S, exercise_id, f)
const series = e1rmSeries(S, exercise_id, f)
// A null best has two very different causes: never trained, or trained only above the
// rep cap. Without saying which, an exercise logged for years at 15 reps reads as "no
// records for calf raise" — a confident statement about the opposite of the truth.
const trainedAtAll = (S.workouts || []).some(w =>
(w.entries || []).some(e => e.id === exercise_id && (e.sets || []).some(s => s.done)))
// w/r (not weight/reps) matches pr_table and entry-view — every set in the API surface uses the same couple.
return {
exercise: { id: exercise_id, name: ex.n, body_part: ex.bp || null },
formula: f,
formula_note: `Estimates use the ${f} formula. Cap at ${REP_CAP} reps applies; r=1 is treated as the measurement, not an estimate.`,
best: best ? { est: best.est, w: best.w, r: best.r, date: best.d } : null,
no_estimate_reason: best ? null
: trainedAtAll
? `This exercise has logged sets, but none of them qualify: every set was above the ${REP_CAP}-rep cap, or carried no weight. That is not the same as never having trained it.`
: 'No completed sets logged for this exercise.',
trend: series.map(p => ({ date: p.d, est: p.y, w: p.w, r: p.r }))
}
}
return {
formula: f,
formula_note: `Estimates use the ${f} formula. Cap at ${REP_CAP} reps applies; r=1 is treated as the measurement, not an estimate.`,
pr_table: prTable(S, f)
}
}
}
/** muscle_balance — training distribution per muscle over a period (week/month/all). */
export const muscleBalance = {
name: 'muscle_balance',
description: 'Show which muscles the user has trained in a period, ranked by "effective sets" (volume in kg is intentionally not used — 100 kg leg press vs 12 kg lateral raise say nothing about which muscle worked harder). Reports worked muscles with a 0-4 relative level (1 = some work, 4 = most worked) and the muscles trained zero times in that period — useful for "what am I neglecting?" questions.',
schema: {
period: z.enum(['week', 'month', 'all']).describe('window: last 7 days, last 30 days, or all-time')
},
handler: ({ period }) => {
const S = getState()
if (!S) return noState()
const now = Date.now()
const cutoff = period === 'week' ? now - 7 * 86400000
: period === 'month' ? now - 30 * 86400000
: Number.NEGATIVE_INFINITY
const workouts = (S.workouts || []).filter(w => (w.start || new Date(w.d + 'T12:00:00').getTime()) >= cutoff)
const load = loadOfWorkouts(workouts)
const { worked, missed } = rankOf(load)
const levels = levelsOf(load)
return {
period,
cutoff_iso: period === 'all' ? null : new Date(cutoff).toISOString().slice(0, 10),
workouts_in_period: workouts.length,
worked: worked.map(slug => ({ slug, name: muscleName(slug), level: levels[slug], effective_sets: Math.round((load[slug] || 0) * 10) / 10 })),
neglected: missed.map(slug => ({ slug, name: muscleName(slug) })),
muscle_order_head_to_toe: muscleOrder()
}
}
}
/* ---------- registration list ---------- */
export const TOOLS = [
listRoutines, getRoutine, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance
]
function noState() {
return {
error: 'no synced state yet — sign in at least once from a device so the openGym api can save a state file for this profile',
unit: 'kg'
}
}
+535
View File
@@ -0,0 +1,535 @@
// Tool-layer tests for mcp/src/tools.js, seeded from frontend/src/lib/demoSeed.js — the same
// deterministic fixture the public demo runs on. The pure lib functions have their own 92
// tests in frontend/src/lib/*.test.js; here we pin JSON shape + the user-facing edge cases
// (rest-day override, missing routine, zero-workout history, no synced state, superset links).
import { describe, beforeAll, afterAll, beforeEach, test, expect, vi } from 'vitest'
import { buildDemoState } from '../../frontend/src/lib/demoSeed.js'
import { EXDB } from '../../frontend/src/lib/exercises.js'
import { _seedStateForTests } from '../src/state.js'
import { TOOLS } from '../src/tools.js'
// Re-stated here so the assertions stand alone without reaching into lib internals to learn
// the demo state's exact values.
const FAKE_TODAY_ISO = '2026-07-27' // Monday — Push Day is scheduled
const GOAL_WEIGHT = 77
// Re-pinned against the v1.2.4 seed, which moved when the demo learned about bodyweight work
// and effort. Hand-checked rather than copied off a failing run: 18412.5 is the sum of w×r
// over the twenty completed sets, and 1.3 is 78.3 − 77.
const NEWEST_WORKOUT = { date: '2026-07-24', name: 'Leg Day', volume: 18412.5, bw: 78.4, sets_done: 20, sets_total: 20, duration: '1h 11m' }
const LATEST_BW = { date: '2026-07-27', weight: 78.3, delta: 1.3 }
const LEG_PRESS_ID = '0739' // sled 45° leg press in the demo data
const LEG_PRESS_BEST = { w: 152.5, r: 12, epley: 213.5, brzycki: 219.6 }
const byName = Object.fromEntries(TOOLS.map(t => [t.name, t.handler]))
let S = null
function call(name, params = {}) {
const h = byName[name]
if (!h) throw new Error(`unknown tool ${name}`)
return h(params)
}
function freshState() {
const s = buildDemoState()
s.unit = 'kg'
return s
}
// Pin "today" before building state so dayPlan/week alignment matches the assertions below.
// `toFake: ['Date']` only — keeps fs.watch and the rest of the event loop real.
beforeAll(() => {
vi.useFakeTimers({ now: new Date(FAKE_TODAY_ISO + 'T12:00:00Z'), toFake: ['Date'] })
S = freshState()
_seedStateForTests(S)
})
afterAll(() => {
vi.useRealTimers()
})
// Fresh state per test — tests that mutate dayPlan can't leak into siblings.
beforeEach(() => {
S = freshState()
_seedStateForTests(S)
})
/* ---------- list_routines ---------- */
describe('list_routines', () => {
test('returns the three starter routines with names + counts', () => {
const r = call('list_routines')
expect(r.unit).toBe('kg')
expect(r.routines.length).toBe(3)
expect(r.routines.map(x => x.name).sort()).toEqual(['Leg Day', 'Pull Day', 'Push Day'])
r.routines.forEach(rn => {
expect(typeof rn.id).toBe('string')
expect(rn.exercise_count).toBeGreaterThan(0)
expect(typeof rn.superset_groups).toBe('number')
expect(['off', 'linear', 'greyskull', 'double', 'time']).toContain(rn.policy)
})
})
test('list_routines entries line up with get_routine (no id drift)', () => {
const list = call('list_routines').routines
list.forEach(summary => {
const detail = call('get_routine', { routine_id: summary.id })
expect(detail.id).toBe(summary.id)
expect(detail.name).toBe(summary.name)
expect(detail.exercises.length).toBe(summary.exercise_count)
})
})
})
/* ---------- get_routine ---------- */
describe('get_routine', () => {
test('returns the full exercise list for Push Day with per-exercise summaries', () => {
const push = call('list_routines').routines.find(x => x.name === 'Push Day')
const r = call('get_routine', { routine_id: push.id })
expect(r.name).toBe('Push Day')
expect(r.exercises.length).toBe(push.exercise_count)
expect(r.policy_name).toBeTruthy()
r.exercises.forEach(e => {
expect(['reps', 'time', 'cardio']).toContain(e.mode)
// Every summary has "N × M" with a non-ASCII × (the lib uses U+00D7, not ASCII 'x')
expect(e.summary).toMatch(/\d+\s*×\s*\d+/)
expect(e.superset_group === null || typeof e.superset_group === 'string').toBe(true)
})
})
test('throws ENOENT on a bogus routine id', () => {
expect(() => call('get_routine', { routine_id: 'bogus' })).toThrow()
})
test('reports superset links when an adjacent pair shares an sg id', () => {
// Inject a superset pair into a clone, since the starter plan has none.
S.routines[0].ex[0].sg = 'A'
S.routines[0].ex[1].sg = 'A'
const r = call('get_routine', { routine_id: S.routines[0].id })
expect(r.exercises[0].superset_group).toBe('A')
expect(r.exercises[1].superset_group).toBe('A')
expect(r.exercises[2].superset_group).toBeNull()
})
test('preserves mode + per-mode fields for a timed entry and a cardio entry', () => {
// Append synthetic entries the starter plan doesn't ship: a timed plank (sec, no w) and a
// cardio treadmill block (min + speed). These exercise ids don't exist in EXDB, so exOr
// returns a placeholder named "Unknown exercise" — that's fine, we test the cfg fields.
const push = S.routines.find(r => r.name === 'Push Day')
push.ex.push({ id: 'synth-plank', sets: 3, sec: 60, weight: 0, mode: 'time' })
push.ex.push({ id: 'synth-treadmill', sets: 1, min: 20, speed: 8, mode: 'cardio' })
const r = call('get_routine', { routine_id: push.id })
const t = r.exercises[r.exercises.length - 2]
const c = r.exercises[r.exercises.length - 1]
expect(t.mode).toBe('time')
expect(t.sec).toBe(60)
expect(t.reps).toBeUndefined()
expect(c.mode).toBe('cardio')
expect(c.min).toBe(20)
expect(c.speed).toBe(8)
})
})
/* ---------- get_week_plan ---------- */
describe('get_week_plan', () => {
test('reports each weekday in getDay() order (Sunday=0 … Saturday=6) with names', () => {
const r = call('get_week_plan')
expect(r.weekdays.length).toBe(7)
expect(r.weekdays.map(d => d.weekday)).toEqual([0, 1, 2, 3, 4, 5, 6])
expect(r.weekdays.map(d => d.weekday_name))
.toEqual(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
})
test('today is the pinned Monday, and Push Day is scheduled', () => {
const r = call('get_week_plan')
expect(r.today).toBe(FAKE_TODAY_ISO)
const push = S.routines.find(x => x.name === 'Push Day')
expect(r.today_routine_id).toBe(push.id)
expect(r.today_routine_name).toBe('Push Day')
})
test('week[1]/[3]/[5] map to Push/Pull/Leg, other weekdays are rest', () => {
const r = call('get_week_plan')
const byWd = Object.fromEntries(r.weekdays.map(d => [d.weekday, d]))
expect(byWd[1].routine_name).toBe('Push Day')
expect(byWd[3].routine_name).toBe('Pull Day')
expect(byWd[5].routine_name).toBe('Leg Day')
;[0, 2, 4, 6].forEach(wd => {
expect(byWd[wd].routine_id).toBeNull()
expect(byWd[wd].routine_name).toBeNull()
})
})
test('a "rest" override on today cancels the scheduled routine', () => {
// Sanity check first — without the override, today has a routine.
const before = call('get_week_plan')
expect(before.today_routine_id).not.toBeNull()
S.dayPlan[FAKE_TODAY_ISO] = 'rest'
const after = call('get_week_plan')
expect(after.today_routine_id).toBeNull()
expect(after.today_routine_name).toBeNull()
// The override is surfaced on the matching weekday entry.
const todayWd = new Date(FAKE_TODAY_ISO + 'T12:00:00Z').getDay()
expect(after.weekdays.find(d => d.weekday === todayWd).override_for_today_or_null).toBe('rest')
})
test('a routine-id override on today replaces the weekday default', () => {
const legs = S.routines.find(r => r.name === 'Leg Day')
S.dayPlan[FAKE_TODAY_ISO] = legs.id
const r = call('get_week_plan')
expect(r.today_routine_id).toBe(legs.id)
expect(r.today_routine_name).toBe('Leg Day')
})
test('empty week + no override → today has no routine (a quiet Sunday)', () => {
S.week = {}
S.dayPlan = {}
const r = call('get_week_plan')
expect(r.today_routine_id).toBeNull()
expect(r.today_routine_name).toBeNull()
r.weekdays.forEach(d => expect(d.routine_id).toBeNull())
})
})
/* ---------- list_workouts ---------- */
describe('list_workouts', () => {
test('newest first, with computed volume/duration matching hand-calculated values', () => {
const r = call('list_workouts', {})
expect(r.returned_count).toBeGreaterThan(0)
expect(r.total_count).toBeGreaterThanOrEqual(r.returned_count)
// newest-first check
const dates = r.workouts.map(w => w.date)
expect([...dates].sort().reverse()).toEqual(dates)
// The newest workout is the Friday before the pinned Monday today.
expect(r.workouts[0].date).toBe(NEWEST_WORKOUT.date)
expect(r.workouts[0].routine_name).toBe(NEWEST_WORKOUT.name)
expect(r.workouts[0].volume).toBe(NEWEST_WORKOUT.volume)
expect(r.workouts[0].sets_done).toBe(NEWEST_WORKOUT.sets_done)
expect(r.workouts[0].sets_planned).toBe(NEWEST_WORKOUT.sets_total)
expect(r.workouts[0].sets_ratio).toBe(`${NEWEST_WORKOUT.sets_done}/${NEWEST_WORKOUT.sets_total}`)
// Past the hour the lib switches format, so the expectation carries the rendered string
// rather than assuming a "N min" shape that only held while the session was shorter.
expect(r.workouts[0].duration).toBe(NEWEST_WORKOUT.duration)
expect(r.workouts[0].bodyweight_at_workout).toBe(NEWEST_WORKOUT.bw)
r.workouts.forEach(w => {
expect(w.sets_done).toBeLessThanOrEqual(w.sets_planned)
expect(typeof w.volume).toBe('number')
expect(w.sets_ratio).toMatch(/^\d+\/\d+$/)
})
})
test('date range filter narrows results (closed interval, both endpoints inclusive)', () => {
const all = call('list_workouts')
expect(all.workouts.length).toBeGreaterThan(2)
const earliest = all.workouts[all.workouts.length - 1].date
// closed on both ends — earliest's own date should still appear
const restricted = call('list_workouts', { from: earliest, to: earliest })
expect(restricted.returned_count).toBe(1)
expect(restricted.workouts[0].date).toBe(earliest)
})
test('a from > to range yields zero workouts (not an error, not silently everything)', () => {
const r = call('list_workouts', { from: '2026-07-27', to: '2026-01-01' })
expect(r.returned_count).toBe(0)
expect(r.workouts).toEqual([])
expect(r.total_count).toBeGreaterThan(0) // total still reflects the real history
})
test('respects limit (caps returned_count, never total_count)', () => {
const r = call('list_workouts', { limit: 3 })
expect(r.returned_count).toBeLessThanOrEqual(3)
expect(r.total_count).toBeGreaterThanOrEqual(r.returned_count)
})
})
/* ---------- get_workout ---------- */
describe('get_workout', () => {
test('matches the newest workout from list_workouts, every set has a readable label', () => {
const list = call('list_workouts', {}).workouts
const w = call('get_workout', { date: list[0].date })
expect(w.date).toBe(list[0].date)
expect(w.entries.length).toBe(list[0].exercise_count)
expect(w.volume).toBe(list[0].volume)
w.entries.forEach(e => {
expect(['reps', 'time', 'cardio']).toContain(e.mode)
e.sets.forEach(s => {
expect(typeof s.label).toBe('string')
expect(s.label.length).toBeGreaterThan(0)
})
})
})
test('throws ENOENT on a date with no workout', () => {
expect(() => call('get_workout', { date: '1900-01-01' })).toThrow()
})
test('two sessions on one day are both reachable, and the date alone never picks one silently', () => {
// Lifting in the morning, a run in the evening: ordinary, and it used to make the second
// session unreachable while questions about it were answered with the first one's numbers.
const day = '2026-07-26'
S.workouts.push(
{ id: 'w-morning', d: day, name: 'Pull', start: 1000, end: 1000 + 40 * 60000, vol: 0, prs: [], entries: [] },
{ id: 'w-evening', d: day, name: 'Cardio', start: 2000, end: 2000 + 55 * 60000, vol: 0, prs: [], entries: [] }
)
_seedStateForTests(S)
const amb = call('get_workout', { date: day })
expect(amb.ambiguous).toBe(true)
expect(amb.workouts.map(w => w.id).sort()).toEqual(['w-evening', 'w-morning'])
// Each is retrievable by the id the ambiguous answer handed back.
expect(call('get_workout', { workout_id: 'w-evening' }).routine_name).toBe('Cardio')
expect(call('get_workout', { workout_id: 'w-morning' }).routine_name).toBe('Pull')
// And list_workouts carries the id, or nothing above could ask for one.
expect(call('list_workouts', {}).workouts.every(w => 'id' in w)).toBe(true)
})
test('an unknown workout_id is an error, not the wrong workout', () => {
expect(() => call('get_workout', { workout_id: 'nope' })).toThrow()
expect(() => call('get_workout', {})).toThrow()
})
test('renders reps/time/cardio set labels in the lib format on a synthetic workout', () => {
// The starter routine has only reps-mode exercises — synthesise a workout that includes a
// timed plank and a cardio row so the label rendering is actually exercised.
S.workouts = [{
id: 'synth-1', d: '2026-07-25', start: 0, end: 1800000, routineId: 'x', name: 'Synth',
bw: 78, vol: 0, prs: [],
entries: [
{ id: 'squat', target: { mode: 'reps' }, sets: [{ w: 60, r: 5, done: true }] },
{ id: 'plank', target: { mode: 'time' }, sets: [{ sec: 90, w: 0, done: true }] },
{ id: 'plank-w', target: { mode: 'time' }, sets: [{ sec: 90, w: 20, done: true }] },
{ id: 'row', target: { mode: 'cardio' }, sets: [{ min: 20, speed: 8, done: true }] }
]
}]
const w = call('get_workout', { date: '2026-07-25' })
expect(w.entries[0].sets[0].label).toBe('60×5') // reps
// 90 sec → 1 min 30 sec → mm:ss label is "1:30" (fmtSec in history.js)
expect(w.entries[1].sets[0].label).toBe('1:30') // 90 s in mm:ss, no weight
expect(w.entries[2].sets[0].label).toBe('1:30 · 20') // weighted plank
expect(w.entries[3].sets[0].label).toBe('20 min @ 8 km/h') // cardio
})
test('infers cardio mode from the exercise id when the target has no mode key', () => {
// Reproduces the review bug: the sheet saves a cardio target as {sets, min, speed} with
// no mode and no id. modeOf must fall through to isCardio(id), which needs the id on the
// cfg — entryView has to spread id into the cfg the way every app call site does.
const CARDIO_ID = EXDB.find(e => e.bp === 'cardio').id
S.workouts = [{
id: 'synth-cardio', d: '2026-07-25', start: 0, end: 1800000, routineId: 'x', name: 'Synth',
bw: 78, vol: 0, prs: [],
entries: [
{ id: CARDIO_ID, target: { sets: 1, min: 20, speed: 8 }, sets: [{ min: 20, speed: 8, done: true }] }
]
}]
const w = call('get_workout', { date: '2026-07-25' })
expect(w.entries[0].mode).toBe('cardio')
expect(w.entries[0].sets[0].label).toBe('20 min @ 8 km/h')
})
})
/* ---------- get_bodyweight ---------- */
describe('get_bodyweight', () => {
test('returns weigh-ins with the goal, the latest entry, and exact delta vs goal', () => {
const r = call('get_bodyweight')
expect(r.goal).toBe(GOAL_WEIGHT)
expect(r.entries.length).toBeGreaterThan(0)
// Newest is the LATEST_BW entry (deterministic from the demo seed at the pinned time).
expect(r.latest).toBeTruthy()
expect(r.latest.date).toBe(LATEST_BW.date)
expect(r.latest.weight).toBe(LATEST_BW.weight)
expect(r.latest.delta_vs_goal).toBe(LATEST_BW.delta)
// entries are chronological
const dates = r.entries.map(e => e.date)
expect([...dates].sort()).toEqual(dates)
})
test('closed date range returns a single matching entry on the boundary', () => {
const all = call('get_bodyweight')
expect(all.entries.length).toBeGreaterThan(1)
const earliest = all.entries[0].date
const restricted = call('get_bodyweight', { from: earliest, to: earliest })
expect(restricted.entries.length).toBe(1)
expect(restricted.entries[0].date).toBe(earliest)
})
test('no goal set → delta_vs_goal is null, not NaN, not zero', () => {
S.targetW = null
const r = call('get_bodyweight')
expect(r.goal).toBeNull()
r.entries.forEach(e => expect(e.delta_vs_goal).toBeNull())
expect(r.latest.delta_vs_goal).toBeNull()
})
})
/* ---------- estimate_1rm ---------- */
describe('estimate_1rm', () => {
test('PR table across all reps-mode exercises; epley formula is the default', () => {
const r = call('estimate_1rm', {})
expect(r.formula).toBe('epley')
expect(Array.isArray(r.pr_table)).toBe(true)
expect(r.pr_table.length).toBeGreaterThan(0)
r.pr_table.forEach(p => {
expect(typeof p.est).toBe('number')
expect(p.est).toBeGreaterThan(0)
expect(typeof p.exName).toBe('string')
expect(typeof p.exId).toBe('string') // exId surfaced (regression test for the bug where callers passed exName as id)
})
// sort order: descending by est
for (let i = 1; i < r.pr_table.length; i++) {
expect(r.pr_table[i].est).toBeLessThanOrEqual(r.pr_table[i - 1].est)
}
})
test('top-of-table values exactly match the hand-computed Epley for the demo seed', () => {
const r = call('estimate_1rm', {})
const top = r.pr_table[0]
// Demo seed's hardest set: sled 45° leg press at 152.5×12 (r=12 hits estimate1RM's REP_CAP).
expect(top.exId).toBe(LEG_PRESS_ID)
expect(top.w).toBe(LEG_PRESS_BEST.w)
expect(top.r).toBe(LEG_PRESS_BEST.r)
expect(top.est).toBeCloseTo(LEG_PRESS_BEST.epley, 1)
})
test('per-exercise trend + best, with formula honours (Epley vs Brzycki numbers diverge)', () => {
const epley = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: 'epley' })
expect(epley.exercise.id).toBe(LEG_PRESS_ID)
expect(epley.formula).toBe('epley')
expect(Array.isArray(epley.trend)).toBe(true)
expect(epley.best).toBeTruthy()
expect(epley.best.w).toBe(LEG_PRESS_BEST.w)
expect(epley.best.r).toBe(LEG_PRESS_BEST.r)
expect(epley.best.est).toBeCloseTo(LEG_PRESS_BEST.epley, 1)
const brz = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: 'brzycki' })
expect(brz.formula).toBe('brzycki')
expect(brz.best.est).toBeCloseTo(LEG_PRESS_BEST.brzycki, 1)
// Distinct formulas must produce distinct estimates for this set.
expect(epley.best.est).not.toBeCloseTo(brz.best.est, 1)
})
test('exercises with no reps-mode history get null best + empty trend (not a 0 estimate)', () => {
S.workouts = []
_seedStateForTests(S)
const r = call('estimate_1rm', { exercise_id: LEG_PRESS_ID })
expect(r.best).toBeNull()
expect(r.trend).toEqual([])
const table = call('estimate_1rm', {}).pr_table
expect(table).toEqual([])
})
test('a null estimate says which kind of null it is', () => {
// "Never trained" and "trained, but always above the rep cap" are opposite facts that both
// arrive as best: null. Undistinguished, the second one reads as the first and an assistant
// reports "no records" for an exercise in the log every week.
S.workouts = [{
id: 'w-highrep', d: '2026-07-26', name: 'Accessories', start: 1000, end: 1000 + 20 * 60000,
vol: 0, prs: [],
entries: [{
id: LEG_PRESS_ID, target: { sets: 2, reps: 20, mode: 'reps' },
sets: [{ w: 40, r: 20, done: true }, { w: 40, r: 18, done: true }]
}]
}]
_seedStateForTests(S)
const capped = call('estimate_1rm', { exercise_id: LEG_PRESS_ID })
expect(capped.best).toBeNull()
expect(capped.no_estimate_reason).toMatch(/above the \d+-rep cap/)
// An exercise that genuinely has no sets must not borrow that explanation.
const never = call('estimate_1rm', { exercise_id: '0684' })
expect(never.best).toBeNull()
expect(never.no_estimate_reason).toMatch(/No completed sets/)
// And the cap is stated on this branch at all, which it never used to be.
expect(capped.formula_note).toMatch(/Cap at/)
})
test('all three formulas are accepted', () => {
['epley', 'brzycki', 'lombardi'].forEach(f => {
const r = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: f })
expect(r.formula).toBe(f)
expect(r.best).not.toBeNull()
})
})
})
/* ---------- muscle_balance ---------- */
describe('muscle_balance', () => {
test('reports worked + neglected muscles in head-to-toe order over all time', () => {
const r = call('muscle_balance', { period: 'all' })
expect(r.period).toBe('all')
expect(r.workouts_in_period).toBeGreaterThan(0)
expect(Array.isArray(r.worked)).toBe(true)
expect(Array.isArray(r.neglected)).toBe(true)
expect(r.muscle_order_head_to_toe[0]).toBe('trapezius')
expect(r.muscle_order_head_to_toe.at(-1)).toBe('tibialis')
r.worked.forEach(w => {
expect(w.level).toBeGreaterThanOrEqual(1)
expect(w.level).toBeLessThanOrEqual(4)
expect(typeof w.name).toBe('string')
expect(typeof w.effective_sets).toBe('number')
})
})
test('worked + neglected partition every muscle exactly once', () => {
const r = call('muscle_balance', { period: 'all' })
const all = new Set(r.muscle_order_head_to_toe)
const worked = new Set(r.worked.map(w => w.slug))
const neg = new Set(r.neglected.map(n => n.slug))
expect(worked.size + neg.size).toBe(all.size)
expect([...worked].every(s => all.has(s))).toBe(true)
expect([...neg].every(s => all.has(s))).toBe(true)
})
test('period windows are inclusive: week ≤ month ≤ all', () => {
const all = call('muscle_balance', { period: 'all' }).workouts_in_period
const month = call('muscle_balance', { period: 'month' }).workouts_in_period
const week = call('muscle_balance', { period: 'week' }).workouts_in_period
expect(week).toBeLessThanOrEqual(month)
expect(month).toBeLessThanOrEqual(all)
})
test('zero-workout state still returns all 18 muscles as neglected (not empty)', () => {
S.workouts = []
const r = call('muscle_balance', { period: 'all' })
expect(r.workouts_in_period).toBe(0)
expect(r.worked).toEqual([])
expect(r.neglected.length).toBe(r.muscle_order_head_to_toe.length)
expect(r.neglected.length).toBe(18)
})
})
/* ---------- shared: no-state fallback ---------- */
describe('shared: no-state fallback', () => {
test('every tool answers gracefully when state is null (fresh account, never signed in)', () => {
_seedStateForTests(null)
// Each tool gets the minimum args its zod schema mandates; under real LLM-client use the
// SDK rejects missing ones before the handler runs, so we only test the post-validation path.
const calls = {
list_routines: {},
get_routine: { routine_id: '0031' },
get_week_plan: {},
list_workouts: {},
get_workout: { date: '2026-07-26' },
get_bodyweight: {},
estimate_1rm: {},
muscle_balance: { period: 'all' }
}
for (const t of TOOLS) {
const r = t.handler(calls[t.name] || {})
expect(r).toHaveProperty('error')
}
})
// Restore state after the no-state detour so a future test that forgets to seed sees the
// failure rather than inherits null silently.
afterAll(() => { _seedStateForTests(S = freshState()) })
})
+12
View File
@@ -0,0 +1,12 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['test/**/*.test.js'],
globals: false,
environment: 'node',
pool: 'forks',
isolate: true,
reporters: ['default']
}
})
+1 -1
View File
@@ -126,7 +126,7 @@
<li class="no">No cross-device sync</li>
</ul>
<a class="btn" href="openGym.apk" download>Download for Android</a>
<p class="meta">v1.2.3 · 4.3 MB · Android 6.0+ · signed APK, sideload (your browser will ask — that's normal outside the Play Store)</p>
<p class="meta">v1.2.4 · 4.3 MB · Android 6.0+ · signed APK, sideload (your browser will ask — that's normal outside the Play Store)</p>
<p class="meta"><b>iPhone?</b> Apple doesn't allow installs outside the App Store — use the
self-hosted version as a home-screen app instead, or see <a href="docs.html#iphone">the docs</a>.</p>
</div>