Coach: the validator, and the apply path it exists to protect
PR 1 stopped at transport and held every answer as `unvalidated`. This closes that seam. validate.js is the gate: a closed list of eighteen change types with no default case, every exercise id resolved against the real catalogue, every target resolved against the plan it claims to be about, and a rationale required on every change. A hostile note in someone's free text can talk a model into saying anything at all; it cannot invent a change type. Its errors join the parse failures on the same single repair round, so a model that named an exercise nobody has is told which one — and a model that cannot be told is a failed job rather than a retry loop. frontend/src/lib/coach.js is the other half: snapshot, apply, revert, and the staleness rules. Applying happens on the client because it is ordinary local editing — offline, synced like everything else, reversible without the server knowing. A change-set is all-or-nothing, and a change aimed at something the user has since edited by hand is disabled with its reason rather than silently overwriting them. Two things the seam was hiding, both from PR 1: hashPlan hashed the pre-1.2.4 field list while canonicalPlan had already learned repsMax, bodyweight and side — so it computed all three and threw them away. A rep ceiling raised by hand fingerprinted as an untouched plan, on exactly the exercises where that ceiling is how progression works. Both runtimes now hash what canonicalPlan reports, with a test per field. `refine` reads pending.bundle, and pending only ever carried `unvalidated`, so `previous` resolved to null every time: the model was asked to refine a plan it had never been shown. It works now, and the fixture echoes whether the previous bundle arrived so a test can tell the difference. The validator also enforces the two rules prompts/common.md states and could not guarantee: unilateral reps are a total across both sides and must be even, and a rep ceiling may not sit below its own floor. "Nothing to change" keeps the reading it came with, on the profile's own record — deliberately not in the instance log, which stays counts and outcomes only. api 65/65, frontend 403/403, build clean, locales in sync, library in sync at 1324 exercises. No new dependency. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
de7f25cbe7
commit
34d41b8e64
10 files changed
+1726
-30
No files matched your search
@@ -0,0 +1,446 @@
|
||||
// The AI Coach, on the client side: everything that decides what a proposal *does* to a plan.
|
||||
//
|
||||
// The server produces proposals; it never writes into your state. Applying one is ordinary
|
||||
// local editing — snapshot, mutate the draft, log — which is what makes it work offline, sync
|
||||
// like every other change, and stay reversible without the server knowing anything about it.
|
||||
//
|
||||
// Every function here is pure over a draft state `s` (call them inside store.update), so the
|
||||
// interesting parts are testable without a browser, a server or an AI account. That matters
|
||||
// more here than elsewhere in the app: this is the code that edits a plan on the strength of
|
||||
// something a language model said, and "it looked right on my phone" is not a standard.
|
||||
//
|
||||
// The screens that call it arrive in PR 4. Nothing in this file needs one to be tested, which
|
||||
// is the point of it being separate from them.
|
||||
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { modeOf, isBw, isPerSide, cleanupSg } from './history.js'
|
||||
import { uid } from './format.js'
|
||||
import { mergePlan } from './plan-share.js'
|
||||
import { POLICIES } from './progression.js'
|
||||
import { t } from './i18n.js'
|
||||
|
||||
// Bumping this re-prompts everyone: it means what we share, or who we share it with, changed.
|
||||
export const CONSENT_VERSION = 1
|
||||
|
||||
// Bounds. The whole state has to stay inside the server's 5 MB body limit, and a Coach log
|
||||
// that grows forever is exactly the kind of thing that eats it invisibly. Worst case here is
|
||||
// ~75 KB; the namespace guard is the backstop for the case nobody predicted.
|
||||
export const SNAPSHOT_MAX = 3
|
||||
export const LOG_MAX = 50
|
||||
const NAMESPACE_MAX = 256 * 1024
|
||||
|
||||
export const emptyCoach = () => ({
|
||||
consent: null, profile: null, cadence: 'off', lastReview: null, log: [], snapshots: []
|
||||
})
|
||||
const coachOf = s => (s.coach = s.coach || emptyCoach())
|
||||
|
||||
/* ============================ gating ============================ */
|
||||
|
||||
// One predicate, one place. Every Coach entry point in the UI is behind it, which is what
|
||||
// makes "an instance with no provider is byte-identical to before" a claim worth testing.
|
||||
//
|
||||
// The demo build is the one exception, and it is deliberate: it has no backend and no
|
||||
// account, but it does have a canned provider, and hiding the app's most interesting feature
|
||||
// from the page people are sent to look at it on would be a strange choice. The mobile build
|
||||
// stays out — there is no server there to fake anything with.
|
||||
export const coachAvailable = (config, user, { demo, mobile } = {}) =>
|
||||
mobile ? false : demo ? true : !!(config?.coach?.enabled && user)
|
||||
export const hasConsent = S => !!S?.coach?.consent?.agreedAt && S.coach.consent.version === CONSENT_VERSION
|
||||
|
||||
/* ============================ plan fingerprint ============================ */
|
||||
|
||||
/**
|
||||
* Mirror of `canonicalPlan` in api/coach/payload.js — field for field, including the rule
|
||||
* that every absent value is written out as a zero so "no weight" and "0 kg" cannot hash
|
||||
* apart, and that `bodyweight`/`side` are *resolved* against the catalogue rather than copied,
|
||||
* so a plan that says nothing and an exercise the dataset already calls bodyweight hash the
|
||||
* same. If you change one, change both; coach.test.js checks them against shared fixtures.
|
||||
*/
|
||||
export function canonicalPlan(S) {
|
||||
return {
|
||||
routines: (S.routines || []).map(r => ({
|
||||
id: r.id, name: r.name || '', prog: r.prog || '',
|
||||
ex: (r.ex || []).map(e => {
|
||||
const mode = modeOf(e)
|
||||
return {
|
||||
id: e.id, mode, sets: e.sets || 0,
|
||||
reps: mode === 'reps' ? (e.reps || 0) : 0,
|
||||
sec: mode === 'time' ? (e.sec || 0) : 0,
|
||||
min: mode === 'cardio' ? (e.min || 0) : 0,
|
||||
speed: mode === 'cardio' ? (e.speed || 0) : 0,
|
||||
weight: mode === 'cardio' ? 0 : (e.weight || 0),
|
||||
prog: e.prog || '', inc: e.inc || 0, repsMin: e.repsMin || 0, repsMax: e.repsMax || 0,
|
||||
bodyweight: isBw(e), side: isPerSide(e),
|
||||
sg: e.sg || ''
|
||||
}
|
||||
})
|
||||
})),
|
||||
week: Object.fromEntries([1, 2, 3, 4, 5, 6, 0].filter(d => S.week?.[d]).map(d => [d, S.week[d]]))
|
||||
}
|
||||
}
|
||||
|
||||
/** FNV-1a-ish 64-bit fingerprint. Mirror of hashPlan in api/coach/jobs.js. */
|
||||
export function hashPlan(plan) {
|
||||
const canon = JSON.stringify({
|
||||
routines: (plan?.routines || []).map(r => [r.id, r.name, r.prog, (r.ex || []).map(e =>
|
||||
[e.id, e.mode, e.sets, e.reps, e.sec, e.min, e.speed, e.weight, e.prog, e.inc,
|
||||
e.repsMin, e.repsMax, e.bodyweight, e.side, e.sg].join(':')
|
||||
)]),
|
||||
week: Object.keys(plan?.week || {}).sort().map(k => k + '=' + plan.week[k])
|
||||
})
|
||||
let h1 = 0x811c9dc5, h2 = 0x01000193
|
||||
for (let i = 0; i < canon.length; i++) {
|
||||
const c = canon.charCodeAt(i)
|
||||
h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0
|
||||
h2 = Math.imul(h2 ^ ((c << 3) | i & 7), 0x85ebca6b) >>> 0
|
||||
}
|
||||
return h1.toString(16).padStart(8, '0') + h2.toString(16).padStart(8, '0')
|
||||
}
|
||||
export const planHash = S => hashPlan(canonicalPlan(S))
|
||||
|
||||
/* ============================ staleness ============================ */
|
||||
|
||||
const findRoutine = (S, id) => (S.routines || []).find(r => r.id === id) || null
|
||||
const findEx = (routine, id) => (routine?.ex || []).find(e => e.id === id) || null
|
||||
|
||||
/** The plan's current value for whatever a change is about — what `before` is checked against. */
|
||||
export function currentValue(S, change) {
|
||||
const r = findRoutine(S, change.target?.routineId)
|
||||
const e = change.target?.exId ? findEx(r, change.target.exId) : null
|
||||
switch (change.type) {
|
||||
case 'sets': return e?.sets ?? null
|
||||
case 'reps': return e?.reps ?? null
|
||||
case 'repsMin': return e?.repsMin ?? null
|
||||
case 'repsMax': return e?.repsMax ?? null
|
||||
case 'sec': return e?.sec ?? null
|
||||
case 'inc': return e?.inc ?? null
|
||||
case 'exercise-prog': return e?.prog ?? null
|
||||
case 'routine-prog': return r?.prog ?? null
|
||||
case 'rename-routine': return r?.name ?? null
|
||||
case 'week': return S.week?.[change.target?.weekday] ?? null
|
||||
default: return undefined // structural changes have no single scalar to compare
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark what can no longer be applied. Two independent checks, because they fail differently:
|
||||
* the whole proposal is stale when the plan has moved since it was computed, and an individual
|
||||
* change is stale when the thing it names is gone or has already been changed by hand.
|
||||
*
|
||||
* A stale change is disabled, never silently skipped — someone who edited their plan on
|
||||
* another device should be told why the suggestion is greyed out.
|
||||
*/
|
||||
export function markStale(proposal, S) {
|
||||
if (!proposal) return proposal
|
||||
const planMoved = !!proposal.planHash && proposal.planHash !== planHash(S)
|
||||
const changes = (proposal.changes || []).map(c => {
|
||||
const r = c.target?.routineId ? findRoutine(S, c.target.routineId) : null
|
||||
let stale = false
|
||||
if (c.type !== 'add-routine' && c.type !== 'week' && !r) stale = true
|
||||
else if (c.target?.exId && !findEx(r, c.target.exId)) stale = true
|
||||
else {
|
||||
const cur = currentValue(S, c)
|
||||
// `before` is what the Coach saw. If the live plan disagrees, someone has already
|
||||
// changed it — applying would silently overwrite their edit with a stale premise.
|
||||
if (cur !== undefined && c.before != null && cur !== c.before && cur !== null) stale = true
|
||||
}
|
||||
return { ...c, status: stale ? 'stale' : (c.status === 'stale' ? 'proposed' : c.status || 'proposed') }
|
||||
})
|
||||
return { ...proposal, planMoved, changes }
|
||||
}
|
||||
export const applicable = proposal => (proposal?.changes || []).filter(c => c.status !== 'stale')
|
||||
|
||||
/* ============================ validation ============================ */
|
||||
|
||||
/** Client-side mirror of the server's gate — the plan must survive a bad day at either end. */
|
||||
export function validateProposal(p) {
|
||||
if (!p || typeof p !== 'object') throw new Error(t('That proposal can’t be read.'))
|
||||
if (p.bundle) {
|
||||
if (!Array.isArray(p.bundle.routines) || !p.bundle.routines.length) throw new Error(t('That proposal can’t be read.'))
|
||||
return true
|
||||
}
|
||||
if (!Array.isArray(p.changes)) throw new Error(t('That proposal can’t be read.'))
|
||||
for (const c of p.changes) {
|
||||
if (!CHANGE_APPLY[c.type]) throw new Error(t('That proposal can’t be read.'))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/* ============================ snapshots & revert ============================ */
|
||||
|
||||
const clone = o => JSON.parse(JSON.stringify(o))
|
||||
|
||||
/** Snapshot `{routines, week}` before touching either. The unit of revert (FR-30/31). */
|
||||
export function pushSnapshot(s, proposalId, label) {
|
||||
const c = coachOf(s)
|
||||
c.snapshots = [...(c.snapshots || []), {
|
||||
at: Date.now(), proposalId: proposalId || null, label: label || '',
|
||||
routines: clone(s.routines || []), week: clone(s.week || {})
|
||||
}].slice(-SNAPSHOT_MAX)
|
||||
trim(s)
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the plan back the way it was before the last applied change-set.
|
||||
*
|
||||
* Workouts are untouched, and that is not an oversight: the log is what happened. Reverting a
|
||||
* plan re-derives every future target from that same history, which is exactly what the
|
||||
* progression engine does anyway.
|
||||
*/
|
||||
export function revertLast(s) {
|
||||
const c = coachOf(s)
|
||||
const snap = (c.snapshots || []).pop()
|
||||
if (!snap) return false
|
||||
s.routines = clone(snap.routines)
|
||||
s.week = clone(snap.week)
|
||||
appendLog(s, { kind: 'revert', at: Date.now(), proposalId: snap.proposalId, summary: t('Reverted the last Coach changes.') })
|
||||
return true
|
||||
}
|
||||
export const canRevert = S => !!(S?.coach?.snapshots || []).length
|
||||
|
||||
/* ============================ the log ============================ */
|
||||
|
||||
export function appendLog(s, entry) {
|
||||
const c = coachOf(s)
|
||||
c.log = [...(c.log || []), { id: entry.id || uid(), ...entry }].slice(-LOG_MAX)
|
||||
trim(s)
|
||||
}
|
||||
|
||||
/**
|
||||
* Last line of defence for the 5 MB sync body: if the Coach namespace ever outgrows its
|
||||
* budget, drop the oldest history rather than let a PUT start failing for reasons nobody
|
||||
* would connect to this feature.
|
||||
*/
|
||||
function trim(s) {
|
||||
const c = coachOf(s)
|
||||
let guard = 0
|
||||
while (JSON.stringify(c).length > NAMESPACE_MAX && guard++ < 60) {
|
||||
if ((c.snapshots || []).length > 1) c.snapshots.shift()
|
||||
else if ((c.log || []).length > 1) c.log.shift()
|
||||
else break
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================ applying a created plan ============================ */
|
||||
|
||||
/**
|
||||
* Accepting a created plan is exactly importing a plan file (FR-18): routines arrive as new
|
||||
* ones with fresh ids, existing routines and history are never touched, and the week schedule
|
||||
* only moves if you asked it to.
|
||||
*/
|
||||
export function applyCreatedPlan(s, proposal, { schedule } = {}) {
|
||||
validateProposal(proposal)
|
||||
pushSnapshot(s, proposal.id, t('Before the Coach’s plan'))
|
||||
const bundle = proposal.bundle
|
||||
// The Coach's `why` texts are for the review screen; they have no place in the routine data.
|
||||
const stripped = {
|
||||
...bundle,
|
||||
routines: bundle.routines.map(r => ({ ...r, why: undefined, ex: r.ex.map(e => ({ ...e, why: undefined, name: undefined })) }))
|
||||
}
|
||||
const res = mergePlan(s, stripped, { schedule })
|
||||
appendLog(s, {
|
||||
kind: 'create', at: Date.now(), proposalId: proposal.id,
|
||||
summary: proposal.summary || '', routines: res.routines, iteration: proposal.iteration || 1
|
||||
})
|
||||
return res
|
||||
}
|
||||
|
||||
/* ============================ applying a change-set ============================ */
|
||||
|
||||
// One implementation per allowed type. The object is the closed list on this side of the
|
||||
// wire: a type with no entry here cannot be applied, whatever the server let through.
|
||||
const CHANGE_APPLY = {
|
||||
'add-exercise': (s, c) => {
|
||||
const r = need(findRoutine(s, c.target.routineId))
|
||||
const a = c.after || {}
|
||||
const e = { id: a.id, sets: a.sets || 3, mode: a.mode || 'reps' }
|
||||
if (e.mode === 'cardio') { e.min = a.min || 20; e.speed = a.speed || 8 }
|
||||
else if (e.mode === 'time') e.sec = a.sec || 45
|
||||
else e.reps = a.reps || 10
|
||||
if (a.weight > 0) e.weight = a.weight
|
||||
if (POLICIES.includes(a.prog)) e.prog = a.prog
|
||||
if (Number.isInteger(a.repsMin)) e.repsMin = a.repsMin
|
||||
if (Number.isInteger(a.repsMax)) e.repsMax = a.repsMax
|
||||
// Only when the Coach disagreed with the catalogue: an absent flag has always meant
|
||||
// "whatever the exercise says", and writing one out would freeze today's dataset into
|
||||
// the plan.
|
||||
if (a.bodyweight != null) e.bodyweight = !!a.bodyweight
|
||||
if (a.side) e.side = true
|
||||
const at = Number.isInteger(a.position) ? Math.min(a.position, r.ex.length) : r.ex.length
|
||||
r.ex.splice(at, 0, e)
|
||||
cleanupSg(r.ex)
|
||||
},
|
||||
'remove-exercise': (s, c) => {
|
||||
const r = need(findRoutine(s, c.target.routineId))
|
||||
r.ex = r.ex.filter(e => e.id !== c.target.exId)
|
||||
cleanupSg(r.ex)
|
||||
},
|
||||
'swap-exercise': (s, c) => {
|
||||
const r = need(findRoutine(s, c.target.routineId))
|
||||
const i = r.ex.findIndex(e => e.id === c.target.exId)
|
||||
if (i < 0) throw new Error('missing exercise')
|
||||
const old = r.ex[i], a = c.after || {}
|
||||
// Keep the old prescription unless the Coach deliberately changed it: a swap is about the
|
||||
// movement, and silently resetting sets and reps would be a second change nobody approved.
|
||||
//
|
||||
// The two v1.2.4 flags are the exception, and they have to be: they describe the *movement*,
|
||||
// not the prescription. Carrying `side: true` from a lunge onto a leg press would make the
|
||||
// app halve a rep count that was never per-side, so an explicit flag is dropped and the new
|
||||
// exercise goes back to whatever the catalogue says about it.
|
||||
const { bodyweight, side, ...keep } = old
|
||||
r.ex[i] = { ...keep, id: a.id, ...(a.sets ? { sets: a.sets } : {}), ...(a.reps ? { reps: a.reps } : {}), ...(a.weight > 0 ? { weight: a.weight } : {}) }
|
||||
},
|
||||
sets: (s, c) => { need(findExIn(s, c)).sets = c.after },
|
||||
reps: (s, c) => { need(findExIn(s, c)).reps = c.after },
|
||||
repsMin: (s, c) => { need(findExIn(s, c)).repsMin = c.after },
|
||||
repsMax: (s, c) => { need(findExIn(s, c)).repsMax = c.after },
|
||||
sec: (s, c) => { need(findExIn(s, c)).sec = c.after },
|
||||
cardio: (s, c) => {
|
||||
const e = need(findExIn(s, c))
|
||||
if (c.after?.min != null) e.min = c.after.min
|
||||
if (c.after?.speed != null) e.speed = c.after.speed
|
||||
},
|
||||
inc: (s, c) => { need(findExIn(s, c)).inc = c.after },
|
||||
'exercise-prog': (s, c) => { need(findExIn(s, c)).prog = c.after },
|
||||
'routine-prog': (s, c) => { need(findRoutine(s, c.target.routineId)).prog = c.after },
|
||||
reorder: (s, c) => {
|
||||
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')
|
||||
r.ex = next
|
||||
cleanupSg(r.ex)
|
||||
},
|
||||
superset: (s, c) => {
|
||||
const r = need(findRoutine(s, c.target.routineId))
|
||||
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 }
|
||||
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.
|
||||
const [partner] = r.ex.splice(j, 1)
|
||||
const at = r.ex.findIndex(e => e.id === c.target.exId)
|
||||
r.ex.splice(at + 1, 0, partner)
|
||||
const tag = uid().slice(0, 6)
|
||||
r.ex[at].sg = tag
|
||||
r.ex[at + 1].sg = tag
|
||||
},
|
||||
'add-routine': (s, c) => {
|
||||
const a = c.after
|
||||
s.routines.push({
|
||||
id: uid(), name: a.name, emoji: a.emoji || '🏋️',
|
||||
...(POLICIES.includes(a.prog) ? { prog: a.prog } : {}),
|
||||
ex: a.ex.map(e => ({
|
||||
id: e.id, sets: e.sets || 3, mode: e.mode || 'reps',
|
||||
...(e.mode === 'time' ? { sec: e.sec || 45 } : { reps: e.reps || 10 }),
|
||||
...(Number.isInteger(e.repsMax) ? { repsMax: e.repsMax } : {}),
|
||||
...(e.bodyweight != null ? { bodyweight: !!e.bodyweight } : {}),
|
||||
...(e.side ? { side: true } : {})
|
||||
}))
|
||||
})
|
||||
},
|
||||
'remove-routine': (s, c) => {
|
||||
const id = c.target.routineId
|
||||
s.routines = s.routines.filter(r => r.id !== id)
|
||||
// A week pointing at a routine that no longer exists reads as a rest day anyway; clearing
|
||||
// it keeps the plan honest rather than merely harmless.
|
||||
Object.keys(s.week || {}).forEach(d => { if (s.week[d] === id) delete s.week[d] })
|
||||
},
|
||||
'rename-routine': (s, c) => { need(findRoutine(s, c.target.routineId)).name = c.after },
|
||||
week: (s, c) => {
|
||||
const d = c.target.weekday
|
||||
if (c.after == null || c.after === 'rest') delete s.week[d]
|
||||
else s.week[d] = c.after
|
||||
}
|
||||
}
|
||||
export const CHANGE_TYPES = Object.keys(CHANGE_APPLY)
|
||||
|
||||
function findExIn(s, c) { return findEx(findRoutine(s, c.target.routineId), c.target.exId) }
|
||||
function need(x) { if (!x) throw new Error('missing target'); return x }
|
||||
|
||||
/**
|
||||
* Apply the accepted subset, atomically (FR-30).
|
||||
*
|
||||
* Atomic comes free from how the store works: `update()` hands us a throwaway clone and only
|
||||
* keeps it if we return normally. Throwing part-way through therefore discards every change
|
||||
* this function already made, which is precisely the transaction we want — no half-applied
|
||||
* change-set, ever.
|
||||
*/
|
||||
export function applyChangeSet(s, proposal, acceptedIds) {
|
||||
validateProposal(proposal)
|
||||
const accepted = new Set(acceptedIds || [])
|
||||
const changes = (proposal.changes || []).filter(c => accepted.has(c.id) && c.status !== 'stale')
|
||||
if (!changes.length) return { applied: 0 }
|
||||
|
||||
pushSnapshot(s, proposal.id, t('Before the Coach’s changes'))
|
||||
const applied = []
|
||||
for (const c of changes) {
|
||||
CHANGE_APPLY[c.type](s, c)
|
||||
applied.push({ id: c.id, type: c.type, target: c.target, before: c.before, after: c.after, why: c.why, status: 'accepted' })
|
||||
}
|
||||
const rejected = (proposal.changes || [])
|
||||
.filter(c => !accepted.has(c.id))
|
||||
.map(c => ({ id: c.id, type: c.type, why: c.why, status: 'rejected' }))
|
||||
|
||||
appendLog(s, {
|
||||
kind: 'review', at: Date.now(), proposalId: proposal.id,
|
||||
summary: proposal.summary || '', evidence: proposal.evidence || null,
|
||||
notes: proposal.notes || [], decisions: [...applied, ...rejected]
|
||||
})
|
||||
coachOf(s).lastReview = { at: Date.now() }
|
||||
return { applied: applied.length, rejected: rejected.length }
|
||||
}
|
||||
|
||||
/** Turned down whole, or expired: recorded so a later review knows not to re-propose it. */
|
||||
export function recordDismissal(s, proposal) {
|
||||
appendLog(s, {
|
||||
kind: proposal.kind === 'create' ? 'create' : 'review', at: Date.now(), proposalId: proposal.id,
|
||||
summary: proposal.summary || '', dismissed: true,
|
||||
decisions: (proposal.changes || []).map(c => ({ id: c.id, type: c.type, why: c.why, status: 'rejected' }))
|
||||
})
|
||||
if (proposal.kind !== 'create') coachOf(s).lastReview = { at: Date.now() }
|
||||
}
|
||||
|
||||
/* ============================ display helpers ============================ */
|
||||
|
||||
export const exName = id => EXIDX[id]?.n || t('Unknown exercise')
|
||||
|
||||
/** Human label for a change, used on the review screen and in the log. */
|
||||
export function changeTitle(c) {
|
||||
const ex = c.target?.exId ? exName(c.target.exId) : null
|
||||
switch (c.type) {
|
||||
case 'add-exercise': return t('Add {0}', exName(c.after?.id))
|
||||
case 'remove-exercise': return t('Drop {0}', ex)
|
||||
case 'swap-exercise': return t('Swap {0} for {1}', ex, exName(c.after?.id))
|
||||
case 'sets': return t('{0}: sets', ex)
|
||||
case 'reps': return t('{0}: reps', ex)
|
||||
case 'repsMin': return t('{0}: rep-range floor', ex)
|
||||
case 'repsMax': return t('{0}: rep-range ceiling', ex)
|
||||
case 'sec': return t('{0}: hold time', ex)
|
||||
case 'cardio': return t('{0}: duration & pace', ex)
|
||||
case 'inc': return t('{0}: load step', ex)
|
||||
case 'exercise-prog': return t('{0}: progression', ex)
|
||||
case 'routine-prog': return t('Routine progression')
|
||||
case 'reorder': return t('Reorder exercises')
|
||||
case 'superset': return c.after?.link ? t('Superset {0} with {1}', ex, exName(c.after.with)) : t('Unlink superset on {0}', ex)
|
||||
case 'add-routine': return t('Add routine “{0}”', c.after?.name)
|
||||
case 'remove-routine': return t('Remove a routine')
|
||||
case 'rename-routine': return t('Rename routine to “{0}”', c.after)
|
||||
case 'week': return t('Change what’s planned on one day')
|
||||
default: return c.type
|
||||
}
|
||||
}
|
||||
|
||||
/** Short before/after strings for the diff column. */
|
||||
export function changeValues(c) {
|
||||
const fmt = v => {
|
||||
if (v == null) return '—'
|
||||
if (typeof v === 'object') return v.id ? exName(v.id) : v.name || JSON.stringify(v)
|
||||
if (Array.isArray(v)) return v.length + ''
|
||||
return String(v)
|
||||
}
|
||||
if (['add-exercise', 'add-routine', 'reorder'].includes(c.type)) return null
|
||||
if (['remove-exercise', 'remove-routine'].includes(c.type)) return null
|
||||
return { before: fmt(c.before), after: fmt(c.after) }
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
canonicalPlan, planHash, hashPlan, markStale, applicable, currentValue,
|
||||
pushSnapshot, revertLast, canRevert, appendLog, applyChangeSet, applyCreatedPlan,
|
||||
recordDismissal, validateProposal, coachAvailable, hasConsent,
|
||||
CHANGE_TYPES, SNAPSHOT_MAX, LOG_MAX, CONSENT_VERSION
|
||||
} from './coach.js'
|
||||
import { registerCustom } from './exercises.js'
|
||||
|
||||
// The two runtimes share no build step, so the client's copy of the fingerprint logic is
|
||||
// checked against the server's actual source rather than against a transcribed expectation.
|
||||
import * as serverPayload from '../../../api/coach/payload.js'
|
||||
import { hashPlan as serverHashPlan } from '../../../api/coach/jobs.js'
|
||||
|
||||
const state = (over = {}) => ({
|
||||
unit: 'kg', lang: 'en', customEx: [], workouts: [], bodyweight: [], exWeights: {}, dayPlan: {},
|
||||
routines: [{
|
||||
id: 'r1', name: 'Full body A', emoji: '💪', prog: 'linear',
|
||||
ex: [
|
||||
{ id: '0001', sets: 3, reps: 10, mode: 'reps', weight: 20, prog: 'linear' },
|
||||
{ id: '0007', sets: 3, sec: 45, mode: 'time' },
|
||||
{ id: '0009', sets: 3, reps: 12, mode: 'reps' }
|
||||
]
|
||||
}, { id: 'r2', name: 'Full body B', ex: [{ id: '0002', sets: 4, reps: 6, mode: 'reps' }] }],
|
||||
week: { 1: 'r1', 3: 'r2', 5: 'r1' },
|
||||
coach: { consent: { agreedAt: '2026-07-01T00:00:00Z', version: CONSENT_VERSION }, log: [], snapshots: [], cadence: 'off' },
|
||||
...over
|
||||
})
|
||||
|
||||
const change = over => ({ id: 'c1', type: 'sets', target: { routineId: 'r1', exId: '0001' }, before: 3, after: 4, why: 'stalled twice', ...over })
|
||||
const proposal = (changes, over = {}) => ({ id: 'p1', kind: 'review', summary: 's', changes, ...over })
|
||||
/** Apply against a throwaway draft, the way the store does. */
|
||||
const apply = (S, p, ids) => { const s = JSON.parse(JSON.stringify(S)); applyChangeSet(s, p, ids); return s }
|
||||
|
||||
describe('gating', () => {
|
||||
it('shows nothing unless the instance offers it and someone is signed in', () => {
|
||||
expect(coachAvailable({ coach: { enabled: true } }, { id: 'u' })).toBe(true)
|
||||
expect(coachAvailable({}, { id: 'u' })).toBe(false)
|
||||
expect(coachAvailable(null, { id: 'u' })).toBe(false)
|
||||
expect(coachAvailable({ coach: { enabled: true } }, null)).toBe(false)
|
||||
})
|
||||
|
||||
it('is off in the mobile build, which has no server to run anything', () => {
|
||||
expect(coachAvailable({ coach: { enabled: true } }, { id: 'u' }, { mobile: true })).toBe(false)
|
||||
expect(coachAvailable(null, null, { mobile: true })).toBe(false)
|
||||
})
|
||||
|
||||
it('is on in the demo build, which fakes the provider locally', () => {
|
||||
expect(coachAvailable(null, null, { demo: true })).toBe(true)
|
||||
})
|
||||
|
||||
it('treats an older consent version as no consent', () => {
|
||||
expect(hasConsent(state())).toBe(true)
|
||||
expect(hasConsent(state({ coach: { consent: { agreedAt: 'x', version: 0 } } }))).toBe(false)
|
||||
expect(hasConsent(state({ coach: {} }))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('plan fingerprint', () => {
|
||||
it('ignores nothing that matters and reacts to nothing that does not', () => {
|
||||
const S = state()
|
||||
expect(planHash(S)).toBe(planHash(state()))
|
||||
// A field the plan does not carry cannot move the hash.
|
||||
expect(planHash(state({ theme: 'light' }))).toBe(planHash(S))
|
||||
// Everything the Coach can change does.
|
||||
const moved = state(); moved.routines[0].ex[0].sets = 4
|
||||
expect(planHash(moved)).not.toBe(planHash(S))
|
||||
const week = state(); week.week[6] = 'r1'
|
||||
expect(planHash(week)).not.toBe(planHash(S))
|
||||
})
|
||||
|
||||
it('cannot tell "no weight" from "0 kg" — both mean unloaded', () => {
|
||||
const a = state(); delete a.routines[0].ex[2].weight
|
||||
const b = state(); b.routines[0].ex[2].weight = 0
|
||||
expect(planHash(a)).toBe(planHash(b))
|
||||
})
|
||||
|
||||
it('moves for the rep ceiling and the two v1.2.4 flags', () => {
|
||||
// These are plan fields a user can edit by hand, so a proposal computed before the edit
|
||||
// has to read as stale afterwards. They were in canonicalPlan and not in the hash.
|
||||
const S = state()
|
||||
for (const [field, value] of Object.entries({ repsMax: 20, bodyweight: false, side: true })) {
|
||||
const edited = state(); edited.routines[0].ex[0][field] = value
|
||||
expect(planHash(edited), field).not.toBe(planHash(S))
|
||||
}
|
||||
})
|
||||
|
||||
it('agrees with the server, field for field', () => {
|
||||
const withFlags = state()
|
||||
withFlags.routines[0].ex[0] = { ...withFlags.routines[0].ex[0], repsMin: 8, repsMax: 20, bodyweight: true }
|
||||
withFlags.routines[1].ex[0] = { ...withFlags.routines[1].ex[0], side: true, reps: 16 }
|
||||
for (const S of [state(), state({ week: {} }), state({ routines: [] }), withFlags]) {
|
||||
expect(canonicalPlan(S)).toEqual(serverPayload.canonicalPlan(S))
|
||||
expect(planHash(S)).toBe(serverHashPlan(serverPayload.canonicalPlan(S)))
|
||||
expect(hashPlan(canonicalPlan(S))).toBe(serverHashPlan(serverPayload.canonicalPlan(S)))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('staleness', () => {
|
||||
it('flags the whole proposal when the plan moved underneath it', () => {
|
||||
const S = state()
|
||||
const p = { ...proposal([change()]), planHash: planHash(S) }
|
||||
expect(markStale(p, S).planMoved).toBe(false)
|
||||
const edited = state(); edited.routines[0].ex[0].sets = 5
|
||||
expect(markStale(p, edited).planMoved).toBe(true)
|
||||
})
|
||||
|
||||
it('flags a change whose target is gone', () => {
|
||||
const S = state(); S.routines[0].ex = S.routines[0].ex.filter(e => e.id !== '0001')
|
||||
const [c] = markStale(proposal([change()]), S).changes
|
||||
expect(c.status).toBe('stale')
|
||||
})
|
||||
|
||||
it('flags a change someone already made by hand, rather than overwriting them', () => {
|
||||
const S = state(); S.routines[0].ex[0].sets = 5 // Coach saw 3, user has since set 5
|
||||
const [c] = markStale(proposal([change()]), S).changes
|
||||
expect(c.status).toBe('stale')
|
||||
expect(applicable(markStale(proposal([change()]), S))).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('leaves an untouched change applyable', () => {
|
||||
const [c] = markStale(proposal([change()]), state()).changes
|
||||
expect(c.status).toBe('proposed')
|
||||
})
|
||||
|
||||
it('reads the current value for every scalar change type', () => {
|
||||
const S = state()
|
||||
S.routines[0].ex[0].repsMax = 20
|
||||
expect(currentValue(S, change({ type: 'sets' }))).toBe(3)
|
||||
expect(currentValue(S, change({ type: 'reps' }))).toBe(10)
|
||||
expect(currentValue(S, change({ type: 'repsMax' }))).toBe(20)
|
||||
expect(currentValue(S, change({ type: 'exercise-prog' }))).toBe('linear')
|
||||
expect(currentValue(S, change({ type: 'routine-prog' }))).toBe('linear')
|
||||
expect(currentValue(S, change({ type: 'week', target: { weekday: 1 } }))).toBe('r1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('applying changes', () => {
|
||||
it('has an implementation for every type the server can send', async () => {
|
||||
const { CHANGE_TYPES: serverTypes } = await import('../../../api/coach/validate.js')
|
||||
expect([...CHANGE_TYPES].sort()).toEqual([...serverTypes].sort())
|
||||
})
|
||||
|
||||
it('sets, reps, rep floor, rep ceiling, hold time, load step and policies', () => {
|
||||
const S = state()
|
||||
expect(apply(S, proposal([change({ type: 'sets', after: 4 })]), ['c1']).routines[0].ex[0].sets).toBe(4)
|
||||
expect(apply(S, proposal([change({ type: 'reps', after: 12 })]), ['c1']).routines[0].ex[0].reps).toBe(12)
|
||||
expect(apply(S, proposal([change({ type: 'repsMin', after: 8 })]), ['c1']).routines[0].ex[0].repsMin).toBe(8)
|
||||
expect(apply(S, proposal([change({ type: 'repsMax', before: null, after: 20 })]), ['c1']).routines[0].ex[0].repsMax).toBe(20)
|
||||
expect(apply(S, proposal([change({ type: 'sec', target: { routineId: 'r1', exId: '0007' }, before: 45, after: 60 })]), ['c1']).routines[0].ex[1].sec).toBe(60)
|
||||
expect(apply(S, proposal([change({ type: 'inc', before: null, after: 5 })]), ['c1']).routines[0].ex[0].inc).toBe(5)
|
||||
expect(apply(S, proposal([change({ type: 'exercise-prog', before: 'linear', after: 'double' })]), ['c1']).routines[0].ex[0].prog).toBe('double')
|
||||
expect(apply(S, proposal([change({ type: 'routine-prog', target: { routineId: 'r1' }, before: 'linear', after: 'greyskull' })]), ['c1']).routines[0].prog).toBe('greyskull')
|
||||
})
|
||||
|
||||
it('adds an exercise at the position asked for', () => {
|
||||
const out = apply(state(), proposal([change({
|
||||
type: 'add-exercise', target: { routineId: 'r1' }, before: null,
|
||||
after: { id: '0002', sets: 3, reps: 8, mode: 'reps', position: 1 }
|
||||
})]), ['c1'])
|
||||
expect(out.routines[0].ex.map(e => e.id)).toEqual(['0001', '0002', '0007', '0009'])
|
||||
expect(out.routines[0].ex[1].sets).toBe(3)
|
||||
})
|
||||
|
||||
it('carries a rep ceiling and the two flags onto an added exercise, and only when set', () => {
|
||||
const withFlags = apply(state(), proposal([change({
|
||||
type: 'add-exercise', target: { routineId: 'r1' }, before: null,
|
||||
after: { id: '0002', sets: 3, reps: 16, mode: 'reps', repsMin: 10, repsMax: 24, bodyweight: true, side: true }
|
||||
})]), ['c1']).routines[0].ex.at(-1)
|
||||
expect(withFlags).toMatchObject({ repsMin: 10, repsMax: 24, bodyweight: true, side: true })
|
||||
|
||||
const plain = apply(state(), proposal([change({
|
||||
type: 'add-exercise', target: { routineId: 'r1' }, before: null,
|
||||
after: { id: '0002', sets: 3, reps: 8, mode: 'reps' }
|
||||
})]), ['c1']).routines[0].ex.at(-1)
|
||||
// Absent means "whatever the catalogue says". Writing a flag out would freeze today's
|
||||
// dataset into the plan.
|
||||
expect(plain.bodyweight).toBeUndefined()
|
||||
expect(plain.side).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops an exercise without touching the rest', () => {
|
||||
const out = apply(state(), proposal([change({ type: 'remove-exercise' })]), ['c1'])
|
||||
expect(out.routines[0].ex.map(e => e.id)).toEqual(['0007', '0009'])
|
||||
})
|
||||
|
||||
it('keeps the prescription when swapping the movement', () => {
|
||||
const out = apply(state(), proposal([change({ type: 'swap-exercise', after: { id: '0002' } })]), ['c1'])
|
||||
const e = out.routines[0].ex[0]
|
||||
expect(e.id).toBe('0002')
|
||||
expect(e.sets).toBe(3)
|
||||
expect(e.reps).toBe(10) // not silently reset — that would be a change nobody approved
|
||||
})
|
||||
|
||||
it('drops flags that described the old movement when swapping', () => {
|
||||
const S = state()
|
||||
S.routines[0].ex[0] = { ...S.routines[0].ex[0], side: true, reps: 16, bodyweight: true }
|
||||
const e = apply(S, proposal([change({ type: 'swap-exercise', after: { id: '0002' } })]), ['c1']).routines[0].ex[0]
|
||||
// A lunge's "per side" is not a leg press's. Carrying it over would have the app halve a
|
||||
// rep count that was never per-side; the new exercise goes back to the catalogue.
|
||||
expect(e.side).toBeUndefined()
|
||||
expect(e.bodyweight).toBeUndefined()
|
||||
expect(e.reps).toBe(16) // the prescription itself still survives
|
||||
})
|
||||
|
||||
it('reorders only with a complete permutation', () => {
|
||||
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()
|
||||
})
|
||||
|
||||
it('supersets by moving the partner adjacent and tagging both', () => {
|
||||
const out = apply(state(), proposal([change({ type: 'superset', after: { link: true, with: '0009' } })]), ['c1'])
|
||||
const ex = out.routines[0].ex
|
||||
expect(ex[0].id).toBe('0001')
|
||||
expect(ex[1].id).toBe('0009')
|
||||
expect(ex[0].sg).toBeTruthy()
|
||||
expect(ex[0].sg).toBe(ex[1].sg)
|
||||
})
|
||||
|
||||
it('unlinks a superset and cleans up the orphan tag', () => {
|
||||
const S = state()
|
||||
S.routines[0].ex[0].sg = 'a'; S.routines[0].ex[1].sg = 'a'
|
||||
const out = apply(S, proposal([change({ type: 'superset', after: { link: false } })]), ['c1'])
|
||||
expect(out.routines[0].ex[0].sg).toBeUndefined()
|
||||
expect(out.routines[0].ex[1].sg).toBeUndefined()
|
||||
})
|
||||
|
||||
it('adds, renames and removes routines, clearing any day that pointed at one', () => {
|
||||
const added = apply(state(), proposal([change({
|
||||
type: 'add-routine', target: {}, before: null,
|
||||
after: { name: 'Full body C', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps' }] }
|
||||
})]), ['c1'])
|
||||
expect(added.routines).toHaveLength(3)
|
||||
expect(added.routines[2].id).not.toBe('r1')
|
||||
|
||||
const renamed = apply(state(), proposal([change({ type: 'rename-routine', target: { routineId: 'r1' }, before: 'Full body A', after: 'Upper' })]), ['c1'])
|
||||
expect(renamed.routines[0].name).toBe('Upper')
|
||||
|
||||
const removed = apply(state(), proposal([change({ type: 'remove-routine', target: { routineId: 'r2' } })]), ['c1'])
|
||||
expect(removed.routines.map(r => r.id)).toEqual(['r1'])
|
||||
expect(removed.week[3]).toBeUndefined() // Wednesday pointed at r2
|
||||
})
|
||||
|
||||
it('moves a day, and clears one', () => {
|
||||
const moved = apply(state(), proposal([change({ type: 'week', target: { weekday: 6 }, before: null, after: 'r1' })]), ['c1'])
|
||||
expect(moved.week[6]).toBe('r1')
|
||||
const cleared = apply(state(), proposal([change({ type: 'week', target: { weekday: 1 }, before: 'r1', after: 'rest' })]), ['c1'])
|
||||
expect(cleared.week[1]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('never touches history, weigh-ins or settings', () => {
|
||||
const S = state({
|
||||
workouts: [{ id: 'w1', d: '2026-07-20', entries: [] }],
|
||||
bodyweight: [{ d: '2026-07-20', w: 80 }],
|
||||
exWeights: { '0001': { w: 20 } }, unit: 'kg', restSec: 90
|
||||
})
|
||||
const out = apply(S, proposal([change({ type: 'sets', after: 4 })]), ['c1'])
|
||||
expect(out.workouts).toEqual(S.workouts)
|
||||
expect(out.bodyweight).toEqual(S.bodyweight)
|
||||
expect(out.exWeights).toEqual(S.exWeights)
|
||||
expect(out.unit).toBe('kg')
|
||||
expect(out.restSec).toBe(90)
|
||||
})
|
||||
})
|
||||
|
||||
describe('accepting a subset', () => {
|
||||
it('applies only what was accepted and records the rest as declined', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
const p = proposal([
|
||||
change({ id: 'c1', type: 'sets', after: 4 }),
|
||||
change({ id: 'c2', type: 'reps', before: 10, after: 12 })
|
||||
])
|
||||
const res = applyChangeSet(s, p, ['c1'])
|
||||
expect(res).toEqual({ applied: 1, rejected: 1 })
|
||||
expect(s.routines[0].ex[0].sets).toBe(4)
|
||||
expect(s.routines[0].ex[0].reps).toBe(10)
|
||||
const decisions = s.coach.log.at(-1).decisions
|
||||
expect(decisions.find(d => d.id === 'c2').status).toBe('rejected')
|
||||
})
|
||||
|
||||
it('refuses to apply a stale change even if it was ticked', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
const p = markStale(proposal([change()]), { ...s, routines: [{ id: 'r1', name: 'A', ex: [] }] })
|
||||
expect(applyChangeSet(s, p, ['c1'])).toEqual({ applied: 0 })
|
||||
})
|
||||
|
||||
it('is all-or-nothing: a failure part-way leaves the plan exactly as it was', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
const before = JSON.stringify(s.routines)
|
||||
const p = proposal([
|
||||
change({ id: 'c1', type: 'sets', after: 4 }),
|
||||
change({ id: 'c2', type: 'reps', target: { routineId: 'r1', exId: 'ghost' }, before: null, after: 12 })
|
||||
])
|
||||
// The store hands us a clone and keeps it only if we return; throwing discards everything.
|
||||
expect(() => applyChangeSet(s, p, ['c1', 'c2'])).toThrow()
|
||||
const s2 = JSON.parse(JSON.stringify(state()))
|
||||
try { applyChangeSet(s2, p, ['c1', 'c2']) } catch { /* draft discarded by the caller */ }
|
||||
expect(JSON.stringify(state().routines)).toBe(before)
|
||||
})
|
||||
})
|
||||
|
||||
describe('snapshots and revert', () => {
|
||||
it('puts the plan back and leaves the training log alone', () => {
|
||||
const s = JSON.parse(JSON.stringify(state({ workouts: [{ id: 'w1', d: '2026-07-20', entries: [] }] })))
|
||||
const original = JSON.stringify(s.routines)
|
||||
applyChangeSet(s, proposal([change({ type: 'sets', after: 4 })]), ['c1'])
|
||||
expect(s.routines[0].ex[0].sets).toBe(4)
|
||||
expect(canRevert(s)).toBe(true)
|
||||
expect(revertLast(s)).toBe(true)
|
||||
expect(JSON.stringify(s.routines)).toBe(original)
|
||||
expect(s.workouts).toHaveLength(1)
|
||||
expect(s.coach.log.at(-1).kind).toBe('revert')
|
||||
})
|
||||
|
||||
it('keeps a bounded number of snapshots', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
for (let i = 0; i < SNAPSHOT_MAX + 3; i++) pushSnapshot(s, 'p' + i)
|
||||
expect(s.coach.snapshots).toHaveLength(SNAPSHOT_MAX)
|
||||
expect(s.coach.snapshots.at(-1).proposalId).toBe('p' + (SNAPSHOT_MAX + 2))
|
||||
})
|
||||
|
||||
it('reverting with nothing to revert to is a no-op, not a crash', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
expect(revertLast(s)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the log', () => {
|
||||
it('is bounded', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
for (let i = 0; i < LOG_MAX + 10; i++) appendLog(s, { kind: 'review', at: i, summary: 's' + i })
|
||||
expect(s.coach.log).toHaveLength(LOG_MAX)
|
||||
expect(s.coach.log.at(-1).summary).toBe('s' + (LOG_MAX + 9))
|
||||
})
|
||||
|
||||
it('stays well inside the sync budget even when full', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
for (let i = 0; i < LOG_MAX; i++) {
|
||||
appendLog(s, { kind: 'review', at: i, summary: 'x'.repeat(200), decisions: [{ id: 'c', type: 'sets', why: 'y'.repeat(200), status: 'accepted' }] })
|
||||
}
|
||||
for (let i = 0; i < SNAPSHOT_MAX; i++) pushSnapshot(s, 'p' + i)
|
||||
expect(JSON.stringify(s.coach).length).toBeLessThan(300 * 1024)
|
||||
})
|
||||
|
||||
it('records a dismissal so a later review knows not to nag', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
recordDismissal(s, proposal([change()]))
|
||||
expect(s.coach.log.at(-1).decisions[0].status).toBe('rejected')
|
||||
})
|
||||
})
|
||||
|
||||
describe('created plans', () => {
|
||||
const bundle = {
|
||||
opengym_plan: 1, name: 'Coach plan', summary: 'three days',
|
||||
week: { 1: 'x1', 3: 'x2' },
|
||||
routines: [
|
||||
{ id: 'x1', name: 'A', emoji: '💪', why: 'why A', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps', why: 'why ex' }] },
|
||||
{ id: 'x2', name: 'B', emoji: '🏋️', ex: [{ id: '0002', sets: 3, reps: 8, mode: 'reps' }] }
|
||||
],
|
||||
customEx: []
|
||||
}
|
||||
|
||||
it('adds routines as new ones and never modifies what was already there', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: false })
|
||||
expect(s.routines).toHaveLength(4)
|
||||
expect(s.routines[0].name).toBe('Full body A') // untouched
|
||||
expect(s.routines[2].id).not.toBe('x1') // fresh ids, like a plan import
|
||||
expect(s.week[1]).toBe('r1') // schedule left alone
|
||||
})
|
||||
|
||||
it('replaces the week only when asked, and remaps to the new ids', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: true })
|
||||
expect(s.week[1]).toBe(s.routines[2].id)
|
||||
expect(s.week[3]).toBe(s.routines[3].id)
|
||||
expect(s.week[5]).toBeUndefined() // a day the new plan leaves empty is rest
|
||||
})
|
||||
|
||||
it('keeps the Coach\'s prose out of the routine data', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, {})
|
||||
expect(s.routines[2].why).toBeUndefined()
|
||||
expect(s.routines[2].ex[0].why).toBeUndefined()
|
||||
expect(s.routines[2].ex[0].name).toBeUndefined()
|
||||
})
|
||||
|
||||
it('carries the rep ceiling and the flags the validator let through', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, {
|
||||
id: 'p1', kind: 'create',
|
||||
bundle: {
|
||||
...bundle,
|
||||
routines: [{ id: 'x1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 12, mode: 'reps', repsMin: 8, repsMax: 20, bodyweight: true }] }]
|
||||
}
|
||||
}, {})
|
||||
expect(s.routines[2].ex[0]).toMatchObject({ repsMin: 8, repsMax: 20, bodyweight: true })
|
||||
})
|
||||
|
||||
it('is revertible like any other change', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: true })
|
||||
revertLast(s)
|
||||
expect(s.routines).toHaveLength(2)
|
||||
expect(s.week[1]).toBe('r1')
|
||||
})
|
||||
|
||||
it('brings custom exercises along and registers them', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, {
|
||||
id: 'p1', kind: 'create',
|
||||
bundle: { ...bundle, routines: [{ id: 'x1', name: 'A', ex: [{ id: 'cx1', sets: 3, reps: 10 }] }], customEx: [{ id: 'cx1', n: 'Sandbag carry', bp: 'back' }] }
|
||||
}, {})
|
||||
expect(s.customEx).toHaveLength(1)
|
||||
registerCustom(s.customEx)
|
||||
expect(s.routines[2].ex[0].id).toBe(s.customEx[0].id)
|
||||
})
|
||||
})
|
||||
|
||||
describe('validation', () => {
|
||||
it('rejects an unreadable proposal rather than half-applying it', () => {
|
||||
expect(() => validateProposal(null)).toThrow()
|
||||
expect(() => validateProposal({})).toThrow()
|
||||
expect(() => validateProposal({ changes: [{ type: 'drop-database' }] })).toThrow()
|
||||
expect(() => validateProposal({ bundle: { routines: [] } })).toThrow()
|
||||
expect(validateProposal({ changes: [change()] })).toBe(true)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user