48cf9766358727c7e4f8cd44a8a3647d71330306
48
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
48cf976635 |
Radio: estaciones en vivo mientras entrenás
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
Música tiene una sección **Radio**: estaciones en vivo por género (Workout/Rave, Techno/House, R&B/Soul, Latina, Hip-Hop, Reggae, Chill, Jazz, Rock, Electrónica), sin publicidad primero —SomaFM y Radio Paradise— y detrás el directorio público de radio-browser. Nada de esto suma dependencias: la lista la arma api/radio.js. Tres decisiones que no se ven en la pantalla y son las que hacen que funcione: - **El audio no pasa por el servidor.** La api entrega la lista y después no ve un byte: el teléfono habla con la estación. Sin ancho de banda, sin disco, sin copias. - **La URL del stream viene resuelta en la lista**, porque iOS sólo deja arrancar audio dentro del gesto del toque: cualquier cosa asíncrona entre el dedo y el play() es un botón que no hace nada, sin error en ninguna parte. - **El `<audio>` vive fuera de React** (lib/radio-player.js): un elemento dentro de un componente se desmonta con él, y eso es la música cortándose al cambiar de pantalla — justo lo que no puede pasar en medio de una serie. Barra arriba de la barra de pestañas con pausa (deja la estación donde estaba) y parar; Media Session pone estación, pista y controles en la pantalla bloqueada, y las canciones siguen con el teléfono en el bolsillo. Qué suena lo dicen SomaFM y Radio Paradise y nadie más: en el resto la barra muestra la estación en vez de inventar una pista. api/test/server-radio.test.js guarda las dos puertas (sesión obligatoria, `src`+`id` reconstruidos en vez de confiar en el objeto del cliente); RadioBar.test.jsx y el caso de la fila en Music.test.jsx guardan lo demás. También: radio.js en el COPY del Dockerfile —importar un archivo que no está copiado es un contenedor que arranca en ERR_MODULE_NOT_FOUND—, /api/radio y /api/radio/now (con /api/music/lookup, que faltaba) en la especificación, y docs/RADIO.md. |
||
|
|
91606d9c9e |
Un fallo del Coach dice por qué, sin citar a nadie
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Reportado así: "Mira mi entrenamiento y dime qué cambiarías" → *The Coach answered with something the app couldn't use*, mientras que "¿Cómo fue mi sesión de Back & Triceps?" funcionaba. El código ya sabía la razón y la tiraba: el parser y el validador devuelven qué campo falló, y `pipeline.js` la descartaba — el registro guardaba sólo la clase de error, así que ni la persona ni el dueño podían distinguir prosa de un JSON cortado a la mitad, de un tipo de cambio que no existe, de un ejercicio que no está en el plan. Ahora `unusable` lleva `detail`: **la queja textual** del parser o del validador, que nombra el campo, más una descripción de la forma de la respuesta —prosa o "empieza como JSON", y cuántos caracteres—. Sin citarla nunca, y eso es deliberado: este renglón va al registro de instancia, que es visible para el admin y abarca a todos los perfiles, y ese registro lleva conteos y resultados, nunca los datos de una persona. Unos pocos caracteres de un plan serían exactamente cómo esa regla se rompe. La longitud más la forma es lo que separa "el modelo ignoró el modo JSON" de "la respuesta se cortó", y no dice nada de nadie. En el prompt de reparación esto es la *segunda* respuesta — la que el modelo manda después de que se le dijo qué estaba mal en la primera —, que es lo más informativo que hay: un modelo que no puede arreglar una queja que acaba de recibir es el problema, no este archivo. Documentado con la tabla de clases de error y qué significa cada una (`docs/AI_COACH.md`), porque el patrón que se reportó se lee solo con ella: el debrief es fácil —todo cadenas y un número— y el review es la tarea más difícil —una lista de cambios tipados, con objetivo, antes/después y un motivo de una tabla fija—. Un modelo que debriefa bien y no puede con el review es un enunciado sobre el modelo. Mutation-check: si el detalle vuelve a estar vacío, el test falla. API 279 en verde. |
||
|
|
9a4394aff5 |
Jev decide mirando el histórico completo, no los últimos 28 días
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
"Para que Jev tome decisiones debía mirar la sesión de progreso, que tiene todos los datos de los
entrenamientos pasados." Exacto, y no lo hacía: el estado llevaba una ventana de cuatro semanas, las
últimas tres sesiones en detalle y un puñado de conteos. Un ejercicio que no se mueve desde hace tres
meses se veía exactamente igual que uno que nunca se entrenó, que es justo la diferencia sobre la que
un plan tiene que decidir.
Ahora el estado lleva, por ejercicio y sobre **todo** el histórico:
· cuántas sesiones, y el mejor set de la primera y de la última;
· el mejor de siempre, con su fecha;
· una serie de hasta diez estimaciones, una por sesión, para que se vea la *forma* y no dos extremos;
· la dirección: las últimas tres sesiones contra las tres anteriores — no contra el récord de
marzo, porque un ejercicio que batió su récord en marzo y está plano desde entonces no progresa;
· y el cuerpo al que pertenece, para que una decisión de selección sepa de qué parte del cuerpo habla.
Más: la carga y el volumen por semana de las últimas diez, los totales de todo el histórico (sesiones,
series, desde cuándo entrena, cuántos sets en total) y los estancamientos del bloque actual. Los topes
son de lo que se *muestra* — 12 ejercicios, 10 puntos, 10 semanas — nunca de la aritmética: cada número
se calcula sobre todas las sesiones que el perfil tenga, y hay un test con 40 sesiones y cinco meses de
historia que falla si alguien mete una ventana otra vez.
La estimación de 1RM se comparte en vez de duplicarse: `api/coach/core/strength.js` es un espejo
deliberado de `frontend/src/lib/onerm.js` — mismo Epley, mismo tope de 12 repeticiones, mismas dos
exclusiones (series de calentamiento; máquinas asistidas, cuyo peso es la ayuda recibida y no la carga
levantada) — y `cohort.js`, que tenía su propia copia del cálculo, ahora usa esa. Un plan escrito desde
un número distinto al que dibuja la pantalla de Progreso es un plan que nadie puede verificar, así que
la fórmula vive en dos lugares a propósito y los tests la comparan con los mismos ejemplos.
Los ids de ejercicios del histórico viajan con su nombre, en la misma línea que ya lo hacían los
estancados: una decisión sobre *qué ejercicio cambiar* tiene que nombrar algo que la app pueda editar.
Tests: el histórico largo, las tres direcciones de tendencia, el tope de puntos con la aritmética
intacta, el volumen de una serie por tiempo (un set sin repeticiones suma al conteo y nada al volumen)
y la estimación compartida. API 279 en verde, frontend 1705.
|
||
|
|
f80ade25f6 |
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
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. |
||
|
|
9a339db85e |
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
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.
|
||
|
|
f7b884be81 |
Salud: dos dispositivos, una caminata — el cubo guarda sus fuentes y muestra una
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
"En mi Apple Salud me dice 946 y en opengym 1700 y pico", y antes 499 contra 840. Ese factor —1,80 y
1,68— es la prueba: una suma de valores acumulados daría 12× o 24× al final del día, no 1,8×. Lo que
da 1,8× es **sumar dos dispositivos**. HealthKit de-duplica la misma caminata entre el Apple Watch y
el iPhone, la app Salud la cuenta una vez, y un payload que trae los dos como puntos separados no la
ha de-duplicado nadie. La tarjeta estaba leyendo dos cosas, exactamente como se sospechó.
Ahora cada cubo —una hora, y el día cuando el teléfono manda un total por día— **guarda sus fuentes
por separado y muestra una**: la que más reportó en ese cubo, después la más nueva, después la más
grande. No es una suma, no es un promedio y no es "el máximo": es el agregado propio de un
dispositivo, o sea el número que ese dispositivo muestra.
Y la elección es **por hora**, no por día, que es lo que hace correctas las dos situaciones a la vez:
una hora que solo registró el teléfono es del teléfono (no se pierde nada), y una hora que
registraron los dos se cuenta una vez (no se duplica nada). Con la elección por día, el caso
"caminata sin el reloj" se habría perdido.
Tres cosas que había que cuidar y están cubiertas por tests:
· **Un payload sin `source`** —casi todos, y en iOS 27+ es lo normal para datos acumulados— vive en
una sola fuente sin nombre, así que un cubo es el cubo y nada cambia para quien tiene un solo
dispositivo. Los 22 tests que ya existían pasaron sin tocarlos, que es la evidencia de eso.
· **Un cubo guardado antes de esto** se adopta como la fuente sin nombre en vez de tirarse: una
actualización no pierde el día que ya tenía, y las dos compiten por cantidad de muestras.
· **Reemplazar una hora borra solo la de esa fuente.** La hora en curso crece en cada envío de un
automatismo de cinco minutos y por eso se reemplaza, pero reemplazar el cubo entero es cómo un
dispositivo borraría en silencio el reporte del otro — que es lo contrario de lo que esto hace.
La hoja lo dice al final: `N días con datos · Apple Watch, iPhone · se usa Apple Watch`, para que el
número se pueda cotejar contra el dispositivo que lo produjo.
Cinco tests del merge más el orden de desempate. Mutation-check de las dos mitades: sin aplicar la
fuente ganadora fallan cuatro, y si reemplazar una hora borra la del otro dispositivo fallan tres.
API 267 en verde, frontend 1705, build OK.
|
||
|
|
4ba9e29d1e |
La app avisa cuando la api es más vieja que ella
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
Validado desde afuera, y era esto: **el frontend desplegado es el nuevo y la api no**. Los hashes que
sirve producción coinciden byte a byte con mi build de HEAD, y el bundle contiene las novedades
("What arrived last", "one total an hour"); pero `/api/vitals/hours`, `/api/insights` y
`/api/music/lookup` responden **404** donde esta versión responde 401. O sea: el número de cada
tarjeta lo calcula la api — y la api que corre es la de antes de las horas, la que lee el total del
día como si fuera la hora 00 y suma 840 donde el reloj dice 499.
Eso explica el reporte completo sin ninguna otra suposición: las actualizaciones llegan, se guardan,
y la pantalla nueva pide cosas que ese servidor no tiene (de ahí que el detalle por hora y el recibo
no aparezcan nunca) mientras muestra el número que el servidor viejo le manda.
La causa de fondo es de despliegue: `web` se reconstruye desde el código en cada deploy, pero el
código de la api se copia *dentro* de su contenedor, y Dokploy no recrea un servicio que ya está
Running. Un deploy entonces refresca la mitad de la aplicación.
Arreglar eso no puede depender de que alguien se acuerde, así que la app ahora lo pregunta:
`GET /api/config` publica `features` — una lista de capacidades, nunca configuración ni credenciales —
y Salud muestra una línea ámbar cuando esa lista falta o no llega hasta `vitals.hours`. Un servidor
viejo ya no puede parecer una pantalla rota.
Tests: el config contra el servidor real (la lista existe, nombra las rutas nuevas, y esas rutas
contestan 401 y no 404, sin claves adentro), y el aviso en la pantalla para los dos casos — api sin
lista y api al día. Mutation-check: si el aviso deja de dispararse con una api sin lista, falla.
|
||
|
|
407d7c47c9 |
Salud: el total del día es el día, y un recibo que explica el número que no cuadra
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
"Las actualizaciones están llegando pero las tarjetas no tienen los mismos números que Salud." Las actualizaciones llegan, entonces: el problema es qué se hace con ellas, y hay dos formas de que un día salga más grande de lo que el reloj dice. **El total del día leído como hora 00.** Si HAE manda el total del día con marca de medianoche en el mismo payload que las horas, ese punto caía en el cubo de las 00:00 y la suma del día lo contaba además de las horas — 499 declarados + 341 de horas = 840, que es exactamente el número reportado. Ahora un punto de medianoche que vale más que todo el resto del payload junto es el total del día (una hora no puede tener más que el día que la contiene) y nunca se convierte en hora 00; un 00:00 chico de verdad sigue siendo la primera hora y se suma como cualquier otra. **Horas sumadas a un total que ya las contenía.** Con el día declarado por el teléfono, cada hora que llegaba después se le sumaba encima — el mismo error, una capa más arriba. Ahora el total declarado **es** el día y las horas nunca se le agregan: son la forma del día, no un segundo número. Su suma queda al lado, en `hours_sum`, y la hoja de la métrica dice cuando los dos difieren, en palabras: tanto el teléfono declaró, tanto suman las horas, y cuál de los dos estás viendo. Un total que no se renueva en seis horas deja de mandar, así que cambiar una automatización de Días a Horas converge en vez de congelarse para el resto del día. Y para la otra forma — horas que en realidad son **totales acumulados** en vez de deltas, que también suman de más — cada envío deja un **recibo por métrica**, visible en la hoja: cuántos datos llegaron, cómo vienen marcados (un total por día, uno por hora, muestras sueltas o mezcla), de qué fuentes, cuánto suman y los tres últimos valores. Una corrida de números que suben (340 → 420 → 499) es la señal de que son acumulados, y eso es la diferencia entre 499 y 840 vista en la pantalla en vez de deducida. Es un recibo, no una lectura: el campo que cita se elige por una lista fija porque este módulo no tiene el catálogo, y nada de él entra en el cálculo de un día. Seis tests nuevos del merge y del recibo, dos de las filas de la hoja y uno de render por la hoja real. Mutation-check de las dos mitades del arreglo: leer el total como hora 00 falla, y sumarle las horas al total declarado falla. API 261 en verde, frontend 1701, build OK. |
||
|
|
90aa802980 |
La segunda opinión: un juicio sobre tus números, con la probabilidad que trae
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
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.
|
||
|
|
5c69540f62 |
Salud: reset one measurement, without losing the rest
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
"Podemos reiniciar los números de esas mediciones para yo enviar el de hoy." The whole-file reset
already existed two taps away in the setup sheet, but it is the wrong size for the question: the
four metrics he suspects are not the profile. Throwing away a month of heart rate to start steps
over is not a reset, it is a tax.
So a metric can now be forgotten on its own: the detail sheet has **Reset this measurement**, which
deletes that metric's days (and hours) and nothing else — the other metrics, the workouts and the
ingest key stay. With any Date Range wider than a day the phone re-sends that metric on its next
sync, which is what makes this a reset rather than a loss: Apple Health still has the data, and a
day total replaces the day it names, so the stored past is rewritten rather than duplicated.
The two destructive rows are worded apart on purpose and the confirm names the metric ("¿Reiniciar
Pasos?"), because the neighbouring action in the setup sheet takes every metric there is.
`dropMetric()` is pure and returns how many days it took, and the route answers `metric: null` for
a metric the profile does not have (or a profile with no health file at all) instead of an error —
a screen that says "nothing stored" is more useful than a 404 answering a button press. Tested
from both ends: the helper's purity and arithmetic, the route against a real server (one metric
gone, the others and the workouts intact, the key still working, and a re-sync rebuilding it), and
the sheet's flow through the real confirm. Mutation-checked: pointing the row at the whole-file
delete fails it.
|
||
|
|
aa6ec8ef22 |
Salud: a card opens onto the day, hour by hour, and onto the days before it
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
Reported as "le doy a cualquier actividad y solo me presenta los pasos de hoy… debiera presentarme una medida por hora, y no me da el histórico". Two separate things, and only one of them was the app's fault. **The history was the automation's setting.** With Date Range on its default (`Today`) every sync carries today and nothing else, so there is exactly one day in the file to draw. That is why a card looked frozen: not a rendering bug, a range that was never sent. The setup steps now say `Previous 7 Days` and say why. **The hours were thrown away by us.** Even when the phone sends 288 readings a day, the receiver folded every one of them into a single day aggregate, so "8,123 steps today" was all there could ever be — a number you cannot look into. Worse, the recommended setting was Time Grouping `Days`, which sends one point per metric per day: the intraday detail never arrived in the first place. The recommendation is now `Hours`, and the storage keeps the hours. The merge rule for them is the same shape as the day rule, for the same reason: a payload whose datapoints all sit on the hour is HAE's own hour grouping, and the hour *in progress* grows on every run of a five-minute automation, so it is replaced and never unioned — 500 + 900 + 1,340 steps in one hour is a number no watch recorded. The day is then recomputed as the sum of its hours, which is what keeps the card and the detail from ever disagreeing, and which also makes switching an automation from Days to Hours mid-day converge instead of double-count. Raw samples (real timestamps) still union by instant plus numbers, and they now land in their own hour, which is where intraday detail comes from when nothing is grouped. Three things that would have been silent bugs, caught while writing it: - The hour rule is decided from the **whole payload**, never from one timestamp. A five-minute automation produces samples that sit exactly on the hour, and reading one of those as an hour total wipes the hour it belongs to. There is a test with a 09:00:00 and a 09:05:00 sample in one payload, and it fails against the per-point version of the rule. - A day that arrived as a day total keeps its hours beside it, and a day stored before this existed keeps its aggregate when the first hour shows up — recomputing it from hours it does not have would delete 2,000 steps. Both are mutation-checked (removing either guard fails a test). - A payload grouped by hour writes the ledger row anyway, because a later payload with real minutes can describe the same instant and the union path can only see the ledger. Without it the raw-sample route test double-counts a single sample. The hours are the bulky part of this data, so they are kept for a week (the day aggregates still live the full 400 days), pruned when the night's file is written, and fetched one metric and one day at a time — `GET /api/vitals/hours`. A screen listing forty cards downloads none of them; the day view carries only a count per day, which is what tells the sheet whether it is worth asking. The sheet draws the hours, the days before it (tapping one moves the hour list to that day), and every field the watch sent; when the automation groups by Days it says so instead of leaving a gap where a chart should be. Coverage: 6 new tests in `api/test/vitals.test.js` (19 total) and a route test in `api/test/server-vitals.test.js` (5), the hour/history model in `vitals-view.test.js` (31), three render tests through the real sheet, the route documented in `api/openapi.yaml` and `website/api.html`, and `docs/HEALTH.md` with the settings, the new merge row and the two symptoms now in Troubleshooting. |
||
|
|
caed0cbaa0 |
Música: a playlist screen per profile, with Apple's limits stated plainly
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
The idea was "each person types their Apple Music username and their public playlists appear". Apple does not allow that, and it is worth writing down rather than discovering later: there is no API for another person's public playlists — their own developer forums answer that request with "you can't" (threads 692941 and 123894) — and a profile page is rendered by JavaScript with nothing behind it to call. MusicKit offers the catalog and the *signed-in* user's own library, and the second needs an Apple Developer Program membership for a developer token plus a Music-User-Token per person: a private key and a third-party secret in an app that holds none, to fetch something other than what was asked for. What a self-hosted app can do is the share link, which every playlist has: Music → Share → Copy Link. So the Música screen (next to Salud in Home's header, plus a section in Settings) keeps a list of them per profile, in the profile document like the routines — so they sync to the other devices and travel in a backup — and tapping one opens it in Apple Music on the iPhone. The username is a link to the person's public profile. The list is nicer than a column of URLs because the API reads each link's public page for a title, artwork and track count. That is scraping, so it is built to lose: a page that says nothing leaves the card showing the name its owner typed, and nothing on the screen depends on it. `POST /api/music/lookup` is host-allowlisted to Apple's music hosts — https only, checked again on the URL a redirect lands on — because the api container sits on the same network as everything else the owner runs, and a route that fetches whatever it is handed is a request-forgery lever. That boundary has its own tests, including the LAN addresses it must refuse. The parsing lives in api/music.js rather than in both halves: two copies of a parser kept in step by hand is a bomb, and this is the same shape as vitals.js. It is in the Dockerfile's COPY for the same reason vitals.js had to be. |
||
|
|
691e664d3f |
Apple Health (Salud): a per-profile ingest endpoint, and a tab that draws it
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
An iOS automation in Health Auto Export POSTs Apple Health to /api/vitals/ingest, and the new Salud tab (next to Plan) draws whatever arrived: steps, heart rate, sleep, weight, oxygen, workouts and every other metric HAE can export, grouped into cards with a trend, a sparkline and a 7/30/90/365-day range. Nothing on that screen is an input, and the watch's workouts stay out of the history on purpose — they carry no sets and no weights, so folding them into progression, PRs and the recovery model would be inventing data. The interesting part is duplicates. A five-minute automation re-sends overlapping windows: with Date Range "Today", appending would count a day of steps again on every run, and with "Since Last Sync", replacing would throw away everything but the last five minutes. So the endpoint decides per payload instead. Datapoints that sit on midnight are HAE's own day grouping, i.e. a *total*, and a day total replaces the day it names — re-sending the same day all afternoon converges on that day's total. Anything else is a real sample, identified by its instant plus its numbers and stored once, which is right for overlapping and disjoint windows alike. Every sync answers with a receipt (received / duplicates / stored), so a misconfigured automation is visible rather than silent, and day keys come from the date the phone wrote — never the server's clock, or every evening's steps would land on tomorrow. Per profile and private by construction. Each profile mints its own ingest key (Salud → ⚙), which is write-only: it can add to that one profile's health file and cannot read a single number back, so a key leaking out of a phone is a nuisance rather than a disclosure. It is its own credential, so rotating it disconnects a phone without signing anybody out anywhere. The data lives in data/vitals-<uid>.json, outside the synced state document, so a year of heart rate never round-trips through localStorage on every device, and it is bounded on write: 400 days per metric, a 72 h dedupe ledger, the newest 300 workouts. Two traps that only exist in production, both fixed here and both of which would have shipped broken. api/Dockerfile copies the modules server.js imports by name, and vitals.js was not on that list — a container that boots straight into ERR_MODULE_NOT_FOUND. And the web container's nginx capped every /api body at 5 MB, which a health export with Summarize Data off exceeds; that one route now gets the API's own 32 MB while every other path keeps 5 MB, with the shared proxy settings hoisted to server level so the two locations cannot drift apart. Coverage: vitals.js (13 tests — overlapping, disjoint, day-grouped, raw, heart rate, sleep, blood pressure, pruning, timezones), the routes against a real server (4 — isolation between profiles, a key that cannot read, ten re-sends changing nothing), the card model (18) and the screen (4). docs/HEALTH.md has the Health Auto Export settings and the merge table; the five endpoints are in api/openapi.yaml under the health tag, and website/api.html is rebuilt from it. |
||
|
|
238eb635c5 |
Configure the Coach from the environment
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
An instance can now be pointed at a model entirely from its environment — so a
container is redeployed with the Coach already working, and nobody has to open
an admin screen:
COACH_PROVIDER=compatible
COACH_BASE_URL=https://ai.example.com # WITHOUT /v1 — the adapter adds it
COACH_MODEL=vendor/model-name
COACH_API_KEY=sk-... # or the provider's own variable
Naming a provider is the whole configuration, so it also turns the Coach on: an
instance started this way that then reported itself "off" would be a puzzle with
no clue in it.
Three decisions worth stating:
- The environment is the *base*, the way DEFAULTS is, and the saved file is
layered on top: an admin who picked a provider in the app meant it, and this
only fills what is absent.
- The key is deliberately NOT a field of the config. That object is cached,
written to data/coach.json by any admin action, and included in the backup the
docs tell people to make. envCredentialFor reads it from the process
environment instead, so it is written nowhere and never surfaced by any route
that reports configuration. A pasted credential still outranks it, and a filed
one that fails to decrypt stays a failure rather than quietly falling back to
a key nobody knows is being spent.
- What the environment supplies is stripped before the file is written. A saved
config used to be written back whole, which would have frozen this start-up's
values on disk — and since the file outranks the environment, a later change
to COACH_MODEL would have been silently ignored.
Verified through the server's own path (config → credentialFor → jobEnv →
adapter) against the OpenAI-compatible router this fork runs on: a chest+triceps
request came back as a six-exercise routine with the cardio row first and
correctly marked `mode: cardio`.
|
||
|
|
327aa5211b |
The core of "build a routine with AI": muscles, cardio, intensity
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
The screen that will drive this needs three things underneath it, and all three
are here, tested, with no UI yet.
1. `librarySlice` can be narrowed to the muscles someone picked. A selector is
`{ bp }` or `{ tg }` — the target muscle matters because "biceps" and "triceps"
are both `upper arms`, and asking for one must not hand back the other — and an
exercise is kept when it matches any of them, so "back and biceps" is one list.
`catalogueOnly` drops the person's own exercises, which are the only rows in
the app with no animation; the builder promises every pick can be watched.
Both answers ride in the existing `intake` object rather than a second channel:
the intake is already how "which muscles" reaches the payload, and it travels
the whole way (route → job → build, and local → build) untouched. `cleanGroups`
sanitises it, since it is the one intake field that reaches a filter rather than
the model's reading.
2. `lib/ai-routine.js` — the three questions and what to do with the answer: the
intake the model is asked with, and the routine it hands back, normalised for
this app. Cardio lands in the library and not only in the sentence (a model told
to start with cardio but handed no cardio exercise can only improvise, which is
what it did the first time this was tried), a cardio row becomes one bout
whatever set count came back, and a missing mode is read from the exercise the
same way `modeOf` reads it everywhere else.
3. A validator fix found on the way: the cardio branch set `min` and `speed` but
never `clean.mode = 'cardio'`, unlike the time and reps branches. The app
recovered it from the catalogue, so nothing was visibly broken — but the bundle
did not describe its own prescription, and a model that omitted `mode` (which is
what a model prescribing "8 minutes of cardio" usually does) got "3 × 10 reps"
with a stray `min` nothing reads. Now the mode is stated, and inferred from the
catalogue when it is missing. `time` is deliberately not inferred: nothing in the
catalogue says an exercise is held for seconds.
Verified against the real router behind gym.dploy.lol with the real pipeline: a
back+biceps request produced a 6-exercise routine from an 80/80/22 library slice.
|
||
|
|
ea1af681c2 |
Read an answer that arrives with an SSE terminator glued to it
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
A gateway may answer a request that did not ask for streaming with SSE framing anyway: the whole chat.completion object followed by "\ndata: [DONE]". That body is not JSON, so readJson's strict parse rejected it, `data` came back null, and the job failed with "unexpected response shape: Cannot read properties of null (reading 'choices')" — while the answer it wanted sat in the first few kilobytes. Not hypothetical: the OpenAI-compatible router behind this fork's own instance answers exactly that way, which made every coach job fail against it with a message that says nothing about the real problem. The lenient read takes the first complete JSON value and ignores what follows, counting braces outside of strings so a "}" inside a rationale cannot end the scan early. It cannot paper over a truncated answer — an object that never closes still returns null, which is what the token-limit path depends on — and there are three tests for that: the terminator case, trailing junk after a complete object, and an object that never closes. |
||
|
|
87bfd6d4c4 |
Rebrand to KuentaGYM, and start a new profile in pounds and Spanish
The app is now KuentaGYM everywhere a user can see it, and a fresh profile no longer starts on upstream's English/kg defaults. Both are this fork's decisions, so both are pinned by tests rather than left to a find-and-replace. Rename (1,270 references, 149 files) - Visible surfaces: the Login/Home/mobile-onboarding wordmark, the Settings version line, the printed plan, the PWA title + manifest, and the 17 branded strings across all 14 locale packs. - Infrastructure: repo links, the container images and the release endpoints now name git.dploy.lol/dsantillan/kuentagym; .gitea/workflows/docker-publish.yml publishes to this forge's registry instead of gitea.com. - The Android/iOS application id stays ch.duartesantos.opengym on purpose: changing it would make the mobile app a different app that could never update an installed copy. Three things the mechanical pass would have broken, fixed here - The update check asked gitlab.com for upstream's releases and would have installed upstream's APK, putting the old name back on the phone. It now reads this fork's Gitea releases API (the assets shape differs), with the tests rewritten to the payload Gitea actually returns. - Renaming the mobile state/pairing files (opengym-state.json, opengym-remote.json) would lose the on-device copy of a history whose WebView storage may have been evicted, and silently unpair the device. Both are read under their old names and written forward under the new ones. - Renaming the exported plan-file marker (openGym_plan) rejected every plan shared before the rename as "not a plan file". Both markers are accepted. Defaults: pounds and Spanish - DEF.unit = 'lb', DEF.lang = 'es', plus every fallback that independently assumed en/kg (the <html lang> attribute, the Settings pickers, the Store, the MCP, the Coach payload). - Server-generated push copy existed only in English and pt-BR, so a Spanish profile would have been notified in English; Spanish added. - The demo seed states unit: 'kg' — its seeded numbers are kilograms, and inheriting the new default would have introduced an 82.4 lb lifter benching 60. - The module-level language in i18n-core stays English: it is the only language whose strings need no pack, so `t()`, dates, numbers and lists agree before a pack loads. Starting there on 'es' formats a Spanish-shaped UI with English strings. Also - api/package.json's test glob missed push-messages.test.js and verify-error.test.js, which sat beside the modules they cover and never ran. - README, docs/, website/ and the issue templates no longer describe upstream's GitLab/GitHub pipeline, Discord, sponsorship or public demo as if they were this fork's; upstream history and attribution are preserved (NOTICE.md). |
||
|
|
90a1e8956a |
Admin: delete an account, not just disable it (#107)
Disabling locks someone out but deliberately leaves their state file and credential on disk, so 'no data remains' was not reachable from the dashboard — which is what the request asked for. POST /api/admin/user/delete removes the user, their passkeys, their push subscriptions, their presence entry, their training history and any Coach credential of theirs. Two refusals, because nothing in the UI could undo either: an admin cannot delete their own account, and the last remaining admin cannot be removed. The invite code they joined with stays burned — it was used, and freeing it would quietly widen an invite-only instance. In the dashboard it asks twice, naming the account both times, and offers their data as a download first: the training history is theirs. Five tests drive the real server. |
||
|
|
36123c0d19 |
Admin: a stored state written before the entry filter opens the drill-down instead of 500ing it (QA C16 follow-up)
GET /api/admin/user mapped S.routines straight off disk — `r.id` on every entry — so a single
null routine threw, the route answered 500 {"error":"server error"} with a stack trace in the
log, and the sheet never left "Loading…". The Disable button lives inside that sheet, so the
one account an operator opened the dashboard to stop was the one they could not: exactly the
end state C16 described, reached through routines instead of workouts. C16 hardened the sheet
and taught PUT /api/data to drop such entries, but a document v1.3.7 accepted still sits on
disk and answers to nobody.
A `records(list)` helper next to readState now hands every reader the entries of a stored list
and nothing else, and both admin routes go through it: the routine map, the body-weight log,
the workout history (whose `.slice()` threw in its own right when `workouts` was an object
rather than an array) and the user list's workout count, which counted entries the drill-down
then dropped and read `null` for a non-array list. A routine's exercise count counts entries
too, rather than the length of whatever `ex` happens to be. PUT /api/data reuses the helper
for the filter it already had, unchanged in behaviour.
The reminder tick walks the same two lists outside any route: a null entry threw there, was
logged and skipped, and cost that profile every reminder from then on, day after day. It
skips the entry now, not the profile.
Measured on QA slot 32 with each shape planted directly in the slot's data dir
(scripts/opengym-qa/run/r3-admin-null-routine/plant.mjs, shots alongside it):
routines [null, r] before GET /api/admin/user 500, sheet "Loading…", 0 Disable
buttons, 16 stack frames in api.log
after 200, sheet shows Workouts 1 · Weigh-ins 1 · Routines 1,
disable and re-enable both land in the audit log,
0 stack frames, no console or HTTP errors
workouts/routines as before 500, same dead sheet, 12 stack frames
objects, not arrays after 200 with empty lists
bodyweight [null, b] before 200 but "Weigh-ins 2" for one weigh-in (4 for one plus
three junk entries)
after 1, the number of weigh-ins there are
null and shapeless workout entries, a null customEx, absent lists and an ordinary
profile all open, disable and enable, before and after.
api/test/server-admin-state.test.js covers both admin routes against ten stored shapes, and
server-reminder.test.js gains the null-entry case: 188 api tests (was 185). Frontend
untouched — the sheet's own guard from C16 still does the work the server cannot: 1533 vitest
green, 14 locales in sync, 33 demo-only source strings.
|
||
|
|
f94f8ca320 |
API: a request the client got wrong is a 400 (or 413), never a 500 with a stack trace — bad or non-object JSON, an array as the state document, null workout entries, a rest timer without seconds (QA C17, C19, C20, C16)
readBody rejects with a typed HttpError for unparseable text and for a JSON null, string,
number or array; the catch-all answers it with its status and does not log it — three of
these routes are reachable without a session, and a stack trace per malformed body let
anyone fill the container log. String() on a caller-supplied field went through the same
door ({"code":{"toString":1}} is valid JSON) and is replaced by a text() helper.
PUT /api/data refuses an array state (typeof 'object', but _rev on it is dropped by
JSON.stringify, so the file read back as rev 0 while the response claimed rev N+1) and
drops null and non-object entries from workouts/routines instead of refusing them: such an
entry carries nothing worth keeping, while a 400 would strand a client whose own copy is
already malformed in a re-send loop. Every server-side reader of the document (reminder
tick, admin drill-down) dereferences the entries.
POST /api/push/rest-timer validates seconds before clamping — the clamp ran first, turned
any missing or unusable value into a 1-second push and made the documented 400 unreachable.
A body over 5 MiB is a 413 the client actually gets to read: the remainder of the upload is
drained instead of the socket destroyed under it (which sent a reset that a node client hit
before parsing the answer — the QA proxy reported 502 on 3 of 4 attempts, 5 of 5 read the
413 afterwards); past twice the cap the upload is cut off. openapi.yaml documents the
400/413 bodies and the rest-timer 400.
|
||
|
|
826432a3a2 | Signed in, the server's profile is the truth: sign-in and pairing adopt it and ask once about workouts logged while signed out (Add them / Keep profile as is); the app polls the revision every 30 s and on every resume (GET /api/data/rev) and fetches only what moved; offline and unsynced states show a banner, retry on reconnect and confirm with a toast; pagehide flushes a pending change | ||
|
|
477fc07f8b |
Push: reminders owed within 15 minutes still arrive, the subscription heals itself on every boot, rest-timer alerts belong to the device that started the rest
- reminder tick: a due reminder is sent for up to 15 minutes after its time (once per local date) instead of only on the exact minute — a restart across that minute used to lose the day; state files are stat'ed and re-read only when they changed - sendPush prunes 403 (stale VAPID key) like 404/410; optional device targeting - POST /api/push/subscribe is an upsert that keeps created and stores a deviceId; GET /api/push/status says whether the server holds an endpoint - rest timers keyed per user+device; cancel without a device id keeps the old account-wide behaviour - sw.js: payload parsed inside waitUntil (never a silent push), pushsubscriptionchange re-subscribes and registers the new endpoint - lib/push.js: syncPushSubscription() (called once per signed-in boot from App.jsx and when Settings opens) re-registers a lost row, replaces a subscription made against another key, pushSupported() is false off https; deviceId() per browser - Settings: the notifications switch shows what the server holds - tests: server-reminder (window, dedupe, trained day), server-push-status (upsert, status, per-device timers), lib/push.test.js |
||
|
|
5276f9714a | api: /api/data carries a server revision — GET hands it out, a PUT with a stale baseRev answers 409 with the current document instead of overwriting another device's write; clients without baseRev keep overwriting as before | ||
|
|
6d9d7a6cba | coach (built-in): #160 findings 4/5/6/11 — forget keeps today's count, the instance cap is reserved at enqueue from its own counter instead of the 100-entry log, forget drops queued work, aborts the HTTP call and discards a late result, scheduled reviews advance on the server's own record and wait for an unread proposal | ||
|
|
67a8e68e42 | api: #160 findings 3/7/8/12 — a request target that does not parse answers 400 instead of an unhandled rejection, the reminder tick skips a state it cannot read and PUT /api/data refuses non-array workouts/routines, the push address rule judges every IPv6 spelling and re-checks literals before each send, sign out everywhere voids unredeemed pairing codes | ||
|
|
acff80348f | OpenAI model filter: fall back to the whole list when nothing in it looks like a chat model (the e2e stand-in serves model-a/model-b) | ||
|
|
d0aaa7205d |
Coach: a failed run on the phone says why, a message with no plan asks for one, the chat has context
- Phone with own key: the provider's or validator's reason reaches the chat line and toast (BYOK_ERRORS + jobErrorText); no more "instance owner" wording where there is none (#58) - CoachChat: a message with no routines refines/creates instead of reviewing an empty window; menu entry "Start a new plan" (Discord "Coach reset" thread) - payload: refine without a previous plan becomes a create with userNote; the last six chat lines travel as `conversation` (documented in common.md, prompts.js regenerated) - OpenAI model list cut to Chat-Completions models (isChatModel); Gemini placeholder names AQ. keys - 3 new strings in 14 packs, pt-BR guard 626/616/3db560d7; tests for all of it |
||
|
|
6730549845 |
Coach: cap the plan arrays in the schema, not only in the prompt
create.md asks for "1-7 routines, each 3-12 exercises" and validate.js slices at MAX_ROUTINES / MAX_EX_PER_ROUTINE, but the schema the endpoint decodes against had no bound at all. A model that starts repeating itself never reaches the validator: qwen2.5:3b walks the library id by id, three sets of eight apiece, until it exhausts the 16k output limit — twelve minutes for an answer that arrives truncated, which the adapter turns into "the answer was cut off at the output limit" and a job that would already have hit COACH_JOB_TIMEOUT_MS. maxItems on the two arrays states the caps that already exist, where the decoder can enforce them. |
||
|
|
dafc80f1d6 |
Coach: the create schema requires a routine id and a week
CREATE_SCHEMA is handed to OpenAI-compatible endpoints as a grammar to decode against, and it left both `routines[].id` and `week` optional. Small local models take that offer: llama3.2:3b and qwen2.5:3b both answer with routines that carry no id, and a week naming what they wrote into `name` instead. Nothing in the week then resolves, validate.js reports "the week schedules 0 days but 3 were asked for", the repair round produces the same answer again, and the job ends as `unusable` — "The Coach answered with something the app couldn't use." Requiring the two fields the week resolves through is enough. With them in the schema, llama3.2:3b produces a plan that passes validatePlan on the first attempt, against the payload that failed twice before. The validator is untouched; this only stops the grammar from offering an answer it can never accept. |
||
|
|
02c75b320d |
Coach: ein API-Key gilt fuer die ganze Instanz, Warm-ups zaehlen nicht, Retries bei 429/5xx, sichtbare Admin-Felder
- Instanz-Modus: nur eine persoenliche Anmeldung (Setup-Token/OAuth) bindet sich an das erste Profil, ein API-Key ist gemessen und wird von allen Profilen unter den Tageslimits geteilt. Die Bindung passiert jetzt wirklich beim Einreihen eines Jobs (jobs.enqueue), vorher gab es sie nur in den Tests. - HTTP-Adapter: 429/500/502/503/504/529 werden zweimal mit kurzer Pause wiederholt, ein 4xx nie. retryDelayMs fuer Tests. - Payload: Warm-up-Saetze wie in progression.js aus readSession/stalls, done/planned, Top-Satz, setsByBodyPart und workingWeights herausgefiltert; in vollen Sessions als warmup:true markiert, common.md sagt dem Modell, was das ist. - Admin-Karte: .field im Card hat jetzt eine sichtbare Flaeche, die Limit-Zahlenfelder sind echte Felder statt weisser Browser-Boxen; Text zu 'Whose account pays' unterscheidet API-Key und persoenliche Anmeldung. - Neuer Test e2e-apikey: Key ueber die Admin-Routen einlegen, Modelle listen, Review durch die echte Queue gegen einen lokalen Anthropic/OpenAI/Gemini-Stand-in, inkl. Header, Cache-Block, Schema, Retry und Auth-Fehler. api 150, frontend 1029, mcp 45 gruen. |
||
|
|
10f0844bf9 |
Coach-Warmup: die Review zuletzt waermen, ihr gehoert der einzige Slot
Mit OLLAMA_NUM_PARALLEL=1 gibt es einen Live-Slot, und er gehoert dem letzten Prompt; die Wiederherstellung grosser Prompts aus dem Cache ist nicht verlaesslich. Der Warmup endete mit dem Debrief-Prefix und klaute der Review den Slot: Review nach Debrief-Ping 402 s, nach Review-Ping 26 s. Also: debrief zuerst, review zuletzt. |
||
|
|
e134914026 |
Coach: der Server waermt den Prefix-Cache selbst, und die Tipp-Blase glaubt dem letzten Lauf
Der KV-Prefix-Cache eines lokalen Endpunkts stirbt mit dem Ollama-Prozess; der erste Job danach zahlte still den Kaltstart (~8 min statt ~1). Jetzt pingt der api-Prozess bei Boot und alle 30 Minuten die Review- und Debrief-Prefixe an den kompatiblen Endpunkt — warm kostet der Ping ein Token, kalt macht er die teure Lesung genau einmal, auf niemandes Uhr. Cloud-Provider werden nie gepingt. Und estimateMs nimmt min(Median, letzter Lauf): nach einer Beschleunigung schleppte der Median drei alte 8-Minuten-Laeufe mit. |
||
|
|
5116f8770d |
Coach: Regeln als cachebarer System-Prompt, Schema-erzwungenes JSON, halbierte Payload
Der Prompt ist gesplittet: die Regeln (byteidentisch pro Task) fahren als System-Message,
nur die Payload wechselt — ein llama.cpp/Ollama-Endpunkt trifft damit seinen KV-Prefix-Cache,
Anthropic cached den Block explizit (cache_control ephemeral). Die Payload selbst: kompaktes
JSON statt Einrueckung, volle Saetze nur fuer die letzten fuenf Sessions (aeltere als eine
Zeile pro Uebung; aggregates zaehlt Stalls ohnehin uebers ganze Fenster), Bibliothek als
{id,n,bp} und fuer Reviews auf 100 gedeckelt. ~14.600 Tokens pro Review vorher, ~5.900 jetzt
plus gecachter Prefix. Dazu: response_format json_schema (Fallback json_object, dann ohne,
wie gehabt), temperature 0 nur auf dem kompatiblen Endpunkt, Gemini/Anthropic bekommen die
Regeln ebenfalls als System-Teil. api 142, frontend 799, mcp 36 gruen.
|
||
|
|
9edcdaa9f3 |
Coach: Vorschlaege bleiben, Diagramme in den Karten, Workout-Debrief, Vergleich auf der Instanz, Routine verbessern
Was der Coach vorgeschlagen hat, verschwindet nach Ja/Nein nicht mehr: die Chat-Zeile traegt eine Referenz ins Log, das jetzt jede Aenderung samt before/after (auch abgelehnte), Notizen, Evidenz und bei Plaenen die Routinen behaelt; eine Recap-Karte im Thread und ein Verlauf- Sheet oeffnen alles wieder. Unter jeder Review liegen die Zahlen aus dem zitierten Fenster — Sessions, Dauer, Volumen, Koerpergewicht als Kurve mit Ziel, geschaetztes 1RM erste→letzte Session, Saetze pro Koerperregion — auf dem Geraet gerechnet (lib/coach-insights.js). Neu: Job-Art `debrief` (eine Session, kein Planeingriff: Score 1–10, lief gut / beobachten / naechstes Mal; validateDebrief im Core, eigener Prompt), Vergleich mit anderen auf der Instanz (Admin-Schalter `community`, pro Person Opt-in serverseitig, Mediane ab drei Teilnehmern, Epley-1RM, lb→kg; auch als `cohort` im Prompt), und "Routine verbessern" als fokussierte Review. Schnell-Chips ueber dem Composer, deutsche Strings, Doku, Changelog. Tests: api 136, frontend 799, mcp 36. |
||
|
|
0d38bc07f0 |
Coach: der Server-Fetch wartet so lange wie der Job, nicht 300 s wie undici
Nodes eingebauter fetch bricht nach fuenf Minuten mit 'fetch failed' ab — egal, welches Job-Timeout gesetzt ist. Ollama hatte den 8k-Prompt tatsaechlich fertig, die API hatte nur schon aufgelegt. Jetzt ein undici-Dispatcher, dessen Timeouts aus dem Job-Timeout abgeleitet sind; AbortController gewinnt weiterhin. |
||
|
|
aef950cf7c |
Coach: die Bibliothek im Payload ist gedeckelt (160, ausgewogen, das eigene Training immer dabei)
Bisher gingen alle 1.324 Uebungen mit — 10k+ Tokens pro Job, teuer gegen eine Cloud-API und in den Kontext eines kleinen lokalen Modells passte es gar nicht. Jetzt: Round-Robin ueber die Koerperteile in Katalogreihenfolge (deterministisch), Plan- und History-Uebungen werden immer eingepinnt, damit eine Review benennen kann, worueber sie spricht. Dazu COACH_JOB_TIMEOUT_MS fuer Boxen, auf denen ein lokales Modell laenger als fuenf Minuten braucht. |
||
|
|
d73481e32e | Coach: Routen-Test startet von leerer coach.json und verwechselt Platzhalter nicht mit Keys | ||
|
|
adaae03c48 | Coach: die Admin-Routen unter Test — Keys pro Provider, Basis-URL, Modell-Liste, kein Netz | ||
|
|
7047346da1 |
Coach: Anthropic, OpenAI, Gemini und jeder OpenAI-kompatible Endpunkt per API-Key
Vier Provider, die nur HTTPS sprechen — kein Agent-SDK, keine CLI, kein coach-User:
sie laufen auf dem Default-Image. Eine Factory (core/adapters/http.js) bildet jede
Antwort auf den bestehenden {code,text,stderr}-Vertrag ab, damit die Pipeline nichts
Neues lernen muss: 401/403 werden 'auth', ein abgeschnittenes JSON 'provider' statt
die einzige Reparaturrunde zu verbrennen. Ollama/LM Studio/vLLM/OpenRouter laufen
ueber dieselbe Chat-Completions-Form mit eigener Basis-URL und optionalem Key.
coach.json haelt Key, Modell und Bindung jetzt PRO Provider — Wechseln wirft nichts
mehr weg; die flache v1.2.11-Datei wird einmalig hochgehoben. Das Privilege-Gate
fragt den Adapter, ob er ueberhaupt einen Prozess startet. Die Admin-Karte zeigt
endlich den API-Key-Knopf auch bei Anthropic, listet Modelle vom Endpunkt und
nimmt eine Basis-URL entgegen.
|
||
|
|
697f1b1269 |
Coach: der Kern, den beide Laufzeiten laden koennen
payload, validate, parse, die Prompt-Montage, der Plan-Fingerprint und die invoke→parse→validate→repair-Schleife ziehen nach api/coach/core/ — ohne node:*, damit das Handy sie spaeter genauso importiert wie der Server. Die Bibliothek und die Prompts werden als ES-Module generiert (scripts/build-coach-assets.mjs), weil weder createRequire noch ?raw unter beiden Laufzeiten laden. Das Pseudonym wird uebergeben statt abgeleitet (handle.js behaelt den HMAC). check-core-loadable prueft unter blankem node, was vitest strukturell nicht pruefen kann. |
||
|
|
a710a432be |
Coach: eigene Uebungen duerfen benannt werden, und was der Validator sonst noch durchliess
Die Custom-Uebungen des Nutzers standen im Library-Slice, den das Modell bekam, wurden vom Validator aber abgelehnt — jeder Vorschlag, der eine nannte, verbrannte die einzige Reparaturrunde. Dazu: __proto__-IDs, Gewichts- und Tempo-Obergrenzen, doppelte Uebungen und doppelte Change-IDs, routineName auf jeder Aenderung, und ein Gewicht fuer eine nie gehobene Uebung wird verworfen statt geraten. |
||
|
|
5fb237682b |
Coach: der Fall ohne Vorgeschichte, und was der Validator durchgelassen hat
common.md wird jedem Prompt vorangestellt, also galt Regel 5 -- "jede Begruendung nennt das, was in ihren Daten dafuer sprach" -- auch beim ersten Plan fuer jemanden, der noch nichts geloggt hat. Da gibt es nichts zu nennen, und die Regel hat das Modell genau dorthin gedraengt, wo es sich etwas ausdenkt. Neu steht dabei, worauf man sich stattdessen beruft: Ziel, Erfahrung, Tage, Ausruestung, Einschraenkungen -- und dass ein fehlendes window kein Fehler ist. review.md sagt jetzt ausserdem, dass ohne Sessions die ehrliche Antwort nochange ist, statt einen Grund zu erfinden. repsMax stand im Validator, aber in keiner Tabelle -- das Modell konnte einen Typ nicht verwenden, den wir akzeptieren. payload.js laesst history ganz weg, wenn nichts mit Gewicht geloggt ist. Damit lief die FR-20-Deckelung ins Leere und ein erfundenes Startgewicht ging unveraendert an einen Anfaenger durch. Ohne Vergleichswerte fliegt weight jetzt raus; die erste Session setzt die Basis, so wie create.md es ohnehin verspricht. Dazu vier Luecken, die alle dieselbe Form haben -- etwas wird gezaehlt oder gesetzt, aber nicht auf Eindeutigkeit geprueft: - Zwei Routinen mit derselben id: known ist ein Set, die Woche validierte, ohne dass feststand, welche der beiden gemeint ist. - Dieselbe Uebung zweimal in einer Routine: danach ist jedes reorder unerfuellbar (es verlangt jede id genau einmal) und jede gezielte Aenderung trifft die erste Kopie. - Eine leere Woche uebersprang die Tagesanzahl-Pruefung ganz: "vier Tage" wurde mit einem Plan beantwortet, der gar nichts einplant. - inc war nach oben offen. add-routine trug ausserdem repsMin, prog und inc nicht mit, obwohl der Bundle-Pfad sie kennt. Die drei Codex-Flags sind aus invoke() in ein exportiertes argvFor() gewandert und werden jetzt beim Wert geprueft. Sie waren vorher nirgends getestet -- eines davon zu loeschen war ein gruener Build. |
||
|
|
ef61df50f2 |
Coach: the Codex provider, and a credential that stays out of your backups
The Codex CLI adapter, its runtime and sandbox in the coach image only, and the one placement decision this PR exists to get right. Codex keeps a refreshable sign-in cache of its own rather than taking a token on the environment, so it needs somewhere durable to write. That is ./coach-auth — a sibling of ./data, never a folder inside it, mounted separately, owned by `coach`, mode 0700. The placement is the point. docs/SELF_HOSTING §5 tells owners to back up with `tar czf … data/`, so anything under ./data lands in every archive people are instructed to produce. Workout history belongs there; a live refresh token does not — it keeps working after that archive is copied to a laptop or a cloud drive. Keeping the cache outside ./data is what lets the backup instructions stay true about what they capture, and §5 now says so explicitly rather than leaving the reader to find out. I got to define this rather than fix it: no Codex path was ever committed here, so the nested layout the fork had never reached this repo. A test asserts the sibling relationship directly, because "outside ./data" is the kind of invariant a later refactor breaks by tidying. bubblewrap and the Codex CLI are added in the coach target only — bubblewrap is a Codex requirement, so an owner who never opted in carries neither. The image job now asserts both directions: present and runnable in the coach image (codex-cli 0.147.0, bubblewrap 0.11.2, /coach-auth as coach:0700), and absent from the default one. Codex is usable through the existing connect route with an API key, which needs no new surface. Its ChatGPT device-code sign-in is not in this PR — see the PR description for what that still needs. api 73/73, frontend 404/404, both image targets built and inspected, 11 locales in sync at 767, library in sync at 1324. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
49be4e0626 |
Coach: the Claude provider, and an AI runtime you only carry if you ask
The Agent SDK adapter, its dependency, and the packaging that keeps both out of the image an owner gets when they never wanted the Coach. api/Dockerfile builds two targets. The default one runs `npm ci --omit=optional` and ships no AI runtime at all (~158 MB); `--target coach` drops that flag and adds @anthropic-ai/claude-agent-sdk (~455 MB). The SDK's runtime ships as a per-platform package, so on this Alpine base the lockfile resolves the musl build — the kind of thing that only fails on somebody else's machine, which is why the new api-image CI job builds *and runs* both targets rather than merely building them. Both targets now create the unprivileged `coach` user. That is not a Claude detail: canDropPrivileges() fails closed, so without it every job is refused — including the fixture provider that exists so the loop can be walked before an account is connected. The shipped image could not run one. The adapter imports the SDK lazily, so an absent runtime stays an ordinary reportable state rather than a boot crash: check() says so, isConnected() goes false, and /api/config carries no coach key. Four SDK options are what make this safe next to ./data — tools: [] (no Read, no Bash, no Grep), settingSources: [], skills: [], strictMcpConfig. They are one frozen exported object, asserted by value, so re-enabling one is a red build rather than a quiet capability grant. Verified against the SDK's own type definitions rather than from memory. Two things the fork's draft had wrong: SDKResultError carries no `errors` field, so `message.errors?.join()` was dead code and the failure reason now comes from `subtype` and `stop_reason`; and the client-app version string was hardcoded at 1.2.3 two releases after it stopped being true, so it is read from package.json. The credential connect/disconnect routes land here as promised in 2/6 — they serve a credential, and until this PR there was no provider that had one. authMode and the per-profile pair still wait for the side that consumes them. api 72/72 on macOS and on Linux as uid 65534 with the SDK absent; both image targets built and run; library in sync at 1324. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
9082ac5a2d |
Coach: was durch das Gatter kam, weil es nur gezaehlt und nicht geprueft wurde
Vier Stellen, eine Ursache: strukturierte `after`-Werte werden auf Zugehoerigkeit
geprueft, aber nicht auf die Form-Invarianten, die der Apply-Pfad voraussetzt.
Skalare Aenderungen sind dicht, die zusammengesetzten waren es nicht.
reorder akzeptierte doppelte Ids. ['0001','0001'] hat die richtige Laenge, jede Id
ist enthalten — Server und Client liessen es durch, die dritte Uebung war weg und
die verbliebene stand als dasselbe Objekt in zwei Slots. Ausgerechnet der einzige
Aenderungstyp, fuer den changeValues() null liefert: im Review-Screen ist kein
Vorher/Nachher zu sehen, das es haette verraten koennen. Jetzt Set-Vergleich auf
beiden Seiten.
superset konnte eine Uebung mit sich selbst verknuepfen. Der Partner-Splice nimmt
den Anker unter sich weg, danach schreibt das Tagging durch einen Index, der nicht
mehr aufloest — TypeError nach halbem Umsortieren. Der Client-Test prueft die
Meldung, nicht nur dass geworfen wird: geworfen hat der Bug auch.
add-routine hat unbekannte Exercise-Ids stillschweigend herausgefiltert, waehrend
validatePlan bei derselben Sache abbricht. Das ist FR-16, und es gilt hier genauso:
sonst bekommt jemand die Routine ohne die Uebungen, die es nicht geben konnte,
unter der Summary derjenigen, die er gesehen hat.
`before` war das einzige Feld, das ungeprueft durch das Gatter ging — ein Objekt
beliebiger Groesse landet im synchronisierten Coach-Log, ein bloss falsch getyptes
("3 sets" statt 3) laesst markStale eine voellig gute Aenderung deaktivieren. Der
Plan liegt im Validator bereits vor, also wird `before` dort gelesen statt von der
Antwort uebernommen.
api 68/68, frontend 404/404, Build sauber, Library in sync bei 1324.
|
||
|
|
34d41b8e64 |
Coach: the validator, and the apply path it exists to protect
PR 1 stopped at transport and held every answer as `unvalidated`. This closes that seam. validate.js is the gate: a closed list of eighteen change types with no default case, every exercise id resolved against the real catalogue, every target resolved against the plan it claims to be about, and a rationale required on every change. A hostile note in someone's free text can talk a model into saying anything at all; it cannot invent a change type. Its errors join the parse failures on the same single repair round, so a model that named an exercise nobody has is told which one — and a model that cannot be told is a failed job rather than a retry loop. frontend/src/lib/coach.js is the other half: snapshot, apply, revert, and the staleness rules. Applying happens on the client because it is ordinary local editing — offline, synced like everything else, reversible without the server knowing. A change-set is all-or-nothing, and a change aimed at something the user has since edited by hand is disabled with its reason rather than silently overwriting them. Two things the seam was hiding, both from PR 1: hashPlan hashed the pre-1.2.4 field list while canonicalPlan had already learned repsMax, bodyweight and side — so it computed all three and threw them away. A rep ceiling raised by hand fingerprinted as an untouched plan, on exactly the exercises where that ceiling is how progression works. Both runtimes now hash what canonicalPlan reports, with a test per field. `refine` reads pending.bundle, and pending only ever carried `unvalidated`, so `previous` resolved to null every time: the model was asked to refine a plan it had never been shown. It works now, and the fixture echoes whether the previous bundle arrived so a test can tell the difference. The validator also enforces the two rules prompts/common.md states and could not guarantee: unilateral reps are a total across both sides and must be even, and a rep ceiling may not sit below its own floor. "Nothing to change" keeps the reading it came with, on the profile's own record — deliberately not in the instance log, which stays counts and outcomes only. api 65/65, frontend 403/403, build clean, locales in sync, library in sync at 1324 exercises. No new dependency. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
de7f25cbe7 |
Coach: der Test-Lauf laeuft, und CI kann die Jobs ueberhaupt erreichen
Drei Sachen, die nie gelaufen sind, weil die CI fuer die api noch nicht existierte. canDropPrivileges faellt unter Linux zu, solange der Prozess nicht root ist und kein `coach`-User im Image steht. Ein CI-Runner ist Linux, laeuft als normaler User und hat keinen `coach` — also hat dort jedes enqueue() refused, und acht Tests waeren mit dem neuen api-Job rot geworden. Die Suite pinnt das Urteil jetzt selbst, statt es vom Host zu erben; der Test, dem die Verweigerung selbst gehoert, pinnt die Gegenrichtung und laeuft damit erstmals wirklich (vorher sprang er auf jedem Host raus, auf dem der Drop zufaellig klappte — und rief require() in einem ESM-Modul auf). testRun() griff auf ein `job`, das in seinem Scope nicht existiert: ReferenceError bei jedem Klick auf "Test the Coach", und weil der Wurf vor dem try lag, blieb jedes Mal ein Temp-Verzeichnis liegen. Ohne Nutzer gibt es kein Profil, das zahlt — im Instance-Modus ist das der gebundene Credential, im Profile-Modus niemand. Danach antwortete die Fixture auf den Test-Prompt mit einem ganzen Trainingsplan, weil ohne Payload-Fence auf 'create' geraten wird. Genau dieser fehlende Fence unterscheidet den Rundlauf von einem echten Job. Dazu zwei Kleinigkeiten: /api/coach/disclosure verriet den Provider an Nicht-Angemeldete, und der Poll, der ein Proposal verfallen laesst, lieferte als einziger kein cap-Feld zurueck. |
||
|
|
7be3978476 |
Coach: server plumbing, consent, payload boundary, credential model
First of six. Everything here is transport and boundary: a job can run, its answer can be parsed, and nothing yet judges whether that answer is safe to act on. The validator and the apply path are the next PR, and the seam is explicit — jobs.js carries an answer no further than `unvalidated`, and a test pins that so the next PR has something to replace. Whose account pays, settled first because it decides what the rest may be: instance one account in coach.json, for the single-profile instance profile one account per profile, in its own coach-auth-<uid>.json In instance mode the credential binds to the first profile that spends it and every other profile is refused — no job, not a dismissible warning. A warning moves the decision onto whoever clicks past it and the decision is about somebody's personal subscription. A profile credential is deliberately not a field on state-<uid>.json: that blob syncs and travels in the user's export, and a credential in a backup is the mistake we are avoiding, not repeating. openGym does not interpret any provider's terms; it offers the shape that does not need the interpretation and refuses the shape that does. The privilege drop now fails closed. It only ever engaged when the server ran as root, so adding a USER line to the Dockerfile for unrelated hardening would have silently left the provider runtime on the server's uid. On Linux, no drop means no job, and the admin card says so. ./data is no longer sealed with a blanket 0700. It is a host bind mount and this container is root, so sealing it landed on the host as root-owned and took the owner's own directory hostage — backup scripts, jq, the MCP server in issue #19. The files that hold secrets carry 0600 themselves instead, which is what the directory mode was standing in for; db.json gained an explicit mode rather than inheriting umask once the blanket came off. Bodyweight and per-side, folded in rather than deferred: v1.2.4 made `weight` mean *added* load on a bodyweight exercise, so it is 0 on a good session and every load-shaped signal reads flat. Uncorrected, the Coach would have looked at a working push-up progression and proposed adding weight to a push-up. The payload carries bodyweight/side/repsMax, the session reader carries set count, and the prompts say reps then sets are the progression and per-side targets step in twos. coach-parity.test.js pins the server's three copied reading rules against the frontend's originals over a table of configs — modeOf was never actually pinned, and it is the one that was predicted to drift. No AI dependency lands here: api/ still installs @simplewebauthn/server and web-push and nothing else. Jobs run against the in-repo fixture provider, so CI needs no account, no network and no image build. 33 api tests, 361 frontend tests (169 of them parity), locales in sync. |