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

+55 -1
View File
@@ -149,6 +149,57 @@ Date Range of a week or more the next sync rebuilds it from Apple Health. Becaus
---
## 3b. The second opinion (optional)
Salud can also carry a **judgment** about the profile's own numbers: how ready the person is to
train hard, whether the week calls for easing off, which body part looks least recovered, and which
health metric deserves attention. It is answered by [Jev](https://typesafe.ai), TypeSafe's
"System One" model, which is not a chat model — it takes a state and a set of typed questions and
answers them with a value **and the probability it put there**, in one request. That is the whole
point of using it here rather than a text model: "62% probable" can be argued with, and "take a
deload week" cannot.
It is served through the **OpenCode Zen** gateway, so one account covers this and anything else
configured against that gateway. Off unless a key is set; with no key the card does not exist.
```bash
JEV_API_KEY=… # or OPENCODE_API_KEY
JEV_MODEL=jev-1.13 # jev-1.13-free for the gateway's free tier
JEV_BASE_URL=https://opencode.ai/zen
JEV_MAX_PER_DAY=12 # per profile, per day — every ask costs a request
JEV_MIN_INTERVAL_MS=600000 # ten minutes between asks
JEV_DISABLED= # a fleet operator's kill switch, like COACH_DISABLED
```
What is sent, exactly — this is the part worth reading before turning it on:
| Sent | Not sent |
| --- | --- |
| A week of every health metric the profile has, per field, as the phone wrote them (`qty`, `Avg`, `asleep`…), each day's aggregate folded against the same metric's week | Any identifier: no profile id, no name, no device, no key |
| Sets per body part over four weeks and over the last week, sessions in the window, how many days since the last one, average RPE, whether an exercise has stalled (by library name) | Workout titles, routine names, exercise ids, chat, notes |
| The newest weigh-in, the four-week change, the target | Anything you typed, **except** the Coach intake's `limitations` |
| The intake's goal, experience, days per week and session length — and its `limitations` note, because "bad shoulder" changes the answer | |
The sheet behind the card's ⓘ lists the same thing for the profile it is looking at, from the same
summary the server just sent, so nobody has to take the table above on faith. All of it goes to the
provider you configured, under your own account, and nowhere else — the request is one HTTPS POST
from the api container.
**It is never on a timer.** A judgment costs a request, so it happens when somebody presses *Ask*.
The per-profile daily budget and the ten-minute floor are enforced by the server, not the screen,
and the answer is stored in `data/insight-<uid>.json` (the answers, the model, the moment, and a
digest of the state they were made from). The card says when the data has moved since — after a
session is logged or a night arrives, the judgment is marked out of date rather than quietly left
looking current.
When a judgment is **less than six hours old**, the Coach is given it as `secondOpinion` in its
payload: evidence with a confidence attached, for the Coach to read and cite, never an instruction
and never a change to the plan. `api/jev.js` has the long version of all of this; the questions it
asks live in `buildQuestions` and the reader that tolerates the gateway's response shapes is
`parseAnswers`.
---
## 4. Security
- **The ingest key is write-only.** It can add to one profile's health file and cannot read a single
@@ -195,7 +246,10 @@ and you have backed up your health file too.
cover the merge under overlapping, disjoint, day-grouped, hour-grouped, raw, heart-rate, sleep
and blood-pressure payloads, plus pruning (days and hours), the day-from-hours projection and
timezone handling.
- `api/server.js` — the six routes and the ingest key. Route tests in `api/test/server-vitals.test.js`
- `api/jev.js` — the second opinion: the state that leaves, the questions, the tolerant reader and
the budget. Tests in `api/test/jev.test.js` (the state, the questions, every response shape, the
privacy claim) and the route against a stub gateway in `api/test/server-insights.test.js`.
- `api/server.js` — the eight routes and the ingest key. Route tests in `api/test/server-vitals.test.js`
run the real server and check isolation between profiles, that the key cannot read, and that ten
re-sends of the same window change nothing.
- `frontend/src/lib/vitals-view.js` — the metric catalogue, the card model, the units, the hour