Jev decide mirando el histórico completo, no los últimos 28 días
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s

"Para que Jev tome decisiones debía mirar la sesión de progreso, que tiene todos los datos de los
entrenamientos pasados." Exacto, y no lo hacía: el estado llevaba una ventana de cuatro semanas, las
últimas tres sesiones en detalle y un puñado de conteos. Un ejercicio que no se mueve desde hace tres
meses se veía exactamente igual que uno que nunca se entrenó, que es justo la diferencia sobre la que
un plan tiene que decidir.

Ahora el estado lleva, por ejercicio y sobre **todo** el histórico:

  · cuántas sesiones, y el mejor set de la primera y de la última;
  · el mejor de siempre, con su fecha;
  · una serie de hasta diez estimaciones, una por sesión, para que se vea la *forma* y no dos extremos;
  · la dirección: las últimas tres sesiones contra las tres anteriores — no contra el récord de
    marzo, porque un ejercicio que batió su récord en marzo y está plano desde entonces no progresa;
  · y el cuerpo al que pertenece, para que una decisión de selección sepa de qué parte del cuerpo habla.

Más: la carga y el volumen por semana de las últimas diez, los totales de todo el histórico (sesiones,
series, desde cuándo entrena, cuántos sets en total) y los estancamientos del bloque actual. Los topes
son de lo que se *muestra* — 12 ejercicios, 10 puntos, 10 semanas — nunca de la aritmética: cada número
se calcula sobre todas las sesiones que el perfil tenga, y hay un test con 40 sesiones y cinco meses de
historia que falla si alguien mete una ventana otra vez.

La estimación de 1RM se comparte en vez de duplicarse: `api/coach/core/strength.js` es un espejo
deliberado de `frontend/src/lib/onerm.js` — mismo Epley, mismo tope de 12 repeticiones, mismas dos
exclusiones (series de calentamiento; máquinas asistidas, cuyo peso es la ayuda recibida y no la carga
levantada) — y `cohort.js`, que tenía su propia copia del cálculo, ahora usa esa. Un plan escrito desde
un número distinto al que dibuja la pantalla de Progreso es un plan que nadie puede verificar, así que
la fórmula vive en dos lugares a propósito y los tests la comparan con los mismos ejemplos.

Los ids de ejercicios del histórico viajan con su nombre, en la misma línea que ya lo hacían los
estancados: una decisión sobre *qué ejercicio cambiar* tiene que nombrar algo que la app pueda editar.

Tests: el histórico largo, las tres direcciones de tendencia, el tope de puntos con la aritmética
intacta, el volumen de una serie por tiempo (un set sin repeticiones suma al conteo y nada al volumen)
y la estimación compartida. API 279 en verde, frontend 1705.
This commit is contained in:
dsantillan committed 2026-09-23 19:16:24 -04:00
1 parent f80ade25f6
commit 9a4394aff5
7 files changed
+311 -19

No files matched your search

+118 -2
View File
@@ -12,6 +12,7 @@ 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;
@@ -50,7 +51,8 @@ const vitals = () => ({
});
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 state = (over = {}) => buildState({ S, vitals: vitals(), now: NOW, bodyPartOf, nameOf, ...over });
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 ---------- */
@@ -253,7 +255,7 @@ test('the stored judgment is small, dated and tied to the state it was made from
// 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 }));
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 });
@@ -323,3 +325,117 @@ test('the health summary is bounded, so a prompt cannot be flooded by an export
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: [] });
});