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.

CI: one required check (tests-ok), path-filtered jobs, test stats in the job summary, pinned actions

Duarte Santoseed624ec3579
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index 5d1221143..2b5cdbe2a 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -58,6 +58,17 @@ updates:
patterns: ['*']
update-types: ['major']
+ # MCP bridge — mcp/package.json
+ - package-ecosystem: npm
+ directory: /mcp
+ schedule:
+ interval: monthly
+ open-pull-requests-limit: 2
+ groups:
+ mcp:
+ patterns: ['*']
+ update-types: ['minor', 'patch']
+
# Base images — api/Dockerfile (node:22-alpine)
- package-ecosystem: docker
directory: /api
@@ -89,7 +100,8 @@ updates:
interval: monthly
open-pull-requests-limit: 2
groups:
- # These are all first-party actions/* and docker/* pinned to a major tag; they update
+ # Pinned to commit SHAs (with the tag in a comment), which Dependabot updates the same way;
+ # mostly first-party actions/* and docker/*, they update
# in lockstep and none of them is worth a PR of its own.
actions:
patterns: ['*']
diff --git a/.github/workflows/audit.yml b/.github/workflows/audit.yml
new file mode 100644
index 000000000..adf203746
--- /dev/null
+++ b/.github/workflows/audit.yml
@@ -0,0 +1,124 @@
+# Weekly health check that no single push pays for:
+#
+# - dependencies: known vulnerabilities in what the app and server actually ship (fails on
+# high/critical in runtime dependencies), dev tooling and outdated packages as a report;
+# - robustness: the frontend and api suites under conditions CI never has on a normal run.
+# Other time zones (a gym log is full of "today": a test that only passes in UTC broke on a
+# developer's machine in Zurich), a clock six weeks ahead (fixture dates aged out of the
+# Coach's review window on 2026-10-13 and turned every pull request red overnight), and a
+# shuffled test order (a test that only passes after another one has run).
+#
+# A red run here is a list of real problems, not a broken build: nothing waits on it.
+name: Weekly audit
+
+on:
+ schedule:
+ - cron: '23 4 * * 1' # Mondays 04:23 UTC
+ workflow_dispatch:
+ # A change to the audit itself is tried out before it waits a week for its first run.
+ pull_request:
+ paths: ['.github/workflows/audit.yml', 'scripts/ci/deps-audit.mjs']
+ push:
+ branches: ['ci-*']
+ paths: ['.github/workflows/audit.yml', 'scripts/ci/deps-audit.mjs']
+
+permissions:
+ contents: read
+
+concurrency:
+ group: audit-${{ github.ref }}
+ cancel-in-progress: true
+
+env:
+ NODE_VERSION: 22
+
+jobs:
+ dependencies:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ - name: npm audit (runtime fails on high, dev tooling reported)
+ run: node scripts/ci/deps-audit.mjs frontend api mcp
+ - name: Outdated packages (report only)
+ if: always()
+ run: |
+ {
+ echo "### Outdated packages"
+ for d in frontend api mcp; do
+ echo "#### $d"
+ echo '```'
+ (cd "$d" && npm outdated --long 2>/dev/null || true) | head -60
+ echo '```'
+ done
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ robustness:
+ runs-on: ubuntu-latest
+ timeout-minutes: 40
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ # Fourteen hours ahead of UTC, and six weeks later: "today" is tomorrow for UTC, and
+ # fixed fixture dates age.
+ - name: 'UTC+14, six weeks ahead, shuffled'
+ tz: Pacific/Kiritimati
+ shift: '+42d'
+ # Behind UTC with a daylight-saving change in the range most fixtures use.
+ - name: 'America/Los_Angeles, shuffled'
+ tz: America/Los_Angeles
+ shift: ''
+ name: robustness (${{ matrix.name }})
+ env:
+ TZ: ${{ matrix.tz }}
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: npm
+ cache-dependency-path: |
+ frontend/package-lock.json
+ api/package-lock.json
+ - name: Clock
+ run: |
+ sudo apt-get install -y -qq faketime >/dev/null
+ # libfaketime moves the wall clock only (DONT_FAKE_MONOTONIC): timers keep their pace.
+ if [ -n "${{ matrix.shift }}" ]; then
+ echo "FAKETIME=${{ matrix.shift }}" >> "$GITHUB_ENV"
+ echo "DONT_FAKE_MONOTONIC=1" >> "$GITHUB_ENV"
+ echo "FAKE_PRELOAD=$(ls /usr/lib/x86_64-linux-gnu/faketime/libfaketimeMT.so.1)" >> "$GITHUB_ENV"
+ fi
+ - run: npm ci --ignore-scripts --no-audit --no-fund
+ working-directory: frontend
+ - run: npm ci --omit=optional --no-audit --no-fund
+ working-directory: api
+ - name: Frontend suite
+ id: fe
+ continue-on-error: true
+ working-directory: frontend
+ run: |
+ LD_PRELOAD="${FAKE_PRELOAD:-}" node -e 'console.log("clock:", new Date().toString())'
+ LD_PRELOAD="${FAKE_PRELOAD:-}" npx vitest run --sequence.shuffle --reporter=default --reporter=json --outputFile.json=test-results.json
+ - name: API suite
+ id: api
+ continue-on-error: true
+ working-directory: api
+ run: >
+ LD_PRELOAD="${FAKE_PRELOAD:-}" node --test --test-reporter=spec --test-reporter-destination=stdout
+ --test-reporter=tap --test-reporter-destination=test-results.tap test/*.test.js
+ - name: Report
+ if: always()
+ run: |
+ echo "## Robustness: ${{ matrix.name }}" >> "$GITHUB_STEP_SUMMARY"
+ node scripts/ci/test-report.mjs --label "Frontend (${{ matrix.name }})" --root frontend --vitest frontend/test-results.json --out stats/frontend.json > /dev/null
+ node scripts/ci/test-report.mjs --label "API (${{ matrix.name }})" --root api --tap api/test-results.tap --out stats/api.json > /dev/null
+ test "${{ steps.fe.outcome }}" = success && test "${{ steps.api.outcome }}" = success
diff --git a/.github/workflows/catalogue.yml b/.github/workflows/catalogue.yml
deleted file mode 100644
index ce886a945..000000000
--- a/.github/workflows/catalogue.yml
+++ /dev/null
@@ -1,29 +0,0 @@
-# Checks every change to the exercise catalogue: the entries themselves (scripts/catalogue/validate.mjs)
-# and that the files the app is built from were regenerated (build.mjs --check).
-name: Catalogue
-
-on:
- pull_request:
- paths: ['catalogue/**', 'scripts/catalogue/**', 'frontend/src/lib/exercises-data.js', 'frontend/src/instr/**', 'frontend/src/exercise-names/**', 'frontend/src/exercise-desc/**', '.github/workflows/catalogue.yml']
- push:
- branches: [main]
- paths: ['catalogue/**', 'scripts/catalogue/**', '.github/workflows/catalogue.yml']
- workflow_dispatch:
-
-permissions:
- contents: read
-
-jobs:
- validate:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v7
- - uses: actions/setup-node@v7
- with:
- node-version: 22
- - name: Validate the catalogue
- run: node scripts/catalogue/validate.mjs
- - name: Generated files are up to date
- run: node scripts/catalogue/build.mjs --check
- - name: Media stay within 180 px (licence)
- run: node scripts/catalogue/check-media.mjs
diff --git a/.github/workflows/cla-issue.yml b/.github/workflows/cla-issue.yml
index 4df23b7c9..135aa50ec 100644
--- a/.github/workflows/cla-issue.yml
+++ b/.github/workflows/cla-issue.yml
@@ -18,8 +18,9 @@ jobs:
record:
if: github.event.issue.number == 554 && !github.event.issue.pull_request
runs-on: ubuntu-latest
+ timeout-minutes: 5
steps:
- - uses: actions/checkout@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: cla-signatures
- name: Add the signature
@@ -47,6 +48,6 @@ jobs:
if ! git diff --quiet; then
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
- git commit -qam "@${{ github.event.comment.user.login }} has signed the CLA in #554"
+ git commit -qam "@$LOGIN has signed the CLA in #554"
git push
fi
diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml
index fbf9b09ac..d56a4f597 100644
--- a/.github/workflows/cla.yml
+++ b/.github/workflows/cla.yml
@@ -1,4 +1,4 @@
-# CLA check on every pull request (draft for .github/workflows/cla.yml).
+# CLA check on every pull request. Its job `cla` is the required check of the CLA ruleset.
# A first-time contributor is asked once to comment the sign phrase; the signature is stored in
# the repository (signatures/cla.json on the cla-signatures branch), no third-party service.
name: CLA
@@ -15,14 +15,19 @@ permissions:
pull-requests: write
statuses: write
+# pull_request_target runs with a write token, which is safe here only because nothing from the
+# pull request is checked out or executed: the action reads the PR's commit authors through the
+# API and writes to the cla-signatures branch. Keep it that way (no actions/checkout of the head).
jobs:
cla:
+ # Every other comment (most of them) skips the job instead of starting a runner for nothing.
+ # Comments on plain issues (the pinned CLA issue #554) are not pull requests: the action
+ # would look for a PR with that number and fail. Those are recorded by cla-issue.yml.
+ if: (github.event_name == 'issue_comment' && github.event.issue.pull_request && (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA')) || github.event_name == 'pull_request_target'
runs-on: ubuntu-latest
+ timeout-minutes: 5
steps:
- # Comments on plain issues (the pinned CLA issue #554) are not pull requests: the action
- # would look for a PR with that number and fail. Those are recorded by cla-issue.yml.
- - if: (github.event_name == 'issue_comment' && github.event.issue.pull_request && (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA')) || github.event_name == 'pull_request_target'
- uses: contributor-assistant/[email protected]
+ - uses: contributor-assistant/github-action@ca4a40a7d1004f18d9960b404b97e5f30a505a08 # v2.6.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml
index 6ebcb6724..1343e6eb8 100644
--- a/.github/workflows/docker-publish.yml
+++ b/.github/workflows/docker-publish.yml
@@ -13,6 +13,20 @@ name: Publish Docker images
on:
push:
branches: [main]
+ # A docs, website or workflow-only change ships the same images: 181 edge
+ # builds in three months, many of them for a README line. Anything that ends up in an image
+ # still builds (api/, web/, frontend/, catalogue media through the web build).
+ paths-ignore:
+ - '*.md'
+ - 'docs/**'
+ - 'website/**'
+ # (a change to this workflow alone: run it by hand)
+ - '.github/**'
+ - 'helm/**'
+ - 'kubernetes/**'
+ - 'contrib/**'
+ - 'frontend/ios/**'
+ - 'frontend/android/**'
release:
types: [published]
workflow_dispatch:
@@ -21,9 +35,16 @@ permissions:
contents: read
packages: write
+# A newer push to main makes an unfinished `edge` build pointless; a release build is never
+# cancelled (each release has its own group).
+concurrency:
+ group: docker-${{ github.event_name == 'release' && github.ref || 'edge' }}
+ cancel-in-progress: ${{ github.event_name == 'push' }}
+
jobs:
build:
runs-on: ubuntu-latest
+ timeout-minutes: 60
strategy:
matrix:
include:
@@ -34,7 +55,11 @@ jobs:
context: .
file: ./web/Dockerfile
steps:
- - uses: actions/checkout@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+
+ - name: Versions agree with the release tag
+ if: github.event_name == 'release'
+ run: node scripts/ci/release-check.mjs "$GITHUB_REF_NAME"
- name: Lowercase owner (registry names must be lowercase)
id: repo
@@ -53,16 +78,16 @@ jobs:
echo "VCS_REF=${GITHUB_SHA}" >> $GITHUB_OUTPUT
echo "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
- - uses: docker/setup-qemu-action@v4
- - uses: docker/setup-buildx-action@v4
+ - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
+ - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- - uses: docker/[email protected]
+ - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- - uses: docker/metadata-action@v6
+ - uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
id: meta
with:
images: ghcr.io/${{ steps.repo.outputs.owner }}/opengym-${{ matrix.image }}
@@ -72,7 +97,7 @@ jobs:
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- - uses: docker/build-push-action@v7
+ - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
context: ${{ matrix.context }}
file: ${{ matrix.file }}
diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml
index 0c803dd02..8b110766b 100644
--- a/.github/workflows/ios.yml
+++ b/.github/workflows/ios.yml
@@ -5,15 +5,12 @@
name: iOS
on:
+ # Pull requests: when they touch the iOS shell or what goes into it, or when someone puts the
+ # `ios` label on one (a change elsewhere that might still matter on the phone).
pull_request:
- paths:
- - 'frontend/ios/**'
- - 'frontend/package.json'
- - 'frontend/package-lock.json'
- - 'frontend/capacitor.config.json'
- - '.github/workflows/ios.yml'
+ types: [opened, synchronize, reopened, labeled]
push:
- branches: [main, stores]
+ branches: [main, stores, watch]
paths:
- 'frontend/**'
- '.github/workflows/ios.yml'
@@ -27,12 +24,57 @@ concurrency:
cancel-in-progress: true
jobs:
+ # Whether a pull request is one for the Mac at all (macOS minutes are the slow queue).
+ gate:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ pull-requests: read
+ outputs:
+ run: ${{ steps.decide.outputs.run }}
+ steps:
+ - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3
+ id: f
+ if: github.event_name == 'pull_request'
+ with:
+ filters: |
+ ios:
+ - 'frontend/ios/**'
+ - 'frontend/package.json'
+ - 'frontend/package-lock.json'
+ - 'frontend/capacitor.config.json'
+ - 'frontend/src/lib/native*.js'
+ - 'frontend/src/lib/rest-alert.js'
+ - 'frontend/src/lib/watch-sync.js'
+ - 'frontend/src/lib/health-sync.js'
+ - 'frontend/src/lib/widgets.js'
+ - 'frontend/src/lib/live-activity.js'
+ - '.github/workflows/ios.yml'
+ - id: decide
+ env:
+ EVENT: ${{ github.event_name }}
+ ACTION: ${{ github.event.action }}
+ LABEL: ${{ github.event.label.name }}
+ HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'ios') }}
+ IOS: ${{ steps.f.outputs.ios }}
+ run: |
+ run=true
+ if [ "$EVENT" = pull_request ]; then
+ # A label event runs only for the `ios` label itself; any other label is not a reason.
+ if [ "$ACTION" = labeled ]; then [ "$LABEL" = ios ] || run=false
+ else [ "$IOS" = true ] || [ "$HAS_LABEL" = true ] || run=false; fi
+ fi
+ echo "run=$run" >> "$GITHUB_OUTPUT"; echo "iOS jobs: $run"
+
simulator:
+ needs: gate
+ if: needs.gate.outputs.run == 'true'
runs-on: macos-26
timeout-minutes: 60
steps:
- - uses: actions/checkout@v7
- - uses: actions/setup-node@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 22
cache: npm
@@ -79,16 +121,34 @@ jobs:
xcrun simctl boot "$UDID"
xcrun simctl bootstatus "$UDID" -b
xcrun simctl install "$UDID" build/dd/Build/Products/Debug-iphonesimulator/App.app
- # A busy runner can still be starting the simulator's own apps: give the page up to eight
- # minutes to reach its plugins rather than a fixed wait.
- xcrun simctl launch --console-pty "$UDID" ch.opengym.app > build/console.log 2>&1 &
- for i in $(seq 96); do grep -q "RestAlert" build/console.log && break; sleep 5; done
+ # Up to three launches, four minutes each. The known flake (2026-10-13: "the page never
+ # reached the RestAlert plugin" with an empty console) is a first launch on a runner
+ # that is still busy starting the simulator's own apps: the app comes up but its page
+ # never loads. A relaunch, and on the last try a fresh simulator boot, gets past it,
+ # while a page that really cannot reach its plugins fails all three.
+ reached=""
+ for attempt in 1 2 3; do
+ if [ "$attempt" = 3 ]; then
+ echo "::warning::relaunching on a freshly booted simulator"
+ xcrun simctl shutdown "$UDID" || true
+ xcrun simctl boot "$UDID" && xcrun simctl bootstatus "$UDID" -b
+ fi
+ xcrun simctl terminate "$UDID" ch.opengym.app 2>/dev/null || true
+ xcrun simctl launch --console-pty "$UDID" ch.opengym.app > build/console.log 2>&1 &
+ LPID=$!
+ for i in $(seq 48); do grep -q "RestAlert" build/console.log && break; sleep 5; done
+ if grep -q "RestAlert" build/console.log; then reached=$attempt; break; fi
+ echo "::warning::launch $attempt: the page did not reach RestAlert in 4 minutes ($(wc -l < build/console.log) console lines)"
+ cp build/console.log "build/console-attempt-$attempt.log"
+ kill "$LPID" 2>/dev/null || true
+ done
sleep 5
xcrun simctl io "$UDID" screenshot build/first-screen.png || true
- kill %1 || true
- cat build/console.log | grep -v "^\s*$" | head -200
+ kill "$LPID" 2>/dev/null || true
+ grep -v "^\s*$" build/console.log | head -200
if grep -q "not implemented on ios" build/console.log; then echo "::error::a plugin the page uses is missing on iOS"; exit 1; fi
- grep -q "RestAlert" build/console.log || { echo "::error::the page never reached the RestAlert plugin"; exit 1; }
+ [ -n "$reached" ] || { echo "::error::the page never reached the RestAlert plugin (3 launches)"; exit 1; }
+ echo "simulator: the page reached its plugins on launch $reached" >> "$GITHUB_STEP_SUMMARY"
echo "$UDID" > build/udid.txt
# The widgets and the Live Activity as pictures, light and dark (App/WidgetPreview.swift draws
# them with made-up data): nobody can put a widget on a simulator's Home Screen without a Mac.
@@ -223,13 +283,13 @@ jobs:
xcrun simctl shutdown "$UDID" || true
done
find build/watch-promo -type f | sort
- - uses: actions/upload-artifact@v6
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
if: always()
with:
name: ios-simulator
path: |
frontend/ios/App/build/xcodebuild.log
- frontend/ios/App/build/console.log
+ frontend/ios/App/build/console*.log
frontend/ios/App/build/first-screen.png
frontend/ios/App/build/watch
frontend/ios/App/build/watch-promo
@@ -242,11 +302,13 @@ jobs:
# through the -OpenGymUITestPending probe in MainViewController.swift).
# The exercise media are left out of this build; the screenshots show placeholders.
ui-tests:
+ needs: gate
+ if: needs.gate.outputs.run == 'true'
runs-on: macos-26
timeout-minutes: 60
steps:
- - uses: actions/checkout@v7
- - uses: actions/setup-node@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 22
cache: npm
@@ -274,17 +336,28 @@ jobs:
xcrun simctl boot "$UDID" && xcrun simctl bootstatus "$UDID" -b
mkdir -p build
set -o pipefail
+ # A failing test gets two more tries: XCUITest's "Timed out while evaluating UI query"
+ # on a loaded runner was most of this job's red runs (2026-10-13/14). A test that fails
+ # three times in a row is a real failure; one that needed a retry is listed in the
+ # summary below, so a flake stays visible instead of being silently absorbed.
xcodebuild test -workspace App.xcworkspace -scheme AppUITests -destination "id=$UDID" \
+ -retry-tests-on-failure -test-iterations 3 \
-resultBundlePath build/ui.xcresult CODE_SIGNING_ALLOWED=NO \
| tee build/ui-tests.log | grep -E "error:|Test Case|passed|failed|TEST" || exit 1
- name: Keep the screenshots
if: always()
working-directory: frontend/ios/App
run: |
+ {
+ echo "### iOS UI tests"
+ grep -E "^Test Case .*(passed|failed)" build/ui-tests.log | sed -E "s/^Test Case '-\[[^ ]+ ([^]]+)\]' (passed|failed).*\(([0-9.]+) seconds\).*/- \1: \2 (\3 s)/" | sort | uniq -c | sed 's/^ *//' || true
+ echo
+ echo "A test listed as both failed and passed needed a retry: that is a flake to look at."
+ } >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || true
mkdir -p build/shots
xcrun xcresulttool export attachments --path build/ui.xcresult --output-path build/shots || true
ls build/shots
- - uses: actions/upload-artifact@v6
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
if: always()
with:
name: ios-ui-tests
@@ -297,12 +370,13 @@ jobs:
# animations in and sign (scripts/ios/finish-ipa.sh). Built for devices; its media are the
# repo's 180 px ones.
device-archive:
+ needs: gate
+ if: needs.gate.outputs.run == 'true' && github.event_name != 'pull_request'
runs-on: macos-26
timeout-minutes: 60
- if: github.event_name != 'pull_request'
steps:
- - uses: actions/checkout@v7
- - uses: actions/setup-node@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 22
cache: npm
@@ -333,7 +407,7 @@ jobs:
mkdir -p ../../../Payload && cp -R App.app ../../../Payload/
cd ../../.. && echo "$GITHUB_SHA" > ci-commit.txt && zip -qry App-unsigned.ipa Payload ci-commit.txt
ls -la App-unsigned.ipa
- - uses: actions/upload-artifact@v6
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: ios-unsigned-ipa
path: frontend/ios/App/build/App-unsigned.ipa
diff --git a/.github/workflows/mirror.yml b/.github/workflows/mirror.yml
index b93eca4ea..957460c09 100644
--- a/.github/workflows/mirror.yml
+++ b/.github/workflows/mirror.yml
@@ -36,7 +36,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- - uses: actions/checkout@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
fetch-tags: true
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml
index bbb001e0c..3b8ae8065 100644
--- a/.github/workflows/pages.yml
+++ b/.github/workflows/pages.yml
@@ -32,9 +32,10 @@ concurrency:
jobs:
build:
runs-on: ubuntu-latest
+ timeout-minutes: 20
steps:
- - uses: actions/checkout@v7
- - uses: actions/setup-node@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 22
cache: npm
@@ -47,8 +48,8 @@ jobs:
VITE_DEMO: '1'
# The 180 px stills and animations from catalogue/media, served next to the demo
- run: node scripts/catalogue/stage-media.mjs frontend/dist
- - uses: actions/configure-pages@v6
- - uses: actions/upload-pages-artifact@v5
+ - uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0
+ - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
with:
path: frontend/dist
@@ -60,4 +61,4 @@ jobs:
url: ${{ steps.deploy.outputs.page_url }}
steps:
- id: deploy
- uses: actions/deploy-pages@v5
+ uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1
diff --git a/.github/workflows/release-check.yml b/.github/workflows/release-check.yml
new file mode 100644
index 000000000..e32b817a3
--- /dev/null
+++ b/.github/workflows/release-check.yml
@@ -0,0 +1,41 @@
+# Before anything is published for a version: every place that carries the version agrees with
+# the tag, and CHANGELOG.md has its section (scripts/ci/release-check.mjs). Runs on the tag push,
+# i.e. before the GitHub release is published from it, so a mismatch shows up while it is still
+# cheap to re-tag. docker-publish.yml runs the same check before it pushes release images.
+name: Release check
+
+on:
+ push:
+ tags: ['v*']
+ # Changes to the check itself, tried out on a CI branch (prints the table, checks nothing).
+ branches: ['ci-*']
+ paths: ['.github/workflows/release-check.yml', 'scripts/ci/release-check.mjs']
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: 'Version to check, e.g. v1.4.2 (empty: just print the versions)'
+ required: false
+
+permissions:
+ contents: read
+
+jobs:
+ versions:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ fetch-depth: 0
+ - name: Versions agree with the tag
+ env:
+ TAG: ${{ github.event.inputs.tag || (startsWith(github.ref, 'refs/tags/') && github.ref_name) || '' }}
+ run: node scripts/ci/release-check.mjs $TAG
+ # A release of a commit that is not on main would ship code main does not have
+ # (the store branches are merged into main before their release).
+ - name: The tagged commit is on main
+ if: startsWith(github.ref, 'refs/tags/')
+ run: |
+ git merge-base --is-ancestor "$GITHUB_SHA" origin/main \
+ || { echo "::error::$GITHUB_REF_NAME points at ${GITHUB_SHA::8}, which is not on main"; exit 1; }
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 341cf6d1e..d0cd752df 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -1,134 +1,348 @@
-# Runs on pull requests too — the other two workflows only fire on push to main, so
-# contributed changes used to reach main without anything ever having been run.
+# The check every change goes through: pull requests, main, the release branches (stores,
+# watch) and ci-* branches. One workflow, one result: the last job, `tests-ok`, is the one to
+# mark as required in a ruleset. It is green when every job that had something to check passed;
+# jobs with nothing to check (a docs-only change) are skipped, not red, so a required check
+# never hangs waiting for a run that a path filter swallowed.
+#
+# What runs is decided per job by the `changes` job (dorny/paths-filter), not by a workflow
+# level `paths:`. That way the workflow always reports, and a change to api/ alone does not
+# spend four minutes building the frontend.
+#
+# Every run writes its numbers (tests and coverage per app area, slowest tests, runtime) to the
+# job summary through scripts/ci/test-report.mjs and keeps them as the `test-stats` artifact.
name: Tests
on:
pull_request:
- paths:
- - 'frontend/**'
- - 'api/**'
- - 'mcp/**'
- - 'scripts/build-coach-assets.mjs'
- - 'scripts/build-coach-library.mjs'
- - 'scripts/build-api-docs.mjs'
- - 'website/api.html'
- - 'api/coach/prompts/**'
- - '.github/workflows/test.yml'
push:
- branches: [main, coach]
- paths:
- - 'frontend/**'
- - 'api/**'
- - 'mcp/**'
- - 'scripts/build-coach-assets.mjs'
- - 'scripts/build-coach-library.mjs'
- - 'scripts/build-api-docs.mjs'
- - 'website/api.html'
- - 'api/coach/prompts/**'
- - '.github/workflows/test.yml'
+ branches: [main, stores, watch, 'ci-*']
workflow_dispatch:
permissions:
contents: read
concurrency:
- group: test-${{ github.ref }}
+ # One run per PR or branch; a newer push makes the older run pointless.
+ group: tests-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
+env:
+ # The images are node:22-alpine (web/Dockerfile, api/Dockerfile): CI matches production.
+ NODE_VERSION: 22
+ FORCE_COLOR: '1'
+
jobs:
- test:
+ changes:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ permissions:
+ contents: read
+ pull-requests: read
+ outputs:
+ frontend: ${{ steps.f.outputs.frontend == 'true' || github.event_name == 'workflow_dispatch' }}
+ api: ${{ steps.f.outputs.api == 'true' || github.event_name == 'workflow_dispatch' }}
+ mcp: ${{ steps.f.outputs.mcp == 'true' || github.event_name == 'workflow_dispatch' }}
+ images: ${{ steps.f.outputs.images == 'true' || github.event_name == 'workflow_dispatch' }}
+ android: ${{ steps.f.outputs.android == 'true' || github.event_name == 'workflow_dispatch' }}
+ catalogue: ${{ steps.f.outputs.catalogue == 'true' || github.event_name == 'workflow_dispatch' }}
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3
+ id: f
+ with:
+ filters: |
+ frontend:
+ - '.github/workflows/test.yml'
+ - 'scripts/ci/**'
+ - 'frontend/src/**'
+ - 'frontend/public/**'
+ - 'frontend/scripts/**'
+ - 'frontend/index.html'
+ - 'frontend/vite.config.js'
+ - 'frontend/package*.json'
+ # The phone build and the Coach import the api's shared core.
+ - 'api/coach/core/**'
+ - 'api/coach/prompts/**'
+ - 'api/sync-stamps.js'
+ - 'api/nudge-copy.js'
+ - 'api/server.js'
+ - 'api/test/fixtures/**'
+ - 'catalogue/**'
+ - 'scripts/build-coach-*.mjs'
+ - 'web/Dockerfile'
+ api:
+ - '.github/workflows/test.yml'
+ - 'scripts/ci/**'
+ - 'api/**'
+ - 'website/api.html'
+ - 'scripts/build-api-docs.mjs'
+ - 'scripts/build-coach-*.mjs'
+ - 'catalogue/**'
+ - 'frontend/src/lib/**'
+ - 'frontend/src/locales/**'
+ mcp:
+ - '.github/workflows/test.yml'
+ - 'scripts/ci/**'
+ - 'mcp/**'
+ - 'frontend/src/lib/**'
+ images:
+ - '.github/workflows/test.yml'
+ - 'api/Dockerfile'
+ - 'api/package*.json'
+ - 'api/*.js'
+ - 'api/coach/**'
+ - 'web/**'
+ - 'frontend/package*.json'
+ - 'frontend/vite.config.js'
+ android:
+ - '.github/workflows/test.yml'
+ - 'frontend/android/**'
+ - 'frontend/package*.json'
+ - 'frontend/capacitor.config.json'
+ - 'frontend/scripts/check-mobile-bundle.mjs'
+ - 'scripts/android/**'
+ - 'scripts/catalogue/stage-media.mjs'
+ catalogue:
+ - '.github/workflows/test.yml'
+ - 'catalogue/**'
+ - 'scripts/catalogue/**'
+ - 'frontend/src/lib/exercises-data.js'
+ - 'frontend/src/instr/**'
+ - 'frontend/src/exercise-names/**'
+ - 'frontend/src/exercise-desc/**'
+
+ frontend:
+ needs: changes
+ if: needs.changes.outputs.frontend == 'true'
runs-on: ubuntu-latest
+ timeout-minutes: 25
steps:
- - uses: actions/checkout@v7
- # node:22-alpine in web/Dockerfile and api/Dockerfile — CI must match production.
- - uses: actions/setup-node@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- node-version: 22
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
cache: npm
cache-dependency-path: frontend/package-lock.json
- - run: npm ci
+ # --ignore-scripts: nothing the tests or the web build need has a postinstall, and the one
+ # package that does (@capacitor/assets -> sharp, a libvips download) only draws app icons.
+ - run: npm ci --ignore-scripts --no-audit --no-fund
working-directory: frontend
- - run: npm test
+ # Unit + component suite with v8 coverage and a JSON report for the stats step. No
+ # retries: a test that only passes the second time is a bug. Order, time zone and clock
+ # are shaken weekly in audit.yml.
+ - name: Unit and component tests
working-directory: frontend
+ run: >
+ npx vitest run
+ --reporter=default --reporter=json --outputFile.json=test-results.json
+ --reporter=junit --outputFile.junit=junit.xml
+ --coverage --coverage.provider=v8 --coverage.include='src/**'
+ --coverage.reporter=json-summary --coverage.reporter=text-summary
# A broken import or bad JSX fails the build long before any test covers it.
- - run: npm run build
+ - name: Web build
+ run: npm run build
+ working-directory: frontend
+ - name: Bundle size
+ run: node scripts/bundle-size.mjs --out bundle-size.json
working-directory: frontend
- - run: node scripts/check-locales.mjs
+ - name: Locale packs are in sync
+ run: node scripts/check-locales.mjs
working-directory: frontend
# check-locales compares the packs to each other, so a key missing from ALL of them is
- # invisible to it. This walks src/ instead. Report-only for now: there is a known
- # backlog of untranslated demo-view strings to clear before it can fail the build.
- - run: node scripts/check-source-strings.mjs
+ # invisible to it. This walks src/ instead. Report-only (a known backlog of demo strings).
+ - name: Untranslated strings in src (report only)
+ run: node scripts/check-source-strings.mjs
working-directory: frontend
# The fatigue model must never read higher after a rest day than before it.
# Property probe over ~108k comparisons; too slow for the unit suite, cheap here.
- - run: npm run test:fatigue-probe
+ - name: Fatigue model property probe
+ run: npm run test:fatigue-probe
working-directory: frontend
+ - name: Stats
+ if: always()
+ run: >
+ node scripts/ci/test-report.mjs --label Frontend --root frontend
+ --vitest frontend/test-results.json --coverage frontend/coverage/coverage-summary.json
+ --bundle frontend/bundle-size.json --out stats/frontend.json
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ if: always()
+ with:
+ name: stats-frontend
+ path: |
+ stats/frontend.json
+ frontend/junit.xml
+ retention-days: 30
+ if-no-files-found: ignore
+ api:
+ needs: changes
+ if: needs.changes.outputs.api == 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: npm
+ cache-dependency-path: |
+ api/package-lock.json
+ package-lock.json
+ # The Coach tests drive the in-repo fixture provider and a local mock of the Chat
+ # Completions shape: no AI account, no network. The Agent SDK is optional and stays out.
+ - run: npm ci --omit=optional --no-audit --no-fund
+ working-directory: api
+ - name: API tests
+ working-directory: api
+ run: >
+ node --test --experimental-test-coverage
+ --test-coverage-exclude='test/**' --test-coverage-exclude='node_modules/**'
+ --test-reporter=spec --test-reporter-destination=stdout
+ --test-reporter=tap --test-reporter-destination=test-results.tap
+ --test-reporter=lcov --test-reporter-destination=lcov.info
+ --test-reporter=junit --test-reporter-destination=junit.xml
+ test/*.test.js
+ # The api's copy of the exercise catalogue is generated and committed. A dataset change
+ # that forgets to regenerate it would surface as "the Coach can't find that exercise".
+ - name: Generated Coach assets are current
+ run: node scripts/build-coach-assets.mjs --check
+ # website/api.html is generated from api/openapi.yaml and committed. Same reason.
+ - run: npm ci --no-audit --no-fund
+ - name: Generated API docs are current
+ run: node scripts/build-api-docs.mjs --check
+ - name: Coach core loads in plain node
+ run: node api/scripts/check-core-loadable.mjs
+ - name: Stats
+ if: always()
+ run: >
+ node scripts/ci/test-report.mjs --label API --root api
+ --tap api/test-results.tap --lcov api/lcov.info --out stats/api.json
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ if: always()
+ with:
+ name: stats-api
+ path: |
+ stats/api.json
+ api/junit.xml
+ retention-days: 30
+ if-no-files-found: ignore
mcp:
+ needs: changes
+ if: needs.changes.outputs.mcp == 'true'
runs-on: ubuntu-latest
+ timeout-minutes: 10
steps:
- - uses: actions/checkout@v7
- - uses: actions/setup-node@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- node-version: 22
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
cache: npm
cache-dependency-path: mcp/package-lock.json
- - run: npm ci
+ - run: npm ci --no-audit --no-fund
working-directory: mcp
- - run: npm test
+ - name: MCP tests
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
+ run: >
+ npx vitest run
+ --reporter=default --reporter=json --outputFile.json=test-results.json
+ --coverage --coverage.provider=v8 --coverage.reporter=json-summary
+ # The one check the vitest suite structurally cannot make: the MCP server is a bare node
+ # process, but vitest resolves import.meta.glob, .jsx and ?raw happily. That is how a
+ # Vite-only import reached a shared module with 33 green tests over a dead server.
+ - name: Server loads in plain node
+ run: npm run check:node-loadable
working-directory: mcp
+ - name: Stats
+ if: always()
+ run: >
+ node scripts/ci/test-report.mjs --label MCP --root mcp
+ --vitest mcp/test-results.json --coverage mcp/coverage/coverage-summary.json --out stats/mcp.json
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ if: always()
+ with:
+ name: stats-mcp
+ path: stats/mcp.json
+ retention-days: 30
+ if-no-files-found: ignore
- api:
+ # Was its own workflow (catalogue.yml); here it reports into the one required check.
+ catalogue:
+ needs: changes
+ if: needs.changes.outputs.catalogue == 'true'
runs-on: ubuntu-latest
+ timeout-minutes: 10
steps:
- - uses: actions/checkout@v7
- - uses: actions/setup-node@v7
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- node-version: 22
- cache: npm
- cache-dependency-path: api/package-lock.json
- # The Coach tests run on node:test and drive the in-repo fixture provider plus a local mock
- # of the Chat Completions shape, so the job needs no AI account and no network — but it does
- # need the api's own dependencies since the server-side fetch moved onto undici (same
- # install as test:api in .gitlab-ci.yml; the Agent SDK is optional and stays out).
- - run: npm ci --omit=optional
- working-directory: api
- - run: npm test
- working-directory: api
- # The api's copy of the exercise catalogue is generated and committed. A dataset change
- # that forgets to regenerate it would otherwise only surface as "the Coach can't find
- # that exercise" on somebody's instance.
- - run: node scripts/build-coach-assets.mjs --check
- # website/api.html is generated from api/openapi.yaml and committed. Same reason.
- - run: npm ci
- - run: node scripts/build-api-docs.mjs --check
- - run: node api/scripts/check-core-loadable.mjs
-
- # Builds *and runs* both image targets. Building alone would not have caught the api image
- # shipping without coach/ — that image built perfectly and exited on boot. So each target has
- # to answer for itself: the default one starts and serves, and the coach one additionally
- # resolves the Agent SDK's per-platform runtime (musl on this base), which is the one thing
- # that cannot be checked from the source tree.
- api-image:
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ - name: Validate the catalogue
+ run: node scripts/catalogue/validate.mjs
+ - name: Generated files are up to date
+ run: node scripts/catalogue/build.mjs --check
+ - name: Media stay within 180 px (licence)
+ run: node scripts/catalogue/check-media.mjs
+
+ # Builds *and runs* the api image targets and the web image. Building alone would not have
+ # caught the api image shipping without coach/: that image built perfectly and exited on boot.
+ images:
+ needs: changes
+ if: needs.changes.outputs.images == 'true'
runs-on: ubuntu-latest
+ timeout-minutes: 25
steps:
- - uses: actions/checkout@v7
-
- - run: docker build --target default -t opengym-api:default ./api
- - run: docker build --target coach -t opengym-api:coach ./api
- # No --target, exactly like docker-publish.yml. That workflow names no stage, so what it
- # ships is whatever Dockerfile stage happens to be last -- and that untargeted artifact,
- # not opengym-api:default above, is the image every self-hoster pulls as :latest. Build it
- # the same way here so the assertion below is about the thing we actually publish.
- - run: docker build -t opengym-api:published ./api
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
+ # Layers cached between runs (GitHub cache), loaded into the local engine to be started.
+ - name: api, default target
+ uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
+ with:
+ context: ./api
+ target: default
+ load: true
+ tags: opengym-api:default
+ cache-from: type=gha,scope=ci-api
+ cache-to: type=gha,mode=max,scope=ci-api
+ - name: api, coach target
+ uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
+ with:
+ context: ./api
+ target: coach
+ load: true
+ tags: opengym-api:coach
+ cache-from: type=gha,scope=ci-api-coach
+ cache-to: type=gha,mode=max,scope=ci-api-coach
+ # No target, exactly like docker-publish.yml: what that workflow ships is whatever stage
+ # is last, and that untargeted image is what every self-hoster pulls as :latest.
+ - name: api, as published
+ uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
+ with:
+ context: ./api
+ load: true
+ tags: opengym-api:published
+ cache-from: type=gha,scope=ci-api
+ - name: web
+ uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
+ with:
+ context: .
+ file: ./web/Dockerfile
+ load: true
+ tags: opengym-web:ci
+ cache-from: type=gha,scope=ci-web
+ cache-to: type=gha,mode=max,scope=ci-web
- name: the image published as :latest has no AI runtime either
run: |
@@ -139,17 +353,25 @@ jobs:
- name: the default image boots and serves, with no AI runtime in it
run: |
- docker run -d --name api-default -e DATA_DIR=/data -p 3000:3000 opengym-api:default
+ docker network create og
+ docker run -d --name api-default --network og --network-alias api -e DATA_DIR=/data -p 3000:3000 opengym-api:default
for i in $(seq 1 30); do
curl -fsS http://localhost:3000/api/config >/dev/null 2>&1 && break
sleep 1
done
curl -fsS http://localhost:3000/api/config | tee /dev/stderr | grep -q '"invite_only"'
- # Absent by construction, not by accident: --omit=optional is the only thing keeping
- # the AI dependency out of the image an owner gets when they never asked for it.
docker run --rm opengym-api:default node -e \
'import("@anthropic-ai/claude-agent-sdk").then(()=>{console.error("AI runtime present in the default image");process.exit(1)},()=>process.exit(0))'
- docker rm -f api-default
+
+ # The stack the way docker-compose.yml wires it: nginx in the web image proxies /api to
+ # the api container. A green api image and a green web image can still not talk.
+ - name: the web image serves the app and reaches the api through nginx
+ run: |
+ docker run -d --name web --network og -p 8080:80 opengym-web:ci
+ for i in $(seq 1 30); do curl -fsS http://localhost:8080/ >/dev/null 2>&1 && break; sleep 1; done
+ curl -fsS http://localhost:8080/ | grep -q 'id="root"'
+ curl -fsS http://localhost:8080/api/config | grep -q '"invite_only"'
+ docker rm -f web api-default
- name: the coach image carries a runnable Agent SDK
run: |
@@ -164,19 +386,110 @@ jobs:
run: |
docker run --rm opengym-api:coach codex --version
docker run --rm opengym-api:coach bwrap --version
- # Owned by the user jobs drop to, and 0700 — a credential cache readable by anything
+ # Owned by the user jobs drop to, and 0700: a credential cache readable by anything
# else in the container would undo the point of dropping privileges at all.
test "$(docker run --rm opengym-api:coach stat -c '%U %a' /coach-auth)" = "coach 700"
- name: neither Codex nor its sandbox is in the default image
run: |
- # bubblewrap is a Codex requirement, so an owner who never opted in should not be
- # carrying it. Both commands must fail.
! docker run --rm opengym-api:default codex --version 2>/dev/null
! docker run --rm opengym-api:default bwrap --version 2>/dev/null
- name: the privilege drop can actually be performed in the image
run: |
- # canDropPrivileges() fails closed, so a missing `coach` user disables every job —
- # including the fixture provider. Cheaper to assert here than to discover on an instance.
+ # canDropPrivileges() fails closed, so a missing `coach` user disables every job,
+ # including the fixture provider.
docker run --rm opengym-api:default id coach
+
+ # The Android app compiles, its JVM unit tests pass, and the phone bundle inside it is the
+ # mobile flavour (check-mobile-bundle runs inside build:mobile). Debug and unsigned: signing
+ # is the release machine's job (scripts/android/build-release.sh).
+ android:
+ needs: changes
+ if: needs.changes.outputs.android == 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: npm
+ cache-dependency-path: frontend/package-lock.json
+ - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0
+ with:
+ distribution: temurin
+ java-version: 21
+ - uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0
+ with:
+ # Only main and stores write the Gradle cache; other branches and PRs read it.
+ cache-read-only: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/stores' }}
+ add-job-summary: on-failure
+ - run: npm ci --ignore-scripts --no-audit --no-fund
+ working-directory: frontend
+ - name: Phone bundle + cap sync
+ run: npm run build:mobile
+ working-directory: frontend
+ - name: JVM unit tests, sideload APK, play flavour compiles
+ working-directory: frontend/android
+ run: ./gradlew --no-daemon testSideloadDebugUnitTest assembleSideloadDebug compilePlayDebugJavaWithJavac
+ - name: Stats
+ if: always()
+ working-directory: frontend/android
+ run: |
+ {
+ echo "### Android"
+ for a in app/build/outputs/apk/sideload/debug/*.apk; do
+ [ -f "$a" ] && echo "- debug sideload APK: $(numfmt --to=iec "$(stat -c %s "$a")") ($(basename "$a"))"
+ done
+ cat app/build/test-results/testSideloadDebugUnitTest/*.xml 2>/dev/null \
+ | grep -o '<testsuite [^>]*' | sed -E 's/.*name="([^"]*)".*tests="([0-9]+)".*failures="([0-9]+)".*/- JVM: \1: \2 tests, \3 failed/' || true
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ # One summary of the numbers of every suite that ran.
+ report:
+ needs: [frontend, api, mcp]
+ if: always() && !cancelled()
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ sparse-checkout: scripts/ci
+ - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
+ with:
+ pattern: stats-*
+ merge-multiple: true
+ path: dl
+ - name: Test report
+ run: |
+ set -- $(find dl -name '*.json' | sort)
+ if [ $# -eq 0 ]; then echo "Nothing was tested in this run (no matching changes)." >> "$GITHUB_STEP_SUMMARY"; exit 0; fi
+ node scripts/ci/test-report.mjs --combine "$@" --out combined.json
+ - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ name: test-stats
+ path: combined.json
+ retention-days: 90
+ if-no-files-found: ignore
+
+ # The single required check. Green when every job that ran passed and the others were
+ # skipped because nothing they check changed.
+ tests-ok:
+ needs: [changes, frontend, api, mcp, catalogue, images, android]
+ if: always()
+ runs-on: ubuntu-latest
+ timeout-minutes: 2
+ steps:
+ - name: Every job passed or had nothing to check
+ env:
+ RESULTS: ${{ toJSON(needs) }}
+ run: |
+ echo "$RESULTS" | node -e '
+ const n = JSON.parse(require("fs").readFileSync(0, "utf8"))
+ for (const [k, v] of Object.entries(n)) console.log(k.padEnd(10), v.result)
+ const bad = Object.entries(n).filter(([, v]) => !["success", "skipped"].includes(v.result))
+ if (bad.length) { console.log("::error::" + bad.map(([k, v]) => k + ": " + v.result).join(", ")); process.exit(1) }'
diff --git a/.gitignore b/.gitignore
index 57b5fd121..efaa2ae9d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -26,6 +26,10 @@ result-*
# CI reports (test:* jobs write these next to the suites)
junit.xml
coverage/
+test-results.json
+test-results.tap
+lcov.info
+/stats/
frontend/bundle-size.json
# Local planning notes
diff --git a/scripts/ci/deps-audit.mjs b/scripts/ci/deps-audit.mjs
new file mode 100644
index 000000000..740604295
--- /dev/null
+++ b/scripts/ci/deps-audit.mjs
@@ -0,0 +1,43 @@
+#!/usr/bin/env node
+// npm audit for each package directory, split the way it matters: what ships (runtime
+// dependencies: in the images, the APK, the IPA) and what only builds and tests it (dev).
+// Fails when a shipped dependency has a high or critical advisory; dev findings are listed.
+// Reads the lockfiles only, so it needs no `npm ci`.
+//
+// node scripts/ci/deps-audit.mjs frontend api mcp
+import { execFileSync } from 'node:child_process'
+import { appendFileSync } from 'node:fs'
+
+const dirs = process.argv.slice(2)
+const audit = (dir, omitDev) => {
+ let out
+ try {
+ out = execFileSync('npm', ['audit', '--json', ...(omitDev ? ['--omit=dev'] : [])], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
+ } catch (e) {
+ out = e.stdout // npm audit exits 1 when it finds anything
+ }
+ try { return JSON.parse(out) } catch { return { error: String(out).slice(0, 300) } }
+}
+const SEV = ['critical', 'high', 'moderate', 'low', 'info']
+const lines = ['### Dependency audit', '', '| Package dir | Shipped: critical / high / moderate / low | Dev only: critical / high / moderate / low |', '|---|---|---|']
+const details = []
+let fail = false
+for (const dir of dirs) {
+ const prod = audit(dir, true)
+ const all = audit(dir, false)
+ const count = (r) => SEV.slice(0, 4).map((s) => r?.metadata?.vulnerabilities?.[s] ?? '?').join(' / ')
+ const devOnly = {}
+ for (const s of SEV) devOnly[s] = (all?.metadata?.vulnerabilities?.[s] || 0) - (prod?.metadata?.vulnerabilities?.[s] || 0)
+ lines.push(`| ${dir} | ${prod.error ? 'audit failed' : count(prod)} | ${SEV.slice(0, 4).map((s) => devOnly[s]).join(' / ')} |`)
+ const prodNames = new Set(Object.keys(prod?.vulnerabilities || {}))
+ for (const [name, v] of Object.entries(all?.vulnerabilities || {})) {
+ const via = (v.via || []).filter((x) => typeof x === 'object').map((x) => `${x.title} (${x.url})`)
+ const shipped = prodNames.has(name)
+ details.push(`- ${dir}: **${name}** ${v.severity}${shipped ? ' (shipped)' : ' (dev)'}${v.fixAvailable ? ', fix available' : ''}${via.length ? ': ' + via.slice(0, 2).join('; ') : ''}`)
+ if (shipped && (v.severity === 'high' || v.severity === 'critical')) fail = true
+ }
+}
+const md = [...lines, '', details.length ? details.join('\n') : 'No known advisories.', ''].join('\n')
+console.log(md)
+if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, md + '\n')
+if (fail) { console.log('::error::a shipped dependency has a high or critical advisory'); process.exit(1) }
diff --git a/scripts/ci/release-check.mjs b/scripts/ci/release-check.mjs
new file mode 100644
index 000000000..43cefe1a9
--- /dev/null
+++ b/scripts/ci/release-check.mjs
@@ -0,0 +1,43 @@
+#!/usr/bin/env node
+// Does everything that carries a version say the same one? A release whose tag says 1.4.2 while
+// the api reports 1.4.1, or whose APK still calls itself 1.4.1, tells the in-app update check
+// the wrong thing and leaves self-hosters on a "new" version forever.
+//
+// node scripts/ci/release-check.mjs v1.4.2 strict: errors fail (exit 1)
+// node scripts/ci/release-check.mjs report only: prints the table
+//
+// Errors (with a tag): frontend + api package.json, the CHANGELOG section. Warnings: Android
+// versionName and the iOS marketing version, which the store builds may legitimately bump on
+// their own schedule (they are built and signed on the release machine).
+import { appendFileSync, readFileSync } from 'node:fs'
+
+const tag = process.argv[2]
+const want = tag ? tag.replace(/^v/, '') : null
+const read = (p) => { try { return readFileSync(p, 'utf8') } catch { return '' } }
+const found = {
+ 'frontend/package.json': JSON.parse(read('frontend/package.json') || '{}').version,
+ 'api/package.json': JSON.parse(read('api/package.json') || '{}').version,
+ 'Android versionName': /versionName\s+"([^"]+)"/.exec(read('frontend/android/app/build.gradle'))?.[1],
+ 'Android versionCode': /versionCode\s+(\d+)/.exec(read('frontend/android/app/build.gradle'))?.[1],
+ 'iOS MARKETING_VERSION': [...new Set([...read('frontend/ios/App/App.xcodeproj/project.pbxproj').matchAll(/MARKETING_VERSION = ([^;]+);/g)].map((m) => m[1]))].join(', '),
+ 'iOS build number': [...new Set([...read('frontend/ios/App/App.xcodeproj/project.pbxproj').matchAll(/CURRENT_PROJECT_VERSION = ([^;]+);/g)].map((m) => m[1]))].join(', '),
+}
+const changelog = read('CHANGELOG.md')
+const section = want ? new RegExp(`^## v${want.replace(/\./g, '\\.')}([^0-9.]|$)`, 'm').test(changelog) : null
+
+const errors = [], warnings = []
+if (want) {
+ for (const k of ['frontend/package.json', 'api/package.json']) if (found[k] !== want) errors.push(`${k} says ${found[k]}, the tag says ${want}`)
+ if (!section) errors.push(`CHANGELOG.md has no "## v${want}" section (the release notes come from there)`)
+ if (found['Android versionName'] !== want) warnings.push(`Android versionName is ${found['Android versionName']}`)
+ if (found['iOS MARKETING_VERSION'] !== want) warnings.push(`iOS MARKETING_VERSION is ${found['iOS MARKETING_VERSION']}`)
+}
+const md = [`### Versions${tag ? ` for ${tag}` : ''}`, '', '| Where | Version |', '|---|---|',
+ ...Object.entries(found).map(([k, v]) => `| ${k} | ${v ?? '–'} |`),
+ ...(want ? [`| CHANGELOG "## ${tag}" | ${section ? 'present' : 'MISSING'} |`] : []),
+ '', ...errors.map((e) => `- ❌ ${e}`), ...warnings.map((w) => `- ⚠️ ${w}`), ''].join('\n')
+console.log(md)
+if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, md + '\n')
+for (const w of warnings) console.log(`::warning::${w}`)
+for (const e of errors) console.log(`::error::${e}`)
+process.exit(errors.length ? 1 : 0)
diff --git a/scripts/ci/test-areas.mjs b/scripts/ci/test-areas.mjs
new file mode 100644
index 000000000..87de39895
--- /dev/null
+++ b/scripts/ci/test-areas.mjs
@@ -0,0 +1,30 @@
+// The parts of openGym a user would name, and which files belong to each. Used by
+// test-report.mjs to count tests and coverage per area, for test files and source files alike
+// (frontend/src/lib/plates.js and plates.test.js both land in "Plates & equipment").
+//
+// First match wins, so the narrow areas come before the broad ones. A file that matches
+// nothing is "Other UI" for the frontend's views/components and "Other" elsewhere; if an
+// important file shows up there, add a pattern rather than leave the table vague.
+export const AREAS = [
+ { name: 'Sync & no data loss', re: /sync|undo-merge|merge-state|stamps|durable|data-rev|data-wid|data-reset|data-safety|state-cache|state-read|legacy|undo-concurrent|offline|outbox|conflict|backoff|_rev|remote\.|presence/ },
+ { name: 'Coach (AI)', re: /coach|cadence|cohort|adapters|payload|prompt|review-repair|refine-change|jobs\.|warmup\.test|fixture-cli|e2e-apikey|config-migration|categories/ },
+ { name: 'Accounts, auth & security', re: /passkey|password|auth|login|csrf|cors|token|pairing|device-link|account|admin|first-user|rate-limit|anon-flood|credential|cf-access|email|guest|verify-error|recover|csp|audit/ },
+ { name: 'Import, export & backup', re: /import|export|fit-|csv|hevy|backup|zip|plan-share|qr|scan|clipboard/ },
+ { name: 'Plates & equipment', re: /plate|dumbbell|bar\.|bar-|equipment|incline|kg-change/ },
+ { name: 'Rest timer & alerts', re: /rest-|rest\.|resttimer|timer|sound|wakelock|live-activity|nudge|reminder|push|notification|sw\.|sw-/ },
+ { name: 'Progression, 1RM & stats', re: /progress|onerm|1rm|e1rm|effort|fatigue|recovery|strength|structural|stats|history|finish-compare|pyramid|rep-range|heatmap|linechart|measurements|bodyweight|check-?in/ },
+ { name: 'Workout logging', re: /workout|session|set|superset|queue|rotation|routine|plan|week|day-|starter|focusview|home|active-|swap|per-set|duration|speed|backfill|swipe/ },
+ { name: 'Exercise catalogue & media', re: /exercise|catalogue|muscle|anim|media|library|similar|favour|glyph|body-paths|bodymap|instr/ },
+ { name: 'Phone, watch & health apps', re: /native|android|ios|mobile|channel|capacitor|watch|health|widget|system-bars|keyboard|edge-swipe|onboarding|platform|heart-rate|update\./ },
+ { name: 'App state & API server', re: /^usestore|^useui|^server\.js$|^store\.|^api\.js$|^boot\.js$/ },
+ { name: 'Languages', re: /i18n|locale|lang|plural|pt-br|translat|exercise-names|source-strings|empty-placeholder/ },
+]
+
+export function areaOf(path) {
+ const p = String(path || '').toLowerCase()
+ const base = p.split('/').pop()
+ for (const a of AREAS) if (a.re.test(base)) return a.name
+ for (const a of AREAS) if (a.re.test(p)) return a.name
+ if (/(^|\/)(views|components)\//.test(p) || /\.jsx$/.test(p)) return 'Other UI'
+ return 'Other'
+}
diff --git a/scripts/ci/test-report.mjs b/scripts/ci/test-report.mjs
new file mode 100644
index 000000000..e3450be9c
--- /dev/null
+++ b/scripts/ci/test-report.mjs
@@ -0,0 +1,225 @@
+#!/usr/bin/env node
+// Turns a test run into numbers that say something about the app: how many tests guard each
+// part of it (sync, workout logging, plates, rest timer, ...), how much of that part's code
+// they run, which tests are slow, and what failed. CI writes the result to the job summary
+// ($GITHUB_STEP_SUMMARY) and keeps the JSON as an artifact; run it locally the same way.
+//
+// vitest (frontend, mcp):
+// node scripts/ci/test-report.mjs --label Frontend --root frontend \
+// --vitest frontend/test-results.json --coverage frontend/coverage/coverage-summary.json \
+// [--bundle frontend/bundle-size.json] --out stats/frontend.json
+// node:test (api):
+// node scripts/ci/test-report.mjs --label API --root api \
+// --tap api/test-results.tap --lcov api/lcov.info --out stats/api.json
+// several suites into one table:
+// node scripts/ci/test-report.mjs --combine stats/*.json [--out combined.json]
+//
+// Inputs are optional: a suite that crashed before writing its report still gets a line saying
+// so, rather than the step failing on top of the real failure.
+import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { dirname, relative, resolve, sep } from 'node:path'
+import { areaOf, AREAS } from './test-areas.mjs'
+
+const ORDER = [...AREAS.map((a) => a.name), 'Other UI', 'Other']
+
+const argv = process.argv.slice(2)
+const opt = (name) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined }
+const readJSON = (f) => { try { return f && existsSync(f) ? JSON.parse(readFileSync(f, 'utf8')) : null } catch { return null } }
+const rel = (root, f) => relative(resolve(root || '.'), resolve(f)).split(sep).join('/')
+const pct = (c, t) => (t ? Math.round((c / t) * 1000) / 10 : null)
+const fmtPct = (p) => (p == null ? '–' : `${p.toFixed(1)} %`)
+const fmtS = (ms) => (ms >= 60000 ? `${(ms / 60000).toFixed(1)} min` : `${(ms / 1000).toFixed(1)} s`)
+
+// ---- readers ------------------------------------------------------------------------------
+
+// vitest --reporter=json (the jest-compatible shape).
+function fromVitest(file, root) {
+ const j = readJSON(file)
+ if (!j) return null
+ const tests = []
+ const files = []
+ for (const tr of j.testResults || []) {
+ const path = rel(root, tr.name)
+ const dur = (tr.endTime || 0) - (tr.startTime || 0)
+ files.push({ file: path, ms: dur, status: tr.status, tests: (tr.assertionResults || []).length, message: tr.status === 'failed' && !(tr.assertionResults || []).length ? String(tr.message || '').slice(0, 300) : undefined })
+ for (const a of tr.assertionResults || []) {
+ tests.push({ file: path, name: [...(a.ancestorTitles || []), a.title].join(' > '), status: a.status === 'pending' || a.status === 'todo' ? 'skipped' : a.status, ms: a.duration || 0, message: a.status === 'failed' ? String((a.failureMessages || [])[0] || '').split('\n')[0].slice(0, 300) : undefined })
+ }
+ }
+ return { tests, files, startTime: j.startTime }
+}
+
+// node --test --test-reporter=tap. Each test file runs as its own subtest group in node 22;
+// the YAML block after every result carries duration_ms and the location of the test.
+function fromTap(file, root) {
+ if (!file || !existsSync(file)) return null
+ const lines = readFileSync(file, 'utf8').split('\n')
+ const tests = []
+ let cur = null
+ for (let i = 0; i < lines.length; i++) {
+ const m = /^(\s*)(ok|not ok) \d+ - (.*?)(\s+#\s*(SKIP|TODO).*)?$/i.exec(lines[i])
+ if (m) {
+ cur = { indent: m[1].length, name: m[3], status: m[5] ? 'skipped' : m[2] === 'ok' ? 'passed' : 'failed', ms: 0, file: null }
+ tests.push(cur)
+ continue
+ }
+ if (!cur) continue
+ let y
+ if ((y = /^\s*duration_ms: ([\d.]+)/.exec(lines[i]))) cur.ms = Number(y[1])
+ else if ((y = /^\s*location: '(.*?):\d+:\d+'/.exec(lines[i]))) cur.file = rel(root, y[1].replace(/^file:\/\//, ''))
+ else if ((y = /^\s*error: [|>]?-?\s*['"]?(.*?)['"]?$/.exec(lines[i])) && cur.status === 'failed' && !cur.message) cur.message = (y[1] || lines[i + 1] || '').trim().slice(0, 300)
+ else if ((y = /^\s*type: '(suite|test)'/.exec(lines[i]))) cur.type = y[1]
+ }
+ // Keep the leaves: a describe() is a 'suite' and its children are already counted.
+ const leaves = tests.filter((t) => t.type !== 'suite' && t.file)
+ const byFile = new Map()
+ for (const t of leaves) {
+ const f = byFile.get(t.file) || { file: t.file, ms: 0, tests: 0, status: 'passed' }
+ f.tests++
+ f.ms += t.ms
+ if (t.status === 'failed') f.status = 'failed'
+ byFile.set(t.file, f)
+ }
+ return { tests: leaves.map(({ indent, type, ...t }) => t), files: [...byFile.values()] }
+}
+
+// v8 json-summary (vitest --coverage.reporter=json-summary).
+function coverageFromSummary(file, root) {
+ const j = readJSON(file)
+ if (!j) return null
+ const out = []
+ for (const [f, v] of Object.entries(j)) {
+ if (f === 'total') continue
+ out.push({ file: rel(root, f), lines: [v.lines.covered, v.lines.total], branches: [v.branches.covered, v.branches.total], functions: [v.functions.covered, v.functions.total] })
+ }
+ return out
+}
+
+// lcov (node --test-reporter=lcov).
+function coverageFromLcov(file, root) {
+ if (!file || !existsSync(file)) return null
+ const out = []
+ let cur = null
+ for (const line of readFileSync(file, 'utf8').split('\n')) {
+ const [k, v] = line.split(':')
+ if (k === 'SF') cur = { file: rel(root, line.slice(3)), lines: [0, 0], branches: [0, 0], functions: [0, 0] }
+ else if (!cur) continue
+ else if (k === 'LH') cur.lines[0] = +v
+ else if (k === 'LF') cur.lines[1] = +v
+ else if (k === 'BRH') cur.branches[0] = +v
+ else if (k === 'BRF') cur.branches[1] = +v
+ else if (k === 'FNH') cur.functions[0] = +v
+ else if (k === 'FNF') cur.functions[1] = +v
+ else if (line === 'end_of_record') { if (!/(^|\/)(test|node_modules)\//.test(cur.file) && !/\.test\.[cm]?js$/.test(cur.file)) out.push(cur); cur = null }
+ }
+ return out
+}
+
+// ---- aggregation --------------------------------------------------------------------------
+
+function summarise(label, run, cov, bundle) {
+ const s = { label, generated: new Date().toISOString(), ok: !!run }
+ if (!run) return s
+ const t = run.tests
+ s.tests = { total: t.length, passed: t.filter((x) => x.status === 'passed').length, failed: t.filter((x) => x.status === 'failed').length, skipped: t.filter((x) => x.status === 'skipped').length }
+ s.files = run.files.length
+ s.brokenFiles = run.files.filter((f) => f.status === 'failed' && !f.tests).map((f) => ({ file: f.file, message: f.message }))
+ // Sum of per-file wall time: what the suite costs single-threaded (the job runs it in parallel).
+ s.cpuMs = Math.round(run.files.reduce((a, f) => a + (f.ms || 0), 0))
+ s.failures = t.filter((x) => x.status === 'failed').slice(0, 30).map(({ file, name, message }) => ({ file, name, message }))
+ s.slowTests = [...t].sort((a, b) => b.ms - a.ms).slice(0, 10).map(({ file, name, ms }) => ({ file, name, ms: Math.round(ms) }))
+ s.slowFiles = [...run.files].sort((a, b) => b.ms - a.ms).slice(0, 10).map(({ file, ms, tests }) => ({ file, ms: Math.round(ms), tests }))
+ const areas = {}
+ const bump = (a) => (areas[a] = areas[a] || { tests: 0, failed: 0, testFiles: 0, srcFiles: 0, lines: [0, 0], branches: [0, 0], functions: [0, 0] })
+ for (const x of t) { const a = bump(areaOf(x.file)); a.tests++; if (x.status === 'failed') a.failed++ }
+ for (const f of run.files) bump(areaOf(f.file)).testFiles++
+ if (cov) {
+ const tot = { lines: [0, 0], branches: [0, 0], functions: [0, 0] }
+ for (const c of cov) {
+ const a = bump(areaOf(c.file))
+ a.srcFiles++
+ for (const k of ['lines', 'branches', 'functions']) { a[k][0] += c[k][0]; a[k][1] += c[k][1]; tot[k][0] += c[k][0]; tot[k][1] += c[k][1] }
+ }
+ s.coverage = Object.fromEntries(Object.entries(tot).map(([k, [c, n]]) => [k, pct(c, n)]))
+ // The source files with the most uncovered lines: where a new test buys the most.
+ s.leastCovered = cov.filter((c) => c.lines[1] >= 40).map((c) => ({ file: c.file, uncovered: c.lines[1] - c.lines[0], lines: pct(...c.lines) })).sort((a, b) => b.uncovered - a.uncovered).slice(0, 10)
+ }
+ s.areas = Object.fromEntries(Object.entries(areas).sort(([a], [b]) => ORDER.indexOf(a) - ORDER.indexOf(b)).map(([k, v]) => [k, { ...v, linesPct: pct(...v.lines), branchesPct: pct(...v.branches) }]))
+ if (bundle?.total) s.bundle = { rawKB: Math.round(bundle.total.raw / 1024), gzipKB: Math.round(bundle.total.gzip / 1024), files: Object.keys(bundle.files || {}).length }
+ return s
+}
+
+// ---- markdown -----------------------------------------------------------------------------
+
+function md(s) {
+ const out = []
+ out.push(`### ${s.label} tests`)
+ if (!s.ok) { out.push('', 'No test report was written: the suite did not get as far as reporting (see the step log).'); return out.join('\n') }
+ const { total, passed, failed, skipped } = s.tests
+ const icon = failed || s.brokenFiles.length ? '❌' : '✅'
+ out.push('', `${icon} **${passed}/${total} passed**${failed ? `, **${failed} failed**` : ''}${skipped ? `, ${skipped} skipped` : ''} in ${s.files} files · ${fmtS(s.cpuMs)} of test time` + (s.coverage ? ` · coverage: lines ${fmtPct(s.coverage.lines)}, branches ${fmtPct(s.coverage.branches)}, functions ${fmtPct(s.coverage.functions)}` : '') + (s.bundle ? ` · bundle ${s.bundle.gzipKB} kB gzip` : ''))
+ if (s.brokenFiles.length) { out.push('', '**Test files that did not load:**'); for (const f of s.brokenFiles) out.push(`- \`${f.file}\`: ${f.message || ''}`) }
+ if (s.failures.length) { out.push('', '**Failed:**'); for (const f of s.failures) out.push(`- \`${f.file}\` › ${f.name}${f.message ? `: ${f.message.replace(/\|/g, '\\|')}` : ''}`) }
+ out.push('', '| Area | Tests | Test files | Source files | Lines | Branches |', '|---|---:|---:|---:|---:|---:|')
+ for (const [k, a] of Object.entries(s.areas)) out.push(`| ${k}${a.failed ? ' ❌' : ''} | ${a.tests} | ${a.testFiles} | ${a.srcFiles || '–'} | ${fmtPct(a.linesPct)} | ${fmtPct(a.branchesPct)} |`)
+ out.push('', '<details><summary>Slowest tests and files</summary>', '', '| Test | Time |', '|---|---:|')
+ for (const t of s.slowTests) out.push(`| \`${t.file}\` › ${t.name.replace(/\|/g, '\\|').slice(0, 120)} | ${fmtS(t.ms)} |`)
+ out.push('', '| File | Tests | Time |', '|---|---:|---:|')
+ for (const f of s.slowFiles) out.push(`| \`${f.file}\` | ${f.tests} | ${fmtS(f.ms)} |`)
+ out.push('', '</details>')
+ if (s.leastCovered?.length) {
+ out.push('', '<details><summary>Most uncovered lines (where a test buys the most)</summary>', '', '| File | Uncovered lines | Lines |', '|---|---:|---:|')
+ for (const f of s.leastCovered) out.push(`| \`${f.file}\` | ${f.uncovered} | ${fmtPct(f.lines)} |`)
+ out.push('', '</details>')
+ }
+ return out.join('\n')
+}
+
+function mdCombined(list) {
+ const out = ['## Test report', '', '| Suite | Passed | Failed | Skipped | Files | Test time | Lines | Branches |', '|---|---:|---:|---:|---:|---:|---:|---:|']
+ let T = 0, P = 0, F = 0
+ for (const s of list) {
+ if (!s.ok) { out.push(`| ${s.label} | – | did not report | – | – | – | – | – |`); continue }
+ T += s.tests.total; P += s.tests.passed; F += s.tests.failed
+ out.push(`| ${s.label} | ${s.tests.passed} | ${s.tests.failed} | ${s.tests.skipped} | ${s.files} | ${fmtS(s.cpuMs)} | ${fmtPct(s.coverage?.lines)} | ${fmtPct(s.coverage?.branches)} |`)
+ }
+ out.push(`| **all** | **${P}** | **${F}** | | | | | |`)
+ // The same app areas across suites: the api's sync tests and the frontend's together.
+ const areas = {}
+ for (const s of list) for (const [k, a] of Object.entries(s.areas || {})) {
+ const x = (areas[k] = areas[k] || { tests: 0, lines: [0, 0], branches: [0, 0], by: [] })
+ x.tests += a.tests
+ for (const m of ['lines', 'branches']) { x[m][0] += a[m][0]; x[m][1] += a[m][1] }
+ if (a.tests) x.by.push(`${s.label} ${a.tests}`)
+ }
+ out.push('', '| App area | Tests | Where | Lines | Branches |', '|---|---:|---|---:|---:|')
+ for (const name of ORDER) {
+ const a = areas[name]
+ if (!a) continue
+ out.push(`| ${name} | ${a.tests} | ${a.by.join(', ')} | ${fmtPct(pct(...a.lines))} | ${fmtPct(pct(...a.branches))} |`)
+ }
+ out.push('', `${T} tests in total. Per-suite details (slowest tests, least covered files) are in each job's summary.`)
+ return out.join('\n')
+}
+
+// ---- main ---------------------------------------------------------------------------------
+
+function emit(markdown, json) {
+ console.log(markdown)
+ if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, markdown + '\n\n')
+ const out = opt('--out')
+ if (out) { mkdirSync(dirname(resolve(out)), { recursive: true }); writeFileSync(out, JSON.stringify(json, null, 2)) }
+}
+
+const ci = argv.indexOf('--combine')
+if (ci >= 0) {
+ const files = argv.slice(ci + 1).filter((a) => !a.startsWith('--') && a !== opt('--out'))
+ const list = files.map(readJSON).filter((s) => s && s.label)
+ emit(mdCombined(list), { generated: new Date().toISOString(), suites: list })
+} else {
+ const root = opt('--root') || '.'
+ const run = opt('--vitest') ? fromVitest(opt('--vitest'), root) : fromTap(opt('--tap'), root)
+ const cov = opt('--coverage') ? coverageFromSummary(opt('--coverage'), root) : coverageFromLcov(opt('--lcov'), root)
+ const s = summarise(opt('--label') || 'Tests', run, cov, readJSON(opt('--bundle')))
+ emit(md(s), s)
+}