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');
|
||||
});
|
||||
Reference in new issue
Block a user