El Coach ahora sabe para qué cuerpo escribe: tu semana de Salud y tu peso al crear
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
Preguntado como "¿Jev está integrado en el Coach para crear o revisar, según mi peso, mis medidas y
los entrenamientos que ya he hecho?" — y la respuesta honesta tenía dos huecos, que este commit
cierra, y uno que no.
**Lo que ya estaba.** El payload del Coach lleva el cuestionario (objetivo, experiencia, días,
minutos, equipamiento, limitaciones), tu plan, `history.workingWeights` (el mejor peso que ya
manejaste en cada ejercicio, para que las cargas iniciales partan de evidencia), `window` +
`aggregates` en una revisión (las últimas tres sesiones serie por serie, las anteriores resumidas,
estancamientos, adherencia, series por parte del cuerpo), tu peso de las últimas semanas y la segunda
opinión de Jev cuando tiene menos de seis horas.
**Lo que faltaba.**
· **Una semana de Apple Health no llegaba nunca**: el Coach podía leer tu entrenamiento y no tu
recuperación. Ahora `health` viaja en el payload — por métrica y por campo, el promedio diario,
el valor más nuevo y cuántos días tienen datos, con tope de ocho métricas y en el orden del
catálogo. Promedios y no el archivo, a propósito: "durmiendo 6,2 h contra 7,1 la semana
anterior" cambia una decisión de volumen, y 288 muestras de pulso sólo gastan tokens. Va en
crear y en revisar; no en el debrief, porque el promedio de una semana no dice nada de una sesión.
El resumen vive en `jev.js`, junto al orden de métricas que ya usaba, y `jobs.js` lo lee del
mismo archivo que el teléfono escribe.
· **Al crear un plan no le llegaba tu peso.** Revisar y debrief siempre lo llevaron; crear no. Un
plan nuevo se escribía sin saber si estás en déficit o subiendo. Ahora el payload de crear lleva
el objetivo y los últimos ocho pesajes.
· Ambas cosas se documentan al modelo en `prompts/common.md`, con su límite dicho: dos días con
datos no son una semana, así que no se lee una tendencia de ahí.
**Lo que no existe, y lo digo en vez de dejarlo creer: medidas corporales.** La app guarda peso y
nada más — ni cintura, ni pecho, ni brazo. No hay dónde escribirlas, así que "según mis medidas"
todavía no es algo que esta instancia pueda hacer; lo que el Coach lee es la serie de peso. Está
escrito así en `docs/AI_COACH.md`, con la tabla de qué entra en el payload y de dónde sale cada cosa.
Tests: el resumen (promedios por campo, ventana, orden, métricas fuera de la ventana descartadas,
tope de ocho) y el payload (el resumen reducido y saneado, la clave ausente en vez de un objeto vacío,
y el peso en crear). API 269 en verde, frontend 1705.
This commit is contained in:
1 parent
f7b884be81
commit
9a339db85e
8 files changed
+195
-4
No files matched your search
+43
-1
@@ -10,7 +10,7 @@ import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
jevConfig, jevEndpoint, buildState, buildQuestions, parseAnswers, readAnswer,
|
||||
makeInsight, stateHash, insightFreshness, budgetFor, JEV_DEFAULTS
|
||||
makeInsight, stateHash, insightFreshness, budgetFor, healthSummary, JEV_DEFAULTS
|
||||
} from '../jev.js';
|
||||
|
||||
const NOW = Date.parse('2026-09-23T20:00:00Z');
|
||||
@@ -262,3 +262,45 @@ test('the daily budget counts per day and the interval holds a person back', ()
|
||||
assert.equal(budgetFor(null, { now: at, maxPerDay: 2 }).remaining, 2);
|
||||
assert.equal(budgetFor({ at: at - 3600000, day: today, used: 0 }, { now: at, maxPerDay: 0 }).allowed, false);
|
||||
});
|
||||
|
||||
/* ---------- the week the Coach reads ----------
|
||||
*
|
||||
* Averages, never the file: the Coach can act on "sleeping 6.2 h against 7.1" and cannot act on 288
|
||||
* heart-rate samples. Per field as HAE named it, because the catalogue that gives those fields a
|
||||
* meaning lives in the frontend and duplicating it here would give the two a way to disagree. */
|
||||
|
||||
test('the health summary is a week of averages, per metric and per field', () => {
|
||||
const day = (d, n, sum, last) => ({ [d]: { n, lastTs: Date.parse(d + 'T12:00:00Z'), f: { qty: { n, sum, min: 1, max: last, last } } } });
|
||||
const doc = {
|
||||
metrics: {
|
||||
step_count: { units: 'count', days: { ...day('2026-05-01', 1, 9000, 9000), ...day('2026-05-02', 1, 11000, 11000), ...day('2026-05-08', 1, 500, 500) } },
|
||||
// Inside the window on purpose: seven days ending on the 8th starts on the 2nd.
|
||||
sleep_analysis: { units: 'hr', days: { '2026-05-02': { n: 1, lastTs: 0, f: { asleep: { n: 1, sum: 7.4, min: 7.4, max: 7.4, last: 7.4 } } } } },
|
||||
old_metric: { units: '', days: { '2025-01-01': { n: 1, lastTs: 0, f: { qty: { n: 1, sum: 1, min: 1, max: 1, last: 1 } } } } },
|
||||
empty_metric: { units: '', days: {} }
|
||||
}
|
||||
};
|
||||
const sum = healthSummary(doc, { days: 7, now: Date.parse('2026-05-08T23:00:00Z') });
|
||||
assert.equal(sum.window_days, 7);
|
||||
const names = sum.metrics.map(m => m.metric);
|
||||
assert.deepEqual(names, ['sleep_analysis', 'step_count'], 'the catalogue order first, and nothing outside the window');
|
||||
const steps = sum.metrics.find(m => m.metric === 'step_count');
|
||||
assert.equal(steps.days_with_data, 2, 'the 1st is outside a seven-day window ending on the 8th');
|
||||
assert.deepEqual(steps.fields[0], { field: 'qty', avg_per_day: 5750, newest: 500, day: '2026-05-08', days: 2 });
|
||||
// A metric with no readable field is not a metric, and neither is one whose days are all outside
|
||||
// the window — the Coach must not be handed an empty shell it has to interpret.
|
||||
assert.equal(names.includes('empty_metric'), false);
|
||||
assert.equal(names.includes('old_metric'), false);
|
||||
assert.deepEqual(healthSummary(null).metrics, []);
|
||||
});
|
||||
|
||||
test('the health summary is bounded, so a prompt cannot be flooded by an export of everything', () => {
|
||||
const days = {};
|
||||
for (let i = 0; i < 9; i++) days[`2026-05-0${i + 1}`] = { n: 1, lastTs: 0, f: { qty: { n: 1, sum: i, min: 0, max: i, last: i } } };
|
||||
const metrics = {};
|
||||
for (let i = 0; i < 20; i++) metrics[`metric_${String(i).padStart(2, '0')}`] = { units: '', days };
|
||||
const sum = healthSummary({ metrics }, { days: 9, now: Date.parse('2026-05-09T23:00:00Z') });
|
||||
assert.equal(sum.metrics.length, 8, 'eight metrics is what a plan can be written from');
|
||||
assert.equal(sum.metrics[0].metric, 'metric_00', 'and they are the first alphabetically, stably');
|
||||
assert.equal(sum.metrics[0].fields[0].avg_per_day, 4, 'the average is per day with data, not per day in the window');
|
||||
});
|
||||
@@ -17,6 +17,43 @@ test('build refuses to run without a handle — a payload must never fall back t
|
||||
assert.throws(() => payload.build(sampleState(), { kind: 'review' }), /handle/);
|
||||
});
|
||||
|
||||
/* What the plan is written *for*: the body that has to do it. Until this existed the Coach knew the
|
||||
training and nothing about the person's recovery — a week of Apple Health arrives as averages,
|
||||
reduced here, never as the file. */
|
||||
test('the payload carries a week of health, reduced to averages', () => {
|
||||
const health = {
|
||||
window_days: 7,
|
||||
metrics: [
|
||||
{ metric: 'sleep_analysis', units: 'hr', days_with_data: 7, fields: [{ field: 'asleep', avg_per_day: 6.2, newest: 5.4, days: 7 }] },
|
||||
{ metric: 'resting_heart_rate', units: 'bpm', days_with_data: 6, fields: [{ field: 'qty', avg_per_day: 62, newest: 68, days: 6 }, { field: null, avg_per_day: 1 }] },
|
||||
{ metric: 'a_metric_with_nothing_readable', units: '', days_with_data: 3, fields: [{ field: 'x', avg_per_day: null, newest: null }] },
|
||||
{ metric: null, fields: [] }
|
||||
]
|
||||
};
|
||||
const withHealth = payload.build(sampleState(), { handle: handleFor('u1'), kind: 'review', health });
|
||||
assert.deepEqual(withHealth.health.metrics.map(m => m.metric), ['sleep_analysis', 'resting_heart_rate']);
|
||||
assert.deepEqual(withHealth.health.metrics[0].fields[0], { field: 'asleep', avg_per_day: 6.2, newest: 5.4, days: 7 });
|
||||
assert.equal(withHealth.health.metrics[1].fields.length, 1, 'a field with no number is not a field');
|
||||
assert.equal(withHealth.health.window_days, 7);
|
||||
|
||||
// Nothing to say means the key is not there at all, rather than an empty object a model has to
|
||||
// interpret as "this person has no health data".
|
||||
assert.equal(payload.build(sampleState(), { handle: handleFor('u1'), kind: 'review' }).health, undefined);
|
||||
assert.equal(payload.build(sampleState(), { handle: handleFor('u1'), kind: 'review', health: { metrics: [] } }).health, undefined);
|
||||
assert.equal(payload.build(sampleState(), { handle: handleFor('u1'), kind: 'review', health: 'nope' }).health, undefined);
|
||||
|
||||
// A new plan needs the body it is for: the weight when they asked, and what they are aiming at.
|
||||
// The review and the debrief always carried this; create did not.
|
||||
const S = sampleState({
|
||||
unit: 'kg', targetW: 78,
|
||||
bodyweight: [{ d: '2026-05-01', w: 80 }, { d: '2026-05-08', w: 79.4 }]
|
||||
});
|
||||
const created = payload.build(S, { handle: handleFor('u1'), kind: 'create' });
|
||||
assert.deepEqual(created.bodyweight, { goal: 78, series: [{ d: '2026-05-01', w: 80 }, { d: '2026-05-08', w: 79.4 }] });
|
||||
assert.equal(created.health, undefined, 'and a create payload can carry health too — it just has none here');
|
||||
assert.equal(payload.build(S, { handle: handleFor('u1'), kind: 'create', health }).health.metrics.length, 2);
|
||||
});
|
||||
|
||||
/* The promise the consent screen makes is only as good as this test. It asserts on the
|
||||
*absence* of things, which is the awkward direction to test and the only one that matters:
|
||||
a field added to the state blob next year must not be able to ride along. */
|
||||
|
||||
Reference in new issue
Block a user