main
17
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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.
|
||
|
|
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). |
||
|
|
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. |
||
|
|
1cb4909901 |
Coach-Doku: ehrliche Warm-Zeiten (eine bis wenige Minuten, je nach CPU)
Gemessen auf der Staging-VM (~12 Prompt-Tokens/s): Review mit frischer Payload 222 s warm; 'etwa eine Minute' gilt erst auf moderner Hardware. |
||
|
|
ae9d6785ac |
Coach: Admin-Karte als Setup-Assistent, sichtbarer Einstieg im Plan, Doku-Kapitel auf der Website
Solange der Coach aus ist, zeigt die Admin-Karte einen sauberen Pitch mit einem Knopf statt halb ausgegrauter Regler; danach ein echter Assistent: nur der naechste offene Schritt ist aufgeklappt, ein Fortschrittsbalken zaehlt mit, fertige Schritte falten sich zur Quittung. Arbeitende Knoepfe sind getoent statt grau (List models, Replace key), der deaktivierte Test-Knopf erklaert, welcher Schritt noch fehlt, Provider-Chips haben einen klaren gewaehlt-Zustand. Der Coach-Einstieg im Plan ist eine deutliche Karte mit Farbverlauf statt einer Settings-Zeile. Website: das #coach-Kapitel erklaert Pipeline, Provider, den komplett lokalen Betrieb inkl. "jedes Modell, das du pullen kannst, kannst du nutzen" und ehrlicher RAM-/Tempo-Beratung; docs/AI_COACH.md ergaenzt Modellwahl und Performance auf kleinen Boxen. |
||
|
|
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. |
||
|
|
b3340e31b5 |
Coach: eine Session ist kein Trend; Changelog, Doku und .env fuer Chat, Timeout und Bibliotheks-Deckel
Die Review-Regel verbietet strukturelle Aenderungen unter drei Sessions oder einer Woche Daten — qwen2.5:3b hatte auf Staging nach EINER Session eine Bein-Uebung entfernt, 'weil keine Beinarbeit'. Dazu die Changelog-Eintraege fuer den Chat, das Admin-Dashboard, den Job-Timeout und den 160er-Deckel, COACH_JOB_TIMEOUT_MS in .env.example und in AI_COACH.md, und Schritt 3 der Doku beschreibt den Chat statt des alten Intake-Buttons. |
||
|
|
533ca2c9a4 |
Coach: Doku fuer die API-Key-Provider und das Handy, und die Image-Pruefungen in der GitLab-CI
AI_COACH.md trennt die zwei Provider-Familien (HTTPS mit Key auf dem Default-Image, Runtime im coach-Image), beschreibt Endpunkt-Regeln, Modell-Liste, Keys pro Provider samt einmaliger Migration von coach.json und die zwei Wege auf dem Handy. CHANGELOG unter Unreleased, .env.example/README/Website/SELF_HOSTING nachgezogen. .gitlab-ci.yml bekommt test:api (Suite, generierte Assets, core-loadable) und build:api-check, das beide api-Targets baut und laufen laesst: das veroeffentlichte Image hat kein SDK/codex/bwrap, bootet, und konstruiert die HTTPS-Adapter; das coach-Image meldet ein lauffaehiges SDK, /coach-auth ist coach 700. |
||
|
|
a0ac473df7 | Merge remote-tracking branch 'pr/54' into coach | ||
|
|
4ee9a2abbf |
Coach: a way in, and instructions for getting there
Two gaps found by deploying the thing and then trying to use it. The Coach had no entry point. Its three routes have existed since the UI landed and nothing in the app linked to them — not the nav, not Home, not Plan, not Settings. The hub's back button already pointed at /plan, so that is where the link was always meant to be. On a configured instance the feature was enabled, credentialed, running, and reachable only by typing the URL. It sits behind the same coachAvailable() predicate every other Coach surface uses, so an instance without the feature sees exactly the Plan screen it saw before. And there were no setup instructions anywhere. This document said the Coach is "off until an admin turns it on" and then never said how to turn it on: ten sections on what it does and why it is safe, nothing on the four steps that get you from a running instance to a working Coach. .env.example has no Coach knobs and SELF_HOSTING mentions it only in the backup caveat, so there was nowhere else to look either. The new section covers building the target that has a runtime in it, minting a token with `claude setup-token`, connecting and testing it on the admin card, and where a user starts. It also warns up front about the thing a multi-profile instance discovers the hard way: in instance mode the credential binds to the first profile that spends it and every other profile is refused by design, so one person gets the Coach and the rest get a refusal. api 72/72, frontend 404/404, build clean, 11 locales in sync. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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. |