Jev decide y el modelo escribe: el juicio entra en el trabajo del Coach, y juzga la selección
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Recordado como "para mejorar las decisiones en la selección de entrenamiento debe usar Jev y ChatGPT combinado". La combinación estaba a medias por dos razones, y las dos se cierran acá. **El juicio no estaba cuando se escribía el plan.** Viajaba al payload sólo si alguien lo había pedido en Salud hacía menos de seis horas; en la práctica, muchas veces no estaba. Ahora un trabajo del Coach —crear o revisar— **pide su propio juicio** cuando no hay uno fresco (`insightForCoach` en `api/insights.js`), con el mismo cupo que gasta el botón de Salud, así que lo automático no puede costar más que lo manual. Un debrief queda afuera: un veredicto de disposición no habla de una sesión. Y si el proveedor falla, si la instancia no tiene clave o si el cupo se agotó, el trabajo sigue exactamente como antes — el juicio es contexto, nunca una dependencia, y hay tests para los tres casos. **Las preguntas no cubrían la selección.** Jev juzgaba disposición, descarga, limitante y métrica a vigilar; nada sobre *qué cambiar*. Ahora, además de `volume` (hacia dónde va la carga de la semana, cuando hay historia suficiente para tener opinión), recibe **una pregunta por ejercicio estancado**: `keep`, `reduce`, `swap` o `drop`, con la clave del id de la biblioteca y el nombre en la rúbrica — así la respuesta es algo con lo que el plan se puede editar y el modelo lee palabras, no una clave. Los ids de ejercicios pasan a viajar en el estado, y sólo ellos: un id de biblioteca es una fila de un dataset público, no un identificador de persona, y el test de privacidad lo dice ahora en esos términos. Hay una sola forma de producir un juicio: `runInsight` en `api/insights.js`, que usan la ruta de Salud y el trabajo del Coach. Antes esa lógica vivía dentro de la ruta, con sus helpers duplicados en `server.js`; ahora la ruta es una envoltura fina y no hay dos maneras de pedir, cobrar o guardar. En el prompt del escritor quedó dicho con precisión qué es un `swap`: **una propuesta a considerar**, no una decisión a aplicar. Si la evidencia que el propio modelo ve dice que el ejercicio está bien, puede decir por qué y dejarlo; el cambio que envíe tiene que cumplir el esquema y nombrar un id real. Tests: seis del runner y de la regla de cuándo preguntar (contra un gateway de mentira, sin levantar servidor), más los de las preguntas nuevas. API 276 en verde, frontend 1705.
This commit is contained in:
1 parent
9a339db85e
commit
f80ade25f6
9 files changed
+416
-90
No files matched your search
@@ -0,0 +1,172 @@
|
||||
/* The second opinion has two callers now: the Salud card, and a Coach job that is about to write a
|
||||
plan. "Jev decides, the model writes" only happens if the judgment exists when the writing starts,
|
||||
so the decision of *when to ask* is the thing worth testing here — plus the fact that a provider
|
||||
that fails leaves the Coach working, which is what a job that dies on a side quest would break.
|
||||
|
||||
No server is spawned: this is the module the route and the job both call, against a stub gateway. */
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-insight-'));
|
||||
process.env.DATA_DIR = DATA;
|
||||
process.env.JEV_API_KEY = 'test-key';
|
||||
|
||||
const UID = 'u_run1';
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const daysAgo = n => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);
|
||||
|
||||
// A profile with a plan, four sessions and a stall, and a week of health behind it.
|
||||
fs.writeFileSync(path.join(DATA, `state-${UID}.json`), JSON.stringify({
|
||||
unit: 'kg', lang: 'es',
|
||||
coach: { profile: { goal: 'build muscle', daysPerWeek: 3 } },
|
||||
week: { 1: ['r1'], 3: ['r1'], 5: ['r1'] },
|
||||
routines: [{ id: 'r1', ex: [{ id: '0662' }] }],
|
||||
bodyweight: [{ d: today, w: 80 }],
|
||||
workouts: [1, 3, 5, 7].map(n => ({
|
||||
d: daysAgo(n), name: 'Push', start: 1000, end: 3601000,
|
||||
entries: [{ id: '0662', sets: [{ w: 60, r: 8, done: true, rpe: 8 }] }]
|
||||
}))
|
||||
}));
|
||||
const vitalsDay = (d, sum) => ({ [d]: { n: 1, lastTs: Date.now(), f: { qty: { n: 1, sum, min: sum, max: sum, last: sum } } } });
|
||||
fs.writeFileSync(path.join(DATA, `vitals-${UID}.json`), JSON.stringify({
|
||||
metrics: { step_count: { units: 'count', days: { ...vitalsDay(today, 4000), ...vitalsDay(daysAgo(1), 9000) } } }
|
||||
}));
|
||||
|
||||
const freePort = () => new Promise(r => {
|
||||
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
|
||||
});
|
||||
|
||||
/** A gateway that records what it was asked, and can be told to fail. */
|
||||
async function gateway(answer = { answers: { readiness: { value: 3 } } }) {
|
||||
const calls = [];
|
||||
let fail = false;
|
||||
const server = http.createServer((req, res) => {
|
||||
let body = '';
|
||||
req.on('data', c => { body += c; });
|
||||
req.on('end', () => {
|
||||
calls.push(JSON.parse(body || '{}'));
|
||||
if (fail) { res.writeHead(500, { 'Content-Type': 'application/json' }); res.end('{"error":{"message":"upstream is down"}}'); return; }
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify(answer));
|
||||
});
|
||||
});
|
||||
const port = await freePort();
|
||||
await new Promise(r => server.listen(port, '127.0.0.1', r));
|
||||
return { url: `http://127.0.0.1:${port}`, calls, setFail: v => { fail = v; }, close: () => server.close() };
|
||||
}
|
||||
|
||||
const { runInsight, insightForCoach, readInsight, readStateFile, readVitalsFile, summarizeState, stateFor } = await import('../insights.js');
|
||||
const { jevConfig, insightFreshness } = await import('../jev.js');
|
||||
|
||||
test('a judgment is asked with the selection questions and stored for the profile', async t => {
|
||||
const gw = await gateway();
|
||||
t.after(() => gw.close());
|
||||
process.env.JEV_BASE_URL = gw.url;
|
||||
|
||||
const res = await runInsight(UID, { cfg: jevConfig() });
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(gw.calls.length, 1);
|
||||
// The state is built from the profile's own files, and the stalled exercise is a question the plan
|
||||
// can be edited with — that is the whole point of asking Jev before writing.
|
||||
const questions = gw.calls[0].questions;
|
||||
assert.ok(Object.keys(questions).some(k => k.startsWith('exercise_')), 'the stall is asked about by id');
|
||||
assert.equal(questions.volume.type, 'score');
|
||||
assert.equal(gw.calls[0].state.health.metrics[0].name, 'step_count', 'the state names metrics as HAE does');
|
||||
assert.equal(res.sent.stalled.length, 1);
|
||||
assert.equal(res.answered, 1, 'the stub answered readiness and nothing else');
|
||||
assert.equal(res.asked, Object.keys(questions).length);
|
||||
|
||||
// Stored, and fresh by the rule the Salud card shows.
|
||||
const stored = readInsight(UID);
|
||||
assert.equal(stored.answers.readiness.value, 3);
|
||||
assert.equal(insightFreshness(stored).fresh, true);
|
||||
assert.equal(res.budget.used, 1);
|
||||
});
|
||||
|
||||
test('a Coach job asks for one only when there is nothing fresh, and never for a debrief', async t => {
|
||||
const gw = await gateway({ answers: { deload: { probability: 0.2 } } });
|
||||
t.after(() => gw.close());
|
||||
process.env.JEV_BASE_URL = gw.url;
|
||||
fs.rmSync(path.join(DATA, `insight-${UID}.json`), { force: true });
|
||||
|
||||
// A review with nothing stored: asked for here, so the model that writes has a judgment.
|
||||
const first = await insightForCoach(UID, { kind: 'review' });
|
||||
assert.equal(first.answers.deload.p, 0.2);
|
||||
assert.equal(gw.calls.length, 1);
|
||||
|
||||
// A second review straight after: the stored one is fresh, so nothing is spent.
|
||||
const second = await insightForCoach(UID, { kind: 'review' });
|
||||
assert.equal(second.answers.deload.p, 0.2);
|
||||
assert.equal(gw.calls.length, 1, 'a fresh judgment is reused, not re-asked');
|
||||
|
||||
// A debrief reads one session and is not given a readiness verdict at all.
|
||||
assert.equal(await insightForCoach(UID, { kind: 'debrief' }), null);
|
||||
assert.equal(gw.calls.length, 1);
|
||||
|
||||
// A create is treated like a review: the writing starts with the judgment in hand.
|
||||
const created = await insightForCoach(UID, { kind: 'create' });
|
||||
assert.equal(created.answers.deload.p, 0.2);
|
||||
});
|
||||
|
||||
test('a provider that fails leaves the Coach working and stores nothing', async t => {
|
||||
const gw = await gateway();
|
||||
gw.setFail(true);
|
||||
t.after(() => gw.close());
|
||||
process.env.JEV_BASE_URL = gw.url;
|
||||
fs.rmSync(path.join(DATA, `insight-${UID}.json`), { force: true });
|
||||
|
||||
const failed = await runInsight(UID, { cfg: jevConfig() });
|
||||
assert.equal(failed.ok, false);
|
||||
assert.equal(failed.reason, 'provider');
|
||||
assert.equal(failed.status, 500);
|
||||
assert.match(failed.error, /upstream is down|500/);
|
||||
assert.equal(readInsight(UID), null, 'a failed ask is not stored as an answer');
|
||||
|
||||
// ...and the job's path returns nothing rather than throwing, which is the difference between a
|
||||
// Coach job that runs without a second opinion and one that dies because of it.
|
||||
assert.equal(await insightForCoach(UID, { kind: 'review' }), null);
|
||||
});
|
||||
|
||||
test('an unconfigured instance asks nobody, and the budget stops the automatic path too', async t => {
|
||||
const gw = await gateway();
|
||||
t.after(() => gw.close());
|
||||
process.env.JEV_BASE_URL = gw.url;
|
||||
fs.rmSync(path.join(DATA, `insight-${UID}.json`), { force: true });
|
||||
|
||||
const off = await runInsight(UID, { cfg: jevConfig({}) });
|
||||
assert.deepEqual(off, { ok: false, reason: 'unconfigured' });
|
||||
assert.equal(gw.calls.length, 0);
|
||||
// ...and an instance with no key at all: the job asks nobody and writes its plan as it always did.
|
||||
const saved = process.env.JEV_API_KEY;
|
||||
delete process.env.JEV_API_KEY;
|
||||
try {
|
||||
assert.equal(await insightForCoach(UID, { kind: 'create' }), null, 'and the Coach simply has none');
|
||||
assert.equal(gw.calls.length, 0);
|
||||
} finally { process.env.JEV_API_KEY = saved; }
|
||||
|
||||
// The cap is the same one the card spends from: a Coach job cannot ask past it, which is what
|
||||
// keeps an automatic decision from being an unlimited bill.
|
||||
fs.writeFileSync(path.join(DATA, `insight-${UID}.json`), JSON.stringify({
|
||||
v: 1, at: Date.now(), model: 'x', answers: {}, day: today, used: 99
|
||||
}));
|
||||
const capped = await runInsight(UID, { cfg: jevConfig({ JEV_API_KEY: 'k', JEV_MAX_PER_DAY: '2' }) });
|
||||
assert.equal(capped.ok, false);
|
||||
assert.equal(capped.reason, 'budget');
|
||||
assert.equal(gw.calls.length, 0);
|
||||
});
|
||||
|
||||
test('the profile files are read the way the rest of the server writes them', () => {
|
||||
assert.equal(readStateFile(UID).unit, 'kg');
|
||||
assert.ok(readVitalsFile(UID).metrics.step_count);
|
||||
assert.equal(readStateFile('nobody'), null);
|
||||
assert.equal(readVitalsFile('nobody'), null);
|
||||
const state = stateFor(UID, jevConfig({ JEV_API_KEY: 'k', JEV_STATE_DAYS: '3' }));
|
||||
assert.equal(state.health.window_days, 3);
|
||||
assert.equal(state.training.sessions, 4);
|
||||
assert.deepEqual(summarizeState(state).stalled, ['push-up'], 'the library names an id, not a str');
|
||||
});
|
||||
+26
-7
@@ -99,8 +99,11 @@ test('the state carries the training, the body and a week of health, as numbers'
|
||||
assert.equal(s.training.sets_by_body_part_28d.shoulders, 1);
|
||||
assert.equal(s.training.sets_by_body_part_7d.back, 1, 'and the week view is its own count');
|
||||
// e1 was trained three times and its top set was 60 kg every time: that is a stall, and it goes
|
||||
// out as the library's name rather than as an id a model cannot read.
|
||||
assert.deepEqual(s.training.stalled_exercises, ['barbell bench press']);
|
||||
// out as a *decision the app can act on* — the library id, with the name beside it so the model
|
||||
// reads words rather than a key.
|
||||
assert.deepEqual(s.training.stalled, [
|
||||
{ id: 'e1', name: 'barbell bench press', sessions: 3, last_top: 60, body_part: 'chest' }
|
||||
]);
|
||||
assert.equal(s.training.recent_sessions.at(-1).days_ago, 1);
|
||||
assert.equal(s.training.recent_sessions.at(-1).avg_rpe, 10);
|
||||
assert.equal(s.training.recent_sessions.at(-1).minutes, 58);
|
||||
@@ -129,8 +132,11 @@ test('nothing that identifies the person leaves the instance', () => {
|
||||
const json = JSON.stringify(state());
|
||||
assert.equal(json.includes('Push'), false, 'no workout titles');
|
||||
assert.equal(json.includes('Pull'), false);
|
||||
assert.equal(json.includes('"e1"'), false, 'no exercise ids — a stalled exercise goes by name');
|
||||
assert.equal(json.includes('barbell bench press'), true, 'and that name is the library\'s, not a personal one');
|
||||
// Exercise ids DO go out, and only for the stalled ones: a judgment about which exercise to change
|
||||
// has to name something the app can edit, and a library id is a row in a public dataset rather than
|
||||
// an identifier of a person. The names travel with them so the model reads words.
|
||||
assert.equal(json.includes('"e1"'), true, 'a stalled exercise is named by the id the plan uses');
|
||||
assert.equal(json.includes('barbell bench press'), true, 'and by the library\'s own name');
|
||||
assert.equal(json.includes('r1'), false, 'no routine ids');
|
||||
assert.equal(json.includes('u_'), false);
|
||||
// The body parts and metric names that DO go are the vocabulary of the questions, not identity.
|
||||
@@ -157,6 +163,13 @@ test('the questions are built from what this profile actually has', () => {
|
||||
assert.deepEqual(Object.keys(q.deload.criteria), ['true', 'false']);
|
||||
// Only body parts that were trained get an option, plus the honest "nothing stands out".
|
||||
assert.deepEqual(Object.keys(q.limiter.criteria).sort(), ['back', 'chest', 'none', 'shoulders']);
|
||||
// Selection: one question per stalled exercise, keyed by the id the plan can act on, and a
|
||||
// direction for the week's volume once there is enough history to have an opinion.
|
||||
assert.deepEqual(Object.keys(q.exercise_e1.criteria).sort(), ['drop', 'keep', 'reduce', 'swap']);
|
||||
assert.match(q.exercise_e1.instructions, /barbell bench press/);
|
||||
assert.match(q.exercise_e1.instructions, /60/);
|
||||
assert.equal(q.volume.type, 'score');
|
||||
assert.equal(q.volume.criteria.length, 5);
|
||||
// Every metric in the state is a choice, and no metric that is not.
|
||||
assert.equal(Object.keys(q.attention.criteria).includes('step_count'), true);
|
||||
assert.equal(Object.keys(q.attention.criteria).includes('resting_heart_rate'), true);
|
||||
@@ -166,6 +179,8 @@ test('the questions are built from what this profile actually has', () => {
|
||||
// A profile with no training gets no limiter question at all: a choice with no options can only
|
||||
// be answered wrong.
|
||||
const empty = buildQuestions(buildState({ S: {}, vitals: null, now: NOW }));
|
||||
assert.equal(empty.volume, undefined, 'no sessions, no opinion about volume');
|
||||
assert.equal(Object.keys(empty).some(k => k.startsWith('exercise_')), false, 'and nothing stalled to ask about');
|
||||
assert.equal(empty.limiter, undefined);
|
||||
assert.deepEqual(Object.keys(empty.attention.criteria), ['none']);
|
||||
});
|
||||
@@ -216,9 +231,13 @@ test('a question the gateway did not answer is null, and the others still land',
|
||||
assert.equal(answers.deload.p, 0.8);
|
||||
assert.equal(answers.limiter, null);
|
||||
assert.equal(answers.attention, null);
|
||||
// A body that is not an object at all loses every answer rather than throwing in the route.
|
||||
assert.deepEqual(Object.values(parseAnswers(null, questions)), [null, null, null, null]);
|
||||
assert.deepEqual(Object.values(parseAnswers('nope', questions)), [null, null, null, null]);
|
||||
// A body that is not an object at all loses every answer rather than throwing in the route — one
|
||||
// null per question asked, however many that is.
|
||||
const asked = Object.keys(questions).length;
|
||||
assert.equal(asked, 6, 'readiness, deload, attention, limiter, volume and one per stalled exercise (e1)');
|
||||
assert.deepEqual(Object.keys(questions), ['readiness', 'deload', 'attention', 'volume', 'exercise_e1', 'limiter']);
|
||||
assert.deepEqual(Object.values(parseAnswers(null, questions)), new Array(asked).fill(null));
|
||||
assert.deepEqual(Object.values(parseAnswers('nope', questions)), new Array(asked).fill(null));
|
||||
});
|
||||
|
||||
/* ---------- what is stored, and what makes it stale ---------- */
|
||||
|
||||
Reference in new issue
Block a user