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.
733 lines
34 KiB
JavaScript
733 lines
34 KiB
JavaScript
/* jev.js — the second opinion: a judgment about a profile, answered in probabilities.
|
|
*
|
|
* Jev is TypeSafe's "System One" model, served by OpenCode Zen at
|
|
* `POST https://opencode.ai/zen/v1/systemone`. It is **not a chat model**: you hand it a *state*
|
|
* and a map of *typed questions* — yes/no (`noul`), multiple choice (`choice`), rubric score
|
|
* (`score`) — and it answers all of them in one request with the value it settled on plus the
|
|
* probability it put there. That shape is the whole reason this file exists, and the reason it is
|
|
* not part of the Coach: the Coach **writes** (a routine, an explanation); this **judges**, and a
|
|
* judgment that comes with "62% likely" is a different, more honest object than a paragraph.
|
|
*
|
|
* ── What leaves the instance, and what does not ──────────────────────────────────────────────
|
|
*
|
|
* The feature is off unless somebody sets a key (JEV_API_KEY / OPENCODE_API_KEY), and what it
|
|
* sends is built here, by `buildState`, from aggregates only: this week's numbers against the
|
|
* window's, how many sets each body part has taken, how many days ago the last session was, how
|
|
* many days of data exist. No profile id, no user name, no workout titles, no chat, no free text —
|
|
* with **one deliberate exception**: the Coach intake's `limitations` field ("bad shoulder, no
|
|
* overhead press") is sent when the person filled it in, because it is the single most
|
|
* decision-relevant sentence anyone types about themselves and a judgment that ignores it is
|
|
* worse than useless. It is their own note, going to their own provider, on a screen that says so
|
|
* (see `docs/HEALTH.md` and the card's own sheet).
|
|
*
|
|
* ── Why the parser is tolerant ───────────────────────────────────────────────────────────────
|
|
*
|
|
* The request contract is documented; the response is a map of typed answers and this file has
|
|
* never seen one from the live service. So `parseAnswers` accepts every shape the answers plausibly
|
|
* arrive in — `answers`/`results`, a bare top-level map, `option`/`answer`/`choice`, `probability`
|
|
* or a `probabilities` distribution — normalises what it finds, and returns null for anything it
|
|
* cannot read rather than throwing. The raw payload is kept beside the parsed one for exactly that
|
|
* reason: the first real call can be looked at, and a shape this file guessed wrong is a fix, not a
|
|
* mystery. Every number that reaches the screen is either parsed here or absent; nothing is
|
|
* 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;
|
|
|
|
/* ---------- configuration (environment, like the Coach's, and off by default) ---------- */
|
|
|
|
export const JEV_DEFAULTS = Object.freeze({
|
|
// The gateway, not the vendor: OpenCode Zen serves Jev from the same account as its other
|
|
// models, so one key can drive both this and the Coach's provider list.
|
|
baseUrl: 'https://opencode.ai/zen',
|
|
// `jev-1.13-free` is the limited-time free model the gateway also serves.
|
|
model: 'jev-1.13',
|
|
maxPerDay: 12, // requests per profile per day; each one costs money
|
|
minIntervalMs: 10 * 60 * 1000, // and a person cannot meaningfully ask twice in ten minutes
|
|
timeoutMs: 25 * 1000,
|
|
stateDays: 7 // days of health data in the state
|
|
});
|
|
|
|
const envText = (env, name) => String(env[name] || '').trim() || null;
|
|
const envNum = (env, name, fallback) => {
|
|
const raw = envText(env, name);
|
|
// An unset variable is not zero: `Number('')` and `Number(null)` both pass a naive check, and a
|
|
// caps of 0 or a timeout of 0 is a feature that looks configured and never works. Unset, blank
|
|
// or unreadable all mean "use the default".
|
|
if (raw == null) return fallback;
|
|
const n = Number(raw);
|
|
return Number.isFinite(n) && n >= 0 ? n : fallback;
|
|
};
|
|
|
|
/**
|
|
* What this instance was started with. `configured` is the only thing the UI branches on: no key
|
|
* means the card does not exist at all rather than existing and failing.
|
|
*/
|
|
export function jevConfig(env = process.env) {
|
|
const off = /^(1|true|yes|on)$/i.test(envText(env, 'JEV_DISABLED') || '');
|
|
const key = envText(env, 'JEV_API_KEY') || envText(env, 'OPENCODE_API_KEY');
|
|
const baseUrl = (envText(env, 'JEV_BASE_URL') || JEV_DEFAULTS.baseUrl).replace(/\/+$/, '');
|
|
return {
|
|
configured: !!key && !off,
|
|
// Kept out of anything logged or returned to a client, like every other credential here.
|
|
key: key || null,
|
|
baseUrl,
|
|
model: envText(env, 'JEV_MODEL') || JEV_DEFAULTS.model,
|
|
maxPerDay: envNum(env, 'JEV_MAX_PER_DAY', JEV_DEFAULTS.maxPerDay),
|
|
minIntervalMs: envNum(env, 'JEV_MIN_INTERVAL_MS', JEV_DEFAULTS.minIntervalMs),
|
|
timeoutMs: envNum(env, 'JEV_TIMEOUT_MS', JEV_DEFAULTS.timeoutMs),
|
|
stateDays: envNum(env, 'JEV_STATE_DAYS', JEV_DEFAULTS.stateDays)
|
|
};
|
|
}
|
|
|
|
/** The endpoint, from whatever base URL was configured (with or without `/v1`, with or without the path). */
|
|
export function jevEndpoint(baseUrl) {
|
|
const base = String(baseUrl || JEV_DEFAULTS.baseUrl).replace(/\/+$/, '');
|
|
if (/\/v1\/systemone$/.test(base)) return base;
|
|
if (/\/v1$/.test(base)) return base + '/systemone';
|
|
return base + '/v1/systemone';
|
|
}
|
|
|
|
/* ---------- the state: aggregates, and nothing that identifies anybody ---------- */
|
|
|
|
/* The handful of metrics worth asking about, in the order they matter, with the one line of
|
|
* vocabulary the model needs to read them. A metric that is not here still reaches the state — the
|
|
* profile's own health file decides that (see below) — it just arrives without a gloss. */
|
|
const METRIC_GLOSS = {
|
|
resting_heart_rate: 'resting heart rate, beats per minute (lower is usually better trained)',
|
|
heart_rate_variability: 'beat-to-beat variability in ms (higher usually means better recovered)',
|
|
heart_rate: 'heart rate across the day, beats per minute',
|
|
sleep_analysis: 'hours asleep and the stages of last night',
|
|
respiratory_rate: 'breaths per minute while asleep',
|
|
blood_oxygen_saturation: 'oxygen saturation, percent',
|
|
apple_sleeping_wrist_temperature: 'wrist temperature while asleep, degrees',
|
|
step_count: 'steps taken that day',
|
|
active_energy: 'active energy burned, kcal',
|
|
apple_exercise_time: 'minutes of exercise',
|
|
apple_stand_hour: 'hours in which the person stood for a minute',
|
|
distance_walking_running: 'walking and running distance',
|
|
weight_body_mass: 'body mass',
|
|
body_fat_percentage: 'body fat, percent',
|
|
vo2_max: 'estimated VO₂ max',
|
|
cardio_recovery: 'heart-rate drop one minute after exercise'
|
|
};
|
|
/** Preference order for the state, best first: the metrics a readiness judgment actually reads. */
|
|
const METRIC_ORDER = Object.keys(METRIC_GLOSS);
|
|
const MAX_METRICS = 8;
|
|
/* How many stalled exercises the judgment is asked about in one request. Jev answers many questions
|
|
in one call, and each of these is one choice with four options — six is enough to cover a plan,
|
|
and beyond it the answers stop being decisions anybody reads. */
|
|
const MAX_STALLS = 6;
|
|
|
|
/** The body parts the library uses (`bp` in library-data.js), glossed for the choice question. */
|
|
const BODY_PARTS = {
|
|
chest: 'chest and pressing muscles',
|
|
back: 'back, lats and upper back',
|
|
shoulders: 'shoulders and delts',
|
|
'upper arms': 'biceps and triceps',
|
|
'lower arms': 'forearms and grip',
|
|
waist: 'abs and trunk',
|
|
'upper legs': 'quads, hamstrings and glutes',
|
|
'lower legs': 'calves and shins',
|
|
neck: 'neck and traps',
|
|
cardio: 'cardiovascular system'
|
|
};
|
|
|
|
const round = (v, dec = 1) => (Number.isFinite(v) ? Math.round(v * 10 ** dec) / 10 ** dec : null);
|
|
/** A calendar day, from a Date, an epoch or a day string — callers pass all three. */
|
|
const dayISO = t => (t instanceof Date ? t : new Date(t)).toISOString().slice(0, 10);
|
|
const daysBetween = (a, b) => Math.round((Date.parse(b + 'T12:00:00') - Date.parse(a + 'T12:00:00')) / 86400000);
|
|
|
|
/** One metric's fields over a set of days, summed the way an aggregate should be. */
|
|
function foldFields(days) {
|
|
const out = {};
|
|
for (const f of days) {
|
|
for (const [k, v] of Object.entries(f || {})) {
|
|
const cur = out[k] || (out[k] = { n: 0, sum: 0, min: null, max: null, last: null });
|
|
cur.n += v.n || 0;
|
|
cur.sum += v.sum || 0;
|
|
if (v.min != null && (cur.min == null || v.min < cur.min)) cur.min = v.min;
|
|
if (v.max != null && (cur.max == null || v.max > cur.max)) cur.max = v.max;
|
|
cur.last = v.last;
|
|
}
|
|
}
|
|
for (const v of Object.values(out)) {
|
|
// The average per *day with data*, which is the number a person would compare against: a
|
|
// weekly total says nothing about whether last night was bad.
|
|
v.avg = v.n ? round(v.sum / v.n, 2) : null;
|
|
v.sum = round(v.sum, 2);
|
|
v.min = round(v.min, 2);
|
|
v.max = round(v.max, 2);
|
|
v.last = round(v.last, 2);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* The health half of the state: a week of every metric the profile actually has, newest day first
|
|
* in `today`. Deliberately per *field* and uninterpreted — the server does not know that a step
|
|
* count is a total and a heart rate is a rate (that is the frontend's catalogue, and duplicating it
|
|
* here would give the two a way to disagree), so it sends `qty`/`Avg`/`asleep` exactly as HAE named
|
|
* them, summed across the window.
|
|
*/
|
|
function healthPart(vitals, { days, now }) {
|
|
const metrics = (vitals && vitals.metrics) || {};
|
|
const from = dayISO(new Date(now - (days - 1) * 86400000));
|
|
const picked = [];
|
|
for (const name of Object.keys(metrics)) {
|
|
const m = metrics[name];
|
|
const all = Object.keys(m.days || {}).filter(d => d >= from).sort();
|
|
if (!all.length) continue;
|
|
const newest = all[all.length - 1];
|
|
picked.push({
|
|
name,
|
|
units: m.units || '',
|
|
today: { day: newest, fields: foldFields([m.days[newest].f || {}]), samples: m.days[newest].n || 0 },
|
|
week: { days: all.length, from: all[0], fields: foldFields(all.map(d => m.days[d].f || {})) },
|
|
gloss: METRIC_GLOSS[name] || null,
|
|
rank: METRIC_ORDER.indexOf(name)
|
|
});
|
|
}
|
|
// The catalogue's own order first (those are the metrics a judgment is worth making on), then
|
|
// whatever else the phone sends, alphabetically, up to the cap.
|
|
picked.sort((a, b) => {
|
|
const ra = a.rank < 0 ? 1e6 : a.rank, rb = b.rank < 0 ? 1e6 : b.rank;
|
|
return ra - rb || a.name.localeCompare(b.name);
|
|
});
|
|
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);
|
|
const today = dayISO(now);
|
|
const window = workouts.filter(w => daysBetween(w.d, today) <= 28);
|
|
const recent = workouts.slice(-3);
|
|
const sets = (list, withinDays) => {
|
|
const hit = {};
|
|
for (const w of list) {
|
|
if (daysBetween(w.d, today) > withinDays) continue;
|
|
for (const en of w.entries || []) {
|
|
const work = (en.sets || []).filter(s => s && s.done);
|
|
if (!work.length) continue;
|
|
const bp = bodyPartOf(en.id) || 'other';
|
|
hit[bp] = (hit[bp] || 0) + work.length;
|
|
}
|
|
}
|
|
return hit;
|
|
};
|
|
/* No workout title: it is free text a person typed, and a readiness judgment gets nothing from it
|
|
that `sets`, `minutes`, `avg_rpe` and `body_parts` do not already say. Left out rather than
|
|
trusted to be innocuous — "Entreno con Juan en el gimnasio de Málaga" is a valid title. */
|
|
const detail = w => {
|
|
const entries = (w.entries || []).filter(en => (en.sets || []).some(s => s && s.done));
|
|
const rpes = (w.entries || []).flatMap(en => (en.sets || []).filter(s => s.done && s.rpe != null).map(s => s.rpe));
|
|
return {
|
|
days_ago: daysBetween(w.d, today),
|
|
sets: entries.reduce((n, en) => n + (en.sets || []).filter(s => s.done).length, 0),
|
|
minutes: w.end != null && w.start != null ? Math.round((w.end - w.start) / 60000) : null,
|
|
avg_rpe: rpes.length ? round(rpes.reduce((a, b) => a + b, 0) / rpes.length, 1) : null,
|
|
body_parts: [...new Set(entries.map(en => bodyPartOf(en.id)).filter(Boolean))]
|
|
};
|
|
};
|
|
// Stalled: an exercise whose last three sessions have not moved. The Coach's own payload has a
|
|
// richer version of this; what a readiness judgment needs is only the fact and the name — an id
|
|
// means nothing to a model, so the library's own name goes out instead of `e1`.
|
|
const byEx = new Map();
|
|
for (const w of workouts.slice(-12)) {
|
|
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(en);
|
|
}
|
|
}
|
|
const stalled = [];
|
|
for (const [id, list] of byEx) {
|
|
if (list.length < 3) continue;
|
|
const tops = list.slice(-3).map(en => Math.max(...(en.sets || []).filter(s => s.done).map(s => Number(s.w) || 0)));
|
|
if (tops[0] === tops[1] && tops[1] === tops[2] && tops[2] > 0) {
|
|
// The id travels with the name, and only here: a decision about *which exercise to change*
|
|
// has to name the exercise the app can act on, and a library id identifies an exercise in a
|
|
// public dataset rather than a person. The name goes beside it so the model reads words.
|
|
stalled.push({ id, name: nameOf(id) || null, sessions: list.length, last_top: tops[2], body_part: bodyPartOf(id) || null });
|
|
}
|
|
}
|
|
return {
|
|
window_days: 28,
|
|
sessions: window.length,
|
|
last_session_days_ago: workouts.length ? daysBetween(workouts[workouts.length - 1].d, today) : null,
|
|
planned_days_per_week: Object.keys(S.week || {}).filter(k => (S.week[k] || []).length).length,
|
|
sets_by_body_part_28d: sets(workouts, 28),
|
|
sets_by_body_part_7d: sets(workouts, 7),
|
|
stalled: stalled.slice(0, MAX_STALLS).filter(e => e.name),
|
|
recent_sessions: recent.map(detail)
|
|
};
|
|
}
|
|
|
|
/** The body half: the newest weigh-in and how it has moved, which the recovery judgment reads. */
|
|
function bodyPart(S, { now }) {
|
|
const list = (S.bodyweight || []).filter(b => b && b.kg != null);
|
|
if (!list.length) return null;
|
|
const last = list[list.length - 1];
|
|
const monthAgo = list.filter(b => b.d && daysBetween(b.d, dayISO(now)) <= 28);
|
|
return {
|
|
unit: S.unit || 'kg',
|
|
latest: round(last.kg, 2),
|
|
days_ago: last.d ? daysBetween(last.d, dayISO(now)) : null,
|
|
change_28d: monthAgo.length > 1 ? round(last.kg - monthAgo[0].kg, 2) : null,
|
|
target: S.targetW != null ? round(Number(S.targetW), 2) : null
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Build the state Jev is asked about: pure, and the only place that decides what leaves the
|
|
* instance. `bodyPartOf` is injected (the caller passes the library lookup) so this file needs no
|
|
* exercise catalogue of its own.
|
|
*/
|
|
export function buildState({
|
|
S = {}, vitals = null, now = Date.now(), days = JEV_DEFAULTS.stateDays,
|
|
// 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);
|
|
return {
|
|
meta: {
|
|
today: dayISO(t),
|
|
unit: S.unit || 'kg',
|
|
body: S.body || null,
|
|
health_window_days: days,
|
|
effort_scale: 'RPE 1-10 on the logged sets, where 10 is failure'
|
|
},
|
|
profile: intake ? {
|
|
goal: intake.goal || null,
|
|
experience: intake.experience || null,
|
|
days_per_week: intake.daysPerWeek || null,
|
|
session_minutes: intake.sessionMin || null,
|
|
equipment: Array.isArray(intake.equipment) ? intake.equipment.slice(0, 12) : [],
|
|
// 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 }),
|
|
progress: progressPart(S, { now, bodyPartOf, nameOf, exOf })
|
|
},
|
|
bodyweight: bodyPart(S, { now }),
|
|
health: { window_days: days, metrics: healthPart(vitals, { days, now }) }
|
|
};
|
|
}
|
|
|
|
/**
|
|
* A compact read of the last few days, for the Coach.
|
|
*
|
|
* Not the health file: an average, a newest value and a count per metric, over a window. The Coach
|
|
* is writing a training plan, and what it can act on is "sleeping 6.2 h against 7.1 the week before"
|
|
* or "resting heart rate up 6 bpm" — not 288 heart-rate samples. Sending the file would cost tokens,
|
|
* tell the model nothing more, and put a year of somebody's health in a prompt.
|
|
*
|
|
* This module has no catalogue (which field of a metric means something is the frontend's business),
|
|
* so it reports *per field as HAE named it*: `qty`, `Avg`, `asleep`. The metric names and the numbers
|
|
* are the phone's own, which is exactly what makes it safe to add a metric nobody predicted.
|
|
*/
|
|
export function healthSummary(vitals, { days = 7, now = Date.now(), maxMetrics = 8 } = {}) {
|
|
const round2 = v => Math.round(v * 100) / 100;
|
|
const from = new Date(now - (days - 1) * 86400000).toISOString().slice(0, 10);
|
|
const out = [];
|
|
for (const [name, m] of Object.entries((vitals && vitals.metrics) || {})) {
|
|
const inWindow = Object.keys(m.days || {}).filter(k => k >= from).sort();
|
|
if (!inWindow.length) continue;
|
|
const fields = {};
|
|
for (const day of inWindow) {
|
|
const b = m.days[day];
|
|
for (const [k, v] of Object.entries(b.f || {})) {
|
|
const cur = fields[k] || (fields[k] = { days: 0, sum: 0, newest: null, newestDay: null });
|
|
if (v.n) { cur.days++; cur.sum += v.sum || 0; if (day >= (cur.newestDay || '')) { cur.newest = v.last; cur.newestDay = day; } }
|
|
}
|
|
}
|
|
const flat = Object.entries(fields).map(([field, v]) => ({
|
|
field,
|
|
avg_per_day: v.days ? round2(v.sum / v.days) : null,
|
|
newest: round2(v.newest),
|
|
day: v.newestDay,
|
|
days: v.days
|
|
}));
|
|
if (flat.length) out.push({ metric: name, units: m.units || '', days_with_data: inWindow.length, fields: flat });
|
|
}
|
|
// The catalogue's preferred metrics first (readiness is read from sleep, heart rate and steps),
|
|
// then whatever else the phone sends, alphabetically, up to the cap.
|
|
const rank = n => { const i = METRIC_ORDER.indexOf(n); return i < 0 ? 1e6 : i; };
|
|
out.sort((a, b) => rank(a.metric) - rank(b.metric) || a.metric.localeCompare(b.metric));
|
|
return { window_days: days, metrics: out.slice(0, maxMetrics) };
|
|
}
|
|
|
|
/* ---------- the questions: what we want judged, and what each answer would mean ---------- */
|
|
|
|
/**
|
|
* The typed questions, built from the state so that every option is something this profile can
|
|
* actually act on: the body parts it trains, the metrics it has. A choice whose options are
|
|
* guesses ("upper body?") is a question that comes back unusable.
|
|
*/
|
|
export function buildQuestions(state) {
|
|
const trained = Object.keys(state.training?.sets_by_body_part_28d || {});
|
|
const parts = trained.filter(bp => BODY_PARTS[bp]);
|
|
const limiterOptions = {};
|
|
for (const bp of parts) limiterOptions[bp] = BODY_PARTS[bp];
|
|
limiterOptions.none = 'nothing stands out — the data does not point at one part';
|
|
|
|
const metrics = (state.health?.metrics || []).map(m => m.name);
|
|
const attentionOptions = {};
|
|
for (const m of state.health?.metrics || []) attentionOptions[m.name] = m.gloss;
|
|
attentionOptions.none = 'no metric needs attention today';
|
|
const metricList = metrics.length ? metrics.join(', ') : 'none';
|
|
|
|
const q = {
|
|
readiness: {
|
|
type: 'score',
|
|
instructions: 'Given the sleep, resting heart rate, recent training load and how many days it has been since the last session, how ready is this person to train hard today?',
|
|
criteria: [
|
|
'empty — should not train hard, and would be better resting',
|
|
'below par — a light session, technique work, or cardio only',
|
|
'normal — train the planned session as it stands',
|
|
'fresh — a good day to push the top sets',
|
|
'peaking — ready to test a personal best'
|
|
]
|
|
},
|
|
deload: {
|
|
type: 'noul',
|
|
instructions: 'Does this week call for reducing load rather than adding to it — because sleep, resting heart rate or accumulated fatigue point that way?',
|
|
criteria: { true: 'yes — reduce load this week', false: 'no — keep progressing' }
|
|
},
|
|
attention: {
|
|
type: 'choice',
|
|
instructions: `Which of these health metrics most deserves attention today, judging the newest day against the same person's own week (${metricList})?`,
|
|
criteria: attentionOptions
|
|
}
|
|
};
|
|
// How the week should move, when there is enough history to have an opinion about it.
|
|
if ((state.training?.sessions || 0) >= 4) {
|
|
q.volume = {
|
|
type: 'score',
|
|
instructions: 'Given the sessions, the effort logged and how recovery looks, which way should this week\'s training volume go?',
|
|
criteria: [
|
|
'cut it back a lot — this is a week to recover, not to add',
|
|
'ease off slightly',
|
|
'keep it where it is',
|
|
'build it up slightly',
|
|
'build it up a lot — the body is clearly handling it'
|
|
]
|
|
};
|
|
}
|
|
|
|
// Selection, which is the half a plan cannot get from numbers alone: what to do about an exercise
|
|
// that has stopped moving. One question per stalled exercise, keyed by its library id so the answer
|
|
// comes back as something the plan can be edited with — the name rides in the rubric, so the model
|
|
// is still reading words.
|
|
for (const ex of state.training?.stalled || []) {
|
|
q[`exercise_${ex.id}`] = {
|
|
type: 'choice',
|
|
instructions: `"${ex.name}" has stopped progressing: ${ex.sessions} sessions in the window, the last three at the same top set of ${ex.last_top}. What should change about it?`,
|
|
criteria: {
|
|
keep: 'leave the prescription exactly as it is',
|
|
reduce: 'keep the exercise but take volume or load off it',
|
|
swap: 'replace it with a different exercise for the same body part',
|
|
drop: 'take it out of the plan for now'
|
|
}
|
|
};
|
|
}
|
|
|
|
// A choice with no real options is a question that can only be answered wrong, so the limiter
|
|
// one only exists when the profile has trained something we can name.
|
|
if (parts.length) {
|
|
q.limiter = {
|
|
type: 'choice',
|
|
instructions: 'Which body part or system looks least recovered, given the sets it has taken in the last week and the sleep and heart-rate data?',
|
|
criteria: limiterOptions
|
|
};
|
|
}
|
|
return q;
|
|
}
|
|
|
|
/* ---------- the request ---------- */
|
|
|
|
/**
|
|
* One request, every question, no streaming and no retries: a judgment is a request-response and a
|
|
* second attempt costs the same as the first. Returns the parsed JSON body, or throws with the
|
|
* status in the message so the route can turn it into something a person can read.
|
|
*/
|
|
export async function askJev({ cfg, state, questions, fetchImpl = fetch }) {
|
|
const res = await fetchImpl(jevEndpoint(cfg.baseUrl), {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
Authorization: `Bearer ${cfg.key}`,
|
|
// Same reasoning as the music lookup: an instance this small identifies itself, and a gateway
|
|
// asking "what is this traffic" should get an answer.
|
|
'User-Agent': 'KuentaGYM (self-hosted)'
|
|
},
|
|
body: JSON.stringify({ model: cfg.model, state, questions }),
|
|
signal: AbortSignal.timeout(cfg.timeoutMs)
|
|
});
|
|
const text = await res.text();
|
|
let body = null;
|
|
try { body = JSON.parse(text); } catch { /* a gateway that answers with HTML, or with nothing */ }
|
|
if (!res.ok) {
|
|
const e = new Error(`Jev answered ${res.status}${body && body.error && body.error.message ? ': ' + body.error.message : ''}`);
|
|
e.status = res.status;
|
|
throw e;
|
|
}
|
|
if (!body) throw Object.assign(new Error('Jev answered with something that is not JSON'), { status: 502 });
|
|
return body;
|
|
}
|
|
|
|
/* ---------- reading the answer ---------- */
|
|
|
|
const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
|
/** A distribution as `{ option: probability }`, whatever container it arrived in. */
|
|
function distribution(v) {
|
|
const raw = v && typeof v === 'object' && !Array.isArray(v) ? (v.probabilities || v.distribution || v.scores || null) : null;
|
|
if (!raw || typeof raw !== 'object') return null;
|
|
const out = {};
|
|
for (const [k, p] of Object.entries(raw)) {
|
|
const n = num(typeof p === 'object' && p ? p.probability ?? p.p : p);
|
|
if (n != null) out[k] = n;
|
|
}
|
|
return Object.keys(out).length ? out : null;
|
|
}
|
|
const winner = d => {
|
|
if (!d) return null;
|
|
let best = null;
|
|
for (const [k, p] of Object.entries(d)) if (best == null || p > d[best]) best = k;
|
|
return best;
|
|
};
|
|
|
|
/**
|
|
* Normalise one answer. Every shape it might arrive in reduces to the same small object:
|
|
* `{ type, option, value, p, probabilities }` — with `option` the chosen key, `value` a score's
|
|
* weighted level (or 1-based index), `p` the probability that matters for the question's type, and
|
|
* the full distribution when there is one. Anything unreadable becomes null, and the caller
|
|
* decides what to do with a question that came back unanswered (it says so, rather than guessing).
|
|
*/
|
|
export function readAnswer(question, answer) {
|
|
if (!answer || typeof answer !== 'object') return null;
|
|
const type = question && question.type ? question.type : null;
|
|
const probs = distribution(answer);
|
|
const option = [answer.option, answer.answer, answer.choice, answer.label, answer.value]
|
|
.find(v => typeof v === 'string' && v) || winner(probs);
|
|
|
|
if (type === 'noul' || (!type && (num(answer.probability) != null || num(answer.p) != null))) {
|
|
// A yes/no: the probability of yes is the whole answer, whichever way it is spelled.
|
|
let p = num(answer.probability) ?? num(answer.p) ?? num(answer.yes) ?? num(answer.score);
|
|
if (p == null && answer.answer === true) p = 1;
|
|
if (p == null && answer.answer === false) p = 0;
|
|
if (p == null && probs) p = num(probs.true) ?? num(probs.yes) ?? null;
|
|
if (p == null) return null;
|
|
return { type: 'noul', p: round(p, 3), option: p >= 0.5 ? 'true' : 'false' };
|
|
}
|
|
|
|
if (type === 'score') {
|
|
// A rubric score: the gateway may answer with the weighted level, with a 1-based index, or with
|
|
// a distribution over the levels. All three are the same fact, so they all become a level.
|
|
let value = num(answer.value) ?? num(answer.score) ?? num(answer.level);
|
|
if (value == null && option != null && Array.isArray(question?.criteria)) {
|
|
const i = question.criteria.findIndex(c => String(c) === String(option));
|
|
if (i >= 0) value = i + 1;
|
|
}
|
|
if (value == null && probs) {
|
|
const levels = Object.keys(probs);
|
|
const idx = levels.findIndex(k => k === winner(probs));
|
|
if (idx >= 0) value = idx + 1;
|
|
}
|
|
if (value == null) return null;
|
|
return {
|
|
type: 'score',
|
|
value: round(value, 2),
|
|
p: num(answer.probability) ?? num(answer.p) ?? (probs ? round(probs[winner(probs)], 3) : null),
|
|
probabilities: probs
|
|
};
|
|
}
|
|
|
|
// A choice: the option, and how sure it was.
|
|
if (option == null) return null;
|
|
const criteria = (question && question.criteria) || {};
|
|
const known = Object.prototype.hasOwnProperty.call(criteria, option);
|
|
return {
|
|
type: 'choice',
|
|
option: String(option),
|
|
known,
|
|
p: num(answer.probability) ?? num(answer.p) ?? (probs ? round(probs[option], 3) : null),
|
|
probabilities: probs
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The whole response, reduced to one answer per question that was asked. The container is whatever
|
|
* the gateway wrapped it in (`answers`, `results`, or the map at the top level).
|
|
*/
|
|
export function parseAnswers(body, questions) {
|
|
const container = (body && (body.answers || body.results || body.data)) || body || {};
|
|
const out = {};
|
|
for (const [id, question] of Object.entries(questions || {})) {
|
|
const answer = container && typeof container === 'object' ? container[id] : null;
|
|
out[id] = readAnswer(question, answer);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/* ---------- what is stored, and when it is stale ---------- */
|
|
|
|
/** A short digest of the state, so the screen can tell whether the judgment matches the data. */
|
|
export function stateHash(state) {
|
|
return crypto.createHash('sha256').update(JSON.stringify(state)).digest('hex').slice(0, 16);
|
|
}
|
|
|
|
/**
|
|
* The stored judgment. Small on purpose: the answers, when, which model, the digest of the state
|
|
* they were made from, and the raw response (bounded) so a parser that guessed a shape wrong can be
|
|
* looked at instead of debugged. Nothing here is health data — that lives in vitals-<uid>.json.
|
|
*/
|
|
export function makeInsight({ answers, raw, model, stateHash: hash, at = Date.now(), usage = null }) {
|
|
return {
|
|
v: JEV_VERSION,
|
|
at,
|
|
model,
|
|
stateHash: hash || null,
|
|
answers,
|
|
usage,
|
|
raw: raw && JSON.stringify(raw).length > 8000 ? null : raw // bounded; null means "too big to keep"
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Whether a stored judgment should be offered as current. Two reasons it is not: it is older than
|
|
* the window it was made from (a night's sleep changes the answer), or the state has moved under it
|
|
* — the digest catches a session logged or a night of data that arrived since.
|
|
*/
|
|
export function insightFreshness(insight, { now = Date.now(), hash = null, ttlMs = 6 * 3600 * 1000 } = {}) {
|
|
if (!insight || !insight.at) return { fresh: false, reason: 'none' };
|
|
if (now - insight.at > ttlMs) return { fresh: false, reason: 'old' };
|
|
if (hash && insight.stateHash && hash !== insight.stateHash) return { fresh: false, reason: 'data' };
|
|
return { fresh: true, reason: null };
|
|
}
|
|
|
|
/** The per-profile budget, kept in the insight file itself: a cap with no second file to lose. */
|
|
export function budgetFor(insight, { now = Date.now(), maxPerDay = JEV_DEFAULTS.maxPerDay, minIntervalMs = JEV_DEFAULTS.minIntervalMs } = {}) {
|
|
const used = insight && insight.day === dayISO(new Date(now)) ? (insight.used || 0) : 0;
|
|
const since = insight && insight.at ? now - insight.at : Infinity;
|
|
const waitMs = Math.max(0, minIntervalMs - since);
|
|
return {
|
|
used,
|
|
remaining: Math.max(0, maxPerDay - used),
|
|
allowed: used < maxPerDay && waitMs === 0,
|
|
waitMs,
|
|
nextAt: waitMs ? now + waitMs : null
|
|
};
|
|
}
|