Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Coach: the validator, and the apply path it exists to protect

Alex34d41b8e647c
diff --git a/api/coach/fixture-cli.mjs b/api/coach/fixture-cli.mjs
index 9d095db2c..a85050cbc 100644
--- a/api/coach/fixture-cli.mjs
+++ b/api/coach/fixture-cli.mjs
@@ -49,6 +49,22 @@ function payload() {
const P = payload();
const kind = P.task || (/change-set/i.test(prompt) ? 'review' : 'create');
+// Well-formed JSON naming an exercise nobody has. This is the failure validate.js exists for,
+// and it is not the same as garbage: every check upstream of the validator is happy with it.
+// The fixture keeps saying it on the repair round too, because the interesting assertion is
+// that a model which cannot be told produces a failed job rather than a retry loop.
+if (MODE === 'unknown-exercise') {
+ out({
+ coach_contract: 1,
+ summary: 'One change.',
+ changes: [{
+ id: 'c1', type: 'add-exercise', target: { routineId: (P.plan?.routines || [])[0]?.id },
+ after: { id: 'not-a-real-exercise', sets: 3, reps: 10 },
+ why: 'An id that resolves to nothing must never reach a plan.'
+ }]
+ });
+}
+
if (MODE === 'nochange' || (kind === 'review' && !(P.window?.workouts || []).length)) {
out({ coach_contract: 1, nochange: true, reading: 'Not enough new training to read anything into yet — keep logging and ask again in a week.' });
}
@@ -61,7 +77,11 @@ if (kind === 'create') {
opengym_plan: 1,
name: 'Coach plan',
summary: 'A three-day full-body plan built around the equipment you listed.',
- basedOn: 'No training history yet — starting conservatively.',
+ // Echoes whether the previous bundle actually arrived, so a test can tell a refine that
+ // carried its predecessor from one that silently sent `previous: null`.
+ basedOn: P.refine?.previous
+ ? 'Refined from the plan you were shown.'
+ : 'No training history yet — starting conservatively.',
week: { 1: 'r1', 3: 'r2', 5: 'r1' },
routines: [
{
diff --git a/api/coach/jobs.js b/api/coach/jobs.js
index f7de36c21..caf6c7408 100644
--- a/api/coach/jobs.js
+++ b/api/coach/jobs.js
@@ -20,6 +20,7 @@ import * as cfgStore from './config.js';
import { adapterFor } from './adapters/index.js';
import * as payloadLib from './payload.js';
import { extractJSON, contractOK } from './parse.js';
+import { validatePlan, validateReview } from './validate.js';
import { canDropPrivileges, unprivilegedIds } from './adapters/spawn.js';
const DATA = process.env.DATA_DIR || '/data';
@@ -188,7 +189,12 @@ function finish(job, result) {
const rec = readUser(job.uid);
const history = [...(rec.history || []), {
id: job.id, kind: job.kind, trigger: job.trigger, outcome: result.outcome,
- errorClass: result.errorClass || null, at: Date.now()
+ errorClass: result.errorClass || null, at: Date.now(),
+ // "Nothing to change" is an answer with a reason attached, and throwing the reason away
+ // leaves the user with a job that finished and nothing to show for it. It lives here, in
+ // the profile's own file — deliberately not in `detail`, which goes to the instance log
+ // the admin card renders, and which carries counts and outcomes only (FR-12/42).
+ ...(result.reading ? { reading: String(result.reading).slice(0, 1200) } : {})
}].slice(-HISTORY_MAX);
writeUser(job.uid, {
...rec,
@@ -269,7 +275,7 @@ async function execute(job) {
return finish(job, { outcome: 'failed', errorClass: attempt.errorClass, detail: attempt.detail });
}
if (attempt.nochange) {
- return finish(job, { outcome: 'nochange', pending: null, detail: null });
+ return finish(job, { outcome: 'nochange', pending: null, detail: null, reading: attempt.reading });
}
const pending = {
id: job.id,
@@ -304,16 +310,24 @@ async function invoke(adapter, cfg, payload, jobDir, env, job, repair) {
return { ok: false, repairable: !repair, errors: [`coach_contract must be ${payloadLib.CONTRACT}`], raw: r.text, errorClass: 'unusable' };
}
- // The seam. Everything above is transport: did a process run, did it exit cleanly, is there
- // a JSON object in what it said, does it claim the contract this build speaks. Nothing above
- // has judged whether the contents are safe to act on, and nothing here does either — that is
- // validate.js's job, and the validator (not the prompt) is the security boundary.
+ // The seam PR 1 left open. Everything above is transport: did a process run, did it exit
+ // cleanly, is there a JSON object in what it said, does it claim the contract this build
+ // speaks. None of it has judged whether the contents are safe to act on. That judgement is
+ // validate.js's, and the validator — not the prompt — is the security boundary.
//
- // So this PR carries the answer no further than `unvalidated`. Nothing in the client can
- // apply it, because the apply path does not exist yet. The next PR replaces this line with
- // the change-type check and hangs the repair round off its errors, exactly as the parse
- // failures above already do.
- return { ok: true, result: { unvalidated: parsed.value } };
+ // Its errors join the parse failures above on the same one repair round: a model that named
+ // an exercise that does not exist is told which one, and usually gets it right the second
+ // time. A model that cannot be told is a failed job, not a retry loop.
+ const checked = job.kind === 'review'
+ ? validateReview(parsed.value, payload.plan)
+ : validatePlan(parsed.value, {
+ workingWeights: payload.history?.workingWeights,
+ daysPerWeek: payload.coachProfile?.daysPerWeek
+ });
+
+ if (!checked.ok) return { ok: false, repairable: !repair, errors: checked.errors, raw: r.text, errorClass: 'unusable' };
+ if (checked.nochange) return { ok: true, nochange: true, reading: checked.reading };
+ return { ok: true, result: checked.proposal || { bundle: checked.bundle, summary: checked.bundle.summary } };
}
/**
@@ -321,11 +335,18 @@ async function invoke(adapter, cfg, payload, jobDir, env, job, repair) {
* `canonicalPlan`, so both runtimes hash the same normalised shape; the client mirrors this
* function exactly. A mismatch therefore means the plan genuinely moved — not that two
* implementations disagree about key order or about what "no weight" looks like.
+ *
+ * The field list must stay in step with `canonicalPlan`. It did not: that function learned
+ * `repsMax`, `bodyweight` and `side` when the payload did, and this one kept hashing the
+ * pre-1.2.4 list, so a plan whose rep ceiling had been raised by hand fingerprinted as
+ * untouched — which is exactly the edit a proposal about bodyweight progression is stalest
+ * against.
*/
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.sg].join(':')
+ [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])
});
diff --git a/api/coach/routes.js b/api/coach/routes.js
index b0cbccb3d..91606e2fb 100644
--- a/api/coach/routes.js
+++ b/api/coach/routes.js
@@ -160,8 +160,11 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
json(res, 200, r);
},
-
-
+ /* The gap here is `authMode` and connect/clear-credential, and it lands with PR 3 rather
+ than in this file today. Both exist to serve a credential, and the only provider this
+ build ships is the fixture, which has none: `credentialFor` returns before it consults
+ the mode. A switch whose two positions do the same thing is worse than no switch — so it
+ arrives with the setup-token path, in the PR that gives it something to switch between. */
/* Whose account this profile is about to spend. Its own route because both the Coach screen
and the admin card must state it, and neither should be inferring it from settings. */
diff --git a/api/coach/validate.js b/api/coach/validate.js
new file mode 100644
index 000000000..17ff2b3ea
--- /dev/null
+++ b/api/coach/validate.js
@@ -0,0 +1,372 @@
+/* The gate between a language model's output and someone's training plan.
+ *
+ * Everything upstream of here is advisory — the prompt asks for a shape, the model usually
+ * obliges. This file is where "usually" stops mattering. Nothing reaches a user that has not
+ * resolved against the real exercise library, matched the closed list of change types, and
+ * stayed inside the two things the Coach is allowed to touch (routines and the week).
+ *
+ * That closed list is the actual security boundary of the feature. A hostile note in a user's
+ * free text can talk the model into saying anything at all; it cannot invent a change type,
+ * and a change type that does not exist here does nothing. `parse.js` answers "is there JSON
+ * in what the provider said"; this file is the only thing that answers "is it safe to act on".
+ *
+ * Errors are collected rather than thrown one at a time, because they are fed back to the
+ * model verbatim for the one repair round (FR-48) — and a list of six problems produces a
+ * better second attempt than the first of them does.
+ */
+import { libraryHas, libraryName } from './payload.js';
+
+// The closed list (FR-23 / C3). Adding a member here is a deliberate act with an apply
+// implementation on the client to match; there is no default case anywhere.
+export const CHANGE_TYPES = [
+ 'add-exercise', 'remove-exercise', 'swap-exercise',
+ 'sets', 'reps', 'repsMin', 'repsMax', 'sec', 'cardio',
+ 'reorder', 'superset',
+ 'routine-prog', 'exercise-prog', 'inc',
+ 'add-routine', 'remove-routine', 'rename-routine',
+ 'week'
+];
+const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time'];
+const MODES = ['reps', 'time', 'cardio'];
+const MAX_CHANGES = 25;
+const MAX_ROUTINES = 7;
+const MAX_EX_PER_ROUTINE = 20;
+
+const isStr = v => typeof v === 'string' && v.trim().length > 0;
+const isNum = v => typeof v === 'number' && Number.isFinite(v);
+const isInt = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
+const clampStr = (v, n) => String(v == null ? '' : v).slice(0, n);
+
+/* ---------- the two v1.2.4 flags, enforced rather than merely accepted ----------
+ `prompts/common.md` tells the model that unilateral work is prescribed as the total across
+ both sides and therefore steps in twos, and that a rep ceiling is what turns "+1 rep
+ forever" into "add a set". A prompt that asks is not a guarantee; these are the two rules
+ from it that have a single right answer, so they are checked here and the repair round gets
+ a chance to fix them. Everything else in that file is coaching judgement and stays advisory. */
+const ODD_PER_SIDE = where =>
+ `${where} is a per-side exercise, so reps are the total across both sides and must be an even number`;
+const INVERTED_RANGE = where =>
+ `${where} sets a rep ceiling below its own floor — repsMax must be at least repsMin`;
+
+/* =============================== created plans =============================== */
+
+/**
+ * Validate a creation bundle into something `mergePlan` can consume unchanged.
+ * Returns { ok, bundle } or { ok:false, errors }.
+ */
+export function validatePlan(data, ctx = {}) {
+ const errors = [];
+ if (!data || typeof data !== 'object') return fail(['the answer was not an object']);
+ if (data.nochange) return fail(['a plan was requested but the answer said "no change"']);
+ if (!Array.isArray(data.routines) || !data.routines.length) errors.push('routines must be a non-empty array');
+
+ const customEx = (Array.isArray(data.customEx) ? data.customEx : [])
+ .filter(c => c && isStr(c.id) && isStr(c.n))
+ .slice(0, 20)
+ .map(c => ({ id: clampStr(c.id, 40), n: clampStr(c.n, 60), bp: clampStr(c.bp || 'waist', 30), ...(c.desc ? { desc: clampStr(c.desc, 400) } : {}) }));
+ const proposedIds = new Set(customEx.map(c => c.id));
+
+ const routines = [];
+ (Array.isArray(data.routines) ? data.routines : []).slice(0, MAX_ROUTINES).forEach((r, ri) => {
+ if (!r || typeof r !== 'object') { errors.push(`routines[${ri}] is not an object`); return; }
+ if (!isStr(r.name)) errors.push(`routines[${ri}].name is required`);
+ if (r.prog != null && !POLICIES.includes(r.prog)) errors.push(`routines[${ri}].prog "${r.prog}" is not one of ${POLICIES.join(', ')}`);
+ const ex = [];
+ (Array.isArray(r.ex) ? r.ex : []).slice(0, MAX_EX_PER_ROUTINE).forEach((e, ei) => {
+ const where = `routines[${ri}].ex[${ei}]`;
+ if (!e || !isStr(e.id)) { errors.push(`${where}.id is required`); return; }
+ // FR-16: an id that resolves to nothing invalidates the proposal rather than being
+ // dropped into a plan that renders blank the first time it is trained.
+ if (!libraryHas(e.id) && !proposedIds.has(e.id)) {
+ errors.push(`${where}.id "${e.id}" is not in the exercise library and is not one of your own customEx entries — use an id from the library provided in the payload`);
+ return;
+ }
+ const clean = { id: e.id, sets: isInt(e.sets, 1, 10) ? e.sets : 3 };
+ const mode = MODES.includes(e.mode) ? e.mode : 'reps';
+ const perSide = !!e.side;
+ if (mode === 'cardio') {
+ clean.min = isInt(e.min, 1, 180) ? e.min : 20;
+ clean.speed = isNum(e.speed) && e.speed > 0 ? e.speed : 8;
+ } else if (mode === 'time') {
+ clean.mode = 'time';
+ clean.sec = isInt(e.sec, 5, 3600) ? e.sec : 45;
+ if (isNum(e.weight) && e.weight > 0) clean.weight = e.weight;
+ } else {
+ clean.mode = 'reps';
+ clean.reps = isInt(e.reps, 1, 100) ? e.reps : 10;
+ if (perSide && clean.reps % 2) { errors.push(ODD_PER_SIDE(`${where}.reps`)); return; }
+ if (isNum(e.weight) && e.weight > 0) clean.weight = e.weight;
+ }
+ if (e.prog != null) {
+ if (!POLICIES.includes(e.prog)) errors.push(`${where}.prog "${e.prog}" is not one of ${POLICIES.join(', ')}`);
+ else clean.prog = e.prog;
+ }
+ if (isNum(e.inc) && e.inc > 0) clean.inc = e.inc;
+ if (isInt(e.repsMin, 1, 100)) clean.repsMin = e.repsMin;
+ // The ceiling that makes bodyweight progression terminate (upstream #33): reaching it
+ // adds a set and restarts the reps. Without it the Coach can neither see nor prescribe
+ // how a push-up is meant to get harder.
+ if (isInt(e.repsMax, 1, 100)) clean.repsMax = e.repsMax;
+ if (clean.repsMax != null && clean.repsMin != null && clean.repsMax < clean.repsMin) {
+ errors.push(INVERTED_RANGE(where)); return;
+ }
+ // Written out only when the plan disagrees with the catalogue, matching plan-share.js —
+ // an absent flag means "whatever the exercise says", which is what every plan written
+ // before these existed relies on.
+ if (e.bodyweight != null) clean.bodyweight = !!e.bodyweight;
+ if (perSide) clean.side = true;
+ if (isStr(e.sg)) clean.sg = clampStr(e.sg, 20);
+ if (isStr(e.why)) clean.why = clampStr(e.why, 400);
+ ex.push(clean);
+ });
+ if (!ex.length) errors.push(`routines[${ri}] has no valid exercises`);
+ routines.push({
+ id: isStr(r.id) ? clampStr(r.id, 40) : 'r' + ri,
+ name: clampStr(r.name || 'Routine', 40),
+ emoji: clampStr(r.emoji || '🏋️', 8),
+ ...(POLICIES.includes(r.prog) ? { prog: r.prog } : {}),
+ ...(isStr(r.why) ? { why: clampStr(r.why, 400) } : {}),
+ ex
+ });
+ });
+
+ // The week may only point at routines this bundle actually defines.
+ const known = new Set(routines.map(r => r.id));
+ const week = {};
+ Object.entries(data.week || {}).forEach(([d, rid]) => {
+ const day = +d;
+ if (!isInt(day, 0, 6)) { errors.push(`week key "${d}" is not a weekday number 0-6`); return; }
+ if (!known.has(rid)) { errors.push(`week[${d}] points at "${rid}", which is not one of the routines in this plan`); return; }
+ week[day] = rid;
+ });
+
+ // FR-20: never start someone above what they have actually lifted.
+ const caps = new Map((ctx.workingWeights || []).map(w => [w.id, w.best]));
+ routines.forEach(r => r.ex.forEach(e => {
+ const cap = caps.get(e.id);
+ if (cap != null && e.weight > cap) e.weight = cap;
+ }));
+
+ // FR-17: honour the number of training days the user asked for.
+ const want = ctx.daysPerWeek;
+ if (isInt(want, 1, 7) && Object.keys(week).length && Object.keys(week).length !== want) {
+ errors.push(`the week schedules ${Object.keys(week).length} days but ${want} were asked for`);
+ }
+
+ if (errors.length) return fail(errors);
+ return {
+ ok: true,
+ bundle: {
+ opengym_plan: 1,
+ name: clampStr(data.name || 'Coach plan', 40),
+ summary: clampStr(data.summary || '', 1200),
+ basedOn: clampStr(data.basedOn || '', 400),
+ week, routines, customEx
+ }
+ };
+}
+
+/* =============================== review change-sets =============================== */
+
+/**
+ * Validate a review answer. Returns { ok, nochange } | { ok, proposal } | { ok:false, errors }.
+ * `plan` is the payload's cleaned plan — every target must resolve against it, so a change
+ * aimed at a routine that no longer exists never reaches the review screen.
+ */
+export function validateReview(data, plan) {
+ if (!data || typeof data !== 'object') return fail(['the answer was not an object']);
+ if (data.nochange) {
+ return { ok: true, nochange: true, reading: clampStr(data.reading || data.summary || '', 1200) };
+ }
+ const errors = [];
+ const routines = new Map((plan?.routines || []).map(r => [r.id, r]));
+ const changes = [];
+ const list = Array.isArray(data.changes) ? data.changes : null;
+ if (!list) return fail(['changes must be an array (or set "nochange": true with a "reading")']);
+
+ list.slice(0, MAX_CHANGES).forEach((c, i) => {
+ const where = `changes[${i}]`;
+ if (!c || typeof c !== 'object') { errors.push(`${where} is not an object`); return; }
+ if (!CHANGE_TYPES.includes(c.type)) {
+ errors.push(`${where}.type "${c.type}" is not allowed — use one of: ${CHANGE_TYPES.join(', ')}`);
+ return;
+ }
+ if (!isStr(c.why)) { errors.push(`${where}.why is required — every change must cite the evidence behind it`); return; }
+ const target = c.target || {};
+ const routine = target.routineId ? routines.get(target.routineId) : null;
+
+ // Targets: everything but add-routine and week must name a routine that exists; anything
+ // touching an exercise must name one that is actually in it.
+ if (!['add-routine', 'week'].includes(c.type)) {
+ if (!routine) { errors.push(`${where}.target.routineId "${target.routineId}" is not one of the routines in the plan`); return; }
+ }
+ const needsEx = ['remove-exercise', 'swap-exercise', 'sets', 'reps', 'repsMin', 'repsMax', 'sec', 'cardio', 'exercise-prog', 'inc', 'superset'];
+ let planned = null;
+ if (needsEx.includes(c.type)) {
+ if (!target.exId) { errors.push(`${where}.target.exId is required for type "${c.type}"`); return; }
+ planned = (routine.ex || []).find(e => e.id === target.exId) || null;
+ if (!planned) {
+ errors.push(`${where}.target.exId "${target.exId}" is not in routine "${routine.name}"`); return;
+ }
+ }
+
+ const out = {
+ id: isStr(c.id) ? clampStr(c.id, 40) : 'c' + i,
+ type: c.type,
+ target: {
+ ...(target.routineId ? { routineId: target.routineId } : {}),
+ ...(target.exId ? { exId: target.exId } : {}),
+ ...(isInt(target.weekday, 0, 6) ? { weekday: target.weekday } : {})
+ },
+ why: clampStr(c.why, 600),
+ before: c.before ?? null,
+ 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.
+ switch (c.type) {
+ case 'add-exercise': {
+ const a = c.after || {};
+ if (!isStr(a.id) || !libraryHas(a.id)) { errors.push(`${where}.after.id must be an exercise id from the library`); return; }
+ const perSide = !!a.side;
+ if (perSide && isInt(a.reps, 1, 100) && a.reps % 2) { errors.push(ODD_PER_SIDE(`${where}.after.reps`)); return; }
+ if (isInt(a.repsMax, 1, 100) && isInt(a.repsMin, 1, 100) && a.repsMax < a.repsMin) { errors.push(INVERTED_RANGE(`${where}.after`)); return; }
+ out.after = {
+ id: a.id, name: libraryName(a.id),
+ sets: isInt(a.sets, 1, 10) ? a.sets : 3,
+ ...(MODES.includes(a.mode) ? { mode: a.mode } : { mode: 'reps' }),
+ ...(isInt(a.reps, 1, 100) ? { reps: a.reps } : {}),
+ ...(isInt(a.sec, 5, 3600) ? { sec: a.sec } : {}),
+ ...(isNum(a.weight) && a.weight > 0 ? { weight: a.weight } : {}),
+ ...(POLICIES.includes(a.prog) ? { prog: a.prog } : {}),
+ ...(isInt(a.repsMin, 1, 100) ? { repsMin: a.repsMin } : {}),
+ ...(isInt(a.repsMax, 1, 100) ? { repsMax: a.repsMax } : {}),
+ ...(a.bodyweight != null ? { bodyweight: !!a.bodyweight } : {}),
+ ...(perSide ? { side: true } : {}),
+ ...(isInt(a.position, 0, MAX_EX_PER_ROUTINE) ? { position: a.position } : {})
+ };
+ break;
+ }
+ case 'swap-exercise': {
+ const a = c.after || {};
+ if (!isStr(a.id) || !libraryHas(a.id)) { errors.push(`${where}.after.id must be an exercise id from the library`); return; }
+ if (a.id === target.exId) { errors.push(`${where} swaps an exercise for itself`); return; }
+ out.after = {
+ id: a.id, name: libraryName(a.id),
+ ...(isInt(a.sets, 1, 10) ? { sets: a.sets } : {}),
+ ...(isInt(a.reps, 1, 100) ? { reps: a.reps } : {}),
+ ...(isNum(a.weight) && a.weight > 0 ? { weight: a.weight } : {})
+ };
+ break;
+ }
+ case 'remove-exercise':
+ case 'remove-routine':
+ out.after = null;
+ break;
+ case 'sets': if (!isInt(c.after, 1, 10)) { errors.push(`${where}.after must be a whole number of sets (1-10)`); return; } break;
+ case 'reps':
+ if (!isInt(c.after, 1, 100)) { errors.push(`${where}.after must be a whole number of reps (1-100)`); return; }
+ // The plan is what says whether this exercise is unilateral, so the rule is checked
+ // against the plan rather than against whatever the change claims about itself.
+ if (planned?.side && c.after % 2) { errors.push(ODD_PER_SIDE(`${where}.after`)); return; }
+ break;
+ case 'repsMin':
+ if (!isInt(c.after, 1, 100)) { errors.push(`${where}.after must be a whole number (1-100)`); return; }
+ if (planned?.repsMax != null && c.after > planned.repsMax) { errors.push(INVERTED_RANGE(where)); return; }
+ break;
+ case 'repsMax':
+ if (!isInt(c.after, 1, 100)) { errors.push(`${where}.after must be a whole number (1-100)`); return; }
+ if (planned?.repsMin != null && c.after < planned.repsMin) { errors.push(INVERTED_RANGE(where)); return; }
+ break;
+ case 'sec': if (!isInt(c.after, 5, 3600) ) { errors.push(`${where}.after must be seconds (5-3600)`); return; } break;
+ case 'cardio': {
+ const a = c.after || {};
+ if (!isInt(a.min, 1, 180) && !isNum(a.speed)) { errors.push(`${where}.after must carry min and/or speed`); return; }
+ out.after = { ...(isInt(a.min, 1, 180) ? { min: a.min } : {}), ...(isNum(a.speed) && a.speed > 0 ? { speed: a.speed } : {}) };
+ break;
+ }
+ case 'inc': if (!isNum(c.after) || c.after <= 0) { errors.push(`${where}.after must be a positive increment`); return; } break;
+ case 'routine-prog':
+ case 'exercise-prog':
+ if (!POLICIES.includes(c.after)) { errors.push(`${where}.after must be one of ${POLICIES.join(', ')}`); return; }
+ break;
+ case 'reorder': {
+ 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;
+ }
+ out.after = order;
+ break;
+ }
+ case 'superset': {
+ const a = c.after || {};
+ if (a.link && !isStr(a.with)) { errors.push(`${where}.after.with is required when linking a superset`); 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;
+ }
+ 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);
+ 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; }
+ out.after = {
+ name: clampStr(a.name, 40), emoji: clampStr(a.emoji || '🏋️', 8),
+ ...(POLICIES.includes(a.prog) ? { prog: a.prog } : {}),
+ ex: ex.map(e => ({
+ id: e.id, name: libraryName(e.id),
+ sets: isInt(e.sets, 1, 10) ? e.sets : 3,
+ mode: MODES.includes(e.mode) ? e.mode : 'reps',
+ ...(isInt(e.reps, 1, 100) ? { reps: e.reps } : {}),
+ ...(isInt(e.sec, 5, 3600) ? { sec: e.sec } : {}),
+ ...(isInt(e.repsMax, 1, 100) ? { repsMax: e.repsMax } : {}),
+ ...(e.bodyweight != null ? { bodyweight: !!e.bodyweight } : {}),
+ ...(e.side ? { side: true } : {})
+ }))
+ };
+ break;
+ }
+ case 'rename-routine':
+ if (!isStr(c.after)) { errors.push(`${where}.after must be the new routine name`); return; }
+ out.after = clampStr(c.after, 40);
+ break;
+ case 'week': {
+ if (!isInt(target.weekday, 0, 6)) { errors.push(`${where}.target.weekday must be 0-6`); return; }
+ // null/'rest' clears the day; anything else has to be a routine that exists.
+ if (c.after != null && c.after !== 'rest' && !routines.has(c.after)) {
+ errors.push(`${where}.after must be a routine id from the plan, "rest", or null`); return;
+ }
+ out.after = c.after ?? null;
+ break;
+ }
+ }
+ changes.push(out);
+ });
+
+ if (errors.length) return fail(errors);
+ if (!changes.length) {
+ // An empty change list and "no changes" are the same outcome; treat it as the latter
+ // rather than showing someone an empty proposal screen (FR-25).
+ return { ok: true, nochange: true, reading: clampStr(data.summary || data.reading || '', 1200) };
+ }
+ return {
+ ok: true,
+ proposal: {
+ summary: clampStr(data.summary || '', 1200),
+ evidence: {
+ from: data.evidence?.from || null,
+ to: data.evidence?.to || null,
+ sessions: isInt(data.evidence?.sessions, 0, 10000) ? data.evidence.sessions : null
+ },
+ changes,
+ notes: (Array.isArray(data.notes) ? data.notes : []).filter(isStr).slice(0, 6).map(n => clampStr(n, 600))
+ }
+ };
+}
+
+function fail(errors) { return { ok: false, errors }; }
diff --git a/api/test/jobs.test.js b/api/test/jobs.test.js
index 64c9466a6..257e32b88 100644
--- a/api/test/jobs.test.js
+++ b/api/test/jobs.test.js
@@ -2,8 +2,9 @@
itself. Every outcome the user can be shown is reachable here without an AI account, which
is the whole reason the fixture CLI exists.
- This PR stops at transport: a job runs, exits, and its answer is parsed. The validator and
- the apply path arrive next, and the tests that assert them travel with them. */
+ PR 1 stopped at transport and held its answer as `unvalidated`. This PR closes that seam, so
+ the assertions below are about what now comes out the other end: a checked bundle, a checked
+ change-set, and the two ways a job can fail the validator rather than the parser. */
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
@@ -12,6 +13,8 @@ import { tempData, writeState, sampleState } from './helpers.mjs';
const DIR = tempData();
const cfg = await import('../coach/config.js');
const jobs = await import('../coach/jobs.js');
+const payload = await import('../coach/payload.js');
+const { CHANGE_TYPES } = await import('../coach/validate.js');
const { forcePrivilegeVerdict } = await import('../coach/adapters/spawn.js');
cfg.save({ enabled: true, provider: 'fixture' });
@@ -123,8 +126,7 @@ test('a job interrupted by a restart is reported as failed, not left spinning',
assert.equal(lastOutcome(uid).errorClass, 'restart');
});
-test('the plan fingerprint moves when the plan does, and only then', async () => {
- const payload = await import('../coach/payload.js');
+test('the plan fingerprint moves when the plan does, and only then', () => {
const plan = payload.canonicalPlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 10 }] }], week: { 1: 'r1' } });
const same = payload.canonicalPlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 10, weight: 0 }] }], week: { 1: 'r1' } });
const moved = payload.canonicalPlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 4, reps: 10 }] }], week: { 1: 'r1' } });
@@ -132,20 +134,109 @@ test('the plan fingerprint moves when the plan does, and only then', async () =>
assert.notEqual(jobs.hashPlan(plan), jobs.hashPlan(moved));
});
+test('the fingerprint covers every field canonicalPlan reports, including the v1.2.4 three', () => {
+ // canonicalPlan learned repsMax, bodyweight and side when the payload did; hashPlan kept
+ // hashing the pre-1.2.4 list, so it computed all three and then threw them away. A rep
+ // ceiling raised by hand read as "plan untouched" — on exactly the exercises where that
+ // ceiling is how progression works.
+ const of = ex => payload.canonicalPlan({ routines: [{ id: 'r1', name: 'A', ex: [ex] }], week: { 1: 'r1' } });
+ const base = { id: '0001', sets: 3, reps: 10, repsMin: 8, repsMax: 20, bodyweight: true };
+ const h = ex => jobs.hashPlan(of(ex));
-test('the answer is carried no further than parsed — nothing here can apply it', async () => {
- const uid = 'u-seam';
+ assert.equal(h(base), h({ ...base }), 'the same plan hashes the same');
+ for (const [field, value] of Object.entries({ repsMax: 25, bodyweight: false, side: true })) {
+ assert.notEqual(h(base), h({ ...base, [field]: value }), `${field} must move the fingerprint`);
+ }
+});
+
+
+test('a review job produces a checked change-set, and nothing is left unvalidated', async () => {
+ const uid = 'u-review';
+ writeState(DIR, uid, sampleState());
+ jobs.enqueue(uid, { kind: 'review' });
+ const s = await settle(uid);
+
+ assert.equal(lastOutcome(uid).outcome, 'ready');
+ assert.ok(s.pending, 'a proposal is held for the user');
+ assert.equal(s.pending.unvalidated, undefined, 'the PR 1 seam is closed');
+ assert.ok(Array.isArray(s.pending.changes) && s.pending.changes.length, 'real changes');
+ assert.ok(s.pending.changes.every(c => CHANGE_TYPES.includes(c.type)), 'every change is on the closed list');
+ assert.ok(s.pending.changes.every(c => c.why), 'every change cites its evidence');
+ assert.equal(s.pending.planHash, jobs.hashPlan(payload.canonicalPlan(jobs.readState(uid))));
+});
+
+test('a create job produces a bundle the client can merge unchanged', async () => {
+ const uid = 'u-create';
+ writeState(DIR, uid, sampleState());
+ jobs.enqueue(uid, { kind: 'create' });
+ const s = await settle(uid);
+
+ assert.equal(lastOutcome(uid).outcome, 'ready');
+ assert.equal(s.pending.unvalidated, undefined);
+ assert.equal(s.pending.bundle.opengym_plan, 1);
+ assert.ok(s.pending.bundle.routines.length);
+ // FR-16, end to end: every id in the bundle resolves against the real catalogue.
+ const ids = s.pending.bundle.routines.flatMap(r => r.ex.map(e => e.id));
+ assert.ok(ids.length && ids.every(id => payload.libraryHas(id)), 'no invented exercises reach the plan');
+ assert.equal(s.pending.iteration, 1);
+});
+
+test('a well-formed answer naming an exercise nobody has is refused, twice, and applies nothing', async () => {
+ const uid = 'u-ghostex';
+ writeState(DIR, uid, sampleState());
+ // Not garbage: it parses, and it claims the right contract. Only the validator objects —
+ // which is the whole point of the validator being the boundary rather than the parser.
+ process.env.FIXTURE_MODE = 'unknown-exercise';
+ jobs.enqueue(uid, { kind: 'review' });
+ const s = await settle(uid);
+ delete process.env.FIXTURE_MODE;
+
+ assert.equal(lastOutcome(uid).outcome, 'failed');
+ assert.equal(lastOutcome(uid).errorClass, 'unusable');
+ assert.equal(s.pending, null, 'nothing partial is ever left behind');
+});
+
+test('the one repair round rescues an answer the validator rejected', async () => {
+ const uid = 'u-repair';
+ writeState(DIR, uid, sampleState());
+ process.env.FIXTURE_MODE = 'invalid-then-valid';
+ jobs.enqueue(uid, { kind: 'review' });
+ const s = await settle(uid);
+ delete process.env.FIXTURE_MODE;
+
+ assert.equal(lastOutcome(uid).outcome, 'ready', 'the second attempt is accepted');
+ assert.ok(s.pending.changes.length);
+ assert.equal(jobs.readUser(uid).history.filter(h => h.outcome === 'failed').length, 0, 'the user never sees the first attempt');
+});
+
+test('"nothing to change" keeps the reason it gave, and proposes nothing', async () => {
+ const uid = 'u-nochange';
writeState(DIR, uid, sampleState());
+ process.env.FIXTURE_MODE = 'nochange';
jobs.enqueue(uid, { kind: 'review' });
const s = await settle(uid);
+ delete process.env.FIXTURE_MODE;
+
+ assert.equal(lastOutcome(uid).outcome, 'nochange');
+ assert.equal(s.pending, null, 'an empty proposal screen is not an outcome');
+ assert.match(lastOutcome(uid).reading, /keep logging/i, 'the reading survives the job that produced it');
+});
+
+test('a refine carries the plan it is refining, and counts as the next iteration', async () => {
+ const uid = 'u-refine';
+ writeState(DIR, uid, sampleState());
+ jobs.enqueue(uid, { kind: 'create' });
+ const first = await settle(uid);
+ assert.equal(first.pending.iteration, 1);
+ assert.match(first.pending.bundle.basedOn, /No training history/);
- assert.equal(lastOutcome(uid) === undefined || s.pending !== null, true);
- assert.ok(s.pending, 'a parsed answer is held for the user');
- // The seam this PR draws: an answer that parsed, and no judgement about it. PR 2 replaces
- // `unvalidated` with a checked proposal, and this assertion with the real shape.
- assert.ok(Object.hasOwn(s.pending, 'unvalidated'), 'the answer is explicitly unvalidated');
- assert.equal(s.pending.bundle, undefined, 'no applyable bundle exists yet');
- assert.equal(s.pending.proposal, undefined, 'no applyable proposal exists yet');
+ jobs.enqueue(uid, { kind: 'create', refine: 'More upper body, fewer days.' });
+ const second = await settle(uid);
+ // `previous` reads pending.bundle. Until the validator landed, pending only ever carried
+ // `unvalidated`, so it silently resolved to null on every refine — the model was asked to
+ // refine a plan it was never shown.
+ assert.match(second.pending.bundle.basedOn, /Refined from the plan/);
+ assert.equal(second.pending.iteration, 2);
});
test('the admin test-run completes a round trip without a user to spend', async () => {
diff --git a/api/test/parse.test.js b/api/test/parse.test.js
new file mode 100644
index 000000000..99f5b1879
--- /dev/null
+++ b/api/test/parse.test.js
@@ -0,0 +1,32 @@
+/* The transport half of the seam, pinned on its own.
+ *
+ * It matters that these two failure kinds stay distinguishable: "there was no JSON in what the
+ * provider said" and "there was, and the validator refused it" both feed the same single repair
+ * round, but only the second can name what was wrong. If extraction quietly succeeded on half
+ * an object, the validator would be arguing with a truncated answer.
+ */
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { tempData } from './helpers.mjs';
+
+tempData();
+const { extractJSON, contractOK } = await import('../coach/parse.js');
+
+test('JSON is recovered from whatever the model wrapped it in', () => {
+ assert.deepEqual(extractJSON('{"a":1}').value, { a: 1 });
+ assert.deepEqual(extractJSON('```json\n{"a":1}\n```').value, { a: 1 });
+ assert.deepEqual(extractJSON('Here you go:\n```\n{"a":1}\n```\nHope that helps!').value, { a: 1 });
+ assert.deepEqual(extractJSON('Sure. {"a":1} — let me know.').value, { a: 1 });
+});
+
+test('an answer with no JSON in it fails rather than being guessed at', () => {
+ assert.ok(extractJSON('I cannot help with that.').error);
+ assert.ok(extractJSON('').error);
+ assert.ok(extractJSON('{"a": ').error, 'half an object is not an object');
+});
+
+test('an answer may omit the contract version, but may not claim a different one', () => {
+ assert.equal(contractOK({ ok: true }), true);
+ assert.equal(contractOK({ coach_contract: 1 }), true);
+ assert.equal(contractOK({ coach_contract: 2 }), false);
+});
diff --git a/api/test/validate.test.js b/api/test/validate.test.js
new file mode 100644
index 000000000..dbb206623
--- /dev/null
+++ b/api/test/validate.test.js
@@ -0,0 +1,245 @@
+/* The validator, on its own — no queue, no child process, no provider.
+ *
+ * This is the file that decides whether something a language model said is allowed to touch a
+ * training plan, so the tests are written as the attacks and accidents it exists to stop: an
+ * invented change type, an exercise id that resolves to nothing, a target in the wrong routine,
+ * a plan that ignores what the user asked for.
+ *
+ * The closed list gets its own sweep at the bottom: every member of CHANGE_TYPES must have a
+ * well-formed instance here, so adding a type without an apply implementation and a test is a
+ * red build rather than a discovery.
+ */
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { tempData } from './helpers.mjs';
+
+tempData();
+const { validatePlan, validateReview, CHANGE_TYPES } = await import('../coach/validate.js');
+
+const PLAN = {
+ routines: [{
+ id: 'r1', name: 'Full body A',
+ ex: [{ id: '0001', sets: 3, reps: 10 }, { id: '0007', sets: 3, sec: 45 }]
+ }, {
+ id: 'r2', name: 'Full body B', ex: [{ id: '0009', sets: 3, reps: 8 }]
+ }, {
+ // The v1.2.4 shapes, as cleanEx would hand them over: a unilateral exercise whose reps are
+ // the total across both sides, and a bodyweight one with a rep ceiling.
+ id: 'r3', name: 'Legs',
+ ex: [
+ { id: '0043', sets: 3, reps: 16, side: true },
+ { id: '0001', sets: 3, reps: 12, repsMin: 8, repsMax: 20, bodyweight: true }
+ ]
+ }],
+ week: { 1: 'r1', 3: 'r2' }
+};
+const change = over => ({ id: 'c1', type: 'sets', target: { routineId: 'r1', exId: '0001' }, before: 3, after: 4, why: 'stalled twice', ...over });
+const review = changes => validateReview({ coach_contract: 1, summary: 's', changes }, PLAN);
+
+/* ---------------- created plans ---------------- */
+
+test('a plan referencing an unknown exercise is rejected, not quietly trimmed', () => {
+ const r = validatePlan({
+ routines: [{ name: 'A', ex: [{ id: '0001', sets: 3, reps: 10 }, { id: 'not-a-real-id', sets: 3, reps: 10 }] }]
+ });
+ assert.equal(r.ok, false);
+ assert.ok(r.errors.some(e => e.includes('not-a-real-id')));
+});
+
+test('a plan may reference a custom exercise it defines in the same answer', () => {
+ const r = validatePlan({
+ routines: [{ name: 'A', ex: [{ id: 'cx1', sets: 3, reps: 10 }] }],
+ customEx: [{ id: 'cx1', n: 'Sandbag carry', bp: 'back' }]
+ });
+ assert.equal(r.ok, true);
+ assert.equal(r.bundle.customEx[0].n, 'Sandbag carry');
+});
+
+test('the week may only point at routines the plan actually defines', () => {
+ const r = validatePlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 10 }] }], week: { 1: 'ghost' } });
+ assert.equal(r.ok, false);
+ assert.ok(r.errors.some(e => e.includes('ghost')));
+});
+
+test('proposed baselines are capped at what the lifter has actually handled', () => {
+ const r = validatePlan(
+ { routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 10, weight: 100 }] }] },
+ { workingWeights: [{ id: '0001', best: 40 }] }
+ );
+ assert.equal(r.ok, true);
+ assert.equal(r.bundle.routines[0].ex[0].weight, 40, 'optimism is clamped to evidence');
+});
+
+test('a plan that ignores the requested number of training days is rejected', () => {
+ const r = validatePlan(
+ { routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 10 }] }], week: { 1: 'r1', 2: 'r1', 3: 'r1', 4: 'r1' } },
+ { daysPerWeek: 3 }
+ );
+ assert.equal(r.ok, false);
+ assert.ok(r.errors.some(e => e.includes('4 days') && e.includes('3')));
+});
+
+test('an unknown progression policy is rejected', () => {
+ const r = validatePlan({ routines: [{ name: 'A', prog: 'vibes', ex: [{ id: '0001', sets: 3, reps: 10 }] }] });
+ assert.equal(r.ok, false);
+ assert.ok(r.errors.some(e => e.includes('vibes')));
+});
+
+/* ---------------- the two v1.2.4 flags ---------------- */
+
+test('a created plan carries the rep ceiling and the two flags through unchanged', () => {
+ const r = validatePlan({
+ routines: [{
+ id: 'r1', name: 'A', ex: [
+ { id: '0001', sets: 3, reps: 12, repsMin: 8, repsMax: 20, bodyweight: true },
+ { id: '0043', sets: 3, reps: 16, side: true }
+ ]
+ }]
+ });
+ assert.equal(r.ok, true);
+ const [bw, side] = r.bundle.routines[0].ex;
+ assert.equal(bw.repsMax, 20, 'without the ceiling the Coach cannot say how a push-up progresses');
+ assert.equal(bw.bodyweight, true);
+ assert.equal(side.side, true);
+ assert.equal(bw.side, undefined, 'a flag nobody set stays absent, so the catalogue still decides');
+});
+
+test('unilateral reps are a total across both sides, so an odd one is refused', () => {
+ const odd = validatePlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '0043', sets: 3, reps: 15, side: true }] }] });
+ assert.equal(odd.ok, false);
+ assert.ok(odd.errors.some(e => e.includes('even')));
+ // The same number is perfectly fine on an exercise that is not per-side.
+ assert.equal(validatePlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '0043', sets: 3, reps: 15 }] }] }).ok, true);
+});
+
+test('a rep ceiling below its own floor is refused at both ends', () => {
+ const created = validatePlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 10, repsMin: 12, repsMax: 8 }] }] });
+ assert.equal(created.ok, false);
+ assert.ok(created.errors.some(e => e.includes('repsMax')));
+ // …and on review, checked against the floor the plan already has (r3's second exercise: 8).
+ const tgt = { routineId: 'r3', exId: '0001' };
+ assert.equal(review([change({ type: 'repsMax', target: tgt, after: 6 })]).ok, false);
+ assert.equal(review([change({ type: 'repsMax', target: tgt, after: 25 })]).ok, true);
+});
+
+test('a review cannot prescribe an odd total on a per-side exercise', () => {
+ const tgt = { routineId: 'r3', exId: '0043' };
+ assert.equal(review([change({ type: 'reps', target: tgt, after: 17 })]).ok, false);
+ assert.equal(review([change({ type: 'reps', target: tgt, after: 18 })]).ok, true);
+ // The rule follows the plan, not the change: the same value on r1's 0001 is fine.
+ assert.equal(review([change({ type: 'reps', after: 17 })]).ok, true);
+});
+
+/* ---------------- review change-sets ---------------- */
+
+test('an invented change type does nothing at all', () => {
+ const r = review([change({ type: 'delete-all-workouts' })]);
+ assert.equal(r.ok, false);
+ assert.ok(r.errors[0].includes('not allowed'));
+ assert.ok(!CHANGE_TYPES.includes('delete-all-workouts'));
+});
+
+test('every change must target something that exists', () => {
+ assert.equal(review([change({ target: { routineId: 'ghost', exId: '0001' } })]).ok, false);
+ assert.equal(review([change({ target: { routineId: 'r1', exId: '9999' } })]).ok, false, 'exercise not in that routine');
+ assert.equal(review([change({ target: { routineId: 'r2', exId: '0001' } })]).ok, false, 'right exercise, wrong routine');
+});
+
+test('a change without a rationale is rejected', () => {
+ const r = review([change({ why: '' })]);
+ assert.equal(r.ok, false);
+ assert.ok(r.errors[0].includes('why'));
+});
+
+test('values are type-checked per change type', () => {
+ assert.equal(review([change({ type: 'sets', after: 'four' })]).ok, false);
+ assert.equal(review([change({ type: 'sets', after: 99 })]).ok, false);
+ assert.equal(review([change({ type: 'reps', after: 0 })]).ok, false);
+ assert.equal(review([change({ type: 'exercise-prog', after: 'linear' })]).ok, true);
+ assert.equal(review([change({ type: 'exercise-prog', after: 'vibes' })]).ok, false);
+ assert.equal(review([change({ type: 'inc', after: -5 })]).ok, false);
+});
+
+test('adding an exercise requires a real library id', () => {
+ const ok = review([change({ type: 'add-exercise', target: { routineId: 'r1' }, after: { id: '0009', sets: 3, reps: 12 } })]);
+ assert.equal(ok.ok, true);
+ assert.equal(ok.proposal.changes[0].after.name, 'assisted chest dip (kneeling)');
+ assert.equal(review([change({ type: 'add-exercise', target: { routineId: 'r1' }, after: { id: 'made-up' } })]).ok, false);
+});
+
+test('an added exercise may declare itself bodyweight, per-side and capped', () => {
+ const r = review([change({
+ type: 'add-exercise', target: { routineId: 'r1' },
+ after: { id: '0043', sets: 3, reps: 16, side: true, bodyweight: true, repsMin: 10, repsMax: 24 }
+ })]);
+ assert.equal(r.ok, true);
+ assert.deepEqual(
+ (({ side, bodyweight, repsMin, repsMax }) => ({ side, bodyweight, repsMin, repsMax }))(r.proposal.changes[0].after),
+ { side: true, bodyweight: true, repsMin: 10, repsMax: 24 }
+ );
+ // And the parity rule applies to what it declares about itself.
+ assert.equal(review([change({
+ type: 'add-exercise', target: { routineId: 'r1' }, after: { id: '0043', sets: 3, reps: 15, side: true }
+ })]).ok, false);
+});
+
+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');
+});
+
+test('a week change may only schedule a routine that exists, rest, or nothing', () => {
+ assert.equal(review([change({ type: 'week', target: { weekday: 6 }, after: 'r2' })]).ok, true);
+ assert.equal(review([change({ type: 'week', target: { weekday: 6 }, after: 'rest' })]).ok, true);
+ assert.equal(review([change({ type: 'week', target: { weekday: 6 }, after: null })]).ok, true);
+ assert.equal(review([change({ type: 'week', target: { weekday: 9 }, after: 'r1' })]).ok, false);
+ assert.equal(review([change({ type: 'week', target: { weekday: 6 }, after: 'ghost' })]).ok, false);
+});
+
+test('"nothing to change" is a first-class answer, and so is an empty change list', () => {
+ const a = validateReview({ nochange: true, reading: 'Plan is working.' }, PLAN);
+ assert.equal(a.nochange, true);
+ assert.equal(a.reading, 'Plan is working.');
+ const b = review([]);
+ assert.equal(b.nochange, true, 'no changes and "no changes" are the same outcome');
+});
+
+test('advice-only notes survive but carry no change', () => {
+ const r = validateReview({ summary: 's', changes: [change()], notes: ['Body weight is flat — eat more.'] }, PLAN);
+ assert.equal(r.proposal.notes.length, 1);
+ assert.equal(r.proposal.changes.length, 1);
+});
+
+test('one bad change fails the whole set — nothing is ever half-applied', () => {
+ const r = review([change(), change({ id: 'c2', type: 'not-a-type' })]);
+ assert.equal(r.ok, false);
+});
+
+test('every allowed change type has a validator that accepts a well-formed instance', () => {
+ const good = {
+ 'add-exercise': change({ type: 'add-exercise', target: { routineId: 'r1' }, after: { id: '0009', sets: 3, reps: 10 } }),
+ 'remove-exercise': change({ type: 'remove-exercise' }),
+ 'swap-exercise': change({ type: 'swap-exercise', after: { id: '0009' } }),
+ sets: change({ type: 'sets', after: 4 }),
+ reps: change({ type: 'reps', after: 12 }),
+ repsMin: change({ type: 'repsMin', after: 8 }),
+ repsMax: change({ type: 'repsMax', after: 20 }),
+ sec: change({ type: 'sec', target: { routineId: 'r1', exId: '0007' }, after: 60 }),
+ cardio: change({ type: 'cardio', after: { min: 25, speed: 9 } }),
+ reorder: change({ type: 'reorder', target: { routineId: 'r1' }, after: ['0007', '0001'] }),
+ superset: change({ type: 'superset', after: { link: true, with: '0007' } }),
+ 'routine-prog': change({ type: 'routine-prog', target: { routineId: 'r1' }, after: 'double' }),
+ 'exercise-prog': change({ type: 'exercise-prog', after: 'greyskull' }),
+ inc: change({ type: 'inc', after: 2.5 }),
+ 'add-routine': change({ type: 'add-routine', target: {}, after: { name: 'C', ex: [{ id: '0001', sets: 3, reps: 10 }] } }),
+ 'remove-routine': change({ type: 'remove-routine', target: { routineId: 'r2' } }),
+ 'rename-routine': change({ type: 'rename-routine', target: { routineId: 'r1' }, after: 'Upper' }),
+ week: change({ type: 'week', target: { weekday: 2 }, after: 'r1' })
+ };
+ for (const type of CHANGE_TYPES) {
+ assert.ok(good[type], `no fixture for change type "${type}" — add one`);
+ const r = review([good[type]]);
+ assert.equal(r.ok, true, `${type} should validate: ${JSON.stringify(r.errors)}`);
+ }
+});
diff --git a/docs/AI_COACH.md b/docs/AI_COACH.md
index 818907468..cf92569cd 100644
--- a/docs/AI_COACH.md
+++ b/docs/AI_COACH.md
@@ -4,8 +4,8 @@ An optional AI that **designs** a training plan and **revises it from what you a
running on your own server under your own provider account, off until an admin turns it on.
> This document grows with the feature. What is described here is what has landed: the server
-> plumbing, the consent and payload boundary, and the credential model. The validator and the
-> apply path, the provider adapters, and the UI arrive in the PRs that follow.
+> plumbing, the consent and payload boundary, the credential model, and the validator and apply
+> path. The provider adapters and the UI arrive in the PRs that follow.
---
@@ -77,6 +77,42 @@ The server re-implements three reading rules the frontend owns — `modeOf`, `is
because the api image has no build step in common with the frontend. `coach-parity.test.js`
pins them against the originals over a table of configs, so the copies cannot drift silently.
+## What comes back, and what it is allowed to do
+
+The prompt asks for a shape and the model usually obliges. `api/coach/validate.js` is where
+"usually" stops mattering, and it — not the prompt — is the security boundary. Nothing reaches
+you that has not:
+
+- **matched the closed list of change types.** Eighteen of them, each with an apply
+ implementation on the client to match. A hostile note in your own free text can talk a model
+ into saying anything at all; it cannot invent a change type, and a change type that is not on
+ the list does nothing. There is no default case anywhere.
+- **resolved against the real exercise library.** An id nobody has invalidates the whole
+ proposal rather than being quietly dropped into a plan that renders blank the first time you
+ train it.
+- **hit something that exists.** Every target names a routine in your plan, and anything about
+ an exercise names one that is actually in that routine.
+- **cited its evidence.** A change with no `why` is refused.
+
+A rejected answer gets **one** repair round, with the errors handed back verbatim. Two failures
+is a provider problem rather than a prompting problem, and a retry loop against a paid account
+is a bad way to find that out.
+
+The Coach may only touch **routines and the week**. Your training log, your weigh-ins and your
+settings are not reachable from any change type that exists.
+
+Applying happens **on the client**, not the server — ordinary local editing, so it works
+offline, syncs like everything else, and stays reversible without the server knowing. Every
+apply takes a snapshot of `{routines, week}` first, so one tap puts the plan back; workouts are
+deliberately untouched by a revert, because the log is what happened. A change-set is
+all-or-nothing: a failure part-way through discards the whole draft rather than leaving a
+half-applied proposal.
+
+Proposals carry a fingerprint of the plan they were computed against. If the plan has moved
+since — you edited it on another device, or changed by hand the exact thing a change is
+about — that change is shown greyed out with the reason, and cannot be applied. Silently
+overwriting an edit you made yourself would be the worse failure.
+
## Isolation
Jobs run as an unprivileged `coach` user that cannot read the files holding secrets, with an
diff --git a/frontend/src/lib/coach.js b/frontend/src/lib/coach.js
new file mode 100644
index 000000000..b97c1b6dd
--- /dev/null
+++ b/frontend/src/lib/coach.js
@@ -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) }
+}
diff --git a/frontend/src/lib/coach.test.js b/frontend/src/lib/coach.test.js
new file mode 100644
index 000000000..49349dd60
--- /dev/null
+++ b/frontend/src/lib/coach.test.js
@@ -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)
+ })
+})