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

+113 -2
View File
@@ -32,6 +32,7 @@
* invented to fill a gap.
*/
import crypto from 'node:crypto';
import { bestEstimate, isWarmup as isWarmupRow } from './coach/core/strength.js';
export const JEV_VERSION = 1;
@@ -198,6 +199,111 @@ function healthPart(vitals, { days, now }) {
return picked.slice(0, MAX_METRICS).map(({ rank, ...m }) => m);
}
/* How much of the history the progress part carries, and why each cap is where it is. The window is
a month because that is the training block a decision is made inside; the *progress* is the whole
history, because a lift that has not moved in three months is the thing a plan is supposed to
change, and a 28-day window cannot see it. Values are capped, never the arithmetic: every number
below is computed over every session the profile has. */
const PROGRESS_WEEKS = 10;
const PROGRESS_EXERCISES = 12;
const PROGRESS_POINTS = 10;
/** The day `n` weeks before `today`, as a day key. */
const weeksAgo = (today, n) => dayISO(Date.parse(today + 'T12:00:00') - n * 7 * 86400000);
/**
* The half of the state that answers "is this working?".
*
* For every exercise the person has actually trained: how many sessions, the estimate of their best
* set then and now, one point per session so the *shape* is visible rather than two endpoints, the
* best they have ever done, and where it has stalled. Plus the weekly load and volume, which is what
* makes "build it up" or "ease off" a decision with something behind it.
*
* The estimate is `api/coach/core/strength.js` — the same Epley the Progreso screen draws, because a
* plan written from a different number than the one on the chart is a plan nobody can check.
*/
function progressPart(S, { now, bodyPartOf, nameOf, exOf }) {
const today = dayISO(now);
const workouts = (S.workouts || []).filter(w => w && w.d && !w.active);
const out = {
sessions_total: workouts.length,
first_session_days_ago: workouts.length ? daysBetween(workouts[0].d, today) : null,
span_days: workouts.length ? daysBetween(workouts[0].d, today) : 0,
sets_total: 0,
weekly: [],
exercises: []
};
if (!workouts.length) return { ...out, sets_total: 0 };
// ---- weekly load and volume, oldest week first
const byWeek = new Map();
for (const w of workouts) {
const back = Math.floor(daysBetween(w.d, today) / 7);
const key = back < 0 ? 0 : back;
const row = byWeek.get(key) || { weeks_ago: key, sessions: 0, sets: 0, volume: 0 };
row.sessions++;
for (const en of w.entries || []) {
for (const set of en.sets || []) {
if (!set || !set.done || isWarmupRow(set)) continue;
row.sets++;
out.sets_total++;
const weight = Number(set.w);
const reps = Number(set.r);
if (weight > 0 && reps > 0) row.volume += weight * reps;
}
}
byWeek.set(key, row);
}
out.weekly = [...byWeek.values()]
.filter(r => r.weeks_ago < PROGRESS_WEEKS)
.sort((a, b) => b.weeks_ago - a.weeks_ago)
.map(r => ({ ...r, volume: Math.round(r.volume) }));
// ---- per exercise, over every session it appears in
const byEx = new Map();
for (const w of workouts) {
for (const en of w.entries || []) {
if (!(en.sets || []).some(s => s && s.done)) continue;
if (!byEx.has(en.id)) byEx.set(en.id, []);
byEx.get(en.id).push({ day: w.d, entry: en });
}
}
const rows = [];
for (const [id, list] of byEx) {
const series = [];
for (const { day, entry } of list) {
const best = bestEstimate(entry, exOf(id));
if (best) series.push({ days_ago: daysBetween(day, today), est: best.est, w: best.w, r: best.r });
}
if (!series.length) continue;
const bestRow = series.reduce((a, b) => (b.est > a.est ? b : a));
const recent = series.slice(-PROGRESS_POINTS);
// "Moving" is the last three sessions against the three before them, not against the all-time
// best: a lift that beat its record in March and has been flat since is not progressing.
const tail = series.slice(-3), head = series.slice(-6, -3);
const mean = a => (a.length ? a.reduce((n, p) => n + p.est, 0) / a.length : null);
const trend = (tail.length && head.length && mean(tail) > mean(head) * 1.02) ? 'up'
: (tail.length && head.length && mean(tail) < mean(head) * 0.98) ? 'down' : 'flat';
rows.push({
id,
name: nameOf(id) || null,
body_part: bodyPartOf(id) || null,
sessions: list.length,
first: series[0],
latest: series[series.length - 1],
best: bestRow,
trend,
series: recent.map(p => p.est)
});
}
rows.sort((a, b) => b.sessions - a.sessions || b.best.est - a.best.est);
out.exercises = rows.slice(0, PROGRESS_EXERCISES).filter(r => r.name);
return out;
}
/** The library row an id names, for `bestEstimate`'s assistance rule. Injected, like the names. */
let LIB_FOR_ESTIMATE = () => null;
export function setLibraryLookup(fn) { LIB_FOR_ESTIMATE = typeof fn === 'function' ? fn : () => null; }
/** The training half: what was lifted, how much of it per body part, and where it has stalled. */
function trainingPart(S, { now, bodyPartOf, nameOf }) {
const workouts = (S.workouts || []).filter(w => w && w.d && !w.active);
@@ -287,7 +393,9 @@ function bodyPart(S, { now }) {
*/
export function buildState({
S = {}, vitals = null, now = Date.now(), days = JEV_DEFAULTS.stateDays,
bodyPartOf = () => null, nameOf = () => null
// The three lookups into the exercise library this needs, injected rather than imported: this
// module stays a pure function of what it is handed, and a test can hand it a tiny fake catalogue.
bodyPartOf = () => null, nameOf = () => null, exOf = () => null
} = {}) {
const intake = (S.coach && S.coach.profile) || null;
const t = new Date(now);
@@ -308,7 +416,10 @@ export function buildState({
// The one free-text field that goes out, and the reason is in the header of this file.
limitations: (intake.limitations || '').toString().slice(0, 300) || null
} : null,
training: trainingPart(S, { now, bodyPartOf, nameOf }),
training: {
...trainingPart(S, { now, bodyPartOf, nameOf }),
progress: progressPart(S, { now, bodyPartOf, nameOf, exOf })
},
bodyweight: bodyPart(S, { now }),
health: { window_days: days, metrics: healthPart(vitals, { days, now }) }
};