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
+24
-74
@@ -21,12 +21,10 @@ 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, stateHash, insightFreshness, budgetFor } from './jev.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';
|
||||
readInsight, clearInsight, runInsight, stateFor, summarizeState, endpointHost
|
||||
} from './insights.js';
|
||||
|
||||
/* What this build of the api offers, for `GET /api/config` (see the note there). Add to this list
|
||||
when a route or a response shape a client depends on lands, and check for it in the client that
|
||||
@@ -133,39 +131,6 @@ 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 => ({
|
||||
@@ -1148,7 +1113,7 @@ const routes = {
|
||||
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;
|
||||
const hash = cfg.configured ? stateHash(stateFor(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 || {};
|
||||
@@ -1156,7 +1121,7 @@ const routes = {
|
||||
ok: true,
|
||||
configured: cfg.configured,
|
||||
model: cfg.configured ? cfg.model : null,
|
||||
host: cfg.configured ? endpointHost(cfg.baseUrl) : null,
|
||||
host: cfg.configured ? endpointHost(jevEndpoint(cfg.baseUrl)) : null,
|
||||
insight: stored ? insight : null,
|
||||
...(stored && wantRaw(req) ? { raw } : {}),
|
||||
freshness: insightFreshness(stored, { hash }),
|
||||
@@ -1171,48 +1136,33 @@ const routes = {
|
||||
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 one way a judgment is produced (api/insights.js): the same call this screen makes, the
|
||||
// same one a Coach job makes for itself when it needs a decision to write from.
|
||||
const asked = await runInsight(user.id, { cfg });
|
||||
if (!asked.ok) {
|
||||
if (asked.reason === 'budget') {
|
||||
const mins = Math.ceil((asked.budget?.waitMs || 0) / 60000);
|
||||
return json(res, 429, {
|
||||
error: asked.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.`
|
||||
});
|
||||
}
|
||||
// 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 });
|
||||
audit(req, 'auth.health.insight', { ok: false, user, msg: String(asked.status || asked.error || asked.reason).slice(0, 120) });
|
||||
return json(res, 502, { error: asked.error || 'The second opinion could not be asked.' });
|
||||
}
|
||||
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}` });
|
||||
audit(req, 'auth.health.insight', { user, msg: `${cfg.model} ${asked.answered}/${asked.asked}` });
|
||||
json(res, 200, {
|
||||
ok: true,
|
||||
configured: true,
|
||||
model: cfg.model,
|
||||
host: endpointHost(cfg.baseUrl),
|
||||
insight: doc,
|
||||
host: endpointHost(jevEndpoint(cfg.baseUrl)),
|
||||
insight: asked.insight,
|
||||
freshness: { fresh: true, reason: null },
|
||||
budget: budgetFor(doc, { maxPerDay: cfg.maxPerDay, minIntervalMs: cfg.minIntervalMs }),
|
||||
sent: summarizeState(state)
|
||||
budget: asked.budget,
|
||||
sent: asked.sent
|
||||
});
|
||||
},
|
||||
|
||||
|
||||
Reference in new issue
Block a user