La segunda opinión: un juicio sobre tus números, con la probabilidad que trae
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

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.
This commit is contained in:
dsantillan committed 2026-09-23 16:36:47 -04:00
1 parent 5c69540f62
commit 90aa802980
24 files changed
+2078 -6

No files matched your search

+131
View File
@@ -21,6 +21,12 @@ import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
import { verifyError } from './verify-error.js';
import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, RETENTION_DAYS } from './vitals.js';
import { hostAllowed, readCapped, parseMusicPage } from './music.js';
import {
jevConfig, jevEndpoint, buildState, buildQuestions, askJev, parseAnswers,
makeInsight, stateHash, insightFreshness, budgetFor, JEV_DEFAULTS
} from './jev.js';
import { readInsight, writeInsight, clearInsight } from './insights.js';
import { LIB_BY_ID } from './coach/core/library.js';
const PORT = +(process.env.PORT || 3000);
const DATA = process.env.DATA_DIR || '/data';
@@ -116,6 +122,41 @@ function readVitals(uid) {
// 0600 like db.json: a year of somebody's heart rate is not for every process on the box.
function writeVitals(uid, doc) { atomicWrite(vitalsFile(uid), JSON.stringify(doc), 0o600); }
/** What a sync is answered with: how much is in the profile now, not just what just arrived. */
/* ---------- the second opinion's helpers ---------- */
/** An exercise id to the body part the library puts it in — the vocabulary the questions use. */
const bodyPartOf = id => LIB_BY_ID.get(id)?.bp || null;
/** ...and to its name, which is what a model can read (`stalled_exercises` is a list of those). */
const exerciseName = id => LIB_BY_ID.get(id)?.n || null;
/** The profile's own data, compacted into what a judgment is asked about (see jev.js). */
const profileState = (uid, cfg) => buildState({
S: readState(uid) || {},
vitals: readVitals(uid),
bodyPartOf,
nameOf: exerciseName,
days: cfg.stateDays
});
/** Counts, never content: what the screen needs to say what it just sent. */
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 || {}),
includes_limitations: !!state.profile?.limitations
};
}
/** The host of the configured endpoint, for the screen to name — never the key with it. */
function endpointHost(baseUrl) {
try { return new URL(jevEndpoint(baseUrl)).host; } catch { return null; }
}
const wantRaw = req => new URL(req.url, 'http://x').searchParams.get('raw') === '1';
const storedCounts = doc => ({
metrics: doc ? Object.keys(doc.metrics || {}).length : 0,
days: doc ? Object.values(doc.metrics || {}).reduce((n, m) => n + Object.keys(m.days || {}).length, 0) : 0,
@@ -1070,6 +1111,92 @@ const routes = {
json(res, 200, { ok: true, days, key: user.healthKey || null, ...vitalsSeries(doc || emptyVitals(), { days }) });
},
/* ---------- the second opinion (Jev, through the OpenCode Zen gateway) ----------
*
* Two routes, and the whole of the feature's server surface. GET says whether this instance is
* configured, what was judged last and whether it still holds; POST builds the state from the
* profile's own aggregates, asks every question in one request, and stores the answers.
*
* Deliberately *named* endpoints rather than a generic "send a prompt" proxy: a route that
* forwards arbitrary text would turn an account somebody pays for into an open gateway for anyone
* who can sign in. What leaves the instance is decided in jev.js, and only there.
*
* It costs money per request, so it is not on a timer and not refreshed in the background: a
* person asks, and the budget (per profile per day, plus a ten-minute floor) is enforced here
* rather than trusted to the client. */
'GET /api/insights': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const cfg = jevConfig();
const stored = readInsight(user.id);
const hash = cfg.configured ? stateHash(profileState(user.id, cfg)) : null;
// The raw gateway payload is debugging detail, not something a screen polls for: it is here
// only when asked for by name, and the POST that produced it already returned it.
const { raw, ...insight } = stored || {};
json(res, 200, {
ok: true,
configured: cfg.configured,
model: cfg.configured ? cfg.model : null,
host: cfg.configured ? endpointHost(cfg.baseUrl) : null,
insight: stored ? insight : null,
...(stored && wantRaw(req) ? { raw } : {}),
freshness: insightFreshness(stored, { hash }),
budget: budgetFor(stored, { maxPerDay: cfg.maxPerDay, minIntervalMs: cfg.minIntervalMs })
});
},
'POST /api/insights': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const cfg = jevConfig();
if (!cfg.configured) {
return json(res, 400, { error: 'The second opinion is not configured on this instance — set JEV_API_KEY (or OPENCODE_API_KEY) and restart.' });
}
const stored = readInsight(user.id);
const budget = budgetFor(stored, { maxPerDay: cfg.maxPerDay, minIntervalMs: cfg.minIntervalMs });
if (!budget.allowed) {
const mins = Math.ceil(budget.waitMs / 60000);
return json(res, 429, {
error: budget.remaining === 0
? 'The second opinion has been asked as often as this instance allows today.'
: `Asked a moment ago — try again in ${mins} min.`
});
}
const state = profileState(user.id, cfg);
const questions = buildQuestions(state);
let body;
try {
body = await askJev({ cfg, state, questions });
} catch (e) {
// The provider's own words, not a stack trace: "401" and "429" mean different things to the
// person who has to fix it, and neither is something this code can act on by itself.
audit(req, 'auth.health.insight', { ok: false, user, msg: String(e.status || e.message || 'error').slice(0, 120) });
return json(res, 502, { error: e.message });
}
const answers = parseAnswers(body, questions);
const asked = Object.keys(questions).length;
const answered = Object.values(answers).filter(Boolean).length;
const today = new Date().toISOString().slice(0, 10);
const doc = {
...makeInsight({ answers, raw: body, model: cfg.model, stateHash: stateHash(state) }),
day: today,
used: budget.used + 1
};
writeInsight(user.id, doc);
audit(req, 'auth.health.insight', { user, msg: `${cfg.model} ${answered}/${asked}` });
json(res, 200, {
ok: true,
configured: true,
model: cfg.model,
host: endpointHost(cfg.baseUrl),
insight: doc,
freshness: { fresh: true, reason: null },
budget: budgetFor(doc, { maxPerDay: cfg.maxPerDay, minIntervalMs: cfg.minIntervalMs }),
sent: summarizeState(state)
});
},
// One metric's hours on one day — the detail sheet, and only the detail sheet. It is a separate
// request because the hours are the bulky part of this data (24 buckets per metric per day) and
// a screen that lists forty cards needs none of it until somebody taps one. Session-only, like
@@ -1116,10 +1243,14 @@ const routes = {
const { doc, days, found } = dropMetric(readVitals(user.id), metric);
// No file, or no such metric in it: nothing to write, and the caller is told which it was.
if (doc && found) writeVitals(user.id, doc);
if (found) clearInsight(user.id); // same reasoning as the whole-file delete below
audit(req, 'auth.health.metric.clear', { user, msg: `${metric}:${days}` });
return json(res, 200, { ok: true, metric: found ? metric : null, days });
}
try { fs.unlinkSync(vitalsFile(user.id)); } catch { /* nothing stored */ }
// The judgment was made about data that no longer exists, so it goes with it rather than
// sitting on the screen describing a profile that has been emptied.
clearInsight(user.id);
audit(req, 'auth.health.clear', { user });
json(res, 200, { ok: true });
},