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.

Tests: property tests for the merge and the plates (fast-check), API stats per file, robustness one condition per job

Duarte Santosa0e4f2e3df58
diff --git a/.github/workflows/audit.yml b/.github/workflows/audit.yml
index adf203746..075c35dbb 100644
--- a/.github/workflows/audit.yml
+++ b/.github/workflows/audit.yml
@@ -63,20 +63,34 @@ jobs:
timeout-minutes: 40
strategy:
fail-fast: false
+ # One condition per run, so a failure says which one it is about.
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'
+ - name: shuffled order
+ tz: UTC
+ shift: ''
+ shuffle: true
+ # Fourteen hours ahead of UTC: the evening in UTC is already tomorrow here.
+ - name: UTC+14
tz: Pacific/Kiritimati
- shift: '+42d'
- # Behind UTC with a daylight-saving change in the range most fixtures use.
- - name: 'America/Los_Angeles, shuffled'
+ shift: ''
+ shuffle: false
+ # Behind UTC, with a daylight-saving change in the range most fixtures use.
+ - name: Los Angeles
tz: America/Los_Angeles
shift: ''
+ shuffle: false
+ # The calendar six weeks on: fixed fixture dates that age out of a window.
+ - name: six weeks ahead
+ tz: UTC
+ shift: '+42d'
+ shuffle: false
name: robustness (${{ matrix.name }})
env:
TZ: ${{ matrix.tz }}
+ # Property tests (fast-check) try more cases than on a push, and the sync fuzz new seeds.
+ PROPERTY_RUNS: 1000
+ SYNC_FUZZ_SEED_BASE: ${{ github.run_number }}000
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -107,18 +121,18 @@ jobs:
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
+ LD_PRELOAD="${FAKE_PRELOAD:-}" npx vitest run ${{ matrix.shuffle && '--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
+ --test-reporter=../scripts/ci/node-test-reporter.mjs --test-reporter-destination=test-results.jsonl 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
+ node scripts/ci/test-report.mjs --label "API (${{ matrix.name }})" --root api --node api/test-results.jsonl --out stats/api.json > /dev/null
test "${{ steps.fe.outcome }}" = success && test "${{ steps.api.outcome }}" = success
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index d0cd752df..2eef65bb7 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -204,7 +204,7 @@ jobs:
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=../scripts/ci/node-test-reporter.mjs --test-reporter-destination=test-results.jsonl
--test-reporter=lcov --test-reporter-destination=lcov.info
--test-reporter=junit --test-reporter-destination=junit.xml
test/*.test.js
@@ -222,7 +222,7 @@ jobs:
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
+ --node api/test-results.jsonl --lcov api/lcov.info --out stats/api.json
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
if: always()
with:
diff --git a/.gitignore b/.gitignore
index efaa2ae9d..1c4fa59de 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,7 +27,7 @@ result-*
junit.xml
coverage/
test-results.json
-test-results.tap
+test-results.jsonl
lcov.info
/stats/
frontend/bundle-size.json
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 6d803ec53..a20063cf3 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -30,6 +30,7 @@
"@capacitor/ios": "^8.5.3",
"@vitejs/plugin-react": "^6.0.3",
"@vitest/coverage-v8": "^4.1.11",
+ "fast-check": "^4.10.2",
"happy-dom": "^20.11.2",
"linkedom": "^0.18.13",
"vite": "^8.1.5",
@@ -2181,6 +2182,29 @@
"node": ">=12.0.0"
}
},
+ "node_modules/fast-check": {
+ "version": "4.10.2",
+ "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.10.2.tgz",
+ "integrity": "sha512-iK2f+YrcmoeGqk6fA0ea2bptcu/itMIm4NfEozq6N25+aG6h7s5HZbB/k1aV7b5w5sFLMCbbtRUsTVR+BgC3xw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/dubzzz"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fast-check"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "pure-rand": "^8.0.0"
+ },
+ "engines": {
+ "node": ">=12.17.0"
+ }
+ },
"node_modules/fast-fifo": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
@@ -3560,6 +3584,23 @@
"once": "^1.3.1"
}
},
+ "node_modules/pure-rand": {
+ "version": "8.4.2",
+ "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-8.4.2.tgz",
+ "integrity": "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/dubzzz"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fast-check"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/rc": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index b9f80662f..4ad56db98 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -35,6 +35,7 @@
"@capacitor/ios": "^8.5.3",
"@vitejs/plugin-react": "^6.0.3",
"@vitest/coverage-v8": "^4.1.11",
+ "fast-check": "^4.10.2",
"happy-dom": "^20.11.2",
"linkedom": "^0.18.13",
"vite": "^8.1.5",
diff --git a/frontend/src/lib/plates.property.test.js b/frontend/src/lib/plates.property.test.js
new file mode 100644
index 000000000..26a3cb867
--- /dev/null
+++ b/frontend/src/lib/plates.property.test.js
@@ -0,0 +1,132 @@
+/* What any plate answer must satisfy, for any weight and any inventory (fast-check). plates.test.js
+ * has the worked examples (the rack, the home gym with one pair of each); these are the rules a
+ * lifter relies on without checking: the plates add up to what the app says is on the bar, it
+ * never hands out plates you do not own, it never loads more than asked, nothing lighter than
+ * the best possible load is offered, and owning more plates never makes the answer worse.
+ */
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import { plateStack, plateDelta, rowLoad, PLATE_SIZES } from './plates.js'
+
+const RUNS = { numRuns: Number(process.env.PROPERTY_RUNS) || 300 }
+const sum = a => a.reduce((s, x) => s + x, 0)
+const Q = 4 // quarter-units, as plates.js counts
+const close = (a, b) => Math.abs(a - b) < 1e-9
+
+// An inventory: some of the real sizes, a few pairs of each, heaviest first like inventoryFor's.
+const inventory = (unit = 'kg', maxSizes = 6, maxPairs = 4) =>
+ fc.subarray(PLATE_SIZES[unit], { minLength: 0, maxLength: maxSizes })
+ .chain(sizes => fc.tuple(...sizes.map(() => fc.integer({ min: 1, max: maxPairs }))).map(ns => sizes.map((w, i) => ({ w, n: ns[i] }))))
+ .map(inv => inv.sort((a, b) => b.w - a.w))
+// Weights as typed: mostly on the quarter grid, sometimes any decimal.
+const weight = fc.oneof(fc.integer({ min: 0, max: 1200 }).map(x => x / 4), fc.double({ min: 0, max: 400, noNaN: true }))
+
+// Every load these plates can make (in quarter-units) with the fewest plates for each: a brute
+// force over small inventories to hold the clever answer against.
+function reachable(inv) {
+ let best = new Map([[0, 0]])
+ for (const { w, n } of inv) {
+ const next = new Map(best)
+ for (const [s, c] of best) for (let k = 1; k <= n; k++) {
+ const t = s + k * Math.round(w * Q)
+ if (!next.has(t) || next.get(t) > c + k) next.set(t, c + k)
+ }
+ best = next
+ }
+ return best
+}
+
+describe('plates for a weight', () => {
+ it('add up to what is on the bar: plates + missing = the weight asked for', () => {
+ fc.assert(fc.property(weight, inventory(), (w, inv) => {
+ const { plates, missing } = plateStack(w, inv)
+ expect(missing).toBeGreaterThanOrEqual(-1e-9)
+ expect(close(sum(plates) + missing, Math.max(0, w))).toBe(true)
+ }), RUNS)
+ })
+
+ it('never use a plate you do not own, nor more of a size than you have', () => {
+ fc.assert(fc.property(weight, inventory(), (w, inv) => {
+ const { plates } = plateStack(w, inv)
+ for (const p of new Set(plates)) {
+ const own = inv.find(x => x.w === p)
+ expect(own, `${p} is not in the inventory`).toBeDefined()
+ expect(plates.filter(x => x === p).length).toBeLessThanOrEqual(own.n)
+ }
+ }), RUNS)
+ })
+
+ it('come heaviest first, the order they go on the bar', () => {
+ fc.assert(fc.property(weight, inventory(), (w, inv) => {
+ const { plates } = plateStack(w, inv)
+ expect(plates).toEqual([...plates].sort((a, b) => b - a))
+ }), RUNS)
+ })
+
+ it('are the heaviest load you can make without going over, with the fewest plates', () => {
+ fc.assert(fc.property(weight, inventory('kg', 4, 3), (w, inv) => {
+ const { plates } = plateStack(w, inv)
+ const target = Math.floor(Math.max(0, w) * Q)
+ const options = reachable(inv)
+ const bestSum = Math.max(...[...options.keys()].filter(s => s <= target))
+ expect(Math.round(sum(plates) * Q)).toBe(bestSum)
+ expect(plates.length).toBe(options.get(bestSum))
+ }), RUNS)
+ })
+
+ it('never get worse when you own more plates', () => {
+ fc.assert(fc.property(weight, inventory(), fc.constantFrom(...PLATE_SIZES.kg), (w, inv, extra) => {
+ const more = inv.some(x => x.w === extra) ? inv.map(x => (x.w === extra ? { ...x, n: x.n + 1 } : x)) : [...inv, { w: extra, n: 1 }].sort((a, b) => b.w - a.w)
+ expect(plateStack(w, more).missing).toBeLessThanOrEqual(plateStack(w, inv).missing + 1e-9)
+ }), RUNS)
+ })
+
+ it('in lb as in kg', () => {
+ fc.assert(fc.property(weight, inventory('lb'), (w, inv) => {
+ const { plates, missing } = plateStack(w, inv)
+ expect(close(sum(plates) + missing, Math.max(0, w))).toBe(true)
+ }), RUNS)
+ })
+})
+
+describe('the load line of a set row', () => {
+ it('on a bar: base + both sides + what is missing on both sides = the logged weight', () => {
+ fc.assert(fc.property(fc.integer({ min: 1, max: 1200 }).map(x => x / 4), fc.constantFrom(0, 10, 15, 20), inventory(), (w, bar, inv) => {
+ const r = rowLoad('pairs', w, bar, inv)
+ if (w <= bar) { expect(r.barOnly).toBe(true); return }
+ expect(r.barOnly).toBe(false)
+ expect(Math.abs(bar + 2 * (sum(r.plates) + r.missing) - w)).toBeLessThan(0.02 + 1e-9)
+ }), RUNS)
+ })
+
+ it('a single stack may use both plates of a pair, a bar side only one', () => {
+ fc.assert(fc.property(fc.integer({ min: 1, max: 800 }).map(x => x / 4), inventory(), (w, inv) => {
+ const single = rowLoad('single', w, 0, inv)
+ for (const p of new Set(single.plates)) expect(single.plates.filter(x => x === p).length).toBeLessThanOrEqual(2 * inv.find(x => x.w === p).n)
+ // Twice the plates to choose from never leaves more missing than one side of a bar would.
+ expect(single.missing).toBeLessThanOrEqual(plateStack(w, inv).missing + 1e-9)
+ }), RUNS)
+ })
+
+ it('has nothing to load for dumbbells, cables or an empty weight', () => {
+ fc.assert(fc.property(weight, inventory(), (w, inv) => {
+ expect(rowLoad('none', w, 0, inv)).toBeNull()
+ expect(rowLoad('pairs', 0, 20, inv)).toBeNull()
+ }), { numRuns: 50 })
+ })
+})
+
+describe('changing plates between sets', () => {
+ it('taking off what comes off and putting on what goes on turns one stack into the next', () => {
+ const stack = fc.array(fc.constantFrom(...PLATE_SIZES.kg), { maxLength: 10 })
+ fc.assert(fc.property(stack, stack, (prev, next) => {
+ const { strip, add } = plateDelta(prev, next)
+ const after = [...prev]
+ for (const p of strip) after.splice(after.indexOf(p), 1)
+ after.push(...add)
+ expect(after.sort((a, b) => a - b)).toEqual([...next].sort((a, b) => a - b))
+ // and nothing is taken off only to go straight back on
+ expect(strip.filter(p => add.includes(p))).toEqual([])
+ }), RUNS)
+ })
+})
diff --git a/frontend/src/lib/sync-fuzz.test.js b/frontend/src/lib/sync-fuzz.test.js
index ae291d6f9..f828d7068 100644
--- a/frontend/src/lib/sync-fuzz.test.js
+++ b/frontend/src/lib/sync-fuzz.test.js
@@ -393,6 +393,10 @@ function run(seed, opts = {}) {
function sortKeys(x) { if (Array.isArray(x)) return x.map(sortKeys); if (x && typeof x === 'object') return Object.fromEntries(Object.keys(x).sort().map(k => [k, sortKeys(x[k])])); return x }
+// The seeds are fixed so a failure reproduces; the weekly robustness run (audit.yml) sets
+// SYNC_FUZZ_SEED_BASE to explore new ones. A failure there names its seed: put it in a test.
+const SEED_BASE = Number(process.env.SYNC_FUZZ_SEED_BASE) || 0
+
const CASES = [
{ name: 'two or three devices, short gaps', seeds: 300, opts: {} },
{ name: 'three devices, long offline gaps', seeds: 300, opts: { ops: 150, replicas: 3, gap: 300000 } },
@@ -404,11 +408,11 @@ describe('sync fuzz: clocks up to a day apart still converge, with nothing dupli
it('three devices, skewed clocks', () => {
const bad = []
for (let s = 1; s <= 200; s++) {
- const { problems } = run(s, { skew: 86400000, ops: 80, replicas: 3 })
+ const { problems } = run(SEED_BASE + s, { skew: 86400000, ops: 80, replicas: 3 })
// which of two changes neither device had seen comes last is the clocks' call; only
// convergence and duplicates are checked here (the ordering is checked without skew)
const hard = problems.filter(p => p.startsWith('no-converge') || p.startsWith('dup'))
- if (hard.length) bad.push(`seed ${s}: ${hard.join('; ')}`)
+ if (hard.length) bad.push(`seed ${SEED_BASE + s}: ${hard.join('; ')}`)
}
expect(bad.slice(0, 5)).toEqual([])
}, 120000)
@@ -419,8 +423,8 @@ describe('sync fuzz: every device converges on every last change', () => {
it(c.name, () => {
const bad = []
for (let s = 1; s <= c.seeds; s++) {
- const { problems } = run(s, c.opts)
- if (problems.length) bad.push(`seed ${s}: ${problems.slice(0, 3).join('; ')}`)
+ const { problems } = run(SEED_BASE + s, c.opts)
+ if (problems.length) bad.push(`seed ${SEED_BASE + s}: ${problems.slice(0, 3).join('; ')}`)
}
expect(bad.slice(0, 5)).toEqual([])
}, 120000)
diff --git a/frontend/src/lib/sync-merge.property.test.js b/frontend/src/lib/sync-merge.property.test.js
new file mode 100644
index 000000000..ddab78abd
--- /dev/null
+++ b/frontend/src/lib/sync-merge.property.test.js
@@ -0,0 +1,161 @@
+/* Algebra of the merge, checked on generated histories (fast-check, shrinking to the smallest
+ * failing case). sync-fuzz.test.js drives whole devices against a server model on fixed seeds;
+ * this file asks what any two or three copies must satisfy whatever the transport did, because
+ * that is what "nothing is ever lost" rests on when a watch, a phone, a phone that was offline
+ * and the server meet in whatever order the network allows:
+ *
+ * - the order two copies meet in does not matter (merge(A, B) = merge(B, A)),
+ * - meeting a copy again changes nothing (merge(M, A) = M once M has A in it),
+ * - three copies end up the same whichever pair meets first,
+ * - and every workout and weigh-in logged anywhere is in the result unless a delete of it
+ * came later, with the sets of the device that edited it last.
+ *
+ * The copies are made the way the store makes them (useStore update: a mutation, then
+ * stampChange), from one common base, on clocks that never tie.
+ */
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import { mergeStates, stampChange, stampWorkout } from './sync-merge.js'
+
+const clone = o => JSON.parse(JSON.stringify(o))
+const EXS = ['bench', 'squat', 'dead', 'row']
+const DAYS = ['2026-10-01', '2026-10-02', '2026-10-03']
+const base = () => ({
+ unit: 'kg', workouts: [
+ { id: 'w0', d: '2026-09-30', start: 1000, end: 2000, entries: [{ id: 'bench', sets: [{ w: 60, r: 5 }] }] },
+ ], routines: [{ id: 'r0', name: 'Push', ex: [{ id: 'bench', sets: 3 }] }], customEx: [], bodyweight: [{ d: '2026-09-30', w: 80, t: 1 }],
+ week: {}, dayPlan: {}, queue: null, restSec: 90, exNotes: {}, favEx: [], gymCards: [], equipProfiles: [], exWeights: {}, barWeights: {}, _ts: 10,
+})
+
+// One user action on a copy, as an op the generator can describe and shrink.
+const op = fc.oneof(
+ fc.record({ k: fc.constant('add'), ex: fc.constantFrom(...EXS), d: fc.constantFrom(...DAYS), w: fc.integer({ min: 20, max: 200 }), r: fc.integer({ min: 1, max: 12 }) }),
+ fc.record({ k: fc.constant('set'), pick: fc.nat(), w: fc.integer({ min: 20, max: 200 }), r: fc.integer({ min: 1, max: 12 }) }),
+ fc.record({ k: fc.constant('fix'), pick: fc.nat(), w: fc.integer({ min: 20, max: 200 }) }),
+ fc.record({ k: fc.constant('del'), pick: fc.nat() }),
+ fc.record({ k: fc.constant('weigh'), d: fc.constantFrom(...DAYS), w: fc.integer({ min: 600, max: 1000 }).map(x => x / 10) }),
+ fc.record({ k: fc.constant('routine'), sets: fc.integer({ min: 1, max: 6 }) }),
+)
+
+// Applies ops on device `dev` (0, 1, 2) and returns the copy. Device clocks interleave (time t on
+// device i is 10·t + i) so no two changes ever carry the same stamp.
+function play(S0, ops, dev, log) {
+ let S = clone(S0)
+ ops.forEach((o, i) => {
+ const prev = S
+ const next = clone(prev)
+ const wall = 100000 + (i + 1) * 30 + dev * 10 + dev
+ const W = next.workouts
+ if (o.k === 'add') {
+ const id = `w${dev}-${i}`
+ W.push({ id, d: o.d, start: wall - 50, end: wall, entries: [{ id: o.ex, sets: [{ w: o.w, r: o.r }] }] })
+ log.push({ dev, k: 'add', id, t: wall })
+ } else if ((o.k === 'set' || o.k === 'fix' || o.k === 'del') && W.length) {
+ const w = W[o.pick % W.length]
+ if (o.k === 'del') { next.workouts = W.filter(x => x !== w); log.push({ dev, k: 'del', id: w.id, t: wall }) }
+ else {
+ if (o.k === 'set') w.entries[0].sets.push({ w: o.w, r: o.r })
+ else w.entries[0].sets[0].w = o.w
+ stampWorkout(w, wall)
+ log.push({ dev, k: 'edit', id: w.id, t: wall })
+ }
+ } else if (o.k === 'weigh') {
+ next.bodyweight = [...next.bodyweight.filter(b => b.d !== o.d), { d: o.d, w: o.w, t: wall }]
+ } else if (o.k === 'routine') {
+ next.routines[0].ex[0].sets = o.sets
+ } else return
+ next._ts = stampChange(prev, next, wall)
+ S = next
+ })
+ return S
+}
+
+// What the user sees of a copy: the data, without the bookkeeping that legitimately differs.
+const view = S => ({
+ workouts: [...(S.workouts || [])].map(w => ({ id: w.id, d: w.d, entries: w.entries })).sort((a, b) => a.id.localeCompare(b.id)),
+ bodyweight: [...(S.bodyweight || [])].map(b => ({ d: b.d, w: b.w })).sort((a, b) => a.d.localeCompare(b.d)),
+ routines: (S.routines || []).map(r => ({ id: r.id, name: r.name, ex: r.ex })),
+})
+const merge = (a, b) => mergeStates(clone(a), clone(b))
+const RUNS = { numRuns: Number(process.env.PROPERTY_RUNS) || 150 }
+const histories = n => fc.array(fc.array(op, { maxLength: 8 }), { minLength: n, maxLength: n })
+
+describe('merging copies of one account', () => {
+ it('the order two copies meet in does not matter', () => {
+ fc.assert(fc.property(histories(2), ([oa, ob]) => {
+ const A = play(base(), oa, 0, []), B = play(base(), ob, 1, [])
+ expect(view(merge(A, B))).toEqual(view(merge(B, A)))
+ }), RUNS)
+ })
+
+ it('meeting a copy a second time changes nothing', () => {
+ fc.assert(fc.property(histories(2), ([oa, ob]) => {
+ const A = play(base(), oa, 0, []), B = play(base(), ob, 1, [])
+ const M = merge(A, B)
+ expect(view(merge(M, A))).toEqual(view(M))
+ expect(view(merge(B, M))).toEqual(view(M))
+ expect(view(merge(A, A))).toEqual(view(A))
+ }), RUNS)
+ })
+
+ it('watch, phone and server end up the same whichever two meet first', () => {
+ fc.assert(fc.property(histories(3), ([oa, ob, oc]) => {
+ const [A, B, C] = [oa, ob, oc].map((o, i) => play(base(), o, i, []))
+ const left = view(merge(merge(A, B), C))
+ expect(view(merge(A, merge(B, C)))).toEqual(left)
+ expect(view(merge(merge(C, A), B))).toEqual(left)
+ }), RUNS)
+ })
+
+ it('nothing logged anywhere is lost unless it was deleted after its last edit', () => {
+ fc.assert(fc.property(histories(3), ([oa, ob, oc]) => {
+ const logs = [[], [], []]
+ const copies = [oa, ob, oc].map((o, i) => play(base(), o, i, logs[i]))
+ const M = view(merge(merge(copies[0], copies[1]), copies[2]))
+ const ids = new Set(M.workouts.map(w => w.id))
+ const all = logs.flat()
+ const deleted = new Set(all.filter(e => e.k === 'del').map(e => e.id))
+ // Every workout some device logged and no device deleted is there.
+ for (const e of all) if (e.k === 'add' && !deleted.has(e.id)) expect(ids.has(e.id), `${e.id} was logged on device ${e.dev} and is gone`).toBe(true)
+ // The base workout too, unless a device deleted it.
+ if (!deleted.has('w0')) expect(ids.has('w0')).toBe(true)
+ // A workout only one device ever touched comes out exactly as that device left it.
+ for (const w of M.workouts) {
+ const touched = new Set(all.filter(e => e.id === w.id).map(e => e.dev))
+ if (touched.size === 1) {
+ const [dev] = touched
+ const own = view(copies[dev]).workouts.find(x => x.id === w.id)
+ if (own) expect(w).toEqual(own)
+ }
+ }
+ // No duplicates: one workout per id, one weigh-in per day.
+ expect(new Set(M.workouts.map(w => w.id)).size).toBe(M.workouts.length)
+ expect(new Set(M.bodyweight.map(b => b.d)).size).toBe(M.bodyweight.length)
+ }), RUNS)
+ })
+
+ it('a delete wins over every edit made before it, on any device', () => {
+ fc.assert(fc.property(histories(3), ([oa, ob, oc]) => {
+ const logs = [[], [], []]
+ const copies = [oa, ob, oc].map((o, i) => play(base(), o, i, logs[i]))
+ const M = view(merge(copies[2], merge(copies[0], copies[1])))
+ const all = logs.flat()
+ for (const d of all.filter(e => e.k === 'del')) {
+ const later = all.some(e => e.id === d.id && e.k !== 'del' && e.t > d.t)
+ if (!later) expect(M.workouts.some(w => w.id === d.id), `${d.id} deleted on device ${d.dev} came back`).toBe(false)
+ }
+ }), RUNS)
+ })
+
+ it('a weigh-in keeps the value entered last for its day, whichever device entered it', () => {
+ fc.assert(fc.property(histories(2), ([oa, ob]) => {
+ const A = play(base(), oa, 0, []), B = play(base(), ob, 1, [])
+ const M = view(merge(A, B))
+ for (const b of M.bodyweight) {
+ const cands = [A, B].flatMap(S => S.bodyweight.filter(x => x.d === b.d))
+ const last = cands.reduce((p, x) => (x.t > p.t ? x : p))
+ expect(b.w).toBe(last.w)
+ }
+ }), RUNS)
+ })
+})
diff --git a/scripts/ci/node-test-reporter.mjs b/scripts/ci/node-test-reporter.mjs
new file mode 100644
index 000000000..5ae3106f0
--- /dev/null
+++ b/scripts/ci/node-test-reporter.mjs
@@ -0,0 +1,21 @@
+// A node:test reporter that writes one JSON line per finished test, with the file it is in.
+// The built-in tap/junit reporters leave the file out for passing tests, and test-report.mjs
+// needs it to count tests per app area.
+//
+// node --test --test-reporter=../scripts/ci/node-test-reporter.mjs --test-reporter-destination=test-results.jsonl
+export default async function* jsonLines(source) {
+ for await (const ev of source) {
+ if (ev.type !== 'test:pass' && ev.type !== 'test:fail') continue
+ const d = ev.data
+ if (d.details?.type === 'suite') continue
+ const err = d.details?.error
+ yield JSON.stringify({
+ file: d.file,
+ name: d.name,
+ nesting: d.nesting,
+ status: d.skip || d.todo ? 'skipped' : ev.type === 'test:pass' ? 'passed' : 'failed',
+ ms: d.details?.duration_ms || 0,
+ message: err ? String(err.cause?.message || err.message || err).split('\n')[0].slice(0, 300) : undefined,
+ }) + '\n'
+ }
+}
diff --git a/scripts/ci/test-areas.mjs b/scripts/ci/test-areas.mjs
index 87de39895..bf2d431b1 100644
--- a/scripts/ci/test-areas.mjs
+++ b/scripts/ci/test-areas.mjs
@@ -7,7 +7,7 @@
// 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: 'Coach (AI)', re: /^parse\.|^validate\.|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/ },
diff --git a/scripts/ci/test-report.mjs b/scripts/ci/test-report.mjs
index e3450be9c..d2aeb5157 100644
--- a/scripts/ci/test-report.mjs
+++ b/scripts/ci/test-report.mjs
@@ -8,9 +8,9 @@
// 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:test (api, run with --test-reporter=scripts/ci/node-test-reporter.mjs):
// node scripts/ci/test-report.mjs --label API --root api \
-// --tap api/test-results.tap --lcov api/lcov.info --out stats/api.json
+// --node api/test-results.jsonl --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]
//
@@ -49,38 +49,20 @@ function fromVitest(file, root) {
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) {
+// node --test with scripts/ci/node-test-reporter.mjs: one JSON line per test, with its file.
+function fromNodeJson(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 tests = readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch { return null } })
+ .filter((t) => t && t.file).map((t) => ({ file: rel(root, t.file), name: t.name, status: t.status, ms: t.ms || 0, message: t.message }))
const byFile = new Map()
- for (const t of leaves) {
+ for (const t of tests) {
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()] }
+ return { tests, files: [...byFile.values()] }
}
// v8 json-summary (vitest --coverage.reporter=json-summary).
@@ -218,7 +200,7 @@ if (ci >= 0) {
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 run = opt('--vitest') ? fromVitest(opt('--vitest'), root) : fromNodeJson(opt('--node'), 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)