diff --git a/api/coach/core/library.js b/api/coach/core/library.js
index 3df4204..0a0643a 100644
--- a/api/coach/core/library.js
+++ b/api/coach/core/library.js
@@ -13,13 +13,47 @@ export const LIB_BY_ID = new Map(LIBRARY.map(e => [e.id, e]));
export const libraryHas = id => LIB_BY_ID.has(id);
export const libraryName = id => LIB_BY_ID.get(id)?.n || null;
-/* ---------- the library slice the model gets to choose from ---------- */
-export function librarySlice(S, equipment) {
+/* ---------- the library slice the model gets to choose from ----------
+ Bounded. The whole catalogue is 1,324 rows — 10k+ tokens on every job, which costs real money
+ against a cloud API and does not fit a small local model's context at all; and a model does
+ not choose better from 1,324 options than from 160. So the slice is capped and balanced: an
+ even share of every body part, in catalogue order (deterministic, so repeated jobs keep the
+ same prefix), with the exercises already in the user's plan or history always included —
+ a review has to be able to name what it is talking about. */
+export const MAX_LIBRARY = 160;
+
+export function librarySlice(S, equipment, { keep = [], max = MAX_LIBRARY } = {}) {
const wanted = (equipment || []).map(x => String(x).toLowerCase());
const customs = (S.customEx || []).map(c => ({ id: c.id, n: c.n, bp: c.bp, tg: null, eq: 'custom', custom: true }));
// No equipment stated (or "everything") ⇒ the whole catalogue. Filtering to nothing would
// leave the Coach unable to propose anything at all, which is a worse failure than a
// slightly larger payload.
- const base = wanted.length ? LIBRARY.filter(e => wanted.includes((e.eq || '').toLowerCase())) : LIBRARY;
- return [...customs, ...(base.length ? base : LIBRARY)];
+ const filtered = wanted.length ? LIBRARY.filter(e => wanted.includes((e.eq || '').toLowerCase())) : LIBRARY;
+ const base = filtered.length ? filtered : LIBRARY;
+
+ const pinned = new Set(keep.filter(id => LIB_BY_ID.has(id)));
+ const out = [];
+ const taken = new Set();
+ const add = e => { if (!taken.has(e.id)) { taken.add(e.id); out.push(e); } };
+ // What the user already trains comes first, filter or no filter.
+ for (const id of pinned) add(LIB_BY_ID.get(id));
+ if (base.length + out.length <= max) {
+ base.forEach(add);
+ } else {
+ // Round-robin across body parts so a 292-row "upper arms" cannot crowd out a 37-row
+ // "lower arms"; order within a body part is the catalogue's own.
+ const groups = new Map();
+ for (const e of base) { if (!groups.has(e.bp)) groups.set(e.bp, []); groups.get(e.bp).push(e); }
+ const lanes = [...groups.keys()].sort().map(k => groups.get(k));
+ const cursor = lanes.map(() => 0);
+ let progressed = true;
+ while (out.length < max && progressed) {
+ progressed = false;
+ for (let i = 0; i < lanes.length && out.length < max; i++) {
+ while (cursor[i] < lanes[i].length && taken.has(lanes[i][cursor[i]].id)) cursor[i]++;
+ if (cursor[i] < lanes[i].length) { add(lanes[i][cursor[i]++]); progressed = true; }
+ }
+ }
+ }
+ return [...customs, ...out];
}
diff --git a/api/coach/core/payload.js b/api/coach/core/payload.js
index bdad479..5163fb9 100644
--- a/api/coach/core/payload.js
+++ b/api/coach/core/payload.js
@@ -10,7 +10,7 @@
* handle stands in), passkey and credential material, push subscriptions, invite data, theme
* and appearance settings, and every other profile's everything.
*/
-import { LIBRARY, LIB_BY_ID, libraryHas, libraryName, librarySlice } from './library.js';
+import { LIBRARY, LIB_BY_ID, libraryHas, libraryName, librarySlice, MAX_LIBRARY } from './library.js';
export const CONTRACT = 1;
// Bounds from FR-22. A review reads a training block, not a training career: more history
@@ -140,7 +140,7 @@ export function cleanPlan(S) {
}
// The catalogue lives in library.js; re-exported so older imports keep resolving.
-export { LIBRARY, libraryHas, libraryName, librarySlice };
+export { LIBRARY, MAX_LIBRARY, libraryHas, libraryName, librarySlice };
/* ---------- effort scale (mirrors history.js effortOf) ---------- */
const effortOf = S => {
@@ -201,6 +201,15 @@ function aggregates(S, workouts) {
};
}
+/** Every exercise id the plan names or the given workouts logged — the ones a proposal has to
+ * be able to refer to, so they ride in the library slice whatever the cap or the filter. */
+function trainedIds(S, workouts) {
+ const ids = new Set();
+ (S.routines || []).forEach(r => (r.ex || []).forEach(e => ids.add(e.id)));
+ (workouts || []).forEach(w => (w.entries || []).forEach(en => ids.add(en.id)));
+ return [...ids];
+}
+
/** One workout, reduced to what a coach reads. */
function cleanWorkout(w) {
return {
@@ -289,9 +298,9 @@ export function build(S, opts = {}) {
series: (S.bodyweight || []).filter(b => !p.window.from || b.d >= p.window.from).map(b => ({ d: b.d, w: b.w }))
};
if (opts.note) p.userNote = String(opts.note).slice(0, 1000);
- p.library = librarySlice(S, profile?.equipment);
+ p.library = librarySlice(S, profile?.equipment, { keep: trainedIds(S, workouts) });
} else {
- p.library = librarySlice(S, profile?.equipment);
+ p.library = librarySlice(S, profile?.equipment, { keep: trainedIds(S, S.workouts || []) });
// Creation for a returning user: what they have actually handled, so proposed baselines
// start from evidence rather than optimism (B2/FR-20).
const best = {};
diff --git a/api/coach/jobs.js b/api/coach/jobs.js
index 01eab30..92d4b97 100644
--- a/api/coach/jobs.js
+++ b/api/coach/jobs.js
@@ -33,7 +33,9 @@ export { hashPlan, buildPrompt };
const DATA = process.env.DATA_DIR || '/data';
const COACH_DIR = path.join(DATA, 'coach');
-export const TIMEOUT_MS = 5 * 60000;
+// Five minutes by default. A local model on a small CPU box can legitimately need more; a
+// cloud API that needs more has a problem. COACH_JOB_TIMEOUT_MS overrides, never below one minute.
+export const TIMEOUT_MS = Math.max(60000, +process.env.COACH_JOB_TIMEOUT_MS || 5 * 60000);
const MAX_CONCURRENT = 2; // these are minutes-scale jobs on often-single-core boxes
const PENDING_DAYS = 14; // FR-33
const HISTORY_MAX = 20;
@@ -104,9 +106,16 @@ export function status(uid) {
return {
job: rec.current ? { id: rec.current.id, kind: rec.current.kind, state: rec.current.state, startedAt: rec.current.startedAt } : null,
pending: rec.pending || null,
- cap: capState(uid)
+ cap: capState(uid),
+ // How the most recent job ended, so the chat can say "nothing to change" or "that failed"
+ // in the Coach's own bubble rather than leaving a job that silently stopped appearing.
+ last: lastOutcome(rec)
};
}
+function lastOutcome(rec) {
+ const h = (rec.history || []).at(-1);
+ return h ? { id: h.id, kind: h.kind, outcome: h.outcome, errorClass: h.errorClass || null, at: h.at, ...(h.reading ? { reading: h.reading } : {}) } : null;
+}
function archive(uid, rec, outcome) {
const history = [...(rec.history || []), {
id: rec.pending?.id, kind: rec.pending?.kind, outcome, at: Date.now()
diff --git a/api/test/payload.test.js b/api/test/payload.test.js
index 50422f5..4e109f6 100644
--- a/api/test/payload.test.js
+++ b/api/test/payload.test.js
@@ -108,14 +108,44 @@ test('creation payload carries working weights so baselines start from evidence'
});
test('the library is filtered to the equipment someone actually has', () => {
- const all = payload.librarySlice({}, []).length;
- const dumbbell = payload.librarySlice({}, ['dumbbell']).length;
- assert.ok(dumbbell < all && dumbbell > 0);
+ const dumbbell = payload.librarySlice({}, ['dumbbell']);
+ assert.ok(dumbbell.length > 0);
+ assert.ok(dumbbell.every(e => e.eq === 'dumbbell'), 'nothing outside the filter');
+ assert.ok(payload.librarySlice({}, ['dumbbell', 'barbell']).some(e => e.eq === 'barbell'));
// Custom exercises always travel: they exist nowhere else and the model cannot guess them.
const withCustom = payload.librarySlice({ customEx: [{ id: 'cx1', n: 'Sandbag carry', bp: 'back' }] }, ['dumbbell']);
assert.equal(withCustom[0].id, 'cx1');
});
+test('the library slice is capped, balanced across body parts, deterministic, and keeps what the user trains', () => {
+ const { MAX_LIBRARY, LIBRARY } = payload;
+ const all = payload.librarySlice({}, []);
+ assert.ok(LIBRARY.length > MAX_LIBRARY, 'the catalogue is bigger than the cap, or this test proves nothing');
+ assert.equal(all.length, MAX_LIBRARY);
+ const byBp = {};
+ all.forEach(e => { byBp[e.bp] = (byBp[e.bp] || 0) + 1; });
+ const parts = Object.keys(byBp).length;
+ assert.ok(parts >= 8, `only ${parts} body parts represented`);
+ // Small groups (neck has two rows) run out early and their share flows to the rest, so the
+ // bound is "nobody dominates", not "everyone equal".
+ assert.ok(Math.max(...Object.values(byBp)) <= MAX_LIBRARY / 4, `one body part dominates: ${JSON.stringify(byBp)}`);
+ assert.equal(byBp.neck, LIBRARY.filter(e => e.bp === 'neck').length, 'a tiny group is present in full');
+ assert.deepEqual(all.map(e => e.id), payload.librarySlice({}, []).map(e => e.id), 'same slice every time');
+
+ // An exercise the user already trains rides along even when the filter would exclude it.
+ const barbell = LIBRARY.find(e => e.eq === 'barbell');
+ const kept = payload.librarySlice({}, ['dumbbell'], { keep: [barbell.id] });
+ assert.equal(kept[0].id, barbell.id);
+ assert.ok(kept.length <= MAX_LIBRARY + 1);
+
+ // …and through build(): the plan's own exercises are in the slice for a review.
+ const S = sampleState();
+ const planIds = S.routines.flatMap(r => r.ex.map(e => e.id));
+ const p = payload.build(S, { handle: 'h'.repeat(16), kind: 'review' });
+ assert.ok(planIds.every(id => p.library.some(e => e.id === id)), 'every plan exercise is in the slice');
+ assert.ok(p.library.length <= MAX_LIBRARY + planIds.length);
+});
+
test('equipment nobody in the library has still yields a usable library', () => {
// Better a slightly larger payload than a Coach that cannot propose anything at all.
assert.ok(payload.librarySlice({}, ['moon rocks']).length > 0);
diff --git a/frontend/src/views/Coach.jsx b/frontend/src/views/Coach.jsx
deleted file mode 100644
index 5969ede..0000000
--- a/frontend/src/views/Coach.jsx
+++ /dev/null
@@ -1,310 +0,0 @@
-import { useEffect, useState } from 'react'
-import { useNavigate } from 'react-router-dom'
-import { useStore, DEF } from '../store/useStore.js'
-import { useUI } from '../store/useUI.js'
-import { t } from '../lib/i18n.js'
-import { fmtDate } from '../lib/format.js'
-import { DEMO } from '../lib/demo.js'
-import { MOBILE } from '../lib/mobile.js'
-import {
- coachAvailable, hasConsent, CONSENT_VERSION, emptyCoach, CATEGORY_TEXT,
- canRevert, revertLast, changeTitle, recordDismissal
-} from '../lib/coach.js'
-import {
- useCoachStatus, requestReview, resolvePending, forgetCoach, disclosure, JOB_ERRORS
-} from '../lib/coach-api.js'
-import { confirmSheet } from '../sheets.jsx'
-import Icon from '../components/Icon.jsx'
-import { Section, Row, Button, TextArea, Switch, SelectRow } from '../components/ui.jsx'
-
-/* The Coach's home: what it's doing, what it's proposing, what it has done before, and every
- switch that turns it off. Deliberately one screen — a feature that edits your training plan
- should not scatter its controls, least of all the ones that stop it. */
-
-const GOALS = ['strength', 'muscle', 'general fitness', 'fat loss', 'endurance']
-
-
-export default function Coach() {
- const nav = useNavigate()
- const S = useStore(s => s.S)
- const user = useStore(s => s.user)
- const config = useStore(s => s.config)
- const coachMode = useStore(s => s.coachLocal?.mode)
- const update = useStore(s => s.update)
- const toast = useUI(s => s.toast)
- const [note, setNote] = useState('')
- const [busy, setBusy] = useState(false)
- const { job, pending, cap, refresh } = useCoachStatus(true)
-
- // Gating lives in one predicate; if the instance isn't offering the Coach this route simply
- // isn't a place you can be.
- useEffect(() => { if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) nav('/home', { replace: true }) }, [config, user, coachMode])
- if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) return null
-
- const consented = hasConsent(S)
- const coach = S.coach || emptyCoach()
-
- const askReview = async () => {
- setBusy(true)
- try {
- await requestReview(note)
- setNote('')
- toast(t('The Coach is reading your training…'))
- refresh()
- } catch (e) { toast(e.message || t('Could not ask the Coach')) }
- setBusy(false)
- }
-
- const turnOff = () => confirmSheet({
- title: t('Turn the Coach off?'),
- message: t('Any pending suggestion is discarded and scheduled reviews stop. Your Coach history stays, and you can turn it back on anytime.'),
- confirmText: t('Turn off'), danger: true,
- onConfirm: async () => {
- try { await forgetCoach() } catch (e) { /* server-side copy goes on the next call */ }
- update(s => { s.coach = { ...(s.coach || emptyCoach()), consent: null, cadence: 'off' } })
- toast(t('The Coach is off'))
- nav('/home')
- }
- })
-
- const doRevert = () => confirmSheet({
- title: t('Undo the last Coach changes?'),
- message: t('Your plan goes back to how it was before you accepted them. Workouts you have logged since are untouched.'),
- confirmText: t('Undo'),
- onConfirm: () => {
- let ok = false
- update(s => { ok = revertLast(s) })
- toast(ok ? t('Plan restored') : t('Nothing to undo'))
- }
- })
-
- return
-
-
-
-
{t('Coach')}
-
{t('Plan design and reviews, from your own training')}
- {info?.payer === 'you'
- ? t('When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.', info.host || info.providerLabel)
- : t('When you ask for a plan or a review, this instance sends the following to {0}, running on this server under the instance owner’s account.',
- info?.providerLabel || config?.coach?.providerLabel || t('the configured AI provider'))}
-
{t('Your name, your sign-in details and everything else about your account stay here. Other people’s data is never included.')}
-
{t('Nothing the Coach suggests is applied on its own — you review every change and can undo it afterwards.')}
-
{t('You can turn this off at any time, which also discards anything the Coach is holding for you.')}
-
{t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}
-
-
-
-
-
- >)
-
- return
-
-
-
{t('Meet the Coach')}
-
-
- {info?.payer === 'you'
- ? t('An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.')
- : t('An AI coach that can design your plan and adjust it from what you actually log. It runs on this server, it never changes anything without your say-so, and it is off until you turn it on.')}
-
-
-
-}
-
-/* ---------------------------------- status ---------------------------------- */
-
-function StatusCard({ job, pending, nav }) {
- if (job) return
-
-
-
-
{t('The Coach is thinking…')}
-
{t('This takes a minute or two. You can leave this screen — it keeps going.')}
-
-
-
-
- if (pending) return
-
nav('/coach/proposal')}>
-
-
-
-
{pending.kind === 'create' ? t('Your plan is ready') : t('Suggestions ready')}
- {t('Doesn’t match your plan any more — can’t be applied.')}
-
}
-
- {!stale && toggle(c.id)} />}
-
-
- })}
-
- {!!marked.notes?.length &&
-
{t('Notes from the Coach')}
- {marked.notes.map((n, i) =>
{n}
)}
-
{t('These change nothing on their own.')}
-
}
-
-
-
-
-
-
-
-}
-
-/* The hub and the intake screen both carry this; the screen where changes are actually accepted
- did not, which is the one place it matters most — this is the tap that changes what somebody
- will do with their body next week. Deliberately immediately above the accept button rather
- than at the top of a scrolling page, so it is on screen at the moment of the decision. */
-function HealthNote() {
- return
- {t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}
-