/* 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 * made them — never the health data itself, which stays in vitals-.json. * * Separate from server.js because two other readers want it: the Coach, which carries the judgment * into its prompt when it is recent enough to still be true, and the routes. Nothing here interprets * the document; the shape belongs to jev.js and the meaning to the screen. */ 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'; export const insightFile = uid => path.join(DATA, 'insight-' + String(uid).replace(/[^a-zA-Z0-9_-]/g, '') + '.json'); export function readInsight(uid) { try { return JSON.parse(fs.readFileSync(insightFile(uid), 'utf8')); } catch { return null; } } export function writeInsight(uid, doc) { const file = insightFile(uid); const tmp = file + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(doc), { mode: 0o600 }); fs.renameSync(tmp, file); } 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 whole row, not just a field: the 1RM estimate has to know an exercise is an assistance // machine, whose load is the help given rather than the weight lifted. const exerciseRow = id => LIB_BY_ID.get(id) || 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, exOf: exerciseRow, 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; }