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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
API: PUT /api/data keeps the removal and edit records, and stamps what an older app or a planner changed
Duarte Santosdb87862a5fbb
diff --git a/api/Dockerfile b/api/Dockerfileindex ee08dc032..93834a929 100644--- a/api/Dockerfile+++ b/api/Dockerfile@@ -53,7 +53,7 @@ RUN npm ci --omit=dev --omit=optional && npm cache clean --force# Every module server.js imports from the api root has to be named here: the image carries nothing# else, and one that is missing only shows at boot, as ERR_MODULE_NOT_FOUND.-COPY server.js push-messages.js nudge.js nudge-copy.js verify-error.js password.js rate-limit.js passkeys-store.js device-link.js media.js queue.js ./+COPY server.js push-messages.js nudge.js nudge-copy.js verify-error.js password.js rate-limit.js passkeys-store.js device-link.js media.js queue.js sync-stamps.js ./COPY coach ./coachENV NODE_ENV=productionENV PORT=3000diff --git a/api/openapi.yaml b/api/openapi.yamlindex a0e3f5e08..69fa4c4f6 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -1430,6 +1430,18 @@ paths:server stamps the new revision into the document as `_rev`; a `_rev` sent bythe client is ignored.+ The records of removals (`deleted`) and of edits (`edited`) never shrink: the+ stored ones are joined into the write (a reset keeps its own). A writer that does+ not stamp its own changes (no `stamped: true`; an API script, an older app) and+ sends the current `baseRev` gets them stamped by the server, at the server's time:+ every entry it removed (a workout, routine, custom exercise, weigh-in, card,+ profile or favourite), every setting and plan day it changed (`queue`,+ `week.<day>`, …), and every entry it edited (`_ts`, per field `_f`). That keeps a+ planner's new week, or a routine it removed, from being undone by a phone that+ reconnects later with an older change. An entry the document holds while a+ removal on record says it was deleted after its last edit is kept and marked as+ added back.+Every accepted write also starts the grace period of each stored file (tag `media`)the new state no longer references, and stops it for each one it references again.That bookkeeping never changes the answer.@@ -1447,6 +1459,12 @@ paths:description: >-The revision this client last read or wrote. Omit or null for anunconditional overwrite.+ stamped:+ type: boolean+ description: >-+ True when the client stamps its own changes in `deleted`, `edited` and+ each entry's `_ts`/`_f`, as the app does. Omit it to have the server+ stamp what changed against the stored document.responses:'200':description: Saved.@@ -3194,6 +3212,19 @@ components:type: integerreadOnly: truedescription: Server-set revision, incremented on every accepted PUT. Ignored when sent by a client.+ deleted:+ type: object+ description: >-+ When entries were removed, per list and entry key ({ workouts: { <id>: ms } }, weigh-ins+ by day, favourites by exercise id). A negative stamp is an add-back after a removal.+ Never shrinks on the server; stamped for writers that do not stamp (see PUT /api/data).+ additionalProperties: { type: object, additionalProperties: { type: number } }+ edited:+ type: object+ description: >-+ When each setting and plan day was last changed, ms ({ queue: ms, 'week.3': ms, … }).+ Never shrinks on the server; stamped for writers that do not stamp (see PUT /api/data).+ additionalProperties: { type: number }unit: { type: string, enum: [kg, lb] }lang:type: string@@ -3210,7 +3241,7 @@ components:queue:type: objectnullable: true- description: A planner's floating week {ids, since, startsOn, label} — the week's sessions as an ordered queue, the first undone one is today's. Written only by an API client (never by the app), read by the reminder tick.+ description: A planner's floating week {ids, since, startsOn, label} — the week's sessions as an ordered queue, the first undone one is today's. Written by an API client or by the app's own rotation feature, read by the reminder tick.week:type: objectdescription: 'Weekly plan: weekday (0=Sunday … 6) → routine id.'diff --git a/api/server.js b/api/server.jsindex b0c170158..5864e8d8b 100644--- a/api/server.js+++ b/api/server.js@@ -32,6 +32,7 @@ import {import { createDeviceLink, findDeviceLink, burnDeviceLink, dropDeviceLinks } from './device-link.js';import { createMediaStore, mediaLimits, mediaConfig, MediaError, HASH_RE } from './media.js';import { effectiveRoutineId } from './queue.js';+import { stampPut } from './sync-stamps.js';import { nudgeFor, nudgeWindowOpen, toneOf } from './nudge.js';const PORT = +(process.env.PORT || 3000);@@ -2109,6 +2110,12 @@ const routes = {if (cur.resetIds && typeof cur.resetIds === 'object') body.state.resetIds = cur.resetIds;else delete body.state.resetIds;}+ // The records of removals and edits only grow, and what a writer that does not stamp its own+ // changes (an older app, an API script) changed is stamped here, so it is neither wiped nor+ // undone by the next device that merges (sync-stamps.js).+ // A document nested too deep to compare is the bad request the stringify below refuses too.+ try { stampPut(cur, body.state, { overRead: body.baseRev != null && body.baseRev === curRev, stamped: body.stamped === true }); }+ catch (e) { if (e instanceof RangeError) return json(res, 400, { error: 'invalid state' }); throw e; }body.state._rev = curRev + 1; // server-owned; whatever the client sent is ignored// JSON.parse takes any nesting, JSON.stringify recurses and runs out of stack on a document// nested some thousands deep. No client builds one; it is a bad request, not a server error.diff --git a/api/sync-stamps.js b/api/sync-stamps.jsnew file mode 100644index 000000000..c7ed567a7--- /dev/null+++ b/api/sync-stamps.js@@ -0,0 +1,201 @@+// The server's half of the sync stamps. Hand-copied (not imported) from+// frontend/src/lib/sync-merge.js, like queue.js: the same rules on both sides, kept as a small+// standalone module so it can be unit-tested without booting the server, and checked against the+// frontend's copy by frontend/src/lib/sync-stamps-parity.test.js.+//+// The app stamps every change itself: `deleted` records what was removed and when, `edited` when+// each setting and plan day was last changed, and every routine, custom exercise, profile, card+// and edited workout carries its own `_ts` (and `_f`, per field). Two kinds of writer do not:+//+// - an older app (v1.3.9 and before), which knows none of it. It pushed back whatever it had+// read without the records, so one offline phone wiped every removal on record and the RC's+// devices brought back what had been deleted; its own deletes and setting changes carried no+// stamp and lost to older ones made on an updated device.+// - an API client: a planner that GETs, changes the queue or a routine, and PUTs. Its new week+// lost to any phone that reconnected with an older, unrelated change.+//+// So PUT /api/data (stampPut):+// 1. never lets the records shrink: `deleted` and `edited` are joined with the stored ones (but+// a reset, which starts the profile over, keeps its own);+// 2. for a writer that does not stamp (no `stamped: true` in the body) and wrote over the+// revision it read: stamps what it changed against the stored copy, at the server's time —+// entries removed, settings and plan days changed, entries edited;+// 3. for every writer: an entry the document holds while a removal on record says it was+// deleted after its last edit is kept, and marked as added back. An updated app never sends+// such a document, so this is an older app's merge (or its Coach undo, or a backup it+// restored) bringing an entry back, and that cannot be told apart from a deliberate re-add:+// a deleted entry that comes back is one tap to remove again, a wanted one dropped is lost.++const isMap = v => !!v && typeof v === 'object' && !Array.isArray(v);+const list = v => (Array.isArray(v) ? v : []);+const same = (x, y) => JSON.stringify(x) === JSON.stringify(y);++const workoutKey = w => (w?.id != null ? w.id : `${w?.d}|${w?.start}`);+const workoutTime = w => Number(w?._ts) || Number(w?.end) || Number(w?.start) || 0;+export const DEL_LISTS = {+ workouts: workoutKey, routines: x => x?.id, customEx: x => x?.id, bodyweight: e => e?.d,+ gymCards: x => x?.id, equipProfiles: x => x?.id, favEx: x => x,+};+const DEL_TIME = {+ workouts: workoutTime, routines: x => Number(x?._ts) || 0, customEx: x => Number(x?._ts) || 0,+ bodyweight: e => Number(e?.t) || 0, gymCards: x => Number(x?._ts) || 0, equipProfiles: x => Number(x?._ts) || 0,+};+export const DELETED_MAX = 5000;+const capStamps = m => {+ const ks = Object.keys(m);+ if (ks.length <= DELETED_MAX) return m;+ ks.sort((x, y) => Math.abs(m[x]) - Math.abs(m[y]));+ for (const k of ks.slice(0, ks.length - DELETED_MAX)) delete m[k];+ return m;+};+const OWN_MERGE = new Set([+ '_ts', '_rev', 'active', 'unit', 'unitSet', 'resetAt', 'resetIds', 'deleted', 'edited',+ 'workouts', 'routines', 'customEx', 'equipProfiles', 'gymCards', 'bodyweight', 'favEx',+ 'exWeights', 'balanceOverrides', 'loadKind', 'plates',+]);+const PER_KEY = new Set(['week', 'dayPlan', 'exNotes', 'barWeights']);+const ENTRY_META = new Set(['id', '_ts', '_f']);+const ENTRY_LISTS = ['routines', 'customEx', 'equipProfiles', 'gymCards', 'workouts'];++/** Both records of removals: per entry, the later stamp. */+export function mergeDeletions(a, b) {+ const out = {};+ for (const f of Object.keys(DEL_LISTS)) {+ const x = isMap(a?.[f]) ? a[f] : {}, y = isMap(b?.[f]) ? b[f] : {};+ const m = { ...x };+ for (const [k, v] of Object.entries(y)) if (!(k in m) || Math.abs(Number(v) || 0) > Math.abs(Number(m[k]) || 0)) m[k] = v;+ if (Object.keys(m).length) out[f] = capStamps(m);+ }+ return Object.keys(out).length ? out : null;+}++/** Both records of edits: per key, the later stamp. */+export function mergeEdits(a, b) {+ const x = isMap(a) ? a : {}, y = isMap(b) ? b : {};+ const out = { ...x };+ for (const [k, v] of Object.entries(y)) if (!((Number(out[k]) || 0) >= (Number(v) || 0))) out[k] = v;+ return Object.keys(out).length ? out : null;+}++/** The latest stamp a copy carries (sync-merge.js highestStamp). */+export function highestStamp(S) {+ let m = 0;+ const see = v => { const n = Math.abs(Number(v) || 0); if (n > m) m = n; };+ if (!S || typeof S !== 'object') return 0;+ see(S._ts); see(S.unitSet?.at); see(S.resetAt);+ if (isMap(S.edited)) for (const v of Object.values(S.edited)) see(v);+ if (isMap(S.deleted)) for (const f of Object.values(S.deleted)) if (isMap(f)) for (const v of Object.values(f)) see(v);+ for (const f of ENTRY_LISTS) {+ for (const x of list(S[f])) {+ if (!x || typeof x !== 'object') continue;+ see(x._ts);+ if (isMap(x._f)) for (const v of Object.values(x._f)) see(v);+ }+ }+ for (const f of ['balanceOverrides', 'loadKind', 'plates']) {+ if (isMap(S[f])) for (const v of Object.values(S[f])) see(isMap(v) ? v._ts : 0);+ }+ return m;+}++/** `x` stamped as an edit of `old` at `now`, per field (sync-merge.js stampEntry). Mutates `x`. */+export function stampEntry(old, x, now) {+ if (!x || typeof x !== 'object') return x;+ x._ts = now;+ if (!old || typeof old !== 'object') return x;+ const f = isMap(old._f) ? { ...old._f } : {};+ for (const k of new Set([...Object.keys(old), ...Object.keys(x)])) {+ if (ENTRY_META.has(k)) continue;+ if ((k in old) !== (k in x) || !same(old[k], x[k])) f[k] = now;+ }+ if (Object.keys(f).length) x._f = f; else delete x._f;+ return x;+}+const sameEntry = (a, b) => same({ ...a, _ts: 0, _f: 0 }, { ...b, _ts: 0, _f: 0 });++// Step 2: what a writer that does not stamp changed against the copy it read, stamped at `now`.+function stampUnstamped(cur, next, sent, now) {+ // Removals: every entry the stored copy had and this one lacks, unless already on record.+ const del = isMap(next.deleted) ? next.deleted : {};+ for (const [f, key] of Object.entries(DEL_LISTS)) {+ const time = DEL_TIME[f] || (() => 0);+ const have = new Set(list(next[f]).filter(x => x != null).map(x => String(key(x))));+ for (const x of list(cur[f])) {+ if (x == null) continue;+ const k = String(key(x));+ if (have.has(k)) continue;+ const m = isMap(del[f]) ? del[f] : (del[f] = {});+ if (!(Number(m[k]) > 0 && Number(m[k]) >= time(x))) m[k] = Math.max(now, time(x) + 1);+ }+ if (isMap(del[f])) capStamps(del[f]);+ }+ if (Object.keys(del).length) next.deleted = del;+ // Settings and plan days changed, whose stamp the writer did not move past the stored one.+ const ed = isMap(next.edited) ? next.edited : {};+ const mine = isMap(sent) ? sent : {}, theirs = isMap(cur.edited) ? cur.edited : {};+ const moved = k => (Number(mine[k]) || 0) > (Number(theirs[k]) || 0);+ for (const k of new Set([...Object.keys(cur), ...Object.keys(next)])) {+ if (OWN_MERGE.has(k)) continue;+ const p = cur[k], n = next[k];+ if (PER_KEY.has(k)) {+ const pm = isMap(p) ? p : {}, nm = isMap(n) ? n : {};+ for (const s of new Set([...Object.keys(pm), ...Object.keys(nm)])) {+ const sk = `${k}.${s}`;+ if (((s in pm) !== (s in nm) || !same(pm[s], nm[s])) && !moved(sk)) ed[sk] = now;+ }+ } else if (n !== undefined && !same(p, n) && !moved(k)) ed[k] = now; // absent: a field the writer does not know+ }+ if (Object.keys(ed).length) next.edited = ed;+ // Entries edited without a stamp of their own: a routine, a custom exercise, a profile, a card,+ // a workout whose content changed while its `_ts` did not move.+ for (const f of ENTRY_LISTS) {+ const before = new Map(list(cur[f]).filter(x => x && x.id != null).map(x => [x.id, x]));+ for (const x of list(next[f])) {+ if (!x || typeof x !== 'object' || x.id == null) continue;+ const old = before.get(x.id);+ if (!old) { if (f !== 'workouts' && x._ts == null) x._ts = now; continue; }+ if ((Number(x._ts) || 0) > (Number(old._ts) || 0) || sameEntry(old, x)) continue;+ stampEntry(old, x, now);+ }+ }+}++// Step 3: an entry held while a removal on record says it was deleted after its last edit is+// kept, and marked as added back.+function keepHeld(next, now) {+ const del = next.deleted;+ if (!isMap(del)) return;+ for (const [f, key] of Object.entries(DEL_LISTS)) {+ const m = del[f];+ if (!isMap(m)) continue;+ const time = DEL_TIME[f] || (() => 0);+ for (const x of list(next[f])) {+ if (x == null) continue;+ const k = String(key(x));+ const at = Number(m[k]) || 0;+ if (at > 0 && at >= time(x)) m[k] = -Math.max(now, at + 1);+ }+ }+}++/**+ * PUT /api/data's stamping (see the top of this file). `cur` is the stored document (or null),+ * `next` the one being written (mutated in place), `opts.overRead` true when the writer sent the+ * revision it read and it is the current one, `opts.stamped` true for a writer that stamps its own+ * changes (the app), `opts.now` the server's clock.+ */+export function stampPut(cur, next, { overRead = false, stamped = false, now = Date.now() } = {}) {+ if (!next || typeof next !== 'object') return next;+ const t = Math.max(Number(now) || 0, highestStamp(cur) + 1, highestStamp(next) + 1);+ const reset = (Number(next.resetAt) || 0) > (Number(cur?.resetAt) || 0);+ const sent = isMap(next.edited) ? { ...next.edited } : null;+ if (cur && !reset) {+ const d = mergeDeletions(cur.deleted, next.deleted);+ if (d) next.deleted = d; else delete next.deleted;+ const e = mergeEdits(cur.edited, next.edited);+ if (e) next.edited = e; else delete next.edited;+ if (!stamped && overRead) stampUnstamped(cur, next, sent, t);+ }+ keepHeld(next, t);+ return next;+}diff --git a/api/test/sync-stamps.test.js b/api/test/sync-stamps.test.jsnew file mode 100644index 000000000..9f0783e90--- /dev/null+++ b/api/test/sync-stamps.test.js@@ -0,0 +1,121 @@+/* PUT /api/data's stamping (sync-stamps.js): the records of removals and edits never shrink, a+ writer that does not stamp (an older app, an API planner) gets what it changed stamped, and an+ entry held against a removal on record is kept as added back. Unit cases first, then the real+ server.js in a child. (QA 2026-10-06: an offline v1.3.9 phone wiped the RC's removal records; a+ planner's new week was undone by a phone that reconnected with an older change.) */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { boundPort } from './helpers.mjs';+import { stampPut } from '../sync-stamps.js';++const clone = v => JSON.parse(JSON.stringify(v));+const NOW = 1_800_000_000_000;+const stored = () => ({+ _ts: NOW - 5000, _rev: 3, restSec: 90, queue: { ids: ['a'] }, week: { 1: 'r1' },+ workouts: [{ id: 'w1', d: '2026-10-01', start: 1, end: 2 }, { id: 'w2', d: '2026-10-02', start: 3, end: 4 }],+ routines: [{ id: 'r1', name: 'Push', ex: [], _ts: NOW - 9000 }, { id: 'r2', name: 'Pull', ex: [], _ts: NOW - 9000 }],+ favEx: ['bench'],+ deleted: { workouts: { w9: NOW - 4000 } }, edited: { restSec: NOW - 4000 },+});++test('an older app\'s push over the current revision keeps the records and gets its changes stamped', () => {+ const cur = stored();+ const next = clone(cur);+ delete next.deleted; delete next.edited; delete next._rev // v1.3.9 never knew them+ next.workouts = next.workouts.filter(w => w.id !== 'w2') // its delete+ next.restSec = 120 // its setting+ next.routines[0].name = 'Push A' // its routine edit, no stamp of its own+ stampPut(cur, next, { overRead: true, stamped: false, now: NOW });+ assert.equal(next.deleted.workouts.w9, NOW - 4000); // kept+ assert.ok(next.deleted.workouts.w2 >= NOW); // stamped+ assert.ok(next.edited.restSec >= NOW);+ assert.ok(next.routines[0]._ts >= NOW);+ assert.ok(next.routines[0]._f.name >= NOW);+ assert.equal(next.routines[1]._ts, NOW - 9000); // untouched+});++test('a planner\'s queue and removed routine are stamped; a field it does not send is left alone', () => {+ const cur = stored();+ cur.hints = { swipeSets: true };+ const next = clone(cur);+ delete next.hints;+ next.queue = { ids: ['b'] };+ next.routines = next.routines.filter(r => r.id !== 'r2');+ stampPut(cur, next, { overRead: true, now: NOW });+ assert.ok(next.edited.queue >= NOW);+ assert.ok(next.deleted.routines.r2 >= NOW);+ assert.equal(next.edited.hints, undefined);+});++test('the app stamps its own changes: only the records are joined', () => {+ const cur = stored();+ const next = clone(cur);+ next.edited = { restSec: NOW - 100 };+ next.restSec = 60;+ next.workouts = next.workouts.filter(w => w.id !== 'w2'); // a delete it stamps itself+ next.deleted = { workouts: { w2: NOW - 100 } };+ stampPut(cur, next, { overRead: true, stamped: true, now: NOW });+ assert.deepEqual(next.deleted.workouts, { w9: NOW - 4000, w2: NOW - 100 });+ assert.equal(next.edited.restSec, NOW - 100);+});++test('an entry held against a removal on record is kept, marked as added back', () => {+ const cur = stored();+ cur.deleted.favEx = { squat: NOW - 4000 };+ cur.deleted.workouts.w1 = NOW - 4000; // a document an older app's merge left inconsistent+ const next = clone(cur);+ next.favEx = ['bench', 'squat']; // starred again on an older app+ stampPut(cur, next, { overRead: true, now: NOW });+ assert.ok(next.deleted.favEx.squat < 0);+ assert.ok(next.deleted.workouts.w1 < 0);+ assert.deepEqual(next.workouts.map(w => w.id), ['w1', 'w2']);+});++test('a reset keeps its own records; a replace without baseRev keeps the stored ones', () => {+ const cur = stored();+ const reset = { _ts: NOW, resetAt: NOW, workouts: [], routines: [] };+ stampPut(cur, reset, { overRead: false, stamped: true, now: NOW });+ assert.equal(reset.deleted, undefined);+ const replace = { _ts: NOW, workouts: [{ id: 'w9', d: '2026-09-01', start: 1, end: 2 }], routines: [] };+ stampPut(cur, replace, { overRead: false, now: NOW });+ assert.ok(replace.deleted.workouts.w9 < 0); // the restored workout is kept and stays+ assert.equal(replace.edited.restSec, NOW - 4000);+});++// ---- the real server -------------------------------------------------------------------------+const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const SECRET = crypto.randomBytes(32).toString('hex');+function mintSession(uid) {+ const payload = `${uid}:${Date.now() + 86400000}:0`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+}+test('PUT /api/data: an older app\'s push does not wipe the records, and its delete is stamped', async t => {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-stamps-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u1', name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: [] }));+ const child = spawn(process.execPath, ['server.js'], { cwd: API, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' } });+ let log = '';+ child.stdout.on('data', d => log += d); child.stderr.on('data', d => log += d);+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ const base = `http://127.0.0.1:${await boundPort(child, () => log)}`;+ const headers = { Cookie: `gymsid=${mintSession('u1')}`, 'Content-Type': 'application/json' };+ const put = async body => { const r = await fetch(`${base}/api/data`, { method: 'PUT', headers, body: JSON.stringify(body) }); return { status: r.status, body: await r.json() }; };+ const get = async () => (await fetch(`${base}/api/data`, { headers })).json();++ // the RC app pushes a delete it stamped itself+ let r = await put({ state: { _ts: 1, workouts: [{ id: 'w2', d: '2026-10-02', start: 3, end: 4 }], routines: [], deleted: { workouts: { w1: 1000 } } }, stamped: true });+ assert.equal(r.status, 200);+ // an older app, which read rev 1, pushes its copy without the records and with w2 deleted+ r = await put({ state: { _ts: 2, workouts: [], routines: [] }, baseRev: 1 });+ assert.equal(r.status, 200);+ const doc = (await get()).state;+ assert.equal(doc.deleted.workouts.w1, 1000);+ assert.ok(doc.deleted.workouts.w2 > 1000);+});diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex 0ccc47e36..90e345c24 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -512,7 +512,7 @@ export function stampEdits(prev, next, now = Date.now()) {}/** Both copies' edit stamps: per key, the later one. */-function mergeEdits(a, b) {+export function mergeEdits(a, b) {const x = isMap(a) ? a : {}, y = isMap(b) ? b : {}const out = { ...x }for (const [k, v] of Object.entries(y)) if (!((Number(out[k]) || 0) >= (Number(v) || 0))) out[k] = vdiff --git a/frontend/src/lib/sync-stamps-parity.test.js b/frontend/src/lib/sync-stamps-parity.test.jsnew file mode 100644index 000000000..f90ae9b52--- /dev/null+++ b/frontend/src/lib/sync-stamps-parity.test.js@@ -0,0 +1,74 @@+/* api/sync-stamps.js is a hand copy of the stamping rules here (sync-merge.js), for the server's+ PUT /api/data. The two must agree; and what the server stamps for a writer that does not stamp+ its own changes (an older app, an API planner) must hold in this side's merge. */+import { describe, expect, it } from 'vitest'+import * as S from '../../../api/sync-stamps.js'+import { highestStamp, mergeDeletions, mergeEdits, mergeStates, stampChange, stampEntry } from './sync-merge.js'++const clone = v => JSON.parse(JSON.stringify(v))+function rng(seed) { let s = seed >>> 0 || 1; return () => { s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0; return s / 4294967296 } }++describe('api/sync-stamps.js matches sync-merge.js', () => {+ it('on random records and entries', () => {+ for (let seed = 1; seed < 300; seed++) {+ const R = rng(seed)+ const n = () => Math.floor(R() * 1000) * (R() < 0.3 ? -1 : 1)+ const recs = () => ({ workouts: { a: n(), b: n() }, favEx: { x: n() }, bodyweight: R() < 0.5 ? { '2026-10-01': n() } : undefined })+ const a = recs(), b = recs()+ expect(S.mergeDeletions(a, b)).toEqual(mergeDeletions(a, b))+ const ea = { restSec: n(), 'week.1': n() }, eb = { restSec: n(), queue: n() }+ expect(S.mergeEdits(ea, eb)).toEqual(mergeEdits(ea, eb))+ const doc = { _ts: n(), edited: ea, deleted: a, routines: [{ id: 'r', _ts: n(), _f: { name: n() } }], plates: { kg: { _ts: n() } } }+ expect(S.highestStamp(doc)).toBe(highestStamp(doc))+ const old = { id: 'r', name: 'A', ex: [1], _f: { ex: 5 } }+ const x = { id: 'r', name: R() < 0.5 ? 'A' : 'B', ex: [1, R() < 0.5 ? 2 : 1] }+ expect(S.stampEntry(clone(old), clone(x), 99)).toEqual(stampEntry(clone(old), clone(x), 99))+ }+ })+})++describe('what the server stamps holds in the merge', () => {+ const T = 1_800_000_000_000+ const change = (prev, wall, mut) => { const n = clone(prev); mut(n); n._ts = stampChange(prev, n, wall); return n }+ const doc0 = () => ({ _ts: T, restSec: 90, queue: { label: 'US W1' }, edited: { queue: T },+ routines: [{ id: 'r1', name: 'A', ex: [], _ts: T }, { id: 'r2', name: 'B', ex: [], _ts: T }],+ workouts: [{ id: 'w1', d: '2026-10-01', start: T - 2e6, end: T - 1e6 }], favEx: [] })++ it('a planner\'s new week and removed routine survive a phone that reconnects with an older change', () => {+ const cur = doc0()+ const phone = change(cur, T + 60e3, S2 => { S2.workouts.push({ id: 'w2', d: '2026-10-06', start: T, end: T + 60e3 }) }) // offline+ const planned = clone(cur)+ planned.queue = { label: 'US W2' }+ planned.routines = planned.routines.filter(r => r.id !== 'r2')+ planned._ts = T + 30e3+ S.stampPut(cur, planned, { overRead: true, now: T + 30e3 })+ // the phone's later push gets the 409 and merges (phone's _ts is newer)+ const m = mergeStates(phone, planned)+ expect(m.queue).toEqual({ label: 'US W2' })+ expect(m.routines.map(r => r.id)).toEqual(['r1'])+ expect(m.workouts.map(w => w.id).sort()).toEqual(['w1', 'w2'])+ })++ it('an older app\'s offline delete and setting hold against an older change from an updated device', () => {+ const cur = doc0()+ const rc = change(cur, T + 5000, S2 => { S2.restSec = 60 }) // updated device, offline, not pushed yet+ const old = clone(cur); delete old.edited+ old.restSec = 180; old.workouts = []; old._ts = T + 9000 // v1.3.9, later+ S.stampPut(cur, old, { overRead: true, now: T + 9000 })+ const m = mergeStates(rc, old)+ expect(m.restSec).toBe(180)+ expect(m.workouts).toEqual([])+ })++ it('an older app\'s push keeps the removals on record, and an entry it brings back stays', () => {+ const cur = change(doc0(), T + 1000, S2 => { S2.workouts = [] }) // the RC deleted w1+ const old = clone(doc0()); delete old.edited // v1.3.9 offline, union brings w1 back+ old.favEx = []; old._ts = T + 2000+ S.stampPut(cur, old, { overRead: true, now: T + 2000 })+ expect(Object.keys(old.deleted.workouts)).toEqual(['w1'])+ expect(old.deleted.workouts.w1).toBeLessThan(0) // kept, as added back: never flips back and forth+ const rcAgain = change(cur, T + 1500, S2 => { S2.restSec = 70 })+ expect(mergeStates(rcAgain, old).workouts.map(w => w.id)).toEqual(['w1'])+ expect(mergeStates(old, rcAgain).workouts.map(w => w.id)).toEqual(['w1'])+ })+})diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 99124e988..6fa6b222b 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -560,7 +560,9 @@ export const useStore = create((set, get) => {forceNext = falseconst asReplace = replaceRevreplaceRev = null- const body = { state: S }+ // `stamped`: this client stamps its own changes; the server stamps only for one that does not+ // (api/sync-stamps.js).+ const body = { state: S, stamped: true }if (asReplace != null) body.baseRev = asReplaceelse if (!force && base) body.baseRev = base.revtry {