Files
kuentagym/api/jev.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

537 lines
25 KiB
JavaScript

/* jev.js — the second opinion: a judgment about a profile, answered in probabilities.
*
* Jev is TypeSafe's "System One" model, served by OpenCode Zen at
* `POST https://opencode.ai/zen/v1/systemone`. It is **not a chat model**: you hand it a *state*
* and a map of *typed questions* — yes/no (`noul`), multiple choice (`choice`), rubric score
* (`score`) — and it answers all of them in one request with the value it settled on plus the
* probability it put there. That shape is the whole reason this file exists, and the reason it is
* not part of the Coach: the Coach **writes** (a routine, an explanation); this **judges**, and a
* judgment that comes with "62% likely" is a different, more honest object than a paragraph.
*
* ── What leaves the instance, and what does not ──────────────────────────────────────────────
*
* The feature is off unless somebody sets a key (JEV_API_KEY / OPENCODE_API_KEY), and what it
* sends is built here, by `buildState`, from aggregates only: this week's numbers against the
* window's, how many sets each body part has taken, how many days ago the last session was, how
* many days of data exist. No profile id, no user name, no workout titles, no chat, no free text —
* with **one deliberate exception**: the Coach intake's `limitations` field ("bad shoulder, no
* overhead press") is sent when the person filled it in, because it is the single most
* decision-relevant sentence anyone types about themselves and a judgment that ignores it is
* worse than useless. It is their own note, going to their own provider, on a screen that says so
* (see `docs/HEALTH.md` and the card's own sheet).
*
* ── Why the parser is tolerant ───────────────────────────────────────────────────────────────
*
* The request contract is documented; the response is a map of typed answers and this file has
* never seen one from the live service. So `parseAnswers` accepts every shape the answers plausibly
* arrive in — `answers`/`results`, a bare top-level map, `option`/`answer`/`choice`, `probability`
* or a `probabilities` distribution — normalises what it finds, and returns null for anything it
* cannot read rather than throwing. The raw payload is kept beside the parsed one for exactly that
* reason: the first real call can be looked at, and a shape this file guessed wrong is a fix, not a
* mystery. Every number that reaches the screen is either parsed here or absent; nothing is
* invented to fill a gap.
*/
import crypto from 'node:crypto';
export const JEV_VERSION = 1;
/* ---------- configuration (environment, like the Coach's, and off by default) ---------- */
export const JEV_DEFAULTS = Object.freeze({
// The gateway, not the vendor: OpenCode Zen serves Jev from the same account as its other
// models, so one key can drive both this and the Coach's provider list.
baseUrl: 'https://opencode.ai/zen',
// `jev-1.13-free` is the limited-time free model the gateway also serves.
model: 'jev-1.13',
maxPerDay: 12, // requests per profile per day; each one costs money
minIntervalMs: 10 * 60 * 1000, // and a person cannot meaningfully ask twice in ten minutes
timeoutMs: 25 * 1000,
stateDays: 7 // days of health data in the state
});
const envText = (env, name) => String(env[name] || '').trim() || null;
const envNum = (env, name, fallback) => {
const raw = envText(env, name);
// An unset variable is not zero: `Number('')` and `Number(null)` both pass a naive check, and a
// caps of 0 or a timeout of 0 is a feature that looks configured and never works. Unset, blank
// or unreadable all mean "use the default".
if (raw == null) return fallback;
const n = Number(raw);
return Number.isFinite(n) && n >= 0 ? n : fallback;
};
/**
* What this instance was started with. `configured` is the only thing the UI branches on: no key
* means the card does not exist at all rather than existing and failing.
*/
export function jevConfig(env = process.env) {
const off = /^(1|true|yes|on)$/i.test(envText(env, 'JEV_DISABLED') || '');
const key = envText(env, 'JEV_API_KEY') || envText(env, 'OPENCODE_API_KEY');
const baseUrl = (envText(env, 'JEV_BASE_URL') || JEV_DEFAULTS.baseUrl).replace(/\/+$/, '');
return {
configured: !!key && !off,
// Kept out of anything logged or returned to a client, like every other credential here.
key: key || null,
baseUrl,
model: envText(env, 'JEV_MODEL') || JEV_DEFAULTS.model,
maxPerDay: envNum(env, 'JEV_MAX_PER_DAY', JEV_DEFAULTS.maxPerDay),
minIntervalMs: envNum(env, 'JEV_MIN_INTERVAL_MS', JEV_DEFAULTS.minIntervalMs),
timeoutMs: envNum(env, 'JEV_TIMEOUT_MS', JEV_DEFAULTS.timeoutMs),
stateDays: envNum(env, 'JEV_STATE_DAYS', JEV_DEFAULTS.stateDays)
};
}
/** The endpoint, from whatever base URL was configured (with or without `/v1`, with or without the path). */
export function jevEndpoint(baseUrl) {
const base = String(baseUrl || JEV_DEFAULTS.baseUrl).replace(/\/+$/, '');
if (/\/v1\/systemone$/.test(base)) return base;
if (/\/v1$/.test(base)) return base + '/systemone';
return base + '/v1/systemone';
}
/* ---------- the state: aggregates, and nothing that identifies anybody ---------- */
/* The handful of metrics worth asking about, in the order they matter, with the one line of
* vocabulary the model needs to read them. A metric that is not here still reaches the state — the
* profile's own health file decides that (see below) — it just arrives without a gloss. */
const METRIC_GLOSS = {
resting_heart_rate: 'resting heart rate, beats per minute (lower is usually better trained)',
heart_rate_variability: 'beat-to-beat variability in ms (higher usually means better recovered)',
heart_rate: 'heart rate across the day, beats per minute',
sleep_analysis: 'hours asleep and the stages of last night',
respiratory_rate: 'breaths per minute while asleep',
blood_oxygen_saturation: 'oxygen saturation, percent',
apple_sleeping_wrist_temperature: 'wrist temperature while asleep, degrees',
step_count: 'steps taken that day',
active_energy: 'active energy burned, kcal',
apple_exercise_time: 'minutes of exercise',
apple_stand_hour: 'hours in which the person stood for a minute',
distance_walking_running: 'walking and running distance',
weight_body_mass: 'body mass',
body_fat_percentage: 'body fat, percent',
vo2_max: 'estimated VO₂ max',
cardio_recovery: 'heart-rate drop one minute after exercise'
};
/** Preference order for the state, best first: the metrics a readiness judgment actually reads. */
const METRIC_ORDER = Object.keys(METRIC_GLOSS);
const MAX_METRICS = 8;
/** The body parts the library uses (`bp` in library-data.js), glossed for the choice question. */
const BODY_PARTS = {
chest: 'chest and pressing muscles',
back: 'back, lats and upper back',
shoulders: 'shoulders and delts',
'upper arms': 'biceps and triceps',
'lower arms': 'forearms and grip',
waist: 'abs and trunk',
'upper legs': 'quads, hamstrings and glutes',
'lower legs': 'calves and shins',
neck: 'neck and traps',
cardio: 'cardiovascular system'
};
const round = (v, dec = 1) => (Number.isFinite(v) ? Math.round(v * 10 ** dec) / 10 ** dec : null);
/** A calendar day, from a Date, an epoch or a day string — callers pass all three. */
const dayISO = t => (t instanceof Date ? t : new Date(t)).toISOString().slice(0, 10);
const daysBetween = (a, b) => Math.round((Date.parse(b + 'T12:00:00') - Date.parse(a + 'T12:00:00')) / 86400000);
/** One metric's fields over a set of days, summed the way an aggregate should be. */
function foldFields(days) {
const out = {};
for (const f of days) {
for (const [k, v] of Object.entries(f || {})) {
const cur = out[k] || (out[k] = { n: 0, sum: 0, min: null, max: null, last: null });
cur.n += v.n || 0;
cur.sum += v.sum || 0;
if (v.min != null && (cur.min == null || v.min < cur.min)) cur.min = v.min;
if (v.max != null && (cur.max == null || v.max > cur.max)) cur.max = v.max;
cur.last = v.last;
}
}
for (const v of Object.values(out)) {
// The average per *day with data*, which is the number a person would compare against: a
// weekly total says nothing about whether last night was bad.
v.avg = v.n ? round(v.sum / v.n, 2) : null;
v.sum = round(v.sum, 2);
v.min = round(v.min, 2);
v.max = round(v.max, 2);
v.last = round(v.last, 2);
}
return out;
}
/**
* The health half of the state: a week of every metric the profile actually has, newest day first
* in `today`. Deliberately per *field* and uninterpreted — the server does not know that a step
* count is a total and a heart rate is a rate (that is the frontend's catalogue, and duplicating it
* here would give the two a way to disagree), so it sends `qty`/`Avg`/`asleep` exactly as HAE named
* them, summed across the window.
*/
function healthPart(vitals, { days, now }) {
const metrics = (vitals && vitals.metrics) || {};
const from = dayISO(new Date(now - (days - 1) * 86400000));
const picked = [];
for (const name of Object.keys(metrics)) {
const m = metrics[name];
const all = Object.keys(m.days || {}).filter(d => d >= from).sort();
if (!all.length) continue;
const newest = all[all.length - 1];
picked.push({
name,
units: m.units || '',
today: { day: newest, fields: foldFields([m.days[newest].f || {}]), samples: m.days[newest].n || 0 },
week: { days: all.length, from: all[0], fields: foldFields(all.map(d => m.days[d].f || {})) },
gloss: METRIC_GLOSS[name] || null,
rank: METRIC_ORDER.indexOf(name)
});
}
// The catalogue's own order first (those are the metrics a judgment is worth making on), then
// whatever else the phone sends, alphabetically, up to the cap.
picked.sort((a, b) => {
const ra = a.rank < 0 ? 1e6 : a.rank, rb = b.rank < 0 ? 1e6 : b.rank;
return ra - rb || a.name.localeCompare(b.name);
});
return picked.slice(0, MAX_METRICS).map(({ rank, ...m }) => m);
}
/** The training half: what was lifted, how much of it per body part, and where it has stalled. */
function trainingPart(S, { now, bodyPartOf, nameOf }) {
const workouts = (S.workouts || []).filter(w => w && w.d && !w.active);
const today = dayISO(now);
const window = workouts.filter(w => daysBetween(w.d, today) <= 28);
const recent = workouts.slice(-3);
const sets = (list, withinDays) => {
const hit = {};
for (const w of list) {
if (daysBetween(w.d, today) > withinDays) continue;
for (const en of w.entries || []) {
const work = (en.sets || []).filter(s => s && s.done);
if (!work.length) continue;
const bp = bodyPartOf(en.id) || 'other';
hit[bp] = (hit[bp] || 0) + work.length;
}
}
return hit;
};
/* No workout title: it is free text a person typed, and a readiness judgment gets nothing from it
that `sets`, `minutes`, `avg_rpe` and `body_parts` do not already say. Left out rather than
trusted to be innocuous — "Entreno con Juan en el gimnasio de Málaga" is a valid title. */
const detail = w => {
const entries = (w.entries || []).filter(en => (en.sets || []).some(s => s && s.done));
const rpes = (w.entries || []).flatMap(en => (en.sets || []).filter(s => s.done && s.rpe != null).map(s => s.rpe));
return {
days_ago: daysBetween(w.d, today),
sets: entries.reduce((n, en) => n + (en.sets || []).filter(s => s.done).length, 0),
minutes: w.end != null && w.start != null ? Math.round((w.end - w.start) / 60000) : null,
avg_rpe: rpes.length ? round(rpes.reduce((a, b) => a + b, 0) / rpes.length, 1) : null,
body_parts: [...new Set(entries.map(en => bodyPartOf(en.id)).filter(Boolean))]
};
};
// Stalled: an exercise whose last three sessions have not moved. The Coach's own payload has a
// richer version of this; what a readiness judgment needs is only the fact and the name — an id
// means nothing to a model, so the library's own name goes out instead of `e1`.
const byEx = new Map();
for (const w of workouts.slice(-12)) {
for (const en of w.entries || []) {
if (!(en.sets || []).some(s => s && s.done)) continue;
if (!byEx.has(en.id)) byEx.set(en.id, []);
byEx.get(en.id).push(en);
}
}
const stalled = [];
for (const [id, list] of byEx) {
if (list.length < 3) continue;
const tops = list.slice(-3).map(en => Math.max(...(en.sets || []).filter(s => s.done).map(s => Number(s.w) || 0)));
if (tops[0] === tops[1] && tops[1] === tops[2] && tops[2] > 0) stalled.push(id);
}
return {
window_days: 28,
sessions: window.length,
last_session_days_ago: workouts.length ? daysBetween(workouts[workouts.length - 1].d, today) : null,
planned_days_per_week: Object.keys(S.week || {}).filter(k => (S.week[k] || []).length).length,
sets_by_body_part_28d: sets(workouts, 28),
sets_by_body_part_7d: sets(workouts, 7),
stalled_exercises: stalled.slice(0, 8).map(nameOf).filter(Boolean),
recent_sessions: recent.map(detail)
};
}
/** The body half: the newest weigh-in and how it has moved, which the recovery judgment reads. */
function bodyPart(S, { now }) {
const list = (S.bodyweight || []).filter(b => b && b.kg != null);
if (!list.length) return null;
const last = list[list.length - 1];
const monthAgo = list.filter(b => b.d && daysBetween(b.d, dayISO(now)) <= 28);
return {
unit: S.unit || 'kg',
latest: round(last.kg, 2),
days_ago: last.d ? daysBetween(last.d, dayISO(now)) : null,
change_28d: monthAgo.length > 1 ? round(last.kg - monthAgo[0].kg, 2) : null,
target: S.targetW != null ? round(Number(S.targetW), 2) : null
};
}
/**
* Build the state Jev is asked about: pure, and the only place that decides what leaves the
* instance. `bodyPartOf` is injected (the caller passes the library lookup) so this file needs no
* exercise catalogue of its own.
*/
export function buildState({
S = {}, vitals = null, now = Date.now(), days = JEV_DEFAULTS.stateDays,
bodyPartOf = () => null, nameOf = () => null
} = {}) {
const intake = (S.coach && S.coach.profile) || null;
const t = new Date(now);
return {
meta: {
today: dayISO(t),
unit: S.unit || 'kg',
body: S.body || null,
health_window_days: days,
effort_scale: 'RPE 1-10 on the logged sets, where 10 is failure'
},
profile: intake ? {
goal: intake.goal || null,
experience: intake.experience || null,
days_per_week: intake.daysPerWeek || null,
session_minutes: intake.sessionMin || null,
equipment: Array.isArray(intake.equipment) ? intake.equipment.slice(0, 12) : [],
// The one free-text field that goes out, and the reason is in the header of this file.
limitations: (intake.limitations || '').toString().slice(0, 300) || null
} : null,
training: trainingPart(S, { now, bodyPartOf, nameOf }),
bodyweight: bodyPart(S, { now }),
health: { window_days: days, metrics: healthPart(vitals, { days, now }) }
};
}
/* ---------- the questions: what we want judged, and what each answer would mean ---------- */
/**
* The typed questions, built from the state so that every option is something this profile can
* actually act on: the body parts it trains, the metrics it has. A choice whose options are
* guesses ("upper body?") is a question that comes back unusable.
*/
export function buildQuestions(state) {
const trained = Object.keys(state.training?.sets_by_body_part_28d || {});
const parts = trained.filter(bp => BODY_PARTS[bp]);
const limiterOptions = {};
for (const bp of parts) limiterOptions[bp] = BODY_PARTS[bp];
limiterOptions.none = 'nothing stands out — the data does not point at one part';
const metrics = (state.health?.metrics || []).map(m => m.name);
const attentionOptions = {};
for (const m of state.health?.metrics || []) attentionOptions[m.name] = m.gloss;
attentionOptions.none = 'no metric needs attention today';
const metricList = metrics.length ? metrics.join(', ') : 'none';
const q = {
readiness: {
type: 'score',
instructions: 'Given the sleep, resting heart rate, recent training load and how many days it has been since the last session, how ready is this person to train hard today?',
criteria: [
'empty — should not train hard, and would be better resting',
'below par — a light session, technique work, or cardio only',
'normal — train the planned session as it stands',
'fresh — a good day to push the top sets',
'peaking — ready to test a personal best'
]
},
deload: {
type: 'noul',
instructions: 'Does this week call for reducing load rather than adding to it — because sleep, resting heart rate or accumulated fatigue point that way?',
criteria: { true: 'yes — reduce load this week', false: 'no — keep progressing' }
},
attention: {
type: 'choice',
instructions: `Which of these health metrics most deserves attention today, judging the newest day against the same person's own week (${metricList})?`,
criteria: attentionOptions
}
};
// A choice with no real options is a question that can only be answered wrong, so the limiter
// one only exists when the profile has trained something we can name.
if (parts.length) {
q.limiter = {
type: 'choice',
instructions: 'Which body part or system looks least recovered, given the sets it has taken in the last week and the sleep and heart-rate data?',
criteria: limiterOptions
};
}
return q;
}
/* ---------- the request ---------- */
/**
* One request, every question, no streaming and no retries: a judgment is a request-response and a
* second attempt costs the same as the first. Returns the parsed JSON body, or throws with the
* status in the message so the route can turn it into something a person can read.
*/
export async function askJev({ cfg, state, questions, fetchImpl = fetch }) {
const res = await fetchImpl(jevEndpoint(cfg.baseUrl), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${cfg.key}`,
// Same reasoning as the music lookup: an instance this small identifies itself, and a gateway
// asking "what is this traffic" should get an answer.
'User-Agent': 'KuentaGYM (self-hosted)'
},
body: JSON.stringify({ model: cfg.model, state, questions }),
signal: AbortSignal.timeout(cfg.timeoutMs)
});
const text = await res.text();
let body = null;
try { body = JSON.parse(text); } catch { /* a gateway that answers with HTML, or with nothing */ }
if (!res.ok) {
const e = new Error(`Jev answered ${res.status}${body && body.error && body.error.message ? ': ' + body.error.message : ''}`);
e.status = res.status;
throw e;
}
if (!body) throw Object.assign(new Error('Jev answered with something that is not JSON'), { status: 502 });
return body;
}
/* ---------- reading the answer ---------- */
const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null);
/** A distribution as `{ option: probability }`, whatever container it arrived in. */
function distribution(v) {
const raw = v && typeof v === 'object' && !Array.isArray(v) ? (v.probabilities || v.distribution || v.scores || null) : null;
if (!raw || typeof raw !== 'object') return null;
const out = {};
for (const [k, p] of Object.entries(raw)) {
const n = num(typeof p === 'object' && p ? p.probability ?? p.p : p);
if (n != null) out[k] = n;
}
return Object.keys(out).length ? out : null;
}
const winner = d => {
if (!d) return null;
let best = null;
for (const [k, p] of Object.entries(d)) if (best == null || p > d[best]) best = k;
return best;
};
/**
* Normalise one answer. Every shape it might arrive in reduces to the same small object:
* `{ type, option, value, p, probabilities }` — with `option` the chosen key, `value` a score's
* weighted level (or 1-based index), `p` the probability that matters for the question's type, and
* the full distribution when there is one. Anything unreadable becomes null, and the caller
* decides what to do with a question that came back unanswered (it says so, rather than guessing).
*/
export function readAnswer(question, answer) {
if (!answer || typeof answer !== 'object') return null;
const type = question && question.type ? question.type : null;
const probs = distribution(answer);
const option = [answer.option, answer.answer, answer.choice, answer.label, answer.value]
.find(v => typeof v === 'string' && v) || winner(probs);
if (type === 'noul' || (!type && (num(answer.probability) != null || num(answer.p) != null))) {
// A yes/no: the probability of yes is the whole answer, whichever way it is spelled.
let p = num(answer.probability) ?? num(answer.p) ?? num(answer.yes) ?? num(answer.score);
if (p == null && answer.answer === true) p = 1;
if (p == null && answer.answer === false) p = 0;
if (p == null && probs) p = num(probs.true) ?? num(probs.yes) ?? null;
if (p == null) return null;
return { type: 'noul', p: round(p, 3), option: p >= 0.5 ? 'true' : 'false' };
}
if (type === 'score') {
// A rubric score: the gateway may answer with the weighted level, with a 1-based index, or with
// a distribution over the levels. All three are the same fact, so they all become a level.
let value = num(answer.value) ?? num(answer.score) ?? num(answer.level);
if (value == null && option != null && Array.isArray(question?.criteria)) {
const i = question.criteria.findIndex(c => String(c) === String(option));
if (i >= 0) value = i + 1;
}
if (value == null && probs) {
const levels = Object.keys(probs);
const idx = levels.findIndex(k => k === winner(probs));
if (idx >= 0) value = idx + 1;
}
if (value == null) return null;
return {
type: 'score',
value: round(value, 2),
p: num(answer.probability) ?? num(answer.p) ?? (probs ? round(probs[winner(probs)], 3) : null),
probabilities: probs
};
}
// A choice: the option, and how sure it was.
if (option == null) return null;
const criteria = (question && question.criteria) || {};
const known = Object.prototype.hasOwnProperty.call(criteria, option);
return {
type: 'choice',
option: String(option),
known,
p: num(answer.probability) ?? num(answer.p) ?? (probs ? round(probs[option], 3) : null),
probabilities: probs
};
}
/**
* The whole response, reduced to one answer per question that was asked. The container is whatever
* the gateway wrapped it in (`answers`, `results`, or the map at the top level).
*/
export function parseAnswers(body, questions) {
const container = (body && (body.answers || body.results || body.data)) || body || {};
const out = {};
for (const [id, question] of Object.entries(questions || {})) {
const answer = container && typeof container === 'object' ? container[id] : null;
out[id] = readAnswer(question, answer);
}
return out;
}
/* ---------- what is stored, and when it is stale ---------- */
/** A short digest of the state, so the screen can tell whether the judgment matches the data. */
export function stateHash(state) {
return crypto.createHash('sha256').update(JSON.stringify(state)).digest('hex').slice(0, 16);
}
/**
* The stored judgment. Small on purpose: the answers, when, which model, the digest of the state
* they were made from, and the raw response (bounded) so a parser that guessed a shape wrong can be
* looked at instead of debugged. Nothing here is health data — that lives in vitals-<uid>.json.
*/
export function makeInsight({ answers, raw, model, stateHash: hash, at = Date.now(), usage = null }) {
return {
v: JEV_VERSION,
at,
model,
stateHash: hash || null,
answers,
usage,
raw: raw && JSON.stringify(raw).length > 8000 ? null : raw // bounded; null means "too big to keep"
};
}
/**
* Whether a stored judgment should be offered as current. Two reasons it is not: it is older than
* the window it was made from (a night's sleep changes the answer), or the state has moved under it
* — the digest catches a session logged or a night of data that arrived since.
*/
export function insightFreshness(insight, { now = Date.now(), hash = null, ttlMs = 6 * 3600 * 1000 } = {}) {
if (!insight || !insight.at) return { fresh: false, reason: 'none' };
if (now - insight.at > ttlMs) return { fresh: false, reason: 'old' };
if (hash && insight.stateHash && hash !== insight.stateHash) return { fresh: false, reason: 'data' };
return { fresh: true, reason: null };
}
/** The per-profile budget, kept in the insight file itself: a cap with no second file to lose. */
export function budgetFor(insight, { now = Date.now(), maxPerDay = JEV_DEFAULTS.maxPerDay, minIntervalMs = JEV_DEFAULTS.minIntervalMs } = {}) {
const used = insight && insight.day === dayISO(new Date(now)) ? (insight.used || 0) : 0;
const since = insight && insight.at ? now - insight.at : Infinity;
const waitMs = Math.max(0, minIntervalMs - since);
return {
used,
remaining: Math.max(0, maxPerDay - used),
allowed: used < maxPerDay && waitMs === 0,
waitMs,
nextAt: waitMs ? now + waitMs : null
};
}