Files
dsantillan 9a4394aff5
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Jev decide mirando el histórico completo, no los últimos 28 días
"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.
2026-09-23 19:16:24 -04:00

144 lines
6.1 KiB
JavaScript

/* insights.js — the second opinion: where it lives, and the one way it is produced.
*
* One small file per profile, beside the health file it was judged from and written the same way
* (write-temp-then-rename, mode 0600). It holds the answers, when they were made and which model
* made them — never the health data itself, which stays in vitals-<uid>.json.
*
* Separate from server.js because two other readers want it: the Coach, which carries the judgment
* into its prompt when it is recent enough to still be true, and the routes. Nothing here interprets
* the document; the shape belongs to jev.js and the meaning to the screen.
*/
import fs from 'node:fs';
import path from 'node:path';
import {
jevConfig, buildState, buildQuestions, askJev, parseAnswers, makeInsight, stateHash,
insightFreshness, budgetFor
} from './jev.js';
import { LIB_BY_ID } from './coach/core/library.js';
const DATA = process.env.DATA_DIR || '/data';
export const insightFile = uid => path.join(DATA, 'insight-' + String(uid).replace(/[^a-zA-Z0-9_-]/g, '') + '.json');
export function readInsight(uid) {
try { return JSON.parse(fs.readFileSync(insightFile(uid), 'utf8')); } catch { return null; }
}
export function writeInsight(uid, doc) {
const file = insightFile(uid);
const tmp = file + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(doc), { mode: 0o600 });
fs.renameSync(tmp, file);
}
export function clearInsight(uid) {
try { fs.unlinkSync(insightFile(uid)); } catch { /* nothing stored */ }
}
/* ---------- the files it judges ---------- */
const profileFile = (prefix, uid) => path.join(DATA, prefix + String(uid).replace(/[^a-zA-Z0-9_-]/g, '') + '.json');
const readJson = file => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } };
export const readStateFile = uid => readJson(profileFile('state-', uid));
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()) {
return buildState({
S: readStateFile(uid) || {},
vitals: readVitalsFile(uid),
bodyPartOf,
nameOf: exerciseName,
exOf: exerciseRow,
days: cfg.stateDays
});
}
/** Counts, never content: what a screen needs to say what it just sent. */
export function summarizeState(state) {
return {
metrics: (state.health?.metrics || []).map(m => m.name),
health_days: state.health?.window_days || 0,
sessions: state.training?.sessions || 0,
last_session_days_ago: state.training?.last_session_days_ago ?? null,
body_parts: Object.keys(state.training?.sets_by_body_part_28d || {}),
stalled: (state.training?.stalled || []).map(e => e.name),
includes_limitations: !!state.profile?.limitations
};
}
/** The endpoint's host, for a screen to name. Never the key with it. */
export function endpointHost(baseUrl) {
try { return new URL(baseUrl).host; } catch { return null; }
}
/* ---------- running it ----------
*
* One function, two callers, and that is the point: the Salud card asks, and so does a Coach job
* that is about to write a plan. "Jev decides, the model writes" only happens if the judgment is
* there when the writing starts, and waiting for somebody to tap a button on another screen is how
* the two halves never meet. The budget is checked here, in the one place, so an automatic ask can
* never spend more than a manual one — and a provider that fails is reported, not thrown, because a
* Coach job that dies because its second opinion was unavailable is worse than one without it. */
/**
* Ask Jev about this profile and store the answer.
*
* @returns {Promise<{ok:true, insight:object, sent:object, budget:object}
* | {ok:false, reason:'unconfigured'|'budget'|'provider', status?:number, error?:string}>}
*/
export async function runInsight(uid, { fetchImpl = fetch, now = Date.now(), cfg = jevConfig() } = {}) {
if (!cfg.configured) return { ok: false, reason: 'unconfigured' };
const stored = readInsight(uid);
const budget = budgetFor(stored, { now, maxPerDay: cfg.maxPerDay, minIntervalMs: cfg.minIntervalMs });
if (!budget.allowed) return { ok: false, reason: 'budget', budget };
const state = stateFor(uid, cfg);
const questions = buildQuestions(state);
let body;
try {
body = await askJev({ cfg, state, questions, fetchImpl });
} catch (e) {
return { ok: false, reason: 'provider', status: e.status || null, error: e.message };
}
const answers = parseAnswers(body, questions);
const doc = {
...makeInsight({ answers, raw: body, model: cfg.model, stateHash: stateHash(state), at: now }),
day: new Date(now).toISOString().slice(0, 10),
used: budget.used + 1
};
writeInsight(uid, doc);
return {
ok: true,
insight: doc,
sent: summarizeState(state),
answered: Object.values(answers).filter(Boolean).length,
asked: Object.keys(questions).length,
budget: budgetFor(doc, { now, maxPerDay: cfg.maxPerDay, minIntervalMs: cfg.minIntervalMs })
};
}
/**
* The judgment a Coach job should use: what is stored, or a fresh one asked for now.
*
* Freshness is the same rule the Salud card shows (`insightFreshness`), so the two cannot disagree
* about what counts as current. A debrief is excluded — it reads one session, and a judgment about
* readiness and volume is not about that session.
*/
export async function insightForCoach(uid, { kind = 'review', fetchImpl = fetch, now = Date.now() } = {}) {
// A debrief reads one session; how ready the person is and which way the week's volume should go
// is not about that session, so it is not asked for there.
if (kind === 'debrief') return null;
const stored = readInsight(uid);
if (insightFreshness(stored, { now }).fresh) return stored;
const asked = await runInsight(uid, { fetchImpl, now });
return asked.ok ? asked.insight : null;
}