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.
This commit is contained in:
Duarte Santos committed 2026-08-30 14:31:10 +02:00
1 parent b3340e31b5
commit 9edcdaa9f3
31 files changed
+1657 -68

No files matched your search

+6
View File
@@ -47,6 +47,11 @@ export const coachStatus = async () => DEMO ? (await demo()).demoStatus() : LOCA
export const requestReview = async note => DEMO ? (await demo()).demoReview(S()) : LOCAL() ? (await local()).localReview(S(), note) : api('/api/coach/review', { method: 'POST', body: JSON.stringify({ note: note || '' }) })
export const requestPlan = async intake => DEMO ? (await demo()).demoPlan(S(), intake) : LOCAL() ? (await local()).localPlan(S(), intake) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ intake }) })
export const refinePlan = async text => DEMO ? (await demo()).demoRefine(S()) : LOCAL() ? (await local()).localRefine(S(), text) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ refine: text }) })
export const requestDebrief = async workoutId => DEMO ? (await demo()).demoDebrief(S(), workoutId) : LOCAL() ? (await local()).localDebrief(S(), workoutId) : api('/api/coach/debrief', { method: 'POST', body: JSON.stringify({ workoutId: workoutId || null }) })
// The room: anonymous medians across the profiles on this instance that opted in. Only a
// server has a room; a phone with its own key and the demo both answer locally.
export const cohortStats = async () => DEMO ? (await demo()).demoCohort(S()) : LOCAL() ? { ok: false, enabled: false } : api('/api/coach/cohort')
export const setCohortShare = async share => (DEMO || LOCAL()) ? { ok: true, sharing: !!share } : api('/api/coach/cohort/share', { method: 'POST', body: JSON.stringify({ share: !!share }) })
export const resolvePending = async body => DEMO ? (await demo()).demoResolve() : LOCAL() ? (await local()).localResolve(body) : api('/api/coach/pending/resolve', { method: 'POST', body: JSON.stringify(body) })
export const forgetCoach = async () => DEMO ? (await demo()).demoResolve() : LOCAL() ? (await local()).localForget() : api('/api/coach/forget', { method: 'POST', body: '{}' })
export const disclosure = async () => DEMO ? (await demo()).demoDisclosure() : LOCAL() ? (await local()).localDisclosure() : api('/api/coach/disclosure')
@@ -116,5 +121,6 @@ export const JOB_ERRORS = {
unusable: 'The Coach answered with something the app couldn’t use.',
restart: 'The server restarted while the Coach was thinking.',
nostate: 'The Coach couldn’t read your training data.',
noworkout: 'There is no workout to look at yet — log one first.',
internal: 'Something went wrong on the server.'
}
+51 -1
View File
@@ -13,7 +13,10 @@
// replaces at build time.
import { EXIDX, EXDB } from './exercises.js'
import { modeOf } from './history.js'
import { modeOf, workoutVolume } from './history.js'
import { isWarmupRow } from './workout-model.js'
import { best1RM } from './onerm.js'
import { fmtNum } from './format.js'
import { planHash } from './coach.js'
import { t } from './i18n.js'
@@ -108,6 +111,49 @@ function buildPlan(S, intake) {
}
}
/** One session, read back with its own numbers — no plan changes, just what a coach would say after. */
function buildDebrief(S, workoutId) {
const all = (S.workouts || []).filter(w => w && w.d)
const w = all.find(x => x.id === workoutId) || all[all.length - 1]
if (!w) return null
const done = (w.entries || []).reduce((n, en) => n + (en.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0)
const planned = (w.entries || []).reduce((n, en) => n + (en.sets || []).filter(s => !isWarmupRow(s)).length, 0)
const vol = Math.round(Number.isFinite(w.vol) ? w.vol : workoutVolume(w))
const prs = (w.prs || []).length
const minutes = w.end && w.start ? Math.round((w.end - w.start) / 60000) : null
const complete = planned > 0 && done >= planned
const score = complete ? (prs ? 9 : 8) : 7
const highlights = [
complete ? t('Every planned set done — {0} of {1}.', done, planned) : t('{0} of {1} planned sets done.', done, planned),
t('{0} {1} moved in total.', fmtNum(vol), S.unit)
]
if (prs) highlights.push(t('{0} new personal records.', prs))
const watch = minutes && minutes > 80 ? [t('{0} minutes is long — rest periods may be creeping up.', minutes)] : [t('Top sets logged without an effort rating; add RIR so the next review can read how hard they were.')]
const nextTime = [complete ? t('Add the next load step on the main lift.') : t('Repeat the same loads and get every set.'), t('Keep the session under an hour and a quarter.')]
return {
id: 'demo-debrief', kind: 'debrief', createdAt: Date.now(), expiresAt: Date.now() + 864e5,
planHash: planHash(S), iteration: 1,
workout: { id: w.id, d: w.d, name: w.name || null, minutes, vol, sets: done, prs },
summary: complete
? t('A clean session: everything on the sheet got done and the loads held. This is exactly what progress looks like from the inside — unremarkable, repeated.')
: t('Most of the work got done. One or two sets fell short, which is fine once — it becomes a signal if the same sets miss next time.'),
score, highlights, watch, nextTime
}
}
/** What "the room" would say on a busy instance — five people, plausible medians, your real bests. */
export function demoCohort(S) {
const since = Date.now() - 56 * 864e5
const you = Math.round((S.workouts || []).filter(w => (w.start || new Date(w.d).getTime()) > since).length / 8 * 10) / 10
const ids = [...new Set((S.routines || []).flatMap(r => (r.ex || []).map(e => e.id)))].slice(0, 5)
const exercises = ids.map(id => {
const b = best1RM(S, id)
const mine = b ? Math.round(b.est * 10) / 10 : null
return { id, name: EXIDX[id]?.n || id, people: 4, median: mine ? Math.round(mine * 0.92) : 60, you: mine }
})
return { ok: true, enabled: true, sharing: true, people: 5, minPeople: 3, unit: S.unit, sessionsPerWeek: { median: 3, you }, exercises, rankPct: 62 }
}
/* ---------------- the API surface the demo stands in for ---------------- */
export const demoStatus = () => ({ job, pending, cap: { used: 0, limit: 0 } })
@@ -125,6 +171,10 @@ export const demoRefine = S => start('create', () => {
const p = buildPlan(S, null)
return { ...p, iteration: (pending?.iteration || 1) + 1, summary: t('Revised as you asked. Everything you did not question is exactly as it was.') + ' ' + p.summary }
})
export const demoDebrief = (S, workoutId) => {
if (!(S.workouts || []).some(w => w && w.d)) throw Object.assign(new Error(t('There is no workout to look at yet — log one first.')), { status: 409, code: 'noworkout' })
return start('debrief', () => buildDebrief(S, workoutId))
}
export const demoResolve = () => { pending = null; return { ok: true } }
export const demoDisclosure = () => ({
provider: 'demo', providerLabel: t('the configured AI provider'),
+106
View File
@@ -0,0 +1,106 @@
// The numbers behind a Coach card, computed on the device from the same training log the
// Coach read — so the chart under a suggestion shows exactly the window the suggestion cites,
// and nothing the model wrote is ever taken as a statistic.
//
// Pure functions over S. Nothing here is persisted: a card recomputes its insights from the
// window it names, which is why an old proposal in the thread still draws its chart months
// later, against the data as it was then.
import { EXIDX } from './exercises.js'
import { workoutVolume } from './history.js'
import { isWarmupRow } from './workout-model.js'
import { bestSetOf } from './onerm.js'
const median = arr => {
const a = arr.filter(n => Number.isFinite(n)).sort((x, y) => x - y)
return a.length ? a[Math.floor(a.length / 2)] : null
}
const bpOf = (S, id) => EXIDX[id]?.bp || (S.customEx || []).find(c => c.id === id)?.bp || null
const nameOf = (S, id) => EXIDX[id]?.n || (S.customEx || []).find(c => c.id === id)?.n || id
const tsOf = w => w.start || new Date(w.d + 'T12:00:00').getTime()
/** Workouts inside an inclusive ISO-date window; either bound may be missing. */
export function windowWorkouts(S, { from, to } = {}) {
return (S.workouts || []).filter(w => w && w.d && (!from || w.d >= from) && (!to || w.d <= to))
}
/**
* What a review looked at, in numbers: how much, how long, which body parts, where the body
* weight went and which lifts moved. `strength` holds up to `topN` exercises with at least two
* estimable sessions in the window, most-trained first, with the first→last e1RM change.
*/
export function insightsFor(S, win = {}, { topN = 3 } = {}) {
const ws = windowWorkouts(S, win)
const minutes = ws.map(w => (w.end && w.start ? Math.round((w.end - w.start) / 60000) : null)).filter(n => n > 0)
const volume = ws.reduce((n, w) => n + (Number.isFinite(w.vol) ? w.vol : workoutVolume(w)), 0)
const byBp = {}
let setsTotal = 0
ws.forEach(w => (w.entries || []).forEach(en => {
const n = (en.sets || []).filter(s => s.done && !isWarmupRow(s)).length
if (!n) return
setsTotal += n
const bp = bpOf(S, en.id) || 'other'
byBp[bp] = (byBp[bp] || 0) + n
}))
const bodyParts = Object.entries(byBp).map(([bp, sets]) => ({ bp, sets, share: setsTotal ? sets / setsTotal : 0 }))
.sort((a, b) => b.sets - a.sets)
const from = win.from || ws[0]?.d || null
const to = win.to || ws[ws.length - 1]?.d || null
const bw = (S.bodyweight || []).filter(b => b && b.d && (!from || b.d >= from) && (!to || b.d <= to))
.map(b => ({ t: b.t || new Date(b.d + 'T12:00:00').getTime(), y: b.w, d: b.d }))
const bodyweight = {
points: bw,
delta: bw.length > 1 ? Math.round((bw[bw.length - 1].y - bw[0].y) * 10) / 10 : null,
last: bw.length ? bw[bw.length - 1].y : null,
goal: Number.isFinite(S.targetW) ? S.targetW : null
}
const series = new Map()
ws.forEach(w => (w.entries || []).forEach(en => {
const best = bestSetOf(en)
if (!best) return
if (!series.has(en.id)) series.set(en.id, [])
series.get(en.id).push({ t: tsOf(w), d: w.d, y: Math.round(best.est * 10) / 10 })
}))
const strength = [...series.entries()]
.filter(([, pts]) => pts.length >= 2)
.sort((a, b) => b[1].length - a[1].length)
.slice(0, topN)
.map(([id, pts]) => {
const first = pts[0].y, last = pts[pts.length - 1].y
return { id, name: nameOf(S, id), sessions: pts.length, first, last, delta: Math.round((last - first) * 10) / 10, pct: first ? Math.round((last - first) / first * 100) : 0, points: pts }
})
return {
from, to, sessions: ws.length, minutes: median(minutes), volume: Math.round(volume), sets: setsTotal,
bodyParts, bodyweight, strength
}
}
/**
* One workout against the last time the same routine was trained: the numbers a debrief
* card puts above the Coach's words.
*/
export function sessionInsights(S, workout) {
if (!workout) return null
const all = (S.workouts || []).filter(w => w && w.d)
const idx = all.findIndex(w => (workout.id && w.id === workout.id) || (w.d === workout.d && w.start === workout.start))
const before = (idx >= 0 ? all.slice(0, idx) : all).filter(w => w.name && w.name === workout.name)
const prev = before[before.length - 1] || null
const stat = w => ({
volume: Math.round(Number.isFinite(w.vol) ? w.vol : workoutVolume(w)),
sets: (w.entries || []).reduce((n, en) => n + (en.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0),
minutes: w.end && w.start ? Math.round((w.end - w.start) / 60000) : null,
prs: (w.prs || []).length
})
const now = stat(workout)
const then = prev ? stat(prev) : null
const lifts = (workout.entries || []).map(en => {
const best = bestSetOf(en)
const pe = prev?.entries?.find(x => x.id === en.id)
const pb = pe ? bestSetOf(pe) : null
return best ? { id: en.id, name: nameOf(S, en.id), est: Math.round(best.est * 10) / 10, w: best.w, r: best.r, prev: pb ? Math.round(pb.est * 10) / 10 : null } : null
}).filter(Boolean)
return { now, then, prevDate: prev?.d || null, lifts }
}
+97
View File
@@ -0,0 +1,97 @@
import { describe, it, expect } from 'vitest'
import { insightsFor, sessionInsights, windowWorkouts } from './coach-insights.js'
import { EXIDX } from './exercises.js'
// Pick two real catalogue ids from different body parts so the body-part grouping is real.
const ids = Object.keys(EXIDX)
const chest = ids.find(id => EXIDX[id].bp === 'chest')
const legs = ids.find(id => EXIDX[id].bp === 'upper legs')
const day = (d, h = 10) => new Date(d + 'T' + String(h).padStart(2, '0') + ':00:00').getTime()
const w = (id, d, entries, over = {}) => ({ id, d, name: 'Push', start: day(d), end: day(d) + 55 * 60000, entries, ...over })
const set = (w_, r, extra = {}) => ({ done: true, w: w_, r, ...extra })
const S = () => ({
unit: 'kg', targetW: 80, customEx: [{ id: 'cx1', n: 'My row', bp: 'back' }],
bodyweight: [{ d: '2026-07-01', w: 90 }, { d: '2026-08-02', w: 84 }, { d: '2026-08-10', w: 83 }, { d: '2026-08-20', w: 82.5 }],
workouts: [
w('w0', '2026-07-20', [{ id: chest, sets: [set(60, 10)] }]), // outside the window
w('w1', '2026-08-03', [{ id: chest, sets: [set(40, 8, { phase: 'warmup' }), set(60, 10), set(60, 10)] }, { id: legs, sets: [set(100, 5)] }]),
w('w2', '2026-08-06', [{ id: chest, sets: [set(65, 10), set(65, 9)] }, { id: 'cx1', sets: [set(50, 10)] }], { name: 'Pull' }),
w('w3', '2026-08-12', [{ id: chest, sets: [set(70, 10), set(70, 10), { done: false, w: 70, r: 0 }] }, { id: legs, sets: [set(110, 5)] }], { prs: [chest] })
]
})
describe('insightsFor', () => {
const win = { from: '2026-08-01', to: '2026-08-15' }
it('counts only the window, and only done, non-warm-up work sets', () => {
const i = insightsFor(S(), win)
expect(i.sessions).toBe(3)
expect(windowWorkouts(S(), win).map(x => x.id)).toEqual(['w1', 'w2', 'w3'])
expect(i.sets).toBe(2 + 1 + 2 + 1 + 2 + 1)
expect(i.minutes).toBe(55)
// volume excludes the warm-up and the unchecked set
expect(i.volume).toBe(60 * 10 * 2 + 100 * 5 + 65 * 10 + 65 * 9 + 50 * 10 + 70 * 10 * 2 + 110 * 5)
})
it('groups sets by body part, custom exercises included, biggest first', () => {
const i = insightsFor(S(), win)
expect(i.bodyParts[0]).toMatchObject({ bp: 'chest', sets: 6 })
expect(i.bodyParts.map(b => b.bp)).toContain('back')
expect(i.bodyParts.reduce((n, b) => n + b.share, 0)).toBeCloseTo(1, 5)
})
it('reads the body weight inside the window with its delta and goal', () => {
const i = insightsFor(S(), win)
expect(i.bodyweight.points.map(p => p.y)).toEqual([84, 83])
expect(i.bodyweight.delta).toBe(-1)
expect(i.bodyweight.goal).toBe(80)
expect(i.bodyweight.last).toBe(83)
})
it('tracks estimated 1RM first → last for exercises with two or more sessions, most-trained first', () => {
const i = insightsFor(S(), win, { topN: 1 })
expect(i.strength).toHaveLength(1)
const c = i.strength[0]
expect(c.id).toBe(chest)
expect(c.sessions).toBe(3)
expect(c.last).toBeGreaterThan(c.first)
expect(c.pct).toBeGreaterThan(0)
expect(c.delta).toBeCloseTo(c.last - c.first, 1)
expect(insightsFor(S(), win).strength.length).toBe(2) // chest + legs; the custom row has one session
})
it('falls back to the workouts’ own span when no window is given', () => {
const i = insightsFor(S())
expect(i.sessions).toBe(4)
expect(i.from).toBe('2026-07-20')
expect(i.to).toBe('2026-08-12')
})
it('is empty-safe', () => {
const i = insightsFor({ workouts: [], bodyweight: [] })
expect(i.sessions).toBe(0)
expect(i.minutes).toBeNull()
expect(i.bodyweight.delta).toBeNull()
expect(i.strength).toEqual([])
})
})
describe('sessionInsights', () => {
it('compares a workout with the previous one of the same name', () => {
const s = S()
const r = sessionInsights(s, s.workouts[3]) // w3 'Push' — previous Push is w1
expect(r.prevDate).toBe('2026-08-03')
expect(r.now.sets).toBe(3)
expect(r.now.prs).toBe(1)
expect(r.then.sets).toBe(3)
expect(r.now.volume - r.then.volume).toBe((70 * 10 * 2 + 110 * 5) - (60 * 10 * 2 + 100 * 5))
const chestLift = r.lifts.find(l => l.id === chest)
expect(chestLift.w).toBe(70)
expect(chestLift.prev).not.toBeNull()
expect(chestLift.est).toBeGreaterThan(chestLift.prev)
})
it('has no comparison when the name was never trained before', () => {
const s = S()
const r = sessionInsights(s, s.workouts[2]) // the only 'Pull'
expect(r.then).toBeNull()
expect(r.prevDate).toBeNull()
expect(r.lifts.every(l => l.prev === null)).toBe(true)
})
it('returns null for nothing', () => { expect(sessionInsights(S(), null)).toBeNull() })
})
+12 -1
View File
@@ -95,6 +95,7 @@ export const localRefine = async (S, text) => {
const pendingCreate = d.pending && d.pending.kind === 'create' ? d.pending : null
return start(S, 'create', { refine: String(text || '').slice(0, 1000), previous: pendingCreate?.bundle || null, iteration: (pendingCreate?.iteration || 1) + 1 })
}
export const localDebrief = (S, workoutId) => start(S, 'debrief', { workoutId: workoutId || null })
export async function localResolve() { await saveCoachDevice({ pending: null }); return { ok: true } }
export async function localForget() { job = null; lastError = null; await saveCoachDevice({ pending: null, daily: null }); return { ok: true } }
@@ -141,7 +142,7 @@ async function start(S, kind, opts) {
async function run(S, kind, opts, d, adapter) {
const key = await getApiKey()
const payload = payloadLib.build(S, {
handle: await handle(), kind, intake: opts.intake, note: opts.note, refine: opts.refine, previous: opts.previous
handle: await handle(), kind, intake: opts.intake, note: opts.note, refine: opts.refine, previous: opts.previous, workoutId: opts.workoutId
})
const attempt = await runPipeline({
adapter, cfg: cfgOf(d), kind, payload,
@@ -162,6 +163,7 @@ async function run(S, kind, opts, d, adapter) {
const pending = {
id: job.id, kind, createdAt: Date.now(), expiresAt: Date.now() + PENDING_DAYS * 86400000,
planHash: planHash(S), iteration: opts.iteration || 1,
...(kind === 'debrief' ? { workout: workoutMetaOf(S, opts.workoutId) } : {}),
...attempt.result
}
await saveCoachDevice({ pending })
@@ -169,5 +171,14 @@ async function run(S, kind, opts, d, adapter) {
if (notify) notify({ kind: 'ready', pending })
}
// The session a debrief is about, in the shape the card reads. The core builds it for the
// server; the fallback covers a core that predates it.
function workoutMetaOf(S, workoutId) {
if (typeof payloadLib.workoutMeta === 'function') return payloadLib.workoutMeta(S, workoutId)
const all = (S.workouts || []).filter(w => w && w.d)
const w = all.find(x => x.id === workoutId) || all[all.length - 1]
return w ? { id: w.id, d: w.d, name: w.name || null } : null
}
// Test seam.
export function _resetLocal() { job = null; lastError = null; last = null }
+51 -9
View File
@@ -262,9 +262,35 @@ export const canRevert = S => !!(S?.coach?.snapshots || []).length
export function appendLog(s, entry) {
const c = coachOf(s)
c.log = [...(c.log || []), { id: entry.id || uid(), ...entry }].slice(-LOG_MAX)
const e = { id: entry.id || uid(), ...entry }
c.log = [...(c.log || []), e].slice(-LOG_MAX)
trim(s)
return e.id
}
export const logEntry = (S, id) => (S?.coach?.log || []).find(e => e.id === id) || null
/**
* What a created plan looked like, small enough to keep: names, days and prescriptions, no
* rationale text. The full bundle was merged into the plan already; this is what the chat
* shows back when someone opens an old proposal months later.
*/
export function lightBundle(b) {
if (!b) return null
return {
name: b.name || '', summary: b.summary || '', week: { ...(b.week || {}) },
routines: (b.routines || []).map(r => ({
id: r.id, name: r.name, emoji: r.emoji || '', why: r.why || '',
ex: (r.ex || []).map(e => ({
id: e.id, sets: e.sets, mode: e.mode || 'reps',
...(e.reps != null ? { reps: e.reps } : {}), ...(e.sec != null ? { sec: e.sec } : {}),
...(e.min != null ? { min: e.min } : {}), ...(e.weight ? { weight: e.weight } : {}),
...(e.why ? { why: String(e.why).slice(0, 200) } : {})
}))
}))
}
}
const decisionOf = (c, status) => ({ id: c.id, type: c.type, target: c.target || null, before: c.before ?? null, after: c.after ?? null, why: c.why, routineName: c.routineName || null, status })
/**
* Last line of defence for the 5 MB sync body: if the Coach namespace ever outgrows its
@@ -346,9 +372,10 @@ export function applyCreatedPlan(s, proposal, { schedule } = {}) {
// Only when the week actually moved — with the switch off the old schedule still stands, and
// so do the reschedules made against it.
if (schedule) sweepDayPlan(s, todayISO())
appendLog(s, {
res.logId = appendLog(s, {
kind: 'create', at: Date.now(), proposalId: proposal.id,
summary: proposal.summary || '', routines: res.routines, iteration: proposal.iteration || 1
summary: proposal.summary || '', routines: res.routines, iteration: proposal.iteration || 1,
bundle: lightBundle(bundle), scheduled: !!schedule
})
return res
}
@@ -498,29 +525,44 @@ export function applyChangeSet(s, proposal, acceptedIds) {
const applied = []
for (const c of changes) {
CHANGE_APPLY[c.type](s, c)
applied.push({ id: c.id, type: c.type, target: c.target, before: c.before, after: c.after, why: c.why, status: 'accepted' })
applied.push(decisionOf(c, 'accepted'))
}
// Turned-down changes keep their before/after too: the chat shows the whole proposal back
// later, and "you declined something about sets" is not a memory anyone can use.
const rejected = (proposal.changes || [])
.filter(c => !accepted.has(c.id))
.map(c => ({ id: c.id, type: c.type, why: c.why, status: 'rejected' }))
.map(c => decisionOf(c, c.status === 'stale' ? 'stale' : 'rejected'))
appendLog(s, {
const logId = appendLog(s, {
kind: 'review', at: Date.now(), proposalId: proposal.id,
summary: proposal.summary || '', evidence: proposal.evidence || null,
notes: proposal.notes || [], decisions: [...applied, ...rejected]
})
coachOf(s).lastReview = { at: Date.now() }
return { applied: applied.length, rejected: rejected.length }
return { applied: applied.length, rejected: rejected.length, logId }
}
/** Turned down whole, or expired: recorded so a later review knows not to re-propose it. */
export function recordDismissal(s, proposal) {
appendLog(s, {
const logId = appendLog(s, {
kind: proposal.kind === 'create' ? 'create' : 'review', at: Date.now(), proposalId: proposal.id,
summary: proposal.summary || '', dismissed: true,
decisions: (proposal.changes || []).map(c => ({ id: c.id, type: c.type, why: c.why, status: 'rejected' }))
evidence: proposal.evidence || null, notes: proposal.notes || [],
...(proposal.bundle ? { bundle: lightBundle(proposal.bundle), iteration: proposal.iteration || 1 } : {}),
decisions: (proposal.changes || []).map(c => decisionOf(c, 'rejected'))
})
if (proposal.kind !== 'create') coachOf(s).lastReview = { at: Date.now() }
return logId
}
/** A debrief has no decision to make: it is read, kept, and shown again on request. */
export function recordDebrief(s, proposal) {
return appendLog(s, {
kind: 'debrief', at: Date.now(), proposalId: proposal.id,
workout: proposal.workout || null,
summary: proposal.summary || '', score: proposal.score ?? null,
highlights: proposal.highlights || [], watch: proposal.watch || [], nextTime: proposal.nextTime || []
})
}
/* ============================ display helpers ============================ */
+57 -1
View File
@@ -3,6 +3,7 @@ import {
canonicalPlan, planHash, hashPlan, markStale, applicable, currentValue,
pushSnapshot, revertLast, canRevert, appendLog, applyChangeSet, applyCreatedPlan,
recordDismissal, validateProposal, coachAvailable, hasConsent,
recordDebrief, logEntry, lightBundle,
CHANGE_TYPES, SNAPSHOT_MAX, LOG_MAX, CONSENT_VERSION
} from './coach.js'
import { registerCustom } from './exercises.js'
@@ -298,7 +299,7 @@ describe('accepting a subset', () => {
change({ id: 'c2', type: 'reps', before: 10, after: 12 })
])
const res = applyChangeSet(s, p, ['c1'])
expect(res).toEqual({ applied: 1, rejected: 1 })
expect(res).toMatchObject({ applied: 1, rejected: 1 })
expect(s.routines[0].ex[0].sets).toBe(4)
expect(s.routines[0].ex[0].reps).toBe(10)
const decisions = s.coach.log.at(-1).decisions
@@ -552,3 +553,58 @@ describe('removing a routine takes its per-date reschedules with it', () => {
expect(s.dayPlan['2099-01-01']).toBe('r2')
})
})
describe('what the log keeps, so a decision never makes a proposal vanish', () => {
const plan = {
opengym_plan: 1, name: 'Coach plan', summary: 'p', week: { 1: 'x1' },
routines: [{ id: 'x1', name: 'A', emoji: '💪', why: 'w', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps', why: 'y'.repeat(300), secret: 1 }] }],
customEx: []
}
it('applyChangeSet returns the log id and keeps the declined change whole', () => {
const s = JSON.parse(JSON.stringify(state()))
const p = proposal([change(), change({ id: 'c2', type: 'reps', before: 10, after: 8, why: 'too many' })])
const res = applyChangeSet(s, p, ['c1'])
expect(res.logId).toBe(s.coach.log.at(-1).id)
const rej = s.coach.log.at(-1).decisions.find(d => d.id === 'c2')
expect(rej).toMatchObject({ status: 'rejected', type: 'reps', before: 10, after: 8, target: { routineId: 'r1', exId: '0001' } })
expect(logEntry(s, res.logId).kind).toBe('review')
})
it('applyCreatedPlan keeps a light copy of the bundle and whether the week was taken', () => {
const s = JSON.parse(JSON.stringify(state()))
const res = applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle: plan, iteration: 2 }, { schedule: false })
const e = logEntry(s, res.logId)
expect(e.kind).toBe('create')
expect(e.scheduled).toBe(false)
expect(e.iteration).toBe(2)
expect(e.bundle.routines[0].ex[0]).toEqual({ id: '0001', sets: 3, mode: 'reps', reps: 10, why: 'y'.repeat(200) })
expect(e.bundle.routines[0].why).toBe('w')
})
it('recordDismissal returns the id and keeps a discarded plan too', () => {
const s = JSON.parse(JSON.stringify(state()))
const id = recordDismissal(s, { id: 'p1', kind: 'create', summary: 'nope', bundle: plan })
const e = logEntry(s, id)
expect(e.dismissed).toBe(true)
expect(e.bundle.name).toBe('Coach plan')
expect(s.coach.lastReview).toBeUndefined()
const rid = recordDismissal(s, proposal([change()], { evidence: { sessions: 4 }, notes: ['n'] }))
expect(logEntry(s, rid)).toMatchObject({ evidence: { sessions: 4 }, notes: ['n'] })
expect(logEntry(s, rid).decisions[0]).toMatchObject({ status: 'rejected', before: 3, after: 4 })
})
it('recordDebrief files the whole reading', () => {
const s = JSON.parse(JSON.stringify(state()))
const id = recordDebrief(s, { id: 'd1', kind: 'debrief', workout: { id: 'w1', name: 'Push' }, summary: 'ok', score: 8, highlights: ['a'], watch: [], nextTime: ['b'] })
expect(logEntry(s, id)).toMatchObject({ kind: 'debrief', score: 8, highlights: ['a'], nextTime: ['b'], workout: { id: 'w1' } })
})
it('lightBundle drops what the card does not show', () => {
const b = lightBundle({ ...plan, customEx: [{ id: 'z' }], basedOn: 'x' })
expect(b.customEx).toBeUndefined()
expect(b.basedOn).toBeUndefined()
expect(Object.keys(b.routines[0].ex[0])).not.toContain('secret')
expect(lightBundle(null)).toBeNull()
})
})