diff --git a/api/coach/validate.js b/api/coach/validate.js index 17ff2b3..02e8d16 100644 --- a/api/coach/validate.js +++ b/api/coach/validate.js @@ -219,12 +219,12 @@ export function validateReview(data, plan) { ...(isInt(target.weekday, 0, 6) ? { weekday: target.weekday } : {}) }, why: clampStr(c.why, 600), - before: c.before ?? null, + before: currentOf(c.type, routine, planned, plan, target), after: c.after ?? null }; - // Per-type checks on `after`. `before` is informational here — the client verifies it - // against the live plan at apply time, which is where staleness actually matters. + // Per-type checks on `after`. `before` is not checked because it is not taken: it is read + // off the plan above, which is the only copy either side should trust. switch (c.type) { case 'add-exercise': { const a = c.after || {}; @@ -295,8 +295,12 @@ export function validateReview(data, plan) { const order = Array.isArray(c.after) ? c.after : null; if (!order) { errors.push(`${where}.after must be an array of exercise ids in the new order`); return; } const have = (routine.ex || []).map(e => e.id); - if (order.length !== have.length || order.some(id => !have.includes(id))) { - errors.push(`${where}.after must list exactly the ${have.length} exercise ids already in "${routine.name}", reordered`); return; + // Same ids, each exactly once. Length plus membership is not enough: a list that names + // one exercise twice and omits another satisfies both, and a reorder is the one change + // type with nothing to show in the diff column — so it deletes an exercise on apply + // with no way for the person approving it to see that it would. + if (order.length !== have.length || new Set(order).size !== order.length || order.some(id => !have.includes(id))) { + errors.push(`${where}.after must list exactly the ${have.length} exercise ids already in "${routine.name}", each once, reordered`); return; } out.after = order; break; @@ -304,6 +308,9 @@ export function validateReview(data, plan) { case 'superset': { const a = c.after || {}; if (a.link && !isStr(a.with)) { errors.push(`${where}.after.with is required when linking a superset`); return; } + // Supersetting something with itself resolves to a real exercise and passes the + // membership check below; the apply path then moves the anchor out from under itself. + if (a.link && a.with === target.exId) { errors.push(`${where} supersets an exercise with itself`); return; } if (a.link && !(routine.ex || []).some(e => e.id === a.with)) { errors.push(`${where}.after.with "${a.with}" is not in routine "${routine.name}"`); return; } out.after = { link: !!a.link, ...(a.link ? { with: a.with } : {}) }; break; @@ -311,7 +318,14 @@ export function validateReview(data, plan) { case 'add-routine': { const a = c.after || {}; if (!isStr(a.name)) { errors.push(`${where}.after.name is required`); return; } - const ex = (Array.isArray(a.ex) ? a.ex : []).filter(e => e && isStr(e.id) && libraryHas(e.id)).slice(0, MAX_EX_PER_ROUTINE); + // FR-16 again, and for the same reason it applies to a created plan: an id that + // resolves to nothing invalidates the proposal. Filtering it out instead would build + // the routine the model asked for minus the exercises it could not have, and hand that + // to someone as if it were what they were shown. + const listed = Array.isArray(a.ex) ? a.ex : []; + const bad = listed.find(e => !e || !isStr(e.id) || !libraryHas(e.id)); + if (bad) { errors.push(`${where}.after.ex "${bad.id}" is not in the exercise library — use an id from the library provided in the payload`); return; } + const ex = listed.slice(0, MAX_EX_PER_ROUTINE); if (!ex.length) { errors.push(`${where}.after.ex must list at least one exercise from the library`); return; } const odd = ex.find(e => e.side && isInt(e.reps, 1, 100) && e.reps % 2); if (odd) { errors.push(ODD_PER_SIDE(`${where}.after.ex "${odd.id}"`)); return; } @@ -369,4 +383,31 @@ export function validateReview(data, plan) { }; } +/** + * What the plan says right now for whatever a change is about — the `before` the client checks + * for staleness. Read off the plan rather than copied from the answer, because the model's idea + * of the current value is the one field on a change that nothing else constrains: an object of + * any size passes through into the proposal and then into the synced Coach log, and a merely + * mistyped one ("3 sets" where the plan holds 3) makes markStale() disable a change that was + * perfectly good. The plan is already in scope here, and it is not a matter of opinion. + * + * Mirrors `currentValue` in frontend/src/lib/coach.js — structural changes have no single + * scalar to compare and get null, which that function reads as "nothing to check". + */ +function currentOf(type, routine, planned, plan, target) { + switch (type) { + case 'sets': return planned?.sets ?? null; + case 'reps': return planned?.reps ?? null; + case 'repsMin': return planned?.repsMin ?? null; + case 'repsMax': return planned?.repsMax ?? null; + case 'sec': return planned?.sec ?? null; + case 'inc': return planned?.inc ?? null; + case 'exercise-prog': return planned?.prog ?? null; + case 'routine-prog': return routine?.prog ?? null; + case 'rename-routine': return routine?.name ?? null; + case 'week': return plan?.week?.[target?.weekday] ?? null; + default: return null; + } +} + function fail(errors) { return { ok: false, errors }; } diff --git a/api/test/validate.test.js b/api/test/validate.test.js index dbb2066..7b54070 100644 --- a/api/test/validate.test.js +++ b/api/test/validate.test.js @@ -187,6 +187,47 @@ test('a reorder must be a permutation of what is already there', () => { assert.equal(review([change({ type: 'reorder', target: { routineId: 'r1' }, after: ['0007', '0001'] })]).ok, true); assert.equal(review([change({ type: 'reorder', target: { routineId: 'r1' }, after: ['0007'] })]).ok, false, 'dropping one is not a reorder'); assert.equal(review([change({ type: 'reorder', target: { routineId: 'r1' }, after: ['0007', '0009'] })]).ok, false, 'nor is smuggling one in'); + // The one that satisfies both a length check and a membership check while still deleting an + // exercise — and reorder is the change type the review screen shows no diff for. + assert.equal(review([change({ type: 'reorder', target: { routineId: 'r1' }, after: ['0001', '0001'] })]).ok, false, 'naming one twice drops the other'); +}); + +test('a superset needs a partner that is not itself', () => { + assert.equal(review([change({ type: 'superset', after: { link: true, with: '0007' } })]).ok, true); + assert.equal(review([change({ type: 'superset', after: { link: true, with: '0001' } })]).ok, false, 'the anchor cannot be its own partner'); + assert.equal(review([change({ type: 'superset', after: { link: false } })]).ok, true, 'unlinking needs no partner'); +}); + +test('a new routine is refused whole when it names an exercise nobody has', () => { + const withEx = ex => review([change({ type: 'add-routine', target: {}, after: { name: 'C', ex } })]); + assert.equal(withEx([{ id: '0001', sets: 3, reps: 10 }]).ok, true); + // Not trimmed to the exercises that did resolve: that would hand someone a routine they were + // never shown, under the summary of the one they were. + const r = withEx([{ id: '0001', sets: 3, reps: 10 }, { id: 'not-a-real-exercise', sets: 3, reps: 10 }]); + assert.equal(r.ok, false); + assert.match(r.errors.join(' '), /not-a-real-exercise/, 'and the repair round is told which one'); +}); + +test('before is read off the plan, never taken from the answer', () => { + // Unchecked in every other respect: the model can say anything here, and whatever it says + // reaches the synced Coach log and the staleness check that decides what stays applicable. + const huge = { junk: 'x'.repeat(100000) }; + const r = review([change({ type: 'sets', before: huge, after: 4 })]); + assert.equal(r.ok, true); + assert.equal(r.proposal.changes[0].before, 3, 'the plan says 3 sets, so before is 3'); + + // A merely mistyped before is the same bug wearing a smaller hat: it survives validation and + // then silently disables the change, because markStale compares it against a number. + const typed = review([change({ type: 'sets', before: '3 sets', after: 4 })]); + assert.equal(typed.proposal.changes[0].before, 3); + + // Structural changes have no scalar to compare; null is what the client reads as "skip". + const structural = review([change({ type: 'reorder', target: { routineId: 'r1' }, before: 'anything', after: ['0007', '0001'] })]); + assert.equal(structural.proposal.changes[0].before, null); + + // And a field the plan does not carry reads as absent rather than as the model's guess. + const absent = review([change({ type: 'inc', before: 2.5, after: 5 })]); + assert.equal(absent.proposal.changes[0].before, null); }); test('a week change may only schedule a routine that exists, rest, or nothing', () => { diff --git a/frontend/src/lib/coach.js b/frontend/src/lib/coach.js index b97c1b6..e09d2b2 100644 --- a/frontend/src/lib/coach.js +++ b/frontend/src/lib/coach.js @@ -307,7 +307,10 @@ const CHANGE_APPLY = { const r = need(findRoutine(s, c.target.routineId)) const by = new Map(r.ex.map(e => [e.id, e])) const next = c.after.map(id => by.get(id)).filter(Boolean) - if (next.length !== r.ex.length) throw new Error('incomplete reorder') + // Distinct exercises, not just the right count: an order naming one id twice maps to the + // same object twice and still counts right, which drops an exercise and leaves the + // survivor aliased into two slots that then edit each other. + if (next.length !== r.ex.length || new Set(next).size !== r.ex.length) throw new Error('incomplete reorder') r.ex = next cleanupSg(r.ex) }, @@ -316,6 +319,9 @@ const CHANGE_APPLY = { const i = r.ex.findIndex(e => e.id === c.target.exId) if (i < 0) throw new Error('missing exercise') if (!c.after?.link) { delete r.ex[i].sg; cleanupSg(r.ex); return } + // Splicing the partner out from under the anchor when they are the same exercise leaves + // nothing to tag; refuse rather than reorder the routine on the way to a TypeError. + if (c.after.with === c.target.exId) throw new Error('superset with itself') const j = r.ex.findIndex(e => e.id === c.after.with) if (j < 0) throw new Error('missing partner') // Supersets are a property of adjacency in this app; move the partner next to it first. diff --git a/frontend/src/lib/coach.test.js b/frontend/src/lib/coach.test.js index 49349dd..e2f048a 100644 --- a/frontend/src/lib/coach.test.js +++ b/frontend/src/lib/coach.test.js @@ -208,6 +208,21 @@ describe('applying changes', () => { const out = apply(state(), proposal([change({ type: 'reorder', target: { routineId: 'r1' }, after: ['0009', '0001', '0007'] })]), ['c1']) expect(out.routines[0].ex.map(e => e.id)).toEqual(['0009', '0001', '0007']) expect(() => apply(state(), proposal([change({ type: 'reorder', target: { routineId: 'r1' }, after: ['0009'] })]), ['c1'])).toThrow() + // A repeated id counts right and resolves to the same object twice: the third exercise + // disappears and the survivor is aliased into two slots. Both gates have to catch this, + // because it is the one change type with nothing in the diff column to give it away. + expect(() => apply(state(), proposal([change({ + type: 'reorder', target: { routineId: 'r1' }, after: ['0009', '0009', '0001'] + })]), ['c1'])).toThrow() + }) + + it('refuses to superset an exercise with itself', () => { + // Reachable only if the server let it past. By the message, not merely by throwing: the + // unfixed path also threw — a TypeError, after it had already moved the exercise — so + // asserting "it throws" would pass against the bug this is here to pin. + expect(() => apply(state(), proposal([change({ + type: 'superset', after: { link: true, with: '0001' } + })]), ['c1'])).toThrow('superset with itself') }) it('supersets by moving the partner adjacent and tagging both', () => {