Files
kuentagym/api/test/server-insights.test.js
T
dsantillan 90aa802980
Tests / test (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
La segunda opinión: un juicio sobre tus números, con la probabilidad que trae
Preguntaste si se podía implementar Jev, y con qué API. Resulta que Jev se sirve por OpenCode Zen,
así que una sola cuenta cubre esto y cualquier otra cosa apuntada a ese gateway:

    POST https://opencode.ai/zen/v1/systemone   Bearer <clave>   model: jev-1.13

Y ahí está la razón de que valga la pena: Jev no es un modelo de chat. Le mandás un *estado* y
preguntas tipadas — sí/no (`noul`), opción (`choice`), rúbrica (`score`) — y contesta todas en una
sola petición con el valor **y la probabilidad que le puso**. "62% probable" se puede discutir;
"tomate una semana de descarga" no. Así que no entra por el Coach (que necesita *escribir*) y no se
fuerza dentro de su lista de proveedores: tiene su módulo, sus dos rutas y su tarjeta.

Qué hace. En Salud, arriba de la grilla, una tarjeta con cuatro respuestas: qué tan listo estás para
entrenar fuerte (nivel 1-5, con el número al lado), si la semana pide bajar carga (62% probable), qué
parte del cuerpo parece menos recuperada, y qué métrica de salud merece atención — esa última con la
última lectura de la métrica que nombró, para que "vigilá tu frecuencia en reposo" venga con el 62
que lo motivó. La hoja detrás del ⓘ dice a dónde va y exactamente qué se envía, con el mismo resumen
que devuelve el servidor.

Lo que sale, y lo que no. Se decide en `api/jev.js` y son agregados: una semana de cada métrica por
campo como la escribió el teléfono, series por parte del cuerpo de 4 semanas y de la última, sesiones,
días desde la última, RPE medio, estancamientos *por nombre de ejercicio*, el último pesaje y su
cambio. Ningún identificador: ni perfil, ni nombre, ni títulos de entrenamientos, ni ids de
ejercicios, ni chat — hay un test que lo afirma sobre el JSON, porque es una promesa que hacen los
docs y nada más la miraba. La única excepción es deliberada y está documentada: la nota de
*limitaciones* del cuestionario del Coach, porque "hombro malo" cambia la respuesta. (Los títulos sí
estuvieron un rato ahí: los saqué al escribir ese test, y el test se quedó.)

Un juicio no es una instrucción, y el código lo trata así. Cada respuesta se muestra con su
probabilidad; una pregunta que el modelo no contestó se muestra como no contestada, nunca como un
cero; un nivel que no habíamos ofrecido se marca en vez de disfrazarse de propio; y si los datos
cambiaron desde que se pidió (una sesión registrada, una noche que llegó) la tarjeta lo dice en lugar
de seguir pareciendo actual. Tampoco corre por temporizador: cuesta una petición, así que pasa cuando
alguien aprieta *Preguntar*, con cupo por perfil y por día y un piso de diez minutos aplicados en el
servidor, no en la pantalla.

El Coach, además, lo recibe como `secondOpinion` en su payload **solo si tiene menos de seis horas**,
como evidencia con confianza adjunta para citar en `why`, nunca como una orden ni como un cambio de
plan. Es la mitad que faltaba de "y el Coach escribe con eso".

El lector de respuestas es tolerante a propósito: el contrato de la petición está documentado, la
respuesta no la vimos nunca del servicio real, así que acepta las formas plausibles
(`answers`/`results`, `option`/`answer`/`choice`, `probability` o una distribución sobre los niveles),
normaliza lo que encuentra y devuelve `null` por lo que no puede leer. El cuerpo crudo queda guardado
al lado del parseado (y sale con `?raw=1`): la primera llamada real se puede mirar, y una forma mal
adivinada es un arreglo, no un misterio.

Dos cosas que encontré escribiendo esto y que quedan arregladas: una variable de entorno vacía se
leía como **cero** (`Number('')` pasa un chequeo ingenuo), así que un cupo sin configurar era "cero
peticiones" — un feature que parece configurado y no funciona nunca; y agregar la palabra *Back*
para la espalda redefinió el botón *Atrás* de la app a "Espalda", porque en un objeto literal la
última clave gana y nada lo dice. El catálogo de español tiene ahora un test que falla si una clave
se escribe dos veces, mutación comprobada.

Cobertura: 11 tests del módulo (el estado, las preguntas, cada forma de respuesta, la promesa de
privacidad, el cupo), 5 de las rutas contra un gateway de mentira y el servidor real, 6 del modelo de
vista en el frontend y 5 de render por la tarjeta real. API 259 en verde, frontend 1696, build OK.
2026-09-23 16:36:47 -04:00

232 lines
11 KiB
JavaScript

/* The second opinion, end to end against the real server: a stub gateway stands in for OpenCode
Zen (the real one needs a paid key, and what is being tested here is our side of the contract).
Two claims matter and both are about money and privacy rather than correctness in the abstract:
an instance with no key has no feature at all, and an instance with one does not let a signed-in
person spend without limit. Everything else is about turning an answer into something a screen
can render without inventing a number. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
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';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
function mintSession(uid, sv = 0) {
const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
}
const cookie = uid => ({ Cookie: `gymsid=${mintSession(uid)}` });
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 answers with a fixed, documented-shaped body. */
async function startGateway(t, answer) {
const calls = [];
const server = http.createServer((req, res) => {
let body = '';
req.on('data', c => { body += c; });
req.on('end', () => {
calls.push({ url: req.url, auth: req.headers.authorization, body: JSON.parse(body || '{}') });
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(typeof answer === 'function' ? answer(calls.length) : answer));
});
});
const port = await freePort();
await new Promise(r => server.listen(port, '127.0.0.1', r));
t.after(() => server.close());
return { url: `http://127.0.0.1:${port}`, calls };
}
const USERS = [{ id: 'u_j1', name: 'One', created: '2026-01-01T00:00:00.000Z' }];
async function startServer(t, env = {}) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-jev-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: USERS, creds: [], subs: [], invites: [] }));
const port = await freePort();
const child = spawn(process.execPath, ['server.js'], {
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
env: {
...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost',
JEV_API_KEY: '', OPENCODE_API_KEY: '', ...env
}
});
const h = { api: `http://127.0.0.1:${port}`, dataDir, log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
let up = false;
for (let i = 0; i < 100 && !up; i++) {
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
if (!up) await new Promise(r => setTimeout(r, 100));
}
assert.ok(up, `server never came up:\n${h.log}`);
return h;
}
/** A profile with a plan, a session and a night of health data, pushed the way the app does. */
async function seed(h, uid) {
const today = new Date().toISOString().slice(0, 10);
const state = {
unit: 'kg', lang: 'es', body: 'male',
coach: { profile: { goal: 'build muscle', daysPerWeek: 3, limitations: 'bad shoulder' } },
week: { 1: ['r1'], 3: ['r1'] },
routines: [{ id: 'r1', ex: [{ id: '0662' }] }],
bodyweight: [{ d: today, kg: 80 }],
workouts: [{ d: today, name: 'Push', start: 1000, end: 3601000, entries: [{ id: '0662', sets: [{ w: 60, r: 8, done: true, rpe: 8 }] }] }]
};
const put = await fetch(`${h.api}/api/data`, {
method: 'PUT',
headers: { ...cookie(uid), 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' },
body: JSON.stringify({ state })
});
assert.equal(put.status, 200, await put.text());
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie(uid) })).json()).key;
const ingest = await fetch(`${h.api}/api/vitals/ingest`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
body: JSON.stringify({ data: { metrics: [
{ name: 'step_count', units: 'count', data: [{ qty: 840, date: `${today} 00:00:00 +0000` }] },
{ name: 'resting_heart_rate', units: 'bpm', data: [{ qty: 62, date: `${today} 09:00:00 +0000` }] }
] } })
});
assert.equal(ingest.status, 200);
}
const ask = (h, uid) => fetch(`${h.api}/api/insights`, { method: 'POST', headers: { ...cookie(uid), 'Sec-Fetch-Site': 'same-origin' } });
const read = (h, uid, q = '') => fetch(`${h.api}/api/insights${q}`, { headers: cookie(uid) });
test('an instance with no key has no second opinion, and says so instead of failing', async t => {
const h = await startServer(t);
await seed(h, 'u_j1');
const before = await (await read(h, 'u_j1')).json();
assert.equal(before.ok, true);
assert.equal(before.configured, false);
assert.equal(before.insight, null);
assert.equal(before.model, null);
assert.equal(before.host, null);
// Asking anyway is a readable answer about the instance, not a crash and not a silent no-op.
assert.equal((await ask(h, 'u_j1')).status, 400);
const refused = await (await ask(h, 'u_j1')).json();
assert.match(refused.error, /JEV_API_KEY/);
// ...and a session is needed even to look.
assert.equal((await fetch(`${h.api}/api/insights`)).status, 401);
assert.equal((await fetch(`${h.api}/api/insights`, { method: 'POST', headers: { 'Sec-Fetch-Site': 'same-origin' } })).status, 401);
});
test('asking sends the state to the configured gateway and stores what comes back', async t => {
const gw = await startGateway(t, {
answers: {
readiness: { value: 2.4, probability: 0.58 },
deload: { probability: 0.62 },
limiter: { choice: 'shoulders', probabilities: { chest: 0.2, shoulders: 0.55, none: 0.25 } },
attention: { choice: 'resting_heart_rate', probabilities: { step_count: 0.3, resting_heart_rate: 0.6 } }
}
});
const h = await startServer(t, { JEV_API_KEY: 'test-key', JEV_BASE_URL: gw.url, JEV_MODEL: 'jev-test' });
await seed(h, 'u_j1');
const res = await ask(h, 'u_j1');
const body = await res.json();
assert.equal(res.status, 200, JSON.stringify(body));
assert.equal(body.ok, true);
assert.equal(body.configured, true);
assert.equal(body.model, 'jev-test');
assert.equal(body.host, gw.url.replace('http://', ''));
// One request, every question, and the model and key the environment named.
assert.equal(gw.calls.length, 1);
assert.equal(gw.calls[0].url, '/v1/systemone');
assert.equal(gw.calls[0].auth, 'Bearer test-key');
assert.equal(gw.calls[0].body.model, 'jev-test');
assert.deepEqual(Object.keys(gw.calls[0].body.questions).sort(), ['attention', 'deload', 'limiter', 'readiness']);
const sent = gw.calls[0].body.state;
assert.equal(sent.training.sessions, 1);
assert.equal(sent.training.sets_by_body_part_28d.chest, 1, 'the library put push-up in chest');
assert.deepEqual(sent.health.metrics.map(m => m.name).sort(), ['resting_heart_rate', 'step_count']);
assert.equal(sent.profile.limitations, 'bad shoulder', 'the one free-text field that goes, on purpose');
// What the screen renders: the answer, parsed, with the probability it came with.
assert.equal(body.insight.answers.readiness.value, 2.4);
assert.equal(body.insight.answers.deload.p, 0.62);
assert.equal(body.insight.answers.limiter.option, 'shoulders');
assert.equal(body.insight.answers.attention.option, 'resting_heart_rate');
assert.equal(body.insight.model, 'jev-test');
assert.ok(body.insight.at > 0);
assert.equal(body.freshness.fresh, true);
// Counts, never content: this is what the sheet shows before it sends anything.
assert.deepEqual(body.sent.metrics.sort(), ['resting_heart_rate', 'step_count']);
assert.equal(body.sent.sessions, 1);
assert.equal(body.sent.includes_limitations, true);
// It is stored, and reading it back does not call the gateway again.
const got = await (await read(h, 'u_j1')).json();
assert.equal(got.configured, true);
assert.equal(got.insight.answers.deload.p, 0.62);
assert.equal(got.insight.raw, undefined, 'the raw payload is not what a screen polls for');
assert.equal(gw.calls.length, 1);
assert.equal(got.budget.used, 1);
// ...unless it is asked for by name, which is how a shape this code guessed wrong gets looked at.
const raw = await (await read(h, 'u_j1', '?raw=1')).json();
assert.deepEqual(raw.raw.answers.deload, { probability: 0.62 });
});
test('a gateway that answers badly is reported, not stored, and costs nothing', async t => {
const gw = await startGateway(t, { hello: 'world' });
const h = await startServer(t, { OPENCODE_API_KEY: 'k2', JEV_BASE_URL: gw.url });
await seed(h, 'u_j1');
const res = await ask(h, 'u_j1');
assert.equal(res.status, 200);
const body = await res.json();
// Every question came back unanswered, and that is what is stored: nulls, not invented values.
assert.deepEqual(Object.values(body.insight.answers), [null, null, null, null]);
const got = await (await read(h, 'u_j1')).json();
assert.equal(got.insight.answers.readiness, null);
});
test('the same profile cannot ask more than the budget allows', async t => {
const gw = await startGateway(t, { answers: { deload: { probability: 0.5 } } });
const h = await startServer(t, { JEV_API_KEY: 'k3', JEV_BASE_URL: gw.url, JEV_MAX_PER_DAY: '2', JEV_MIN_INTERVAL_MS: '0' });
await seed(h, 'u_j1');
assert.equal((await ask(h, 'u_j1')).status, 200);
assert.equal((await ask(h, 'u_j1')).status, 200);
const spent = await ask(h, 'u_j1');
assert.equal(spent.status, 429);
assert.match((await spent.json()).error, /as often as this instance allows/);
assert.equal(gw.calls.length, 2, 'a refused request never reaches the gateway');
// The interval is its own guard, on a fresh profile with budget to spare.
const h2 = await startServer(t, { JEV_API_KEY: 'k4', JEV_BASE_URL: gw.url, JEV_MIN_INTERVAL_MS: '60000' });
await seed(h2, 'u_j1');
assert.equal((await ask(h2, 'u_j1')).status, 200);
const tooSoon = await ask(h2, 'u_j1');
assert.equal(tooSoon.status, 429);
assert.match((await tooSoon.json()).error, /try again in 1 min/);
});
test('wiping the health data takes the judgment with it', async t => {
const gw = await startGateway(t, { answers: { deload: { probability: 0.4 } } });
const h = await startServer(t, { JEV_API_KEY: 'k5', JEV_BASE_URL: gw.url });
await seed(h, 'u_j1');
assert.equal((await ask(h, 'u_j1')).status, 200);
await fetch(`${h.api}/api/vitals`, { method: 'DELETE', headers: { ...cookie('u_j1'), 'Sec-Fetch-Site': 'same-origin' } });
const after = await (await read(h, 'u_j1')).json();
assert.equal(after.insight, null, 'a judgment about data that no longer exists is gone too');
});