Files
kuentagym/deploy/compose-build-at-deploy.yml
T
dsantillan 90aa802980
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
La segunda opinión: un juicio sobre tus números, con la probabilidad que trae
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.
2026-09-23 16:36:47 -04:00

234 lines
12 KiB
YAML

# Build-from-source stack for a host that builds at deploy time (Dokploy and friends).
#
# This is the same five-service shape the instance at gym.dploy.lol runs: `source` clones the
# repository into a volume, `api` installs and runs the backend from that clone, `web-build`
# compiles the frontend, and `web` serves the result with nginx. Nothing is pulled from a
# registry, so `scripts/build-images.sh` and `.gitea/workflows/docker-publish.yml` are not part
# of this path at all.
#
# Five things here are easy to get wrong, and all five are load-bearing:
#
# 1. `web-build` copies the WHOLE repository into /app and builds from /app/frontend, not
# frontend/ on its own. The frontend imports the Coach's core from outside its own directory
# (`frontend/src/lib/coach-local.js` and `views/CoachSetup.jsx` reach into
# `../../../api/coach/core/`), so a build stage that only has frontend/ fails with nine
# UNRESOLVED_IMPORT errors. The repo's own web/Dockerfile copies api/coach/core/ into its
# build stage for the same reason.
#
# 2. The volumes are pinned with `name:`. They hold the users, passkeys, workouts and weigh-ins
# — `kuentagym-data` above all. Those names are this deployment's existing volumes; they are
# spelled out so a restyled stack keeps pointing at the same data instead of silently
# creating empty ones. Never change them without moving the data first, and never run
# `docker compose down -v` — `-v` deletes the volumes, which is every logged set and every
# weigh-in. A plain `docker compose down` is safe. Check yours with `docker volume ls`.
#
# 3. nginx needs `client_max_body_size`, and needs it in two sizes. Its default request limit is
# 1 MB, and the app PUTs the whole profile to /api/data on every change — a couple of years of
# training passes 1 MB and the sync then fails with a 413 the UI cannot explain. So the bulk
# of /api is 5m, matching the API's own MAX_BODY. But the Apple Health ingest takes whole
# exports: a first sync of a year of raw samples is tens of megabytes, and the API allows
# that one route 32 MB (VITALS_MAX_BODY in api/server.js). One global number cannot do both,
# which is why the generated config below has a second location for that one path — nginx
# picks the longest matching prefix, so /api/vitals/ingest gets 32m and everything else keeps
# 5m.
#
# This inline config is the one this deployment actually runs; web/nginx.conf.template is for
# the registry-image path (docker-compose.yml) and is NOT read here. A change to the limits
# has to be made in both, or the two deployment shapes diverge.
#
# 4. X-Forwarded-For uses the APPEND form here, unlike web/nginx.conf.template. In this shape
# nginx is NOT the edge: Traefik terminates TLS in front of it, so `$remote_addr` is Traefik's
# own address and the real client only survives in the header Traefik sends.
# `$proxy_add_x_forwarded_for` carries that one through as the first entry, which is exactly
# what the API reads (see clientIp in api/server.js). The registry template does the opposite
# for the opposite reason — there the web container answers the internet directly, so the
# incoming header can be forged and only $remote_addr can be trusted.
#
# 5. nginx resolves `api` through a VARIABLE, not by name. A plain `proxy_pass http://api:3000`
# is resolved once, when nginx starts, and the address is then pinned for the life of the
# container: recreate the api — a deploy that changes its configuration, a `--force-recreate`,
# a manual restart that gives it a new IP — and every /api call answers 502 until the web
# container is restarted too, including /api/config, so the app cannot even load. The
# `resolver` + `set $api_upstream` pair below makes nginx ask again on every request, which is
# the same fix web/nginx.conf.template carries (and explains at length) for the other shape.
#
# To deploy a change to the code, force the one-shot services to run again — `source` and
# `web-build` have `restart: "no"`, so compose leaves them alone when their configuration has not
# changed:
#
# docker compose up -d --force-recreate
#
# That is also how the `api` service picks up new code: it copies the clone into /app at container
# start, so an `api` that was not recreated keeps running the previous revision while `web-build`
# happily serves the new frontend. Recreate `web` in the same command, and not on its own: its
# `proxy_pass http://api:3000` is resolved once at start-up, so a recreated api means a new IP and
# an nginx still pointing at the old one answers 502 on every /api call.
#
# Set RP_ID, RP_NAME and ORIGIN in the host's environment (or its .env). RP_ID must be the exact
# hostname the app is served from — passkeys are bound to it — and RP_NAME is what the passkey
# prompt shows, so set it to KuentaGYM.
name: kuentagym
services:
# One clone, shared by the two build services below. Shallow: only the tip of the branch is
# ever built, and a full history here would just be a bigger volume.
source:
image: alpine:3.20
volumes:
- kuentagym-source:/work
command:
- /bin/sh
- -c
- "apk add --no-cache git ca-certificates && rm -rf /work/repo && git clone --depth 1 https://git.dploy.lol/dsantillan/kuentagym.git /work/repo"
restart: "no"
# The exercise images and GIFs (~140 MB), fetched once and kept in their own volumes. See
# NOTICE.md: the media belongs to Gym visual and is downloaded here rather than redistributed.
media:
image: alpine:3.20
volumes:
- kuentagym-media-img:/out/img
- kuentagym-media-gif:/out/gif
command:
- /bin/sh
- -c
- "apk add --no-cache git ca-certificates && mkdir -p /out/img /out/gif && if [ -z \"$$(ls -A /out/img 2>/dev/null)\" ]; then rm -rf /tmp/exercises && git clone --depth 1 https://github.com/hasaneyldrm/exercises-dataset.git /tmp/exercises && cp /tmp/exercises/images/*.jpg /out/img/ && cp /tmp/exercises/videos/*.gif /out/gif/; fi"
restart: "no"
api:
image: node:22-alpine
depends_on:
source:
condition: service_completed_successfully
working_dir: /app
volumes:
- kuentagym-source:/source:ro
- kuentagym-data:/data
environment:
PORT: "3000"
DATA_DIR: /data
NODE_ENV: production
RP_ID: ${RP_ID}
RP_NAME: ${RP_NAME}
ORIGIN: ${ORIGIN}
# This list is an allowlist: a variable set in the host's .env reaches the container ONLY
# if it is named here. Host env vars are otherwise used just to substitute ${…} in this
# file, so `COACH_PROVIDER` sitting in the panel while the container never sees it is a
# configuration that looks applied and does nothing. The `:-` defaults are what keep an
# instance that sets none of them exactly as it was: an empty value reads as unset.
COACH_PROVIDER: ${COACH_PROVIDER:-}
COACH_BASE_URL: ${COACH_BASE_URL:-}
COACH_MODEL: ${COACH_MODEL:-}
COACH_API_KEY: ${COACH_API_KEY:-}
COACH_DISABLED: ${COACH_DISABLED:-}
COACH_JOB_TIMEOUT_MS: ${COACH_JOB_TIMEOUT_MS:-}
JEV_API_KEY: ${JEV_API_KEY:-}
JEV_MODEL: ${JEV_MODEL:-}
JEV_BASE_URL: ${JEV_BASE_URL:-}
JEV_MAX_PER_DAY: ${JEV_MAX_PER_DAY:-}
JEV_MIN_INTERVAL_MS: ${JEV_MIN_INTERVAL_MS:-}
JEV_DISABLED: ${JEV_DISABLED:-}
command:
- /bin/sh
- -c
- |
# Keep this container on the revision the clone holds.
#
# `web` needs nothing like this: it serves the frontend build out of a shared volume, so
# every deploy refreshes the app by itself. The api's code is copied INTO this container
# instead, and compose recreates a service only when its configuration or image changed —
# the clone is a volume, so neither does. Without the loop below the api silently keeps
# serving the previous revision after every deploy, which from the outside looks exactly
# like a route that does not exist yet (404 on an endpoint the frontend already calls).
#
# It is also a supervisor: if the server exits, the loop starts it again, where the old
# one-liner left that to the container restart policy (and a full re-copy with it).
src=/source/repo/api
pid=''
last=''
sync_code() {
# Everything except node_modules: the copy IS the code, while wiping the installed
# dependencies would mean a full `npm install` — a minute of downtime — on every deploy.
for f in /app/*; do
case "$$f" in */node_modules) ;; *) rm -rf "$$f" ;; esac
done
cp -a "$$src/." /app/
}
start_api() { cd /app; node server.js & pid=$$!; }
trap 'kill "$$pid" 2>/dev/null; exit 0' TERM INT
while :; do
# server.js is written last by a fresh clone and removed first by `rm -rf /work/repo`, so
# this one test covers both "the clone is not ready yet" and "a deploy is in flight".
if [ -f "$$src/server.js" ]; then
stamp=$$(stat -c %Y "$$src/server.js" 2>/dev/null)
if [ "$$stamp" != "$$last" ]; then
last="$$stamp"
if [ -n "$$pid" ]; then kill "$$pid" 2>/dev/null; wait "$$pid" 2>/dev/null; fi
reinstall=''
if ! cmp -s "$$src/package.json" /app/package.json; then reinstall=1; fi
sync_code
if [ -n "$$reinstall" ]; then npm install --omit=dev; fi
echo "api: synced to the clone at $$(date -u +%H:%M:%SZ)"
start_api
elif [ -n "$$pid" ] && ! kill -0 "$$pid" 2>/dev/null; then
echo 'api: the server exited — starting it again'
start_api
fi
fi
sleep 15
done
restart: unless-stopped
web-build:
image: node:22-alpine
depends_on:
source:
condition: service_completed_successfully
media:
condition: service_completed_successfully
working_dir: /app
volumes:
- kuentagym-source:/source:ro
- kuentagym-web-dist:/dist
- kuentagym-media-img:/media-img:ro
- kuentagym-media-gif:/media-gif:ro
command:
- /bin/sh
- -c
- "rm -rf /app/* && cp -a /source/repo/. /app/ && cd /app/frontend && npm install && npm run build && rm -rf /dist/* && cp -a /app/frontend/dist/. /dist/ && mkdir -p /dist/img /dist/gif && cp -a /media-img/. /dist/img/ && cp -a /media-gif/. /dist/gif/"
restart: "no"
web:
image: nginx:alpine
depends_on:
web-build:
condition: service_completed_successfully
api:
condition: service_started
ports:
- "${WEB_PORT:-8080}:80"
volumes:
- kuentagym-web-dist:/usr/share/nginx/html:ro
command:
- /bin/sh
- -c
- "printf 'server { listen 80; server_name _; root /usr/share/nginx/html; index index.html; client_max_body_size 5m; resolver 127.0.0.11 valid=10s ipv6=off; set $$api_upstream http://api:3000; location /api/vitals/ingest { client_max_body_size 32m; proxy_pass $$api_upstream; proxy_http_version 1.1; proxy_set_header Host $$host; proxy_set_header X-Real-IP $$remote_addr; proxy_set_header X-Forwarded-For $$proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $$scheme; } location /api/ { proxy_pass $$api_upstream; proxy_http_version 1.1; proxy_set_header Host $$host; proxy_set_header X-Real-IP $$remote_addr; proxy_set_header X-Forwarded-For $$proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $$scheme; } location / { try_files $$uri $$uri/ /index.html; } }' > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
restart: unless-stopped
volumes:
# `name:` is what keeps these pointing at the volumes this deployment already has. Change a
# value here and compose uses a different, empty volume — the profiles and the training history
# do not move with it.
kuentagym-source:
name: personales-gymfv-3bahxv_opengym-source
kuentagym-data:
name: personales-gymfv-3bahxv_opengym-data
kuentagym-web-dist:
name: personales-gymfv-3bahxv_opengym-web-dist
kuentagym-media-img:
name: personales-gymfv-3bahxv_opengym-media-img
kuentagym-media-gif:
name: personales-gymfv-3bahxv_opengym-media-gif