/* The second opinion, tested without a model: the state that leaves the instance, the questions built from it, and the reader that turns a gateway's answer into numbers the screen can trust. Two things here are load-bearing beyond the usual. `buildState` is the privacy boundary — a test asserts that nothing identifying goes out, because that is a claim the docs make and nothing else checks it. And `parseAnswers` reads a response shape this codebase has never seen from the live service, so it is tested against every shape it might plausibly be, including the ones it must refuse rather than guess. */ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { jevConfig, jevEndpoint, buildState, buildQuestions, parseAnswers, readAnswer, makeInsight, stateHash, insightFreshness, budgetFor, healthSummary, JEV_DEFAULTS } from '../jev.js'; import { bestEstimate, isAssistedRow, epley, REP_CAP } from '../coach/core/strength.js'; const NOW = Date.parse('2026-09-23T20:00:00Z'); const day = (offset, extra = '') => new Date(NOW - offset * 86400000).toISOString().slice(0, 10) + extra; /** A profile with two routines, three sessions, a stall and a month of weigh-ins. */ const S = { unit: 'kg', body: 'male', targetW: 78, lang: 'es', coach: { profile: { goal: 'build muscle', experience: 'intermediate', daysPerWeek: 4, sessionMin: 60, equipment: ['barbell', 'dumbbell'], limitations: 'bad left shoulder, no overhead press' } }, week: { 1: ['r1'], 3: ['r2'], 5: ['r1'] }, routines: [{ id: 'r1', ex: [{ id: 'e1' }, { id: 'e2' }] }, { id: 'r2', ex: [{ id: 'e3' }] }], bodyweight: [ { d: day(28), kg: 80 }, { d: day(14), kg: 79.2 }, { d: day(1), kg: 78.6 } ], workouts: [ { d: day(9), name: 'Push', start: 1000, end: 3601000, entries: [{ id: 'e1', sets: [{ w: 60, r: 8, done: true, rpe: 8 }] }] }, { d: day(6), name: 'Pull', start: 1000, end: 2701000, entries: [{ id: 'e3', sets: [{ w: 50, r: 10, done: true }] }] }, { d: day(3), name: 'Push', start: 1000, end: 3301000, entries: [ { id: 'e1', sets: [{ w: 60, r: 8, done: true, rpe: 9 }, { w: 60, r: 7, done: false }] }, { id: 'e2', sets: [{ w: 20, r: 12, done: true }] } ] }, { d: day(1), name: 'Push', start: 1000, end: 3501000, entries: [{ id: 'e1', sets: [{ w: 60, r: 8, done: true, rpe: 10 }] }] } ] }; /** A health file shaped like the stored one: per day, per field, phone-local dates. */ const vitals = () => ({ metrics: { step_count: { units: 'count', days: { [day(0)]: { n: 1, f: { qty: { n: 1, sum: 840, min: 840, max: 840, last: 840 } } }, [day(1)]: { n: 1, f: { qty: { n: 1, sum: 9100, min: 9100, max: 9100, last: 9100 } } } } }, resting_heart_rate: { units: 'bpm', days: { [day(0)]: { n: 288, f: { qty: { n: 288, sum: 17856, min: 58, max: 70, last: 62 } } }, [day(2)]: { n: 288, f: { qty: { n: 288, sum: 16128, min: 52, max: 60, last: 56 } } } } }, sleep_analysis: { units: 'hr', days: { [day(0)]: { n: 1, f: { asleep: { n: 1, sum: 5.4, min: 5.4, max: 5.4, last: 5.4 }, deep: { n: 1, sum: 0.7, min: 0.7, max: 0.7, last: 0.7 } } } } }, some_metric_from_2030: { units: 'ms', days: { [day(0)]: { n: 3, f: { qty: { n: 3, sum: 300, min: 90, max: 120, last: 100 } } } } } } }); const bodyPartOf = id => ({ e1: 'chest', e2: 'shoulders', e3: 'back' }[id] || null); const nameOf = id => ({ e1: 'barbell bench press', e2: 'dumbbell lateral raise', e3: 'pull-up' }[id] || null); const exOf = id => ({ e1: { n: 'barbell bench press', bp: 'chest', eq: 'barbell' } }[id] || null); const state = (over = {}) => buildState({ S, vitals: vitals(), now: NOW, bodyPartOf, nameOf, exOf, ...over }); /* ---------- configuration ---------- */ test('the instance is configured by its environment, and off without a key', () => { assert.equal(jevConfig({}).configured, false, 'no key, no feature'); assert.equal(jevConfig({ OPENCODE_API_KEY: 'oc-1' }).configured, true, 'the gateway key works too'); assert.equal(jevConfig({ JEV_API_KEY: 'k', JEV_DISABLED: '1' }).configured, false, 'the kill switch wins'); // An unset or blank variable means the default, never zero: a zero cap is a feature that looks // configured and refuses every request, which is how this was found. const plain = jevConfig({ JEV_API_KEY: 'k' }); assert.equal(plain.maxPerDay, JEV_DEFAULTS.maxPerDay); assert.equal(plain.minIntervalMs, JEV_DEFAULTS.minIntervalMs); assert.equal(plain.timeoutMs, JEV_DEFAULTS.timeoutMs); assert.equal(plain.stateDays, JEV_DEFAULTS.stateDays); assert.equal(jevConfig({ JEV_API_KEY: 'k', JEV_MAX_PER_DAY: '' }).maxPerDay, JEV_DEFAULTS.maxPerDay); assert.equal(jevConfig({ JEV_API_KEY: 'k', JEV_MAX_PER_DAY: 'nonsense' }).maxPerDay, JEV_DEFAULTS.maxPerDay); assert.equal(jevConfig({ JEV_API_KEY: 'k', JEV_MAX_PER_DAY: '0' }).maxPerDay, 0, 'an explicit zero is obeyed'); const cfg = jevConfig({ JEV_API_KEY: 'k', JEV_MODEL: 'jev-1.13-free', JEV_BASE_URL: 'https://gw.example.com/zen/', JEV_MAX_PER_DAY: '3' }); assert.equal(cfg.model, 'jev-1.13-free'); assert.equal(cfg.baseUrl, 'https://gw.example.com/zen', 'the trailing slash goes'); assert.equal(cfg.maxPerDay, 3); assert.equal(cfg.key, 'k'); // The endpoint is built from whatever the base is, and never doubled. assert.equal(jevEndpoint('https://opencode.ai/zen'), 'https://opencode.ai/zen/v1/systemone'); assert.equal(jevEndpoint('https://opencode.ai/zen/'), 'https://opencode.ai/zen/v1/systemone'); assert.equal(jevEndpoint('https://opencode.ai/zen/v1'), 'https://opencode.ai/zen/v1/systemone'); assert.equal(jevEndpoint('https://opencode.ai/zen/v1/systemone'), 'https://opencode.ai/zen/v1/systemone'); assert.equal(jevEndpoint(undefined), JEV_DEFAULTS.baseUrl + '/v1/systemone'); }); /* ---------- the state: aggregates out, and nothing that identifies anybody ---------- */ test('the state carries the training, the body and a week of health, as numbers', () => { const s = state(); assert.equal(s.meta.today, day(0)); assert.equal(s.meta.unit, 'kg'); assert.equal(s.profile.goal, 'build muscle'); assert.equal(s.profile.limitations, 'bad left shoulder, no overhead press'); assert.equal(s.training.sessions, 4); assert.equal(s.training.last_session_days_ago, 1); assert.equal(s.training.planned_days_per_week, 3); assert.equal(s.training.sets_by_body_part_28d.chest, 3, 'three done sets of chest, the skipped one is not a set'); assert.equal(s.training.sets_by_body_part_28d.shoulders, 1); assert.equal(s.training.sets_by_body_part_7d.back, 1, 'and the week view is its own count'); // e1 was trained three times and its top set was 60 kg every time: that is a stall, and it goes // out as a *decision the app can act on* — the library id, with the name beside it so the model // reads words rather than a key. assert.deepEqual(s.training.stalled, [ { id: 'e1', name: 'barbell bench press', sessions: 3, last_top: 60, body_part: 'chest' } ]); assert.equal(s.training.recent_sessions.at(-1).days_ago, 1); assert.equal(s.training.recent_sessions.at(-1).avg_rpe, 10); assert.equal(s.training.recent_sessions.at(-1).minutes, 58); assert.equal(s.bodyweight.latest, 78.6); assert.equal(s.bodyweight.change_28d, -1.4); assert.equal(s.bodyweight.target, 78); // Health: today against the week, per field and uninterpreted, newest metric first by catalogue. const names = s.health.metrics.map(m => m.name); assert.deepEqual(names.slice(0, 3), ['resting_heart_rate', 'sleep_analysis', 'step_count']); assert.equal(names.includes('some_metric_from_2030'), true, 'an unknown metric still goes, last'); const rhr = s.health.metrics.find(m => m.name === 'resting_heart_rate'); assert.equal(rhr.units, 'bpm'); assert.equal(rhr.today.fields.qty.avg, 62, 'the day average, from the day total and its count'); assert.equal(rhr.week.days, 2); assert.equal(rhr.week.fields.qty.min, 52); assert.equal(rhr.week.fields.qty.max, 70); assert.equal(state({ days: 400 }).health.window_days, 400); }); test('nothing that identifies the person leaves the instance', () => { // The one claim the docs make about this feature, and the one nothing else could catch: the // state is aggregates. A name, an id or a workout title in here would be a leak in a payload // that is otherwise numbers, and it would leave every night. const json = JSON.stringify(state()); assert.equal(json.includes('Push'), false, 'no workout titles'); assert.equal(json.includes('Pull'), false); // Exercise ids DO go out, and only for the stalled ones: a judgment about which exercise to change // has to name something the app can edit, and a library id is a row in a public dataset rather than // an identifier of a person. The names travel with them so the model reads words. assert.equal(json.includes('"e1"'), true, 'a stalled exercise is named by the id the plan uses'); assert.equal(json.includes('barbell bench press'), true, 'and by the library\'s own name'); assert.equal(json.includes('r1'), false, 'no routine ids'); assert.equal(json.includes('u_'), false); // The body parts and metric names that DO go are the vocabulary of the questions, not identity. assert.ok(json.includes('chest') && json.includes('resting_heart_rate')); }); test('a profile with nothing logged produces a state with no invented numbers', () => { const s = buildState({ S: {}, vitals: null, now: NOW }); assert.equal(s.profile, null); assert.equal(s.training.sessions, 0); assert.equal(s.training.last_session_days_ago, null); assert.deepEqual(s.training.recent_sessions, []); assert.equal(s.bodyweight, null); assert.deepEqual(s.health.metrics, []); }); /* ---------- the questions ---------- */ test('the questions are built from what this profile actually has', () => { const q = buildQuestions(state()); assert.equal(q.readiness.type, 'score'); assert.equal(q.readiness.criteria.length, 5); assert.equal(q.deload.type, 'noul'); assert.deepEqual(Object.keys(q.deload.criteria), ['true', 'false']); // Only body parts that were trained get an option, plus the honest "nothing stands out". assert.deepEqual(Object.keys(q.limiter.criteria).sort(), ['back', 'chest', 'none', 'shoulders']); // Selection: one question per stalled exercise, keyed by the id the plan can act on, and a // direction for the week's volume once there is enough history to have an opinion. assert.deepEqual(Object.keys(q.exercise_e1.criteria).sort(), ['drop', 'keep', 'reduce', 'swap']); assert.match(q.exercise_e1.instructions, /barbell bench press/); assert.match(q.exercise_e1.instructions, /60/); assert.equal(q.volume.type, 'score'); assert.equal(q.volume.criteria.length, 5); // Every metric in the state is a choice, and no metric that is not. assert.equal(Object.keys(q.attention.criteria).includes('step_count'), true); assert.equal(Object.keys(q.attention.criteria).includes('resting_heart_rate'), true); assert.equal(Object.keys(q.attention.criteria).includes('none'), true); assert.match(q.attention.instructions, /step_count/); // A profile with no training gets no limiter question at all: a choice with no options can only // be answered wrong. const empty = buildQuestions(buildState({ S: {}, vitals: null, now: NOW })); assert.equal(empty.volume, undefined, 'no sessions, no opinion about volume'); assert.equal(Object.keys(empty).some(k => k.startsWith('exercise_')), false, 'and nothing stalled to ask about'); assert.equal(empty.limiter, undefined); assert.deepEqual(Object.keys(empty.attention.criteria), ['none']); }); /* ---------- reading the answer ---------- */ test('reads a yes/no however the probability is spelled', () => { const q = { deload: { type: 'noul' } }; assert.deepEqual(parseAnswers({ answers: { deload: { probability: 0.31 } } }, q).deload, { type: 'noul', p: 0.31, option: 'false' }); assert.equal(parseAnswers({ answers: { deload: { p: 0.72 } } }, q).deload.option, 'true'); assert.equal(parseAnswers({ deload: { answer: true } }, q).deload.p, 1, 'a bare boolean is read as certainty'); assert.equal(parseAnswers({ results: { deload: { probabilities: { true: 0.2, false: 0.8 } } } }, q).deload.p, 0.2); assert.equal(parseAnswers({ answers: { deload: { nonsense: 1 } } }, q).deload, null, 'unreadable is null, not a guess'); }); test('reads a choice with its distribution, and says whether the option is one we asked about', () => { const q = { limiter: { type: 'choice', criteria: { chest: 'chest', back: 'back' } } }; const a = parseAnswers({ answers: { limiter: { choice: 'back', probabilities: { chest: 0.3, back: 0.6 } } } }, q).limiter; assert.equal(a.option, 'back'); assert.equal(a.p, 0.6); assert.equal(a.known, true); assert.deepEqual(a.probabilities, { chest: 0.3, back: 0.6 }); // An option outside the criteria is reported rather than dropped: the screen can then say the // judgment named something it was not offered, which is a fact about the answer worth keeping. const odd = parseAnswers({ answers: { limiter: { answer: 'hips' } } }, q).limiter; assert.equal(odd.option, 'hips'); assert.equal(odd.known, false); assert.equal(odd.p, null); // ...and the winner is picked out of a distribution when there is no explicit choice. assert.equal(readAnswer({ type: 'choice' }, { distribution: { a: 0.1, b: 0.9 } }).option, 'b'); }); test('reads a score from a value, an index or a distribution over the levels', () => { const q = { readiness: { type: 'score', criteria: ['a', 'b', 'c', 'd', 'e'] } }; assert.equal(parseAnswers({ readiness: { value: 3.4 } }, q).readiness.value, 3.4); assert.equal(parseAnswers({ readiness: { answer: 'd' } }, q).readiness.value, 4, 'an option becomes its level'); assert.equal(parseAnswers({ readiness: { probabilities: { a: 0.1, b: 0.2, c: 0.6, d: 0.1 } } }, q).readiness.value, 3); const partial = parseAnswers({ readiness: { value: 2.6, probability: 0.55 } }, q).readiness; assert.equal(partial.p, 0.55); assert.equal(parseAnswers({ readiness: {} }, q).readiness, null); }); test('a question the gateway did not answer is null, and the others still land', () => { const questions = buildQuestions(state()); const answers = parseAnswers({ answers: { readiness: { value: 2 }, deload: { probability: 0.8 } } }, questions); assert.equal(answers.readiness.value, 2); assert.equal(answers.deload.p, 0.8); assert.equal(answers.limiter, null); assert.equal(answers.attention, null); // A body that is not an object at all loses every answer rather than throwing in the route — one // null per question asked, however many that is. const asked = Object.keys(questions).length; assert.equal(asked, 6, 'readiness, deload, attention, limiter, volume and one per stalled exercise (e1)'); assert.deepEqual(Object.keys(questions), ['readiness', 'deload', 'attention', 'volume', 'exercise_e1', 'limiter']); assert.deepEqual(Object.values(parseAnswers(null, questions)), new Array(asked).fill(null)); assert.deepEqual(Object.values(parseAnswers('nope', questions)), new Array(asked).fill(null)); }); /* ---------- what is stored, and what makes it stale ---------- */ test('the stored judgment is small, dated and tied to the state it was made from', () => { const s = state(); const insight = makeInsight({ answers: { deload: { type: 'noul', p: 0.2, option: 'false' } }, raw: { answers: {} }, model: 'jev-1.13', stateHash: stateHash(s), at: NOW }); assert.equal(insight.v, 1); assert.equal(insight.at, NOW); assert.equal(insight.model, 'jev-1.13'); assert.equal(insight.raw.answers !== undefined, true); assert.equal(makeInsight({ answers: {}, raw: { big: 'x'.repeat(9000) }, model: 'm' }).raw, null, 'a huge response is not kept'); // Same data, same digest: the judgment still describes what is on screen. assert.equal(stateHash(state()), insight.stateHash); const moved = stateHash(buildState({ S: { ...S, workouts: S.workouts.slice(0, 3) }, vitals: vitals(), now: NOW, bodyPartOf, nameOf, exOf })); assert.notEqual(moved, insight.stateHash, 'a session logged since is a different profile'); assert.deepEqual(insightFreshness(insight, { now: NOW, hash: insight.stateHash }), { fresh: true, reason: null }); assert.equal(insightFreshness(insight, { now: NOW, hash: moved }).reason, 'data'); assert.equal(insightFreshness(insight, { now: NOW + 7 * 3600 * 1000, hash: insight.stateHash }).reason, 'old'); assert.equal(insightFreshness(null).reason, 'none'); assert.equal(insightFreshness(null).fresh, false); }); test('the daily budget counts per day and the interval holds a person back', () => { const at = NOW; const today = new Date(NOW).toISOString().slice(0, 10); assert.equal(budgetFor({ at, day: today, used: 1 }, { now: at }).allowed, false, 'ten minutes have not passed'); const later = budgetFor({ at, day: today, used: 1 }, { now: at + 11 * 60000 }); assert.equal(later.allowed, true); assert.equal(later.remaining, JEV_DEFAULTS.maxPerDay - 1); const spent = budgetFor({ at: at - 3600000, day: today, used: JEV_DEFAULTS.maxPerDay }, { now: at }); assert.equal(spent.allowed, false); assert.equal(spent.remaining, 0); // Yesterday's count does not carry over. assert.equal(budgetFor({ at: at - 86400000, day: '2000-01-01', used: 99 }, { now: at }).used, 0); assert.equal(budgetFor({ at: at - 86400000, day: '2000-01-01', used: 99 }, { now: at }).allowed, true); // A configured cap is obeyed, and zero means "no requests today" rather than "unlimited". assert.equal(budgetFor(null, { now: at, maxPerDay: 2 }).remaining, 2); assert.equal(budgetFor({ at: at - 3600000, day: today, used: 0 }, { now: at, maxPerDay: 0 }).allowed, false); }); /* ---------- the week the Coach reads ---------- * * Averages, never the file: the Coach can act on "sleeping 6.2 h against 7.1" and cannot act on 288 * heart-rate samples. Per field as HAE named it, because the catalogue that gives those fields a * meaning lives in the frontend and duplicating it here would give the two a way to disagree. */ test('the health summary is a week of averages, per metric and per field', () => { const day = (d, n, sum, last) => ({ [d]: { n, lastTs: Date.parse(d + 'T12:00:00Z'), f: { qty: { n, sum, min: 1, max: last, last } } } }); const doc = { metrics: { step_count: { units: 'count', days: { ...day('2026-05-01', 1, 9000, 9000), ...day('2026-05-02', 1, 11000, 11000), ...day('2026-05-08', 1, 500, 500) } }, // Inside the window on purpose: seven days ending on the 8th starts on the 2nd. sleep_analysis: { units: 'hr', days: { '2026-05-02': { n: 1, lastTs: 0, f: { asleep: { n: 1, sum: 7.4, min: 7.4, max: 7.4, last: 7.4 } } } } }, old_metric: { units: '', days: { '2025-01-01': { n: 1, lastTs: 0, f: { qty: { n: 1, sum: 1, min: 1, max: 1, last: 1 } } } } }, empty_metric: { units: '', days: {} } } }; const sum = healthSummary(doc, { days: 7, now: Date.parse('2026-05-08T23:00:00Z') }); assert.equal(sum.window_days, 7); const names = sum.metrics.map(m => m.metric); assert.deepEqual(names, ['sleep_analysis', 'step_count'], 'the catalogue order first, and nothing outside the window'); const steps = sum.metrics.find(m => m.metric === 'step_count'); assert.equal(steps.days_with_data, 2, 'the 1st is outside a seven-day window ending on the 8th'); assert.deepEqual(steps.fields[0], { field: 'qty', avg_per_day: 5750, newest: 500, day: '2026-05-08', days: 2 }); // A metric with no readable field is not a metric, and neither is one whose days are all outside // the window — the Coach must not be handed an empty shell it has to interpret. assert.equal(names.includes('empty_metric'), false); assert.equal(names.includes('old_metric'), false); assert.deepEqual(healthSummary(null).metrics, []); }); test('the health summary is bounded, so a prompt cannot be flooded by an export of everything', () => { const days = {}; for (let i = 0; i < 9; i++) days[`2026-05-0${i + 1}`] = { n: 1, lastTs: 0, f: { qty: { n: 1, sum: i, min: 0, max: i, last: i } } }; const metrics = {}; for (let i = 0; i < 20; i++) metrics[`metric_${String(i).padStart(2, '0')}`] = { units: '', days }; const sum = healthSummary({ metrics }, { days: 9, now: Date.parse('2026-05-09T23:00:00Z') }); assert.equal(sum.metrics.length, 8, 'eight metrics is what a plan can be written from'); assert.equal(sum.metrics[0].metric, 'metric_00', 'and they are the first alphabetically, stably'); assert.equal(sum.metrics[0].fields[0].avg_per_day, 4, 'the average is per day with data, not per day in the window'); }); /* ---------- the progress Jev reads ---------- */ /* Reported as "para que Jev tome decisiones debía mirar la sesión de progreso, que tiene todos los datos de los entrenamientos pasados". It did not: the state carried a 28-day window and the last three sessions, so a lift that has not moved in three months looked exactly like a lift that has never been trained. This is the whole history, per exercise. */ test('the progress part reads the whole history, not the last month', () => { const session = (daysAgo, w, r) => ({ d: new Date(NOW - daysAgo * 86400000).toISOString().slice(0, 10), name: 'Push', start: 1000, end: 3601000, entries: [{ id: 'e1', sets: [{ w, r, done: true, rpe: 8 }] }] }); // Four old sessions that climb (60 → 66 → 70 → 75) and three recent ones stuck at 75, plus one // session for an exercise that has not been touched since: the two shapes a decision turns on. const S2 = { ...S, unit: 'kg', workouts: [ session(140, 60, 8), session(120, 66, 8), session(100, 70, 8), session(80, 75, 8), session(12, 75, 8), session(8, 75, 8), session(4, 75, 8), { d: new Date(NOW - 90 * 86400000).toISOString().slice(0, 10), name: 'Pull', start: 1000, end: 3601001, entries: [{ id: 'e3', sets: [{ w: 20, r: 5, done: true }] }] }, // A timed set: it is a set, and it has no reps, so it counts in the sets and adds no volume. { d: new Date(NOW - 3 * 86400000).toISOString().slice(0, 10), name: 'Core', start: 1000, end: 3601002, entries: [{ id: 'e2', sets: [{ w: 10, sec: 60, done: true }] }] } ] }; const st = buildState({ S: S2, vitals: vitals(), now: NOW, bodyPartOf, nameOf, exOf }); const p = st.training.progress; assert.equal(p.sessions_total, 9); assert.equal(p.first_session_days_ago, 140, 'the first session is five months back, not four weeks'); assert.equal(p.sets_total, 9, 'eight reps-mode sets and one timed'); const bench = p.exercises.find(e => e.id === 'e1'); assert.equal(bench.name, 'barbell bench press'); assert.equal(bench.body_part, 'chest'); assert.equal(bench.sessions, 7); const r1 = v => Math.round(v * 10) / 10; assert.equal(bench.first.est, r1(epley(60, 8))); assert.equal(bench.latest.est, r1(epley(75, 8))); assert.equal(bench.best.est, r1(epley(75, 8))); // The last three sessions against the three before them: this block is heavier than the one under // it, so it reads as progress even though the newest three are all the same weight. assert.equal(bench.trend, 'up'); assert.equal(bench.series.length, 7, 'one point per session, so the shape is visible'); assert.ok(bench.first.days_ago > bench.latest.days_ago); // The exercise nobody has touched in three months is *in* the reading — that is the whole point. const pull = p.exercises.find(e => e.id === 'e3'); assert.equal(pull.sessions, 1); assert.equal(pull.latest.days_ago, 90); assert.equal(pull.trend, 'flat'); // Weekly load and volume are the *recent* trend — ten weeks — while the totals above them are the // whole history. Two different questions, two different windows, said apart. assert.ok(p.weekly.length >= 2); assert.ok(p.weekly.every(w => w.weeks_ago < 10), 'the weekly series is a recent trend'); assert.ok(p.weekly[0].weeks_ago > p.weekly[p.weekly.length - 1].weeks_ago, 'oldest week first'); assert.equal(p.weekly.reduce((n, w) => n + w.sessions, 0), 4, 'the five-month-old sessions are in the totals, not here'); assert.ok(p.weekly.every(w => w.sets > 0)); assert.equal(p.sets_total, 9, 'every done set counts, whatever mode it was'); // The newest week holds the reps-mode session and the timed one: two sets, and the volume of the // reps-mode one only — a timed set has no reps to multiply. const thisWeek = p.weekly.find(w => w.weeks_ago === 0); assert.deepEqual({ sessions: thisWeek.sessions, sets: thisWeek.sets, volume: thisWeek.volume }, { sessions: 2, sets: 2, volume: 75 * 8 }); // A long history, because that is the whole point: a lift that has not moved in months is the // thing a plan exists to change, and any window over "the last N sessions" hides exactly that. const long = []; for (let i = 39; i >= 0; i--) long.push(session(i * 4, 60 + Math.floor((39 - i) / 8) * 5, 8)); const deep = buildState({ S: { ...S2, workouts: long }, vitals: null, now: NOW, bodyPartOf, nameOf, exOf }).training.progress; assert.equal(deep.sessions_total, 40); assert.equal(deep.first_session_days_ago, 156, 'five months of history, not four weeks of it'); assert.equal(deep.exercises[0].sessions, 40, 'and every one of them counts for that exercise'); // The cap is on what is *shown*, never on what is counted: ten points of shape, forty sessions of // arithmetic, and the first/last/best rows point at the whole span. assert.equal(deep.exercises[0].series.length, 10); assert.equal(deep.exercises[0].best.est, Math.round(epley(80, 8) * 10) / 10, 'the estimate is rounded once, in one place'); assert.ok(deep.exercises[0].first.days_ago > 100); //...and the other two directions, so "flat" is a verdict and not just the fallthrough. const trendOf = workouts => buildState({ S: { ...S2, workouts }, vitals: null, now: NOW, bodyPartOf, nameOf, exOf }) .training.progress.exercises[0].trend; assert.equal(trendOf([session(30, 70, 8), session(26, 70, 8), session(22, 70, 8), session(12, 70, 8), session(8, 70, 8), session(4, 70, 8)]), 'flat'); assert.equal(trendOf([session(30, 80, 8), session(26, 80, 8), session(22, 80, 8), session(12, 70, 8), session(8, 70, 8), session(4, 70, 8)]), 'down', 'a block that got lighter is said out loud — that is the one a plan has to answer'); }); test('the estimate is the one the Progreso screen draws', () => { // The same Epley, the same rep cap, and the two exclusions — a warm-up row and an assistance // machine — because a plan written from a different number than the chart is not checkable. assert.equal(epley(100, 5), 100 * (1 + 5 / 30)); assert.equal(epley(100, 30), epley(100, REP_CAP), 'the cap holds'); const entry = { sets: [ { w: 100, r: 5, done: true }, { w: 120, r: 2, done: true, warmup: true }, { w: 90, r: 10, done: false } ] }; assert.equal(bestEstimate(entry).est, 116.7); assert.equal(bestEstimate(entry).w, 100); assert.equal(bestEstimate({ sets: [{ w: 0, r: 5, done: true }] }), null); assert.equal(bestEstimate({ sets: [] }), null); assert.equal(isAssistedRow({ eq: 'assisted', n: 'assisted chest dip (kneeling)' }), true); assert.equal(isAssistedRow({ eq: 'assisted', n: 'chest dip' }), false); assert.equal(bestEstimate(entry, { eq: 'assisted', n: 'assisted chest dip' }), null, 'an assistance machine has no 1RM'); }); test('a profile with no history gets an empty progress part, not a fabricated one', () => { const none = buildState({ S: {}, vitals: null, now: NOW }).training.progress; assert.deepEqual(none, { sessions_total: 0, first_session_days_ago: null, span_days: 0, sets_total: 0, weekly: [], exercises: [] }); });