From 68557f1fd91d5311089be898be3128d9aec86491 Mon Sep 17 00:00:00 2001 From: ehonis Date: Sun, 8 Nov 2026 12:23:35 -0500 Subject: [PATCH] Shared copies from before uids: the first write never duplicates an exercise (#105) Published from the private repository by oss-sync. - Shared copies from before uids: the first write never duplicates an exercise (#105) 4 files changed, 302 insertions(+), 34 deletions(-) --- AGENTS.md | 9 ++- server/http.test.js | 69 +++++++++++++++++++ server/sharedsync.js | 139 +++++++++++++++++++++++++++++--------- server/sharedsync.test.js | 119 ++++++++++++++++++++++++++++++++ 4 files changed, 302 insertions(+), 34 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1213376..ba69131 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -383,7 +383,14 @@ section keeps only the keys `blank()` names, so a removed setting is dropped on never matched on. A model revision is asked for each uid back (the planner's reply schema allows it, the revise prompt says to copy it) and `normalizePrescription` keeps it, so a renamed exercise stays the same one. An item that still arrives without a uid - takes the uid of the same-named item it replaced. + takes the uid of the same-named item it replaced, in its own block only, never one in + another block (#105: a plan can have Back squat in its main block and in a circuit, or + three rounds with the same names). An entry shared before uids existed (no uid, no + `syncBase`) is stamped by its own items on its first write, the stored entry before the + write is laid onto it, with uids derived from where each row is, so both sides get the + same ones whichever is written first. That write is numbers only (the rule below): its + numbers land on the exercise they were written on, and it adds nothing the stored entry + lacks but an exercise its own device logged on, like any numbers-only write. - **The rule** (`intentOf`, stated at the top of `server/sharedsync.js`). Each synced entry carries `data.syncBase` (`{ of: , rev, plan | lifts }`, its structure as the server last wrote it, a new `rev` on every change), and a device sends back the base diff --git a/server/http.test.js b/server/http.test.js index 2fedaf0..83456a6 100644 --- a/server/http.test.js +++ b/server/http.test.js @@ -790,6 +790,75 @@ async function waitFor(fn, label, ms = 8000) { eq(itemsIn(theirsOn(id)).map(i => i.uid), itemsIn(ownOn(id)).map(i => i.uid), 'the two sides no longer share uids') }) + /* + * #105. Copies shared before uids existed (the seed's, Oct 13 to Oct 24) have no uid + * and no syncBase on either side, and a plan can have the same exercise in two blocks + * (Back squat in the main block and in a circuit; three rounds with the same names). + */ + const squatPlan = () => ids({ title: 'Legs', blocks: [ + { name: 'Main', note: '', items: [lifted('Back squat', st(3, { weight: null })), lifted('Romanian deadlift', st(2, { weight: null }))] }, + { name: 'Finisher', note: '', circuit: { work: 40, rest: 20, rounds: 3 }, items: [lifted('Back squat', st(1, { weight: null })), lifted('Lunge', st(1, { weight: null }))] }, + ] }) + const shape = (e) => e.data.plan.blocks.map(b => `${b.name}[${b.items.map(i => `${i.name}:${i.sets.length}`).join(',')}]`) + /** An entry written into a log file as an install from before uids left it. */ + const plant = (file, entry) => { + const doc = JSON.parse(fs.readFileSync(file, 'utf8')) + doc.state.entries[entry.id] = entry + fs.writeFileSync(file, JSON.stringify(doc)) + } + + await step('sync: a pre-uid share (#105): the first write from either side, by the runner or the sheet, adds nothing and lands its numbers where they were written', async () => { + const date = '2026-09-20' + const id = `daily-${date}` + const old = (data) => ({ id, kind: 'daily', date, updatedAt: `${date}T08:00:00.000Z`, data: { optId: 'planned', slot: 'main', done: false, plan: squatPlan(), out: {}, ...data } }) + plant(path.join(two.dataDir, 'state.json'), old({ sharedWith: [{ id: 'sam', entryId: id, sync: true }] })) + plant(path.join(two.dataDir, 'users', 'sam', 'state.json'), old({ sharedFrom: { id: 'owner', name: 'Alex' } })) + const want = shape(ownOn(id)) + // Sam's phone, first: the runner marks set 1 of the main block's Back squat. + const samRun = theirsOn(id) + eq((await saveSams({ ...samRun, data: { ...samRun.data, run: { sets: { b0i0s0: { reps: 5, weight: 40 } }, cursor: 'b0i0s1' } } })).status, 200) + eq([shape(theirsOn(id)), shape(ownOn(id))], [want, want], 'the runner\'s first write added an exercise') + eq(theirsOn(id).data.run.sets, { b0i0s0: { reps: 5, weight: 40 } }, 'Sam\'s mark moved off the main block\'s Back squat') + // The owner's sheet, on a device that still holds the entry from before uids: 100 typed into the same set. + const ownSheet = old({ sharedWith: [{ id: 'sam', entryId: id, sync: true }] }) + ownSheet.data.plan.blocks[0].items[0].sets[0] = { ...ownSheet.data.plan.blocks[0].items[0].sets[0], weight: 100, typed: true } + eq((await saveOwn(ownSheet)).status, 200) + eq([shape(theirsOn(id)), shape(ownOn(id))], [want, want], 'the sheet\'s first write added an exercise') + eq(ownOn(id).data.plan.blocks.map(b => b.items.map(i => i.sets.map(s => s.weight))), [[[100, null, null], [null, null]], [[null], [null]]], 'the owner\'s typed 100 was lost or moved') + eq(theirsOn(id).data.plan.blocks[0].items[0].sets[0].weight, null, 'the owner\'s number crossed to Sam') + // Both sides stamped the same uids, so a change made now crosses once. + eq(itemsIn(theirsOn(id)).map(i => i.uid), itemsIn(ownOn(id)).map(i => i.uid), 'the two sides minted different uids') + eq((await saveOwn(replan(ownOn(id), bs => { bs[1].items.push(lifted('Step-up', st(1, { weight: null }))); return bs }))).status, 200) + eq(shape(theirsOn(id)), ['Main[Back squat:3,Romanian deadlift:2]', 'Finisher[Back squat:1,Lunge:1,Step-up:1]'], 'the owner\'s Step-up did not reach Sam once') + }) + + await step('sync: an old phone\'s copy (no uids) never puts a number on the same-named exercise in another block (#105)', async () => { + const date = '2026-09-21' + const id = `daily-${date}` + // Shared with sync on while the main block had no Back squat; Sam's phone keeps that copy. + const plan = squatPlan() + plan.blocks[0].items.shift() + const fresh = ids(plan) + eq((await saveOwn({ id, kind: 'daily', date, data: { optId: 'planned', slot: 'main', done: false, plan: fresh, out: {} } })).status, 200) + const r = await post('sam', { id, kind: 'daily', date, updatedAt: tick(), data: { optId: 'planned', slot: 'main', done: false, plan: fresh, out: {}, sharedFrom: { id: 'owner' } } }) + const pre = (await r.json()).entry + eq((await saveOwn({ ...ownOn(id), data: { ...ownOn(id).data, sharedWith: [{ id: 'sam', entryId: id, sync: true }] } })).status, 200) + // The owner adds Back squat to the main block; it reaches Sam. + eq((await saveOwn(replan(ownOn(id), bs => { bs[0].items.unshift(lifted('Back squat', st(3, { weight: null }))); return bs }))).status, 200) + const want = ['Main[Back squat:3,Romanian deadlift:2]', 'Finisher[Back squat:1,Lunge:1]'] + eq(shape(theirsOn(id)), want, 'the owner\'s Back squat did not reach Sam, so this proves nothing') + // Sam's old copy: 30 typed into the circuit's Back squat (b1i0s0 there), and the runner's mark on it. + const old = { ...pre, updatedAt: tick(), data: { ...pre.data, run: { sets: { b1i0s0: { seconds: 40 } } } } } + old.data.plan = { ...old.data.plan, blocks: old.data.plan.blocks.map((b, bi) => (bi !== 1 ? b + : { ...b, items: b.items.map((it, ii) => (ii ? it : { ...it, sets: [{ ...it.sets[0], weight: 30, typed: true }] })) })) } + eq((await get(`${two.base}/api/entry`, { method: 'POST', headers: { ...json, ...samSays.headers }, body: JSON.stringify({ entry: old }) })).status, 200) + eq([shape(theirsOn(id)), shape(ownOn(id))], [want, want], 'the old copy changed the structure') + const fin = theirsOn(id).data.plan.blocks[1].items[0] + const main = theirsOn(id).data.plan.blocks[0].items[0] + eq([fin.sets[0].weight, main.sets.map(s => s.weight)], [30, [null, null, null]], 'Sam\'s 30 landed on the main block\'s Back squat') + eq(Object.keys(theirsOn(id).data.run.sets), ['b1i0s0'], 'Sam\'s mark moved to the main block\'s Back squat') + }) + await step('sync: X1, a deadlift set Sam logged offline survives the owner removing Deadlift, on Sam\'s side only', async () => { // A day still to come: an untouched plan there reads as nothing lifted (lib/lifts.js // `liftsDone`), so the owner's removal reaches it. On a done day gone by, its sets diff --git a/server/sharedsync.js b/server/sharedsync.js index 897a477..9081c1b 100644 --- a/server/sharedsync.js +++ b/server/sharedsync.js @@ -25,8 +25,11 @@ * are positional and re-minted by every edit (prescription.js `reindex`), so * they are never used for matching. An item that arrives without a uid (an * older app, a model revision that rebuilt the plan) takes the uid of the - * same-named item it replaces, if there is one. Logged lifts (`out.lifts`) - * already have uids (lib/lifts.js). + * same-named item it replaces IN ITS OWN BLOCK, if there is one, never one in + * another block (`stampPlan`, #105). An entry shared before uids existed is + * stamped by its own items on its first write, the same uids on both sides + * (`fnv` of where each row is). Logged lifts (`out.lifts`) already have uids + * (lib/lifts.js). * * THE RULE. Entries are last-write-wins as a whole, so any device can send back * an old list of exercises: a phone that has not pulled, a copy from before sync @@ -145,36 +148,95 @@ function shapeOf(data) { /* -------------------------------------------------------------- identity */ -/** Give every row a uid: its own, else the unclaimed uid of a same-named row in `ref`, else a new one. */ -function stampList(list, ref, keyOf) { - const own = new Set(list.map(x => x.uid).filter(Boolean)) - const pool = new Map() - for (const r of ref) { - if (!r?.uid || own.has(r.uid)) continue - const k = keyOf(r) - if (!pool.has(k)) pool.set(k, []) - pool.get(k).push(r.uid) +/* + * MATCHING ROWS WITHOUT A UID (#105). Every copy shared before sync identity + * existed has no uid anywhere, and a plan often has the same exercise in two + * blocks (Back squat in the main block and again in a circuit; "Round 1 of 3", + * "Round 2 of 3" with the same names). A row takes a uid from `ref` by where it + * IS: its block first (same place and name, then same name, then same place), + * then, inside the block that matched, an item in the same place with the same + * name, then one with the same name. Never an item from another block: matched + * across blocks, a write's numbers landed on the other block's exercise, and an + * exercise the runner marked was not found and was added a second time. + * Each pass runs over the whole list before the next, so a looser match never + * takes a uid a closer one wanted. A uid is used once (`claimed`). + */ +const nameOf = (x) => String(x?.name || '') +const BLOCK_TESTS = [ + (x, i, r, j) => i === j && nameOf(x) === nameOf(r), + (x, i, r) => nameOf(x) === nameOf(r), + (x, i, r, j) => i === j, +] +const ITEM_TESTS = BLOCK_TESTS.slice(0, 2) + +/** + * The uid for each of `list`: its own (the first row to carry it), else an + * unclaimed one of `ref`'s by the first of `tests` that matches, else a new + * one. `own` is every uid the plan already carries (never given to another + * row), `claimed` the uids handed out so far; both span the whole plan. + */ +function matchUids(list, ref, tests, own, claimed, placeOf = null) { + const uids = list.map(x => { + if (!x.uid || claimed.has(x.uid)) return null + claimed.add(x.uid) + return x.uid + }) + const free = (u) => u && !own.has(u) && !claimed.has(u) + for (const test of tests) { + list.forEach((x, i) => { + if (uids[i]) return + const j = ref.findIndex((r, k) => free(r?.uid) && test(x, i, r, k)) + if (j >= 0) { uids[i] = ref[j].uid; claimed.add(ref[j].uid) } + }) } - const seen = new Set() - let changed = false - const out = list.map(x => { - if (x.uid && !seen.has(x.uid)) { seen.add(x.uid); return x } - const uid = pool.get(keyOf(x))?.shift() || mintUid() - seen.add(uid) - changed = true - return { ...x, uid } + return uids.map((u, i) => { + if (u) return u + const at = placeOf && placeOf[i] + const m = free(at) ? at : mintUid() + claimed.add(m) + return m }) - return changed ? out : list +} + +/* + * A uid FROM WHERE A ROW IS, for a plan stamped with nothing stamped to match + * (#105): its block's name and how many blocks before it have that name, then + * its own name and how many before it in that block have that name. Both sides + * of a workout shared before uids derive the same uid for the same exercise, + * whichever of them is written first, without either reading the other; an + * exercise only one side has, or one moved, gets one of its own. + */ +function fnv(s) { + let h = 0x811c9dc5 + for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193) >>> 0 + return h.toString(36) +} +const occurrences = (list) => { + const n = new Map() + return list.map(x => { const k = nameOf(x); const c = n.get(k) || 0; n.set(k, c + 1); return `${k}#${c}` }) } function stampPlan(plan, ref) { const blocks0 = blocksOf(plan) - const blocks = stampList(blocks0, blocksOf(ref), b => String(b.name || '')) - const flat = blocks.flatMap(itemsOf) - const items = stampList(flat, blocksOf(ref).flatMap(itemsOf), it => String(it.name || '')) - if (blocks === blocks0 && items === flat) return plan - let i = 0 - return { ...plan, blocks: blocks.map(b => ({ ...b, items: itemsOf(b).map(() => items[i++]) })) } + const refBlocks = blocksOf(ref) + const derive = !refBlocks.some(b => b.uid || itemsOf(b).some(it => it.uid)) + const blockPlaces = occurrences(blocks0) + const ownBlocks = new Set(blocks0.map(b => b.uid).filter(Boolean)) + const ownItems = new Set(blocks0.flatMap(itemsOf).map(it => it.uid).filter(Boolean)) + const blockUids = matchUids(blocks0, refBlocks, BLOCK_TESTS, ownBlocks, new Set(), derive ? blockPlaces.map(p => `p${fnv(p)}`) : null) + const claimed = new Set() + let changed = false + const blocks = blocks0.map((b, bi) => { + const items0 = itemsOf(b) + const refItems = itemsOf(refBlocks.find(r => r.uid === blockUids[bi])) + const places = derive ? occurrences(items0).map(p => `p${fnv(`${blockPlaces[bi]}/${p}`)}`) : null + const uids = matchUids(items0, refItems, ITEM_TESTS, ownItems, claimed, places) + const items = items0.map((it, ii) => (it.uid === uids[ii] ? it : { ...it, uid: uids[ii] })) + if (b.uid === blockUids[bi] && items.every((it, ii) => it === items0[ii])) return b + changed = true + return { ...b, uid: blockUids[bi], items } + }) + return changed ? { ...plan, blocks } : plan } /** `data` with a uid on every block and plan item, matched against `ref` (what is stored). */ @@ -864,12 +926,20 @@ function onWrite(prev, next, ids, linksOf) { if (was && same(e, was)) continue const link = linksOf(e, was) if (!link) continue - const live = was && !was.deleted && isObj(was.data) ? was : null - // A copy takes the owner's uids for anything it has none for, so a write - // landing just as sync is switched on cannot mint uids of its own that the - // alignment would then see as different exercises. - const ref = link.ref ? { plan: { blocks: [...blocksOf(live?.data?.plan), ...blocksOf(link.ref.plan)] } } : live?.data - const sent = stampData(e.data, ref) + const was0 = was && !was.deleted && isObj(was.data) ? was : null + /* + * What is stored is stamped first, by its OWN items (#105): a copy takes the + * owner's uids where the owner's block and exercise are where its own are, so + * a write landing just as sync is switched on cannot mint uids that the + * alignment would then see as different exercises; anything else gets a new + * one. Then the write is matched against THAT, block by block. An entry + * shared before uids existed has none on either the stored copy or the one + * its device sends, and matched against nothing, every exercise the write + * had logged on read as missing from the stored plan and was added again. + * Its stamp is no more than any synced write already writes: uids and a base. + */ + const live = was0 && hasPlan(was0.data) ? { ...was0, data: stampData(was0.data, link.ref) } : was0 + const sent = stampData(e.data, live ? live.data : link.ref) let data = sent let intent = null // Only a write that expresses structural intent (`intentOf`) changes or carries structure. @@ -922,7 +992,10 @@ function receive(state, entryId, c, accept) { if (!e || e.deleted || e.kind !== 'daily' || !isObj(e.data) || !accept(e)) return state // Only synced links carry, so a copy that receives one is in step (`flagged`). const at = { date: e.date, today: c.today } - const data = flagged(c.align ? align(c.after, e.data, at) : carry(stampData(e.data, c.after), c.before, c.after, at), true) + // An entry with rows that have no uid yet takes them from what the sender had BEFORE its + // change (#105): that is the structure this side should match, a rename included. + const ref = Array.isArray(c.before?.plan) ? { plan: { blocks: c.before.plan } } : c.after + const data = flagged(c.align ? align(c.after, e.data, at) : carry(stampData(e.data, ref), c.before, c.after, at), true) const base = nextBase(entryId, e.data.syncBase, data) const out = { ...data } if (base) out.syncBase = base diff --git a/server/sharedsync.test.js b/server/sharedsync.test.js index b74d963..96dfc22 100644 --- a/server/sharedsync.test.js +++ b/server/sharedsync.test.js @@ -785,6 +785,125 @@ check('no receipt for a write whose structure did not count, or one last-write-w eq(kept.acks, {}, 'a write that did not land got a receipt') }) +/* + * #105: copies shared before uids existed. The seed's copies from Oct 13 to Oct 24 + * have no uid anywhere and no syncBase, on either side; one of them is three + * "Round N of 3" blocks with the same exercise names, and a plan can have Back + * squat in its main block and again in a circuit. A first write must never add, + * move or duplicate an exercise, and its numbers land on the exercise it wrote them on. + */ +const preUid = (o = {}) => ({ uid: undefined, ...o }) +const strip = (data) => ({ ...data, plan: planOf(data.plan.blocks.map(b => ({ ...b, uid: undefined, items: b.items.map(i => ({ ...i, uid: undefined })) }))) }) +const squatDay = (extra = {}) => ({ + optId: 'planned', done: false, ...extra, + plan: planOf([ + preUid({ name: 'Main', items: [lift(undefined, 'Back squat', [set({ reps: 5 }), set({ reps: 5 }), set({ reps: 5 })]), lift(undefined, 'Romanian deadlift', [set({ reps: 8 })])] }), + preUid({ name: 'Finisher', circuit: { work: 40, rest: 20, rounds: 3 }, items: [lift(undefined, 'Back squat', [set()]), lift(undefined, 'Lunge', [set()])] }), + ]), +}) +const roundsDay = (extra = {}) => { + const round = (n) => preUid({ name: `Round ${n} of 3`, items: ['Crunch', 'Rest / transition', 'Dead bug', 'Rest / transition'].map(nm => ({ ...lift(undefined, nm, [set({ seconds: 40 })]), kind: 'interval' })) }) + return { optId: 'planned', done: false, ...extra, plan: planOf([preUid({ name: 'Warm-up', items: [] }), round(1), round(2), round(3)]) } +} +const ownerOf = (data) => ({ ...data, sharedWith: [{ id: 'sam', entryId: 'd', sync: true }] }) +const copyOf = (data) => ({ ...data, sharedFrom: { id: 'owner', name: 'Alex' } }) +/** One write through onWrite: the stored entry, the same entry as its device sends it after `change`. */ +const firstWrite = (stored, change, linksOf) => { + const was = { id: 'd', kind: 'daily', date: '2026-10-22', updatedAt: '2026-10-22T10:00:00.000Z', data: stored } + const sent = JSON.parse(JSON.stringify(stored)) + change(sent) + const r = onWrite({ entries: { d: was } }, { entries: { d: { ...was, updatedAt: '2026-10-22T10:05:00.000Z', data: sent } } }, ['d'], linksOf) + return { ...r, got: r.state.entries.d.data, sent } +} +const shapeNames = (data) => data.plan.blocks.map(b => `${b.name}[${b.items.map(i => `${i.name}:${i.sets.length}`).join(',')}]`) +const ownerLinks = () => ({ wasSynced: true, to: [{ personId: 'sam', entryId: 'd' }] }) +const copyLinks = (ownerData) => () => ({ wasSynced: true, ref: ownerData, to: [{ ownerEntryId: 'd' }] }) + +check('pre-uid copies (#105): the runner\'s first write marks Back squat in its own block, and adds nothing, on either side', () => { + for (const [side, stored, links] of [ + ['owner', ownerOf(squatDay()), ownerLinks], + ['Sam', copyOf(squatDay()), copyLinks(ownerOf(squatDay()))], + ]) { + const { got, carries } = firstWrite(stored, d => { d.run = { sets: { b0i0s0: { reps: 5, weight: 60 } }, cursor: 'b0i0s1' } }, links) + eq(shapeNames(got), shapeNames(stored), `${side}: the structure changed`) + eq(got.run.sets, { b0i0s0: { reps: 5, weight: 60 } }, `${side}: the mark left the main block's Back squat`) + eq(carries.length, 0, `${side}: a numbers-only write carried`) + ok(got.plan.blocks.every(b => b.uid) && got.plan.blocks.flatMap(b => b.items).every(i => i.uid), `${side}: not stamped`) + eq(got.syncBase.rev, 1, `${side}: no base written`) + } +}) + +check('pre-uid copies (#105): a number typed on the sheet lands on the exercise it was typed into, on either side', () => { + for (const [side, stored, links] of [ + ['owner', ownerOf(squatDay()), ownerLinks], + ['Sam', copyOf(squatDay()), copyLinks(ownerOf(squatDay()))], + ]) { + const { got } = firstWrite(stored, d => { Object.assign(d.plan.blocks[0].items[0].sets[0], { weight: 40, typed: true }) }, links) + eq(shapeNames(got), shapeNames(stored), `${side}: the structure changed`) + eq(got.plan.blocks.map(b => b.items.map(i => i.sets.map(s => s.weight))), [[[40, null, null], [null]], [[null], [null]]], `${side}: the typed 40 was lost or moved`) + ok(got.plan.blocks[0].items[0].sets[0].typed, `${side}: lost its typed mark`) + } +}) + +check('pre-uid copies (#105): the seed\'s three rounds with the same names, a mark and a typed number stay in their round', () => { + for (const [side, stored, links] of [ + ['owner', ownerOf(roundsDay()), ownerLinks], + ['Sam', copyOf(roundsDay()), copyLinks(ownerOf(roundsDay()))], + ]) { + const { got } = firstWrite(stored, d => { + d.run = { sets: { b2i0s0: { seconds: 40 } }, cursor: 'b2i1s0' } + Object.assign(d.plan.blocks[3].items[2].sets[0], { seconds: 35, typed: true }) + }, links) + eq(shapeNames(got), shapeNames(stored), `${side}: the structure changed`) + eq(Object.keys(got.run.sets), ['b2i0s0'], `${side}: the mark moved to another round`) + eq(got.plan.blocks.map(b => b.items.map(i => i.sets[0].seconds)), [[], [40, 40, 40, 40], [40, 40, 40, 40], [40, 40, 35, 40]], `${side}: a number landed in another round`) + // Every exercise has a uid of its own: none is shared across rounds. + const uids = got.plan.blocks.flatMap(b => b.items.map(i => i.uid)) + eq(new Set(uids).size, uids.length, `${side}: two exercises took one uid`) + } +}) + +check('pre-uid copies (#105): the first write is no more than a normal synced write: uids and a base on what was sent', () => { + const stored = copyOf(squatDay()) + const { got, sent } = firstWrite(stored, d => { Object.assign(d.plan.blocks[0].items[0].sets[0], { weight: 40, typed: true }); d.out = { rpe: 7 } }, copyLinks(ownerOf(squatDay()))) + const { syncBase: _b, ...rest } = got + const noUids = (x) => JSON.parse(JSON.stringify(x), (k, v) => (k === 'uid' ? undefined : v)) + eq(noUids(rest), noUids(sent), 'the write rewrote more than uids and the base') +}) + +check('pre-uid copies (#105): whichever side is written first, both sides stamp the same uids, and a later change crosses once', () => { + // Sam writes first: the owner's entry is still unstamped, so there is nothing to take uids from. + const samFirst = firstWrite(copyOf(squatDay()), d => { d.run = { sets: { b0i0s0: { reps: 5 } } } }, copyLinks(ownerOf(squatDay()))).got + const ownerAfter = firstWrite(ownerOf(squatDay()), d => { d.run = { sets: { b0i1s0: { reps: 8 } } } }, ownerLinks).got + const uidsOf = (data) => data.plan.blocks.map(b => [b.uid, b.items.map(i => i.uid)]) + eq(uidsOf(samFirst), uidsOf(ownerAfter), 'the two sides minted different uids for the same exercises') + // The owner, now up to date, takes the circuit's Back squat out and adds a Step-up; Sam's side follows, nothing doubled. + const stored = { id: 'd', kind: 'daily', date: '2026-10-22', updatedAt: '2026-10-22T11:00:00.000Z', data: ownerAfter } + const sent = edit(ownerAfter, bs => { bs[1].items.splice(0, 1); bs[1].items.push(lift(undefined, 'Step-up', [set()])); return bs }) + const r = onWrite({ entries: { d: stored } }, { entries: { d: { ...stored, updatedAt: '2026-10-22T11:05:00.000Z', data: { ...sent, syncBase: ownerAfter.syncBase } } } }, ['d'], ownerLinks) + eq(r.carries.length, 1) + // On a day still to come, so nothing on Sam's side reads as lifted (`liftedOf`) and the removal follows. + const st = receive({ entries: { d: { id: 'd', kind: 'daily', date: '2026-10-22', updatedAt: '2026-10-22T10:05:00.000Z', data: samFirst } } }, 'd', { ...r.carries[0], today: '2026-10-20' }, e => Boolean(e.data.sharedFrom)) + eq(shapeNames(st.entries.d.data), ['Main[Back squat:3,Romanian deadlift:1]', 'Finisher[Lunge:1,Step-up:1]']) + eq(st.entries.d.data.run.sets, { b0i0s0: { reps: 5 } }, 'Sam\'s mark moved') +}) + +check('pre-uid copies (#105): a uid is never taken from another block, even where the names match', () => { + // Stored and stamped. A device from before uids took the main block's Back squat out, offline. + const stored = stampData(squatDay()) + const [mainSquat, circuitSquat] = [stored.plan.blocks[0].items[0].uid, stored.plan.blocks[1].items[0].uid] + const device = edit(strip(stored), bs => { bs[0].items.splice(0, 1); return bs }) + const stamped = stampData(device, stored) + eq(stamped.plan.blocks[1].items[0].uid, circuitSquat, 'the circuit\'s Back squat lost its uid') + ok(!stamped.plan.blocks.flatMap(b => b.items).some(i => i.uid === mainSquat), 'the main block\'s uid was given to an exercise in another block') + // And on receive: an unstamped copy takes the sender's uids by block, not by name across the plan. + const copy = { id: 'd', kind: 'daily', date: '2026-10-22', updatedAt: '2026-10-22T10:00:00.000Z', data: copyOf(edit(squatDay(), bs => { bs[0].items.splice(0, 1); return bs })) } + const after = edit(stored, bs => { bs[1].items[1] = { ...bs[1].items[1], name: 'Walking lunge' }; return bs }) + const st = receive({ entries: { d: copy } }, 'd', { before: shapeOf(stored), after }, e => Boolean(e.data.sharedFrom)) + eq(shapeNames(st.entries.d.data), ['Main[Romanian deadlift:1]', 'Finisher[Back squat:1,Walking lunge:1]']) + eq(st.entries.d.data.plan.blocks[1].items[0].uid, circuitSquat) +}) + check('only links with sync on are synced; older shares are not', () => { const e = { id: 'daily-1', data: { sharedWith: [{ id: 'sam', entryId: 'daily-1', sync: true }, { id: 'robin', entryId: 'daily-1' }] } } eq(syncedLinks(e), [{ id: 'sam', entryId: 'daily-1' }])