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
+109
-1
@@ -1,4 +1,4 @@
|
||||
/* insights.js — where a profile's last second opinion lives.
|
||||
/* insights.js — the second opinion: where it lives, and the one way it is produced.
|
||||
*
|
||||
* One small file per profile, beside the health file it was judged from and written the same way
|
||||
* (write-temp-then-rename, mode 0600). It holds the answers, when they were made and which model
|
||||
@@ -10,6 +10,11 @@
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
jevConfig, buildState, buildQuestions, askJev, parseAnswers, makeInsight, stateHash,
|
||||
insightFreshness, budgetFor
|
||||
} from './jev.js';
|
||||
import { LIB_BY_ID } from './coach/core/library.js';
|
||||
|
||||
const DATA = process.env.DATA_DIR || '/data';
|
||||
|
||||
@@ -29,3 +34,106 @@ export function writeInsight(uid, doc) {
|
||||
export function clearInsight(uid) {
|
||||
try { fs.unlinkSync(insightFile(uid)); } catch { /* nothing stored */ }
|
||||
}
|
||||
|
||||
/* ---------- the files it judges ---------- */
|
||||
|
||||
const profileFile = (prefix, uid) => path.join(DATA, prefix + String(uid).replace(/[^a-zA-Z0-9_-]/g, '') + '.json');
|
||||
const readJson = file => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } };
|
||||
|
||||
export const readStateFile = uid => readJson(profileFile('state-', uid));
|
||||
export const readVitalsFile = uid => readJson(profileFile('vitals-', uid));
|
||||
|
||||
const bodyPartOf = id => LIB_BY_ID.get(id)?.bp || null;
|
||||
const exerciseName = id => LIB_BY_ID.get(id)?.n || null;
|
||||
|
||||
/** The state the judgment is asked about, built from the profile's own files. */
|
||||
export function stateFor(uid, cfg = jevConfig()) {
|
||||
return buildState({
|
||||
S: readStateFile(uid) || {},
|
||||
vitals: readVitalsFile(uid),
|
||||
bodyPartOf,
|
||||
nameOf: exerciseName,
|
||||
days: cfg.stateDays
|
||||
});
|
||||
}
|
||||
|
||||
/** Counts, never content: what a screen needs to say what it just sent. */
|
||||
export 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 || {}),
|
||||
stalled: (state.training?.stalled || []).map(e => e.name),
|
||||
includes_limitations: !!state.profile?.limitations
|
||||
};
|
||||
}
|
||||
|
||||
/** The endpoint's host, for a screen to name. Never the key with it. */
|
||||
export function endpointHost(baseUrl) {
|
||||
try { return new URL(baseUrl).host; } catch { return null; }
|
||||
}
|
||||
|
||||
/* ---------- running it ----------
|
||||
*
|
||||
* One function, two callers, and that is the point: the Salud card asks, and so does a Coach job
|
||||
* that is about to write a plan. "Jev decides, the model writes" only happens if the judgment is
|
||||
* there when the writing starts, and waiting for somebody to tap a button on another screen is how
|
||||
* the two halves never meet. The budget is checked here, in the one place, so an automatic ask can
|
||||
* never spend more than a manual one — and a provider that fails is reported, not thrown, because a
|
||||
* Coach job that dies because its second opinion was unavailable is worse than one without it. */
|
||||
|
||||
/**
|
||||
* Ask Jev about this profile and store the answer.
|
||||
*
|
||||
* @returns {Promise<{ok:true, insight:object, sent:object, budget:object}
|
||||
* | {ok:false, reason:'unconfigured'|'budget'|'provider', status?:number, error?:string}>}
|
||||
*/
|
||||
export async function runInsight(uid, { fetchImpl = fetch, now = Date.now(), cfg = jevConfig() } = {}) {
|
||||
if (!cfg.configured) return { ok: false, reason: 'unconfigured' };
|
||||
const stored = readInsight(uid);
|
||||
const budget = budgetFor(stored, { now, maxPerDay: cfg.maxPerDay, minIntervalMs: cfg.minIntervalMs });
|
||||
if (!budget.allowed) return { ok: false, reason: 'budget', budget };
|
||||
|
||||
const state = stateFor(uid, cfg);
|
||||
const questions = buildQuestions(state);
|
||||
let body;
|
||||
try {
|
||||
body = await askJev({ cfg, state, questions, fetchImpl });
|
||||
} catch (e) {
|
||||
return { ok: false, reason: 'provider', status: e.status || null, error: e.message };
|
||||
}
|
||||
const answers = parseAnswers(body, questions);
|
||||
const doc = {
|
||||
...makeInsight({ answers, raw: body, model: cfg.model, stateHash: stateHash(state), at: now }),
|
||||
day: new Date(now).toISOString().slice(0, 10),
|
||||
used: budget.used + 1
|
||||
};
|
||||
writeInsight(uid, doc);
|
||||
return {
|
||||
ok: true,
|
||||
insight: doc,
|
||||
sent: summarizeState(state),
|
||||
answered: Object.values(answers).filter(Boolean).length,
|
||||
asked: Object.keys(questions).length,
|
||||
budget: budgetFor(doc, { now, maxPerDay: cfg.maxPerDay, minIntervalMs: cfg.minIntervalMs })
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The judgment a Coach job should use: what is stored, or a fresh one asked for now.
|
||||
*
|
||||
* Freshness is the same rule the Salud card shows (`insightFreshness`), so the two cannot disagree
|
||||
* about what counts as current. A debrief is excluded — it reads one session, and a judgment about
|
||||
* readiness and volume is not about that session.
|
||||
*/
|
||||
export async function insightForCoach(uid, { kind = 'review', fetchImpl = fetch, now = Date.now() } = {}) {
|
||||
// A debrief reads one session; how ready the person is and which way the week's volume should go
|
||||
// is not about that session, so it is not asked for there.
|
||||
if (kind === 'debrief') return null;
|
||||
const stored = readInsight(uid);
|
||||
if (insightFreshness(stored, { now }).fresh) return stored;
|
||||
const asked = await runInsight(uid, { fetchImpl, now });
|
||||
return asked.ok ? asked.insight : null;
|
||||
}
|
||||
Reference in new issue
Block a user