Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

CLAUDE.md: describe the repository as it is after v1.4

Duarte Santos1cd4398eca02
diff --git a/CLAUDE.md b/CLAUDE.md
index a78a2337e..d89cf5140 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,142 +1,168 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+For people, the same map with diagrams is [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
## What this is
-openGym is a self-hosted gym & body-weight tracker PWA. Two containers (`api` + `web`) plus a
-`./data` folder the user owns — no third-party account, no telemetry. Passkey (WebAuthn) login,
-installable as a home-screen app, optional Capacitor shells for standalone Android/iOS builds.
-License: AGPL-3.0-or-later.
+openGym is a self-hosted gym and body-weight tracker. Two containers (`api` + `web`) plus a
+`./data` folder the user owns: no third-party account, no telemetry. Passkey (WebAuthn) login,
+installable as a PWA, and Capacitor apps for Android and iPhone (with an Apple Watch app and
+widgets) that work on their own or synced to a server. License: AGPL-3.0-or-later; the exercise
+media are licensed separately (NOTICE.md).
## Project layout
```
-frontend/ React 19 + Vite app (src/views, src/components, src/store, src/lib). Builds to static files.
- android/ + ios/ are the Capacitor shells for the standalone mobile app (docs/MOBILE.md).
-api/ backend — server.js (Node, no framework), deps: @simplewebauthn/server, web-push.
- coach/ is the optional AI coach; openapi.yaml documents every route.
-web/ multi-stage Dockerfile (builds frontend → nginx) + nginx.conf.template (serves app, proxies /api).
-mcp/ optional MCP server — read-only stdio bridge exposing a user's workouts/1RM/muscle
- balance to LLM clients (Claude Desktop, Cursor…). Not part of the Docker build; only
- runs when an LLM client spawns it.
-media/ exercise img/gif, gitignored, fetched at runtime by the `media` compose service.
-website/ static project site (plain HTML/CSS/JS), deployed separately.
-kubernetes/ example manifests (docs/SELF_HOSTING_KUBERNETES.md).
-docs/ guides indexed in docs/README.md (FAQ, SELF_HOSTING*, MOBILE, AI_COACH, DATA_IMPORTS, API);
- docs/dev/ holds feature design notes (SET_TYPES: drop sets/rest-pause, LIST_VIEW, COMBINE_ROUTINES).
+frontend/ React 19 + Vite app (src/views, src/components, src/store, src/lib, src/sheets.jsx).
+ android/ + ios/ are the Capacitor shells (docs/MOBILE.md); ios/ also holds the watch
+ app (Watch, WatchCore, WatchWidgets), the widgets and the animation-pack downloader.
+api/ Backend: server.js (plain node:http) plus small testable modules beside it.
+ coach/ is the optional AI coach; coach/core/ is shared with the phone apps.
+ openapi.yaml documents every route.
+web/ Multi-stage Dockerfile (builds frontend, adds catalogue/media, serves with nginx) and
+ nginx.conf.template (serves the app, proxies /api).
+catalogue/ The exercise database: exercises/<id>.json, i18n/, licensed 180 px media/.
+mcp/ Optional read-only stdio MCP server over DATA_DIR. Not in the Docker build.
+scripts/ Build, CI and release helpers (scripts/README.md).
+website/ opengym.ch, plain HTML/CSS/JS, deployed separately.
+helm/, kubernetes/, contrib/nix/ Other ways to deploy.
+docs/ Guides indexed in docs/README.md; docs/dev/ holds feature design notes.
```
## Commands
```bash
-# Local stack (api + web + media, prebuilt or built from source)
+# Local stack (api + web, prebuilt or built from source)
cp .env.example .env
docker compose up -d --build
# Frontend dev server (hot reload), proxies /api to :3000
cd frontend && npm install && npm run dev
-# Frontend tests (training logic: progression, 1RM, session read-back)
-cd frontend && npm test # vitest run
-cd frontend && npm run test:watch
-npx vitest run src/lib/progression.test.js # single file
-npx vitest run -t "some test name" # single test by name
-
-# API and MCP server tests
-cd api && npm test
+# Tests (Node 22, the version CI and the Dockerfiles use)
+cd frontend && npm test # vitest run, the whole suite
+cd frontend && npx vitest run src/lib/progression.test.js # one file
+cd frontend && npx vitest run -t "some test name" # one test by name
+cd api && npm test # node --test
cd mcp && npm test
-# Production build
+# Checks CI runs besides the suites (run `npm ci` in the repo root once, for js-yaml)
+cd frontend && node scripts/check-locales.mjs && node scripts/check-source-strings.mjs --strict
+node scripts/catalogue/build.mjs --check
+node scripts/build-coach-assets.mjs --check
+node scripts/build-api-docs.mjs --check
+
+# Builds
cd frontend && npm run build
-cd frontend && npm run build:mobile # + cap sync, points media at the CDN dataset
+cd frontend && npm run build:mobile # VITE_MOBILE build + 180 px media from catalogue/media + cap sync
```
-There is no linter/formatter configured (no ESLint/Prettier config in the repo) and no
-TypeScript — match the existing style by hand.
+There is no linter/formatter config and no TypeScript; match the existing style by hand.
GitHub (`github.com/DuarteSantos8/openGym`) is the home of the project; `.github/workflows/mirror.yml`
-pushes `main` and `v*` tags to the GitLab mirror. Pull requests are gated by
-`.github/workflows/test.yml` on Node 22 — the same version as `web/Dockerfile` / `api/Dockerfile`
-(`node:22-alpine`): the frontend, api and MCP suites, the locale checks, and building and booting
-both api image targets. GitLab CI on the mirror (`.gitlab-ci.yml`) builds the release artifacts:
-the signed Android APK, the multi-arch images and the SBOMs. Never push or merge on GitLab
-directly; the mirror is fast-forward only.
+pushes `main` and `v*` tags to the GitLab mirror (fast-forward only, never push or merge there).
+Pull requests are gated by `.github/workflows/test.yml`; `ios.yml` compiles the iPhone app on a Mac
+runner. Release packages (APK, Play bundle, App Store IPA) are built and signed on the release
+machine, never in CI (see "Exercise media" below and docs/APP_STORES.md).
## Architecture
### Frontend (`frontend/src`)
-- **`store/useStore.js`** — single Zustand store holding the entire client-side app state (`S`),
+- **`store/useStore.js`**: a single Zustand store holding the client-side app state (`S`),
persisted to `localStorage` (`gym_state_v1`) and debounce-pushed to the server when signed in
- (`pushState`, see `lib/api.js`). On the Capacitor mobile build it's also mirrored to a file via
- `lib/mobile.js` (`nativeSave`), since WebView storage can be evicted. `store/useUI.js` holds
- ephemeral UI state (modals, active sheet, etc.) separately from persisted data.
-- **`lib/`** — pure, framework-free helpers, each paired with a same-directory `*.test.js`. This
- is where the domain logic lives, most importantly:
- - `progression.js` — the progression-rule engine (linear, Greyskull LP, double progression,
- time-based). Rules implement a shared policy interface; adding a new one plugs in here.
- - `onerm.js` — estimated 1RM from logged sets.
- - `finish-workout.js` — reduces a completed session back into state (weights advance, PRs, etc).
- - `recovery.js` / `recovery-view.js` — fatigue/muscle-recovery model.
- - `workout-model.js`, `supersetFlow.js` — in-session workout state machine, incl. supersets.
- - `exercises.js` / `exercises-data.js` — the exercise library (1,324 built-ins + user-defined).
- - `api.js` — the only place that talks to the backend (`fetch` wrapper, session cookie flows).
+ (`pushState`, see `lib/api.js`). On the phones it is also mirrored to a file via `lib/mobile.js`
+ (`nativeSave`), since WebView storage can be evicted. `store/useUI.js` holds ephemeral UI state
+ (modals, active sheet, rest timer) separately from persisted data.
+- **`lib/`**: pure, framework-free helpers, each paired with a same-directory `*.test.js`. The
+ domain logic lives here, most importantly:
+ - `progression.js`: the progression-rule engine (linear, Greyskull LP, double and triple
+ progression, time-based). Rules implement a shared policy interface.
+ - `onerm.js`: estimated 1RM from logged sets (several formulas).
+ - `finish-workout.js`: reduces a completed session back into state (weights advance, PRs).
+ - `recovery.js` / `recovery-view.js`: the fatigue and muscle-recovery model.
+ - `workout-model.js`, `supersetFlow.js`: the in-session workout state machine.
+ - `sync-merge.js`: the field-by-field merge behind the 409 retry (see "Sync" below).
+ - `exercises.js` / `exercises-data.js`: the exercise library (5,632 catalogue exercises plus
+ user-defined ones). `exercises-data.js`, `instr/`, `exercise-names/` and `exercise-desc/` are
+ generated from `catalogue/` by `scripts/catalogue/build.mjs`; never edit them by hand.
+ - `api.js`: the only place that talks to the backend (`fetch` wrapper, session flows).
+ - Native bridges: `mobile.js` (the `MOBILE` flag, file persistence, notifications),
+ `channel.js` (APK or store build), `watch-sync.js`, `widgets.js`, `health-sync.js`,
+ `anim-quality.js` / `anim-packs.js` (animation sizes in the store apps).
- CONTRIBUTING.md is explicit: **anything that decides what you lift next, or reads a logged
- session back, is a pure helper here with a unit test beside it** — not verifiable by
- clicking, and the progression engine has already had two bugs that only a test caught.
-- **`views/`** — one file per screen (Home, Workout, Plan, Library, Stats, History, Settings,
- Admin, Login, RoutineEdit), routed by `react-router-dom` from `App.jsx`.
-- **`components/`** — shared UI (charts, modals, timers); `instr/` holds per-language exercise
- instruction text; `locales/` is the i18n string catalogue (`lib/i18n.js` / `i18n-core.js`).
-- Mobile: `@capacitor/*` wraps the same web build into native shells under `frontend/android` and
- `frontend/ios` (see `docs/MOBILE.md`); `mobile.js` in `lib/` gates native-only behavior (file
- persistence, local notifications, wake lock) behind a `MOBILE` flag.
+ session back, is a pure helper here with a unit test beside it.**
+- **`views/`**: one file per screen, routed by `react-router-dom` from `App.jsx`.
+- **`sheets.jsx`**: the bottom sheets (exercise picker, exercise config, workout detail, plan
+ import...). It is large; a new sheet can go into `components/` as its own file.
+- **`components/`**: shared UI (charts, modals, timers, media).
+- **`locales/`**: one i18n pack per language, keyed by the English string (`lib/i18n.js`,
+ `i18n-core.js`). A new `t()` string goes into every pack; pt-BR inherits from pt and has a
+ fingerprint test (`scripts/pt-br-inheritance-fingerprint.mjs`).
### API (`api/server.js`)
-Single file, no framework, plain `node:http`. Requests are dispatched through a `routes` object
-keyed by `'METHOD /path'` (e.g. `routes['GET /api/health']`) matched against `req.method + ' ' +
-url.pathname` — add a new endpoint by adding a key here. State is two flat JSON files under
-`DATA_DIR` (`db.json`: users/credentials/subscriptions/invites; `state-<uid>.json`: per-user
-workout data), written with a write-temp-then-rename atomic pattern (`atomicWrite`). Auth is
-WebAuthn passkeys (`@simplewebauthn/server`) plus a signed session cookie (HMAC'd with a
-`DATA_DIR/secret` generated on first boot) — no JWT/session-store dependency. Optional pieces
-gated by env vars: `ADMIN_UIDS` (admin dashboard), `INVITE_ONLY` (signup needs a code),
-`ALLOW_GUEST` (client-only guest mode never hits the server at all), plus a rotating
-`data/audit.log` (JSONL) for sign-in/admin events. Web Push (`web-push`, VAPID keys
-auto-generated into `data/vapid.json`) drives rest-timer-over and day-reminder notifications.
+Plain `node:http`, no framework. Requests are dispatched through a `routes` object keyed by
+`'METHOD /path'` (e.g. `routes['GET /api/health']`); add an endpoint by adding a key and its entry
+in `openapi.yaml` (`openapi-routes.test.js` compares them). State is JSON under `DATA_DIR`:
+`db.json` (users, credentials, push subscriptions, invites) and `state-<uid>.json` per user,
+written temp-then-rename (`durable.js`). Custom-exercise photos and videos live in
+`DATA_DIR/uploads` (`media.js`). Auth is WebAuthn passkeys (`@simplewebauthn/server`), an optional
+password, and a signed session cookie (HMAC with `DATA_DIR/secret`); paired phones get the same
+session as a bearer token. Optional pieces are gated by env vars: `ADMIN_UIDS`, `INVITE_ONLY`,
+`ALLOW_GUEST`, `PASSWORD_LOGIN`, `AUDIT_*`. Web Push (`web-push`, VAPID keys in `data/vapid.json`)
+drives rest-timer and reminder notifications.
+
+### Sync
+
+Each profile is one document with a server revision. A device PUTs with the revision it last saw;
+if another device wrote in between, the server answers 409 with the current document and the
+client merges (`lib/sync-merge.js`) and retries. Every change carries its own stamp, per setting
+and per field, so the newest edit of each wins and deletions stay deleted.
+
+### Code that exists twice on purpose
+
+The API image cannot import the frontend, so some rules are hand-copied. Change both sides
+together: `lib/sync-merge.js` and `api/sync-stamps.js` (parity test), `lib/glyphs.js` and
+`api/coach/core/glyphs.js` (parity test), `lib/nudge.js` and `api/nudge.js`, `lib/queue.js` and
+`api/queue.js` (mirrored test cases only, nothing compares the code). The other way round,
+`lib/coach-local.js` imports `api/coach/core/` directly so the phones run the same coach pipeline.
### MCP server (`mcp/src`)
-Read-only stdio MCP bridge (`@modelcontextprotocol/sdk`) that lets an LLM client read a single
-user's routines/workouts/body-weight/1RM/muscle-balance directly from the same `DATA_DIR` the API
-writes to — no network call, no extra container. `state.js` loads/derives the data, `tools.js`
-defines the exposed MCP tools (zod-validated schemas), `labels.js` maps internal keys to
-human-readable labels, `index.js` wires it together. See `mcp/README.md` for the client-config
-side (Claude Desktop / Cursor).
+Read-only stdio MCP bridge (`@modelcontextprotocol/sdk`) that reads one user's data straight from
+`DATA_DIR`. `state.js` loads and derives the data, `tools.js` defines the tools (zod schemas),
+`labels.js` maps keys to readable labels, `index.js` wires it together. See `mcp/README.md`.
### Passkeys and self-hosting constraints
-WebAuthn passkeys are bound to an exact hostname (`RP_ID`) and require HTTPS (localhost excepted)
-— this shapes a lot of the API and Settings code (`RP_ID`/`ORIGIN` env vars, guest-mode fallback
-when neither is available). Read `docs/SELF_HOSTING.md` before touching auth, session, or
-notification code; it documents the exact env-var contract (`RP_ID`, `ORIGIN`, `PORT`,
-`WEB_PORT`, `NGINX_PORT`, `BACKEND`, `SESSION_DAYS`, `ADMIN_UIDS`, `INVITE_ONLY`, `ALLOW_GUEST`,
-`AUDIT_*`, `VAPID_SUBJECT`) that real deployments depend on.
+WebAuthn passkeys are bound to an exact hostname (`RP_ID`) and need HTTPS (localhost excepted).
+Read `docs/SELF_HOSTING.md` before touching auth, session or notification code; it documents the
+env-var contract (`RP_ID`, `ORIGIN`, `PORT`, `WEB_PORT`, `NGINX_PORT`, `BACKEND`, `SESSION_DAYS`,
+`ADMIN_UIDS`, `INVITE_ONLY`, `ALLOW_GUEST`, `AUDIT_*`, `VAPID_SUBJECT`) that real deployments
+depend on.
### Docker / deploy
-`docker-compose.yml` has three services: `media` (one-shot exercise-asset downloader, gitignored
-output), `api`, `web` (multi-stage build of `frontend/` served by nginx, which also proxies
-`/api` → `api` and serves the shared media volume — single origin, required for passkeys).
-`web/nginx.conf.template` is rendered from env vars at container start (`NGINX_PORT`, `BACKEND`,
-`PORT`), so host/port remapping works against prebuilt images without a rebuild.
+`docker-compose.yml` has two services, `api` and `web`. The web image builds `frontend/`, copies
+`catalogue/media` into it as `/exercise-media/`, and nginx proxies `/api` to the api (one origin,
+which passkeys require). `web/nginx.conf.template` is rendered from env vars at start
+(`NGINX_PORT`, `BACKEND`, `PORT`), so remapping works against prebuilt images.
+
+### Exercise media (licence, read before touching media)
+
+The stills and animations are licensed from Gym visual, not AGPL. Only 180 px files may be in the
+repository, CI, the web image, the demo or a self-hosted server (`scripts/catalogue/check-media.mjs`
+enforces it). Larger sizes exist only inside the APK and store packages, built on the release
+machine, or as Apple-hosted / Play asset packs. Never commit, upload or serve anything larger, and
+never feed the media to an AI tool.
## Guidelines from CONTRIBUTING.md worth knowing before changing code
-- **Dependency-light is a hard constraint, not a preference.** Frontend: React + Router + Zustand
- and nothing else. `api/`: two dependencies total. New dependencies are a hard sell either side.
-- Don't commit `media/` or `data/` (gitignored).
+- **Dependency-light is a hard constraint.** Frontend: React + Router + Zustand (plus Capacitor
+ plugins). `api/`: three dependencies. New dependencies are a hard sell either side.
+- Don't commit `data/`. Don't add or replace anything in `catalogue/media/`.
- Training-logic changes (progression, 1RM, session read-back) need a unit test in `src/lib`
- beside the code, not just manual clicking-through.
+ beside the code.
+- User-facing text: plain and human, no em dashes. CHANGELOG.md is written at release time.