From 9a4394aff57ae3b22fd2e4f257e94c634fe3bacc Mon Sep 17 00:00:00 2001 From: Daniel Santillan Date: Wed, 23 Sep 2026 19:16:24 -0400 Subject: [PATCH] =?UTF-8?q?Jev=20decide=20mirando=20el=20hist=C3=B3rico=20?= =?UTF-8?q?completo,=20no=20los=20=C3=BAltimos=2028=20d=C3=ADas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "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. --- api/coach/cohort.js | 11 +--- api/coach/core/strength.js | 45 ++++++++++++++ api/insights.js | 4 ++ api/jev.js | 115 ++++++++++++++++++++++++++++++++++- api/openapi.yaml | 16 +++-- api/test/jev.test.js | 120 ++++++++++++++++++++++++++++++++++++- docs/AI_COACH.md | 19 ++++++ 7 files changed, 311 insertions(+), 19 deletions(-) create mode 100644 api/coach/core/strength.js diff --git a/api/coach/cohort.js b/api/coach/cohort.js index 57f5e52..a6adb0a 100644 --- a/api/coach/cohort.js +++ b/api/coach/cohort.js @@ -13,6 +13,7 @@ * review — and cached for a few minutes, because a box with forty profiles should not parse * forty JSON blobs on every open of the sheet. */ +import { epley, isWarmup } from './core/strength.js'; import * as cfgStore from './config.js'; import { readState, listUserIds, isSharing } from './jobs.js'; import { libraryName } from './core/library.js'; @@ -23,16 +24,6 @@ const WEEKS_STRENGTH = 12; const WEEKS_FREQUENCY = 8; const CACHE_MS = 5 * 60000; const LB_TO_KG = 0.45359237; -const REP_CAP = 12; // mirrors frontend/src/lib/onerm.js: past twelve reps the estimate stops meaning much - -// Mirror of frontend/src/lib/workout-model.js isWarmupRow: an explicit phase wins over the -// legacy boolean. -const isWarmup = s => { - const ph = typeof s?.phase === 'string' ? s.phase.trim().toLowerCase() : ''; - if (ph) return ph === 'warmup' || ph === 'warm-up' || ph === 'warm_up'; - return s?.warmup === true; -}; -const epley = (w, r) => w * (1 + Math.min(r, REP_CAP) / 30); const round1 = n => Math.round(n * 10) / 10; const median = arr => { const a = arr.filter(n => Number.isFinite(n)).sort((x, y) => x - y); diff --git a/api/coach/core/strength.js b/api/coach/core/strength.js new file mode 100644 index 0000000..32e85ba --- /dev/null +++ b/api/coach/core/strength.js @@ -0,0 +1,45 @@ +/* strength.js — the one estimate of a one-rep max on the server side. + * + * A mirror of `frontend/src/lib/onerm.js`, and deliberately a small one: the formula, the rep cap + * and the two rules that keep an estimate honest. The screen computes this for the person looking at + * it and the server computes it for the Coach and for Jev, and the two must not disagree — a plan + * written from a different number than the one on the chart is a plan nobody can check. + * + * What is mirrored is the *decision*, not the code: Epley (`w · (1 + r/30)`), the same REP_CAP of 12 + * (past that the estimators diverge by double digits and the answer says more about work capacity + * than about strength), warm-up rows excluded, and assistance machines excluded — their load is the + * help given, so Epley on it would rise as the person got weaker and call that a record. + */ +export const REP_CAP = 12; // mirrors frontend/src/lib/onerm.js + +/** Epley 1985. The default there, and the only one used here. */ +export const epley = (w, r) => w * (1 + Math.min(r, REP_CAP) / 30); + +/** Mirror of `isWarmupRow` in frontend/src/lib/workout-model.js: an explicit phase wins over the + * legacy boolean, so a row marked both ways is a warm-up. */ +export const isWarmup = s => { + const ph = typeof s?.phase === 'string' ? s.phase.trim().toLowerCase() : ''; + if (ph) return ph === 'warmup' || ph === 'warm-up' || ph === 'warm_up'; + return s?.warmup === true; +}; + +/** Mirror of `isAssisted` in frontend/src/lib/exercises.js, for a catalogue row. */ +export const isAssistedRow = ex => !!ex && ex.eq === 'assisted' && /assisted/i.test(String(ex.n || '')); + +/** + * The best estimate out of one workout entry's completed sets: `{ est, w, r }`, or null when this + * entry produced nothing an estimate can be made from. `topW` is ignored on purpose — it records a + * working weight with no rep count attached. + */ +export function bestEstimate(entry, ex = null) { + if (isAssistedRow(ex)) return null; + let best = null; + for (const s of entry?.sets || []) { + if (!s || !s.done || isWarmup(s)) continue; + const w = Number(s.w), r = Number(s.r); + if (!(w > 0) || !(r > 0)) continue; + const est = epley(w, r); + if (Number.isFinite(est) && (!best || est > best.est)) best = { est: Math.round(est * 10) / 10, w, r: Math.round(r) }; + } + return best; +} diff --git a/api/insights.js b/api/insights.js index fbf2f0e..4fb4057 100644 --- a/api/insights.js +++ b/api/insights.js @@ -45,6 +45,9 @@ export const readVitalsFile = uid => readJson(profileFile('vitals-', uid)); const bodyPartOf = id => LIB_BY_ID.get(id)?.bp || null; const exerciseName = id => LIB_BY_ID.get(id)?.n || null; +// The whole row, not just a field: the 1RM estimate has to know an exercise is an assistance +// machine, whose load is the help given rather than the weight lifted. +const exerciseRow = id => LIB_BY_ID.get(id) || null; /** The state the judgment is asked about, built from the profile's own files. */ export function stateFor(uid, cfg = jevConfig()) { @@ -53,6 +56,7 @@ export function stateFor(uid, cfg = jevConfig()) { vitals: readVitalsFile(uid), bodyPartOf, nameOf: exerciseName, + exOf: exerciseRow, days: cfg.stateDays }); } diff --git a/api/jev.js b/api/jev.js index 5bb0399..0b05a95 100644 --- a/api/jev.js +++ b/api/jev.js @@ -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 }) } }; diff --git a/api/openapi.yaml b/api/openapi.yaml index b7a0ce4..b0057ee 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -857,13 +857,19 @@ paths: operationId: insightsAsk summary: Ask for a second opinion about this profile description: | - Builds a state from the profile's own aggregates — a week of every health metric it has, the - sets per body part over four weeks, the last few sessions, the newest weigh-in, and the Coach - intake's goal and limitations note — sends it to Jev (TypeSafe's System One model, through + Builds a state from the profile's own data — a week of every health metric it has, the sets + per body part over four weeks, the last few sessions, **the whole training history per + exercise** (sessions, the estimate of the best set then and now, one point per session, and + where it has stalled), the weekly load and volume of the last ten weeks, the newest weigh-in, + and the Coach intake's goal and limitations note — sends it to Jev (TypeSafe's System One model, through the OpenCode Zen gateway) with four typed questions, and stores the answers. - **What leaves the instance is decided server-side and is aggregates only**: no name, no ids, - no workout titles, no chat. The one piece of the person's own writing that goes is the + **What leaves the instance is decided server-side and is aggregates only**: no name, no + workout titles, no chat, and no identifier of a person. The exceptions are deliberate and + small: the Coach intake's `limitations` note, because "bad shoulder" changes the answer, and + the **library id of an exercise that has stopped progressing**, because a question about + which exercise to change has to name something the app can edit — a library id is a row in a + public dataset, not an identifier of anybody. The one piece of the person's own writing that goes is the intake's `limitations` field, because "bad shoulder" changes the answer; the sheet in front of the button lists exactly what will be sent before it is sent. diff --git a/api/test/jev.test.js b/api/test/jev.test.js index 601839f..83bc522 100644 --- a/api/test/jev.test.js +++ b/api/test/jev.test.js @@ -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: [] }); +}); diff --git a/docs/AI_COACH.md b/docs/AI_COACH.md index 893e499..3e278c2 100644 --- a/docs/AI_COACH.md +++ b/docs/AI_COACH.md @@ -44,6 +44,7 @@ purpose — a plan is written from evidence, and evidence is small. | `history.workingWeights` (create) — the best weight actually handled per exercise | every logged session | | `window` + `aggregates` (review, debrief) — the last three sessions set by set, older ones compacted, plus stalls, adherence and sets per body part | the workout history | | `bodyweight` — the weigh-ins of the last weeks and the target weight. Now in a **create** payload too, not only review and debrief | the Stats screen's weigh-in log | +| **What Jev is asked about** | the same state the Coach gets, plus the whole training history per exercise — see the table in *Jev decides, the model writes* below | | `health` — a week of Apple Health **as averages**: per metric and per field, the daily average, the newest value and how many days had data (see below) | `api/jev.js`'s `healthSummary`, over the file the phone posts | | `secondOpinion` — a judgment with probabilities, when one was asked for less than six hours ago | the Salud card (Jev via OpenCode Zen) | | `cohort` (optional) — anonymous medians across profiles that opted in | the community aggregate | @@ -70,6 +71,24 @@ the moment a decision is needed. A debrief is excluded — a readiness verdict i A provider that fails, or an instance with no key, or a spent budget leaves the job running exactly as it did before this existed: the judgment is context, never a dependency. +### What Jev is given + +The judgment is only as good as the state, and the state is built to answer *"is this working?"* — not +just *"what happened lately"*. So it carries the **whole history per exercise**, bounded on what is +shown rather than on what is counted: + +| In the state | Why | +| --- | --- | +| `training.progress.sessions_total`, `first_session_days_ago`, `span_days`, `sets_total` | the span, so "no progress in three months" is visible at all | +| `training.progress.exercises[]` — per exercise: sessions, `first`/`latest` (weight, reps, estimate), `best`, `trend` (last three sessions against the three before), and up to ten points of estimate | a lift that stopped moving, and one that is climbing, are different decisions | +| `training.progress.weekly[]` — sessions, sets and volume per week, ten weeks | which way the load has been going, as numbers | +| `training.window_days` + sets per body part, `stalled`, the last three sessions in detail | the current block, the gaps, and what is stuck *now* | + +The estimate is `api/coach/core/strength.js` — the same Epley, the same rep cap, the same two +exclusions (warm-up rows, assistance machines) that `frontend/src/lib/onerm.js` draws the Progreso +screen with. A plan written from a different number than the one on the chart is a plan nobody can +check, so the formula exists twice on purpose and the two are tested against the same examples. + What Jev is asked, in one request (see `buildQuestions` in `api/jev.js`): | Question | Type | What the writer does with it |