From 91606d9c9ea342b36319eba103f5e90f05744f2e Mon Sep 17 00:00:00 2001 From: Daniel Santillan Date: Wed, 23 Sep 2026 19:27:25 -0400 Subject: [PATCH] =?UTF-8?q?Un=20fallo=20del=20Coach=20dice=20por=20qu?= =?UTF-8?q?=C3=A9,=20sin=20citar=20a=20nadie?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- api/coach/core/pipeline.js | 36 +++++++++++++++++++++++++++++++++--- api/test/jobs.test.js | 14 ++++++++++++++ docs/AI_COACH.md | 24 ++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/api/coach/core/pipeline.js b/api/coach/core/pipeline.js index 98be4ab..b130557 100644 --- a/api/coach/core/pipeline.js +++ b/api/coach/core/pipeline.js @@ -43,9 +43,9 @@ export async function attemptOnce({ adapter, cfg, kind, payload, model, timeoutM } const parsed = extractJSON(r.text); - if (parsed.error) return { ok: false, repairable: !repair, errors: [parsed.error], raw: r.text, errorClass: 'unusable' }; + if (parsed.error) return { ok: false, repairable: !repair, errors: [parsed.error], raw: r.text, ...unusable([parsed.error], r.text) }; if (!contractOK(parsed.value)) { - return { ok: false, repairable: !repair, errors: [`coach_contract must be ${CONTRACT}`], raw: r.text, errorClass: 'unusable' }; + return { ok: false, repairable: !repair, errors: [`coach_contract must be ${CONTRACT}`], raw: r.text, ...unusable([`coach_contract must be ${CONTRACT}`], r.text) }; } // Everything above is transport: did the provider answer, is there a JSON object in what it @@ -69,11 +69,41 @@ export async function attemptOnce({ adapter, cfg, kind, payload, model, timeoutM daysPerWeek: payload.coachProfile?.daysPerWeek }); - if (!checked.ok) return { ok: false, repairable: !repair, errors: checked.errors, raw: r.text, errorClass: 'unusable' }; + if (!checked.ok) return { ok: false, repairable: !repair, errors: checked.errors, raw: r.text, ...unusable(checked.errors, r.text) }; if (checked.nochange) return { ok: true, nochange: true, reading: checked.reading }; return { ok: true, result: checked.proposal || { bundle: checked.bundle, summary: checked.bundle.summary } }; } +/** + * Why an answer was unusable, in a line the admin card can show. + * + * Without this the log said "the app could not use it" and nobody — not the person who asked, not + * the owner who has to fix it — could tell whether the model wrote prose instead of JSON, named a + * change type that does not exist, pointed at an exercise that is not in the plan, or answered a + * different question entirely. + * + * What it carries is the *complaint* (from the parser or the validator, which name the field) and a + * content-free description of the answer — prose or JSON-ish, and how long. Deliberately not a + * quotation: this line goes into the instance log, which is admin-visible and instance-wide, and + * that log carries counts and outcomes and never one person's data. A few words of a plan would be + * how that rule breaks. The length plus the shape is what separates "the model ignored JSON mode" + * from "the answer was cut off mid-object", and it says nothing about anybody. + * + * On a repair round this is the *second* answer — the one sent after being told what was wrong with + * the first — which is the most informative thing there is: a model that cannot fix a complaint it + * was just handed is the problem, not this file. + */ +function unusable(errors, raw) { + const text = String(raw || '').trim(); + const shape = !text ? 'the provider answered with nothing' + : /[[{]/.test(text) ? `an answer of ${text.length} characters that starts like JSON` + : `prose of ${text.length} characters`; + return { + errorClass: 'unusable', + detail: [...(errors || []).slice(0, 4), shape].filter(Boolean).join(' · ').slice(0, 300) + }; +} + /** The whole loop: one attempt, then one repair round if the answer was fixable (FR-48). */ export async function runPipeline(opts) { let attempt = await attemptOnce(opts, null); diff --git a/api/test/jobs.test.js b/api/test/jobs.test.js index 8c0bf35..98c20ae 100644 --- a/api/test/jobs.test.js +++ b/api/test/jobs.test.js @@ -77,6 +77,20 @@ test('an answer that stays unusable fails cleanly and applies nothing', async () assert.equal(last.outcome, 'failed'); assert.equal(last.errorClass, 'unusable'); assert.equal(s.pending, null, 'nothing partial is ever left behind'); + /* ...and it says *why* in the admin's log. Reported live as "The Coach answered with something the + app couldn't use" with nothing behind it: neither the person nor the owner could tell prose from + a bad change type from a name that is not in the plan. The complaint names the field, and the + shape of the answer — prose or JSON, and how long — says whether the model ignored JSON mode or + was cut off. Never a quotation: that log is admin-visible and instance-wide, and it carries + counts and outcomes rather than anybody's data. */ + const logged = cfg.lastError(); + assert.equal(logged.errorClass, 'unusable'); + assert.match(logged.detail, /not JSON/i, 'the parser\'s own complaint'); + assert.match(logged.detail, /prose of \d+ characters/, 'and the shape of what came back, not its words'); + assert.match(logged.detail, /prose of [1-9]\d? characters/, 'a short answer, so nobody hunts for a truncation'); + assert.equal(logged.detail.includes('afraid'), false, 'the profile\'s content never lands in the instance log'); + // The per-profile history keeps the outcome and the class, and no provider words at all. + assert.equal('detail' in last, false); }); test('a provider that crashes is reported, not retried behind the user\'s back', async () => { diff --git a/docs/AI_COACH.md b/docs/AI_COACH.md index 3e278c2..df1ca59 100644 --- a/docs/AI_COACH.md +++ b/docs/AI_COACH.md @@ -57,6 +57,30 @@ The health week is deliberately *not* the health file: averages of a metric per metrics, and never the samples. A week of sleep and resting heart rate is what changes a volume decision; 288 heart-rate samples are tokens spent to tell the model nothing more. +## When it fails + +`api/coach/core/pipeline.js` turns a failed job into one class, and the app turns that class into a +sentence (`frontend/src/lib/coach-api.js`). The classes worth knowing: + +| Class | What it means | Fixed by | +| --- | --- | --- | +| `provider` | the request itself failed — a 4xx/5xx, an endpoint that refused the model, or an answer **cut off at the output limit** (the adapter says so in those words) | the provider setup, or a bigger model for the task | +| `unusable` | the model answered, but not the JSON the app needs — **after** the one repair round, which tells it exactly what was wrong | a model that can hold the schema | +| `auth` | the provider rejected the credential | the key | +| `off` | the Coach is off for this instance | the admin card | + +A review is the hardest task by a distance: a list of typed changes, each with a target, a +before/after of the right shape and a reason from a fixed table. A debrief is all strings and one +number. So *a model that debriefs fine and cannot review* is a normal thing to see, and it is a +statement about the model rather than about this code. + +Which is why an `unusable` failure now **says why** in the admin card's job log +(`lastError.detail`): the parser's or the validator's own complaint, which names the field, plus a +content-free description of the answer — prose or JSON-ish, and how many characters. That is what +separates "the model ignored JSON mode" from "the answer was cut off mid-object"; it is never a +quotation, because the instance log is admin-visible and instance-wide and carries counts and +outcomes rather than the plan it was reading. + ## Jev decides, the model writes Two models with two jobs, and the split is deliberate: **the text model writes the plan** (it is the