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.
This commit is contained in:
Duarte Santos committed 2026-08-30 23:25:00 +02:00
1 parent 20042356d1
commit 5116f8770d
17 files changed
+327 -34

No files matched your search

+2 -1
View File
@@ -295,7 +295,8 @@ test('an HTTPS provider is not refused for lacking a privilege drop, and runs en
assert.equal(seen[0].url, '/v1/chat/completions');
assert.equal(seen[0].auth, undefined, 'no key configured, so no Authorization header');
assert.equal(seen[0].body.model, 'local-model');
assert.ok(seen[0].body.messages[1].content.includes('"coach_contract": 1'), 'the payload rode in the user turn');
assert.ok(seen[0].body.messages[1].content.includes('"coach_contract":1'), 'the payload rode in the user turn');
assert.ok(seen[0].body.messages[0].content.includes('openGym Coach'), 'the rules rode in the system turn');
// And the same host refuses a runtime-backed provider, so the gate itself is intact.
cfg.save({ provider: 'fixture' });
+5 -2
View File
@@ -108,10 +108,13 @@ test('creation payload carries working weights so baselines start from evidence'
});
test('the library is filtered to the equipment someone actually has', () => {
// Slice entries are slimmed to { id, n, bp } — resolve the equipment through the catalogue.
const eqOf = id => (payload.LIBRARY.find(e => e.id === id) || {}).eq;
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'));
assert.ok(dumbbell.every(e => eqOf(e.id) === 'dumbbell'), 'nothing outside the filter');
assert.ok(dumbbell.every(e => e.eq === undefined && e.id && e.n && e.bp), 'entries are slim');
assert.ok(payload.librarySlice({}, ['dumbbell', 'barbell']).some(e => eqOf(e.id) === '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');
+78
View File
@@ -0,0 +1,78 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { buildPrompt, buildPromptParts, taskOf } from '../coach/core/prompt.js';
import { SCHEMAS } from '../coach/core/schemas.js';
import { build, FULL_DETAIL_SESSIONS } from '../coach/core/payload.js';
import { chatCompletionsSpec } from '../coach/core/adapters/openai.js';
const S = (workouts = []) => ({
lang: 'en', unit: 'kg', routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 8 }] }],
week: { 1: 'r1' }, workouts, bodyweight: [],
coach: { consent: { agreedAt: 'x', version: 1 }, profile: { goal: 'muscle', equipment: [] }, log: [] }
});
const workout = (d, done = true) => ({
d, start: 1, end: 60001, name: 'A',
entries: [{ id: '0001', target: { sets: 3, reps: 8, weight: 60 }, sets: [{ done, w: 60, r: 8, rir: 2 }] }]
});
test('the rules half of the prompt is byte-identical across jobs of the same task', () => {
const a = buildPromptParts('review', build(S([workout('2026-08-01')]), { handle: 'h1', kind: 'review' }));
const b = buildPromptParts('review', build(S([workout('2026-08-20')]), { handle: 'h2', kind: 'review' }));
assert.equal(a.system, b.system); // the whole point: a prefix cache can hit
assert.notEqual(a.user, b.user);
assert.ok(a.user.includes('## Payload'));
assert.ok(!a.system.includes('Payload')); // nothing dynamic ahead of the payload
});
test('a repair round changes only the user half', () => {
const p = build(S([workout('2026-08-01')]), { handle: 'h1', kind: 'review' });
const clean = buildPromptParts('review', p);
const repaired = buildPromptParts('review', p, { previous: '{"x":1}', errors: ['bad id'] });
assert.equal(clean.system, repaired.system);
assert.ok(repaired.user.includes('bad id'));
});
test('buildPrompt is exactly the two parts joined, so the CLI adapters lose nothing', () => {
const p = build(S([workout('2026-08-01')]), { handle: 'h1', kind: 'review' });
const parts = buildPromptParts('review', p);
assert.equal(buildPrompt('review', p), parts.system + '\n\n---\n\n' + parts.user);
});
test('every task has a flat schema — no $ref, no anyOf/oneOf (llama.cpp grammar limits)', () => {
for (const task of ['review', 'create', 'refine', 'debrief']) {
const text = JSON.stringify(SCHEMAS[task]);
assert.ok(text.length > 50, task);
assert.ok(!/\$ref|anyOf|oneOf|allOf/.test(text), task);
}
assert.equal(taskOf('review', {}), 'review');
assert.equal(taskOf('create', { refine: 'x' }), 'refine');
});
test('older sessions in a review window are compacted, the recent ones keep full sets', () => {
const many = Array.from({ length: FULL_DETAIL_SESSIONS + 4 }, (_, i) => workout('2026-08-' + String(i + 1).padStart(2, '0')));
const p = build(S(many), { handle: 'h1', kind: 'review' });
const w = p.window.workouts;
assert.equal(w.length, many.length);
assert.ok(w[0].compact);
assert.equal(w[0].entries[0].done, '1/1');
assert.equal(w[0].entries[0].top, '60x8@RIR2');
assert.ok(!w[0].entries[0].sets);
const recent = w[w.length - 1];
assert.ok(!recent.compact);
assert.ok(Array.isArray(recent.entries[0].sets));
});
test('chat-completions spec: schema rides as json_schema, falls back to json_object, then none', () => {
const spec = chatCompletionsSpec('compatible', { maxTokensField: 'max_tokens', temperature: 0 });
const body = spec.body({ model: 'm', prompt: 'p', system: 'RULES', schema: SCHEMAS.review, maxTokens: 100 });
assert.equal(body.response_format.type, 'json_schema');
assert.equal(body.temperature, 0);
assert.ok(body.messages[0].content.includes('RULES'));
const step1 = spec.withoutJsonMode(body);
assert.equal(step1.response_format.type, 'json_object');
const step2 = spec.withoutJsonMode(step1);
assert.equal(step2.response_format, undefined);
// Cloud OpenAI gets no temperature override — some models refuse it.
const cloud = chatCompletionsSpec('openai');
assert.equal(cloud.body({ model: 'm', prompt: 'p', maxTokens: 9 }).temperature, undefined);
});