Combine routines (ENG-9) phase 2: Coach — array-tolerant plan week

The plan fingerprint is computed in two runtimes that share no build step
(frontend/src/lib/coach.js and api/coach/core/) and must stay byte-for-byte
matched. Both now normalise every weekday to a routine-id list:

- canonicalPlan / cleanPlan: day value -> [].concat(S.week[d]); filter
  S.week?.[d]?.length. A legacy bare string and a one-element list are
  indistinguishable downstream.
- hashPlan (both): week join -> k + '=' + list.join('+'). A single-routine
  plan's fingerprint is byte-identical to pre-upgrade — no false-stale storm.
- aggregates.plannedDays counts scheduled days, not routines.
- coach.js currentValue/markStale compare `week` by canonical join;
  CHANGE_APPLY.week writes [c.after] (single-routine op, collapses a
  combined day — same limitation as DayOverride); changeValues.fmt renders
  a week array as " + "-joined routine names before the generic branch.
- prompts/common.md + review.md: plan.week is a list; a `week` change names
  exactly one routine and replaces the day. core/prompts.js regenerated.

Tests: shared combined-day fixture (client hashPlan === server hashPlan),
legacy scalar vs one-element array identical, canonicalPlan order,
CHANGE_APPLY.week, markStale canonical compare, changeValues rendering.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JVbWJtoyQU4WgwFR4eAKgy
This commit is contained in:
HenryandClaude Sonnet 5 committed 2026-09-06 19:27:24 +01:00
1 parent 1c877173f4
commit 8b917b6331
7 files changed
+95 -18

No files matched your search

+29 -7
View File
@@ -98,18 +98,25 @@ export function canonicalPlan(S) {
}
})
})),
week: Object.fromEntries([1, 2, 3, 4, 5, 6, 0].filter(d => S.week?.[d]).map(d => [d, S.week[d]]))
// A weekday holds a routine-id list now. `[].concat` folds a legacy bare string and a
// one-element list to the same shape, so their fingerprint is identical — no false-stale
// storm on the first load after the upgrade. `?.length` keeps a stray `[]` out. Insertion
// order is preserved and never sorted (it is the merge order).
week: Object.fromEntries([1, 2, 3, 4, 5, 6, 0].filter(d => S.week?.[d]?.length).map(d => [d, [].concat(S.week[d])]))
}
}
/** FNV-1a-ish 64-bit fingerprint. Mirror of hashPlan in api/coach/jobs.js. */
/** FNV-1a-ish 64-bit fingerprint. Mirror of hashPlan in api/coach/core/plan-hash.js. */
export function hashPlan(plan) {
const canon = JSON.stringify({
routines: (plan?.routines || []).map(r => [r.id, r.name, r.prog, (r.ex || []).map(e =>
[e.id, e.mode, e.sets, e.reps, e.sec, e.min, e.speed, e.weight, e.prog, e.inc,
e.repsMin, e.repsMax, e.bodyweight, e.side, e.sg].join(':')
)]),
week: Object.keys(plan?.week || {}).sort().map(k => k + '=' + plan.week[k])
// `plan` is a canonicalPlan output, so each day is already an array. `{1:['r1']}` → "1=r1",
// byte-identical to the pre-upgrade fingerprint; `{3:['r2','r3']}` → "3=r2+r3". Weekday
// keys still sorted; the routine list within a day never is.
week: Object.keys(plan?.week || {}).sort().map(k => k + '=' + [].concat(plan.week[k]).join('+'))
})
let h1 = 0x811c9dc5, h2 = 0x01000193
for (let i = 0; i < canon.length; i++) {
@@ -140,7 +147,7 @@ export function currentValue(S, change) {
case 'exercise-prog': return e?.prog ?? null
case 'routine-prog': return r?.prog ?? null
case 'rename-routine': return r?.name ?? null
case 'week': return S.week?.[change.target?.weekday] ?? null
case 'week': return [].concat(S.week?.[change.target?.weekday] ?? []) // routine-id list; [] = rest
default: return undefined // structural changes have no single scalar to compare
}
}
@@ -161,6 +168,12 @@ export function markStale(proposal, S) {
let stale = false
if (c.type !== 'add-routine' && c.type !== 'week' && !r) stale = true
else if (c.target?.exId && !findEx(r, c.target.exId)) stale = true
else if (c.type === 'week') {
// The day's value is a routine-id list; `before` may be a list (a combined day) or a
// legacy bare string. Compare by canonical join so order matters but shape does not.
const join = v => [].concat(v ?? []).join('+')
if (c.before != null && join(currentValue(S, c)) !== join(c.before)) stale = true
}
else {
const cur = currentValue(S, c)
// `before` is what the Coach saw. If the live plan disagrees, someone has already
@@ -504,9 +517,12 @@ const CHANGE_APPLY = {
},
'rename-routine': (s, c) => { need(findRoutine(s, c.target.routineId)).name = c.after },
week: (s, c) => {
// A single-routine op: the slot is a list, but the Coach only ever names one routine (or
// rest), and it replaces the day. This collapses a combined day to one routine — the same
// stated limitation as a DayOverride (see docs/COMBINE_ROUTINES.md §8).
const d = c.target.weekday
if (c.after == null || c.after === 'rest') delete s.week[d]
else s.week[d] = c.after
else s.week[d] = [c.after]
}
}
export const CHANGE_TYPES = Object.keys(CHANGE_APPLY)
@@ -610,10 +626,16 @@ export function changeTitle(c, S) {
export function changeValues(c, S) {
const routineName = id => (S?.routines || []).find(r => r.id === id)?.name || id
const fmt = v => {
if (v == null) return c.type === 'week' ? t('Rest') : '—'
// `week` first — its value is a routine-id list (an array is also an object, so it has to
// win before the generic branches). Render as " + "-joined routine names; null / empty /
// "rest" all read as Rest.
if (c.type === 'week') {
const ids = [].concat(v ?? []).filter(x => x && x !== 'rest')
return ids.length ? ids.map(routineName).join(' + ') : t('Rest')
}
if (v == null) return '—'
if (typeof v === 'object') return v.id ? exTitle(v.id) : v.name || JSON.stringify(v)
if (Array.isArray(v)) return v.length + ''
if (c.type === 'week') return v === 'rest' ? t('Rest') : routineName(v)
return String(v)
}
if (['add-exercise', 'add-routine', 'reorder'].includes(c.type)) return null
+50 -5
View File
@@ -3,7 +3,7 @@ import {
canonicalPlan, planHash, hashPlan, markStale, applicable, currentValue,
pushSnapshot, revertLast, canRevert, appendLog, applyChangeSet, applyCreatedPlan,
recordDismissal, validateProposal, coachAvailable, hasConsent,
recordDebrief, logEntry, lightBundle,
recordDebrief, logEntry, lightBundle, changeValues,
CHANGE_TYPES, SNAPSHOT_MAX, LOG_MAX, CONSENT_VERSION
} from './coach.js'
import { registerCustom } from './exercises.js'
@@ -100,12 +100,31 @@ describe('plan fingerprint', () => {
const withFlags = state()
withFlags.routines[0].ex[0] = { ...withFlags.routines[0].ex[0], repsMin: 8, repsMax: 20, bodyweight: true }
withFlags.routines[1].ex[0] = { ...withFlags.routines[1].ex[0], side: true, reps: 16 }
for (const S of [state(), state({ week: {} }), state({ routines: [] }), withFlags]) {
const combined = state({ week: { 1: ['r1', 'r2'], 3: 'r2', 5: [] } })
for (const S of [state(), state({ week: {} }), state({ routines: [] }), withFlags, combined]) {
expect(canonicalPlan(S)).toEqual(serverPayload.canonicalPlan(S))
expect(planHash(S)).toBe(serverHashPlan(serverPayload.canonicalPlan(S)))
expect(hashPlan(canonicalPlan(S))).toBe(serverHashPlan(serverPayload.canonicalPlan(S)))
}
})
it('a combined day changes the fingerprint, and routine order within a day matters', () => {
const S = state()
expect(planHash(state({ week: { ...S.week, 3: ['r2', 'r1'] } }))).not.toBe(planHash(S))
expect(planHash(state({ week: { 3: ['r1', 'r2'] } }))).not.toBe(planHash(state({ week: { 3: ['r2', 'r1'] } })))
})
it('a legacy bare-string day and its one-element list are the same fingerprint (upgrade stability)', () => {
expect(planHash(state({ week: { 1: 'r1' } }))).toBe(planHash(state({ week: { 1: ['r1'] } })))
// and a stray [] is dropped, exactly like an absent key
expect(planHash(state({ week: { 1: ['r1'], 4: [] } }))).toBe(planHash(state({ week: { 1: ['r1'] } })))
})
it('canonicalPlan omits a [] day and preserves routine order', () => {
expect(canonicalPlan(state({ week: { 2: [] } })).week).toEqual({})
expect(canonicalPlan(state({ week: { 3: ['r2', 'r3'] } })).week[3]).toEqual(['r2', 'r3'])
expect(canonicalPlan(state({ week: { 3: ['r3', 'r2'] } })).week[3]).toEqual(['r3', 'r2'])
})
})
describe('staleness', () => {
@@ -135,6 +154,17 @@ describe('staleness', () => {
expect(c.status).toBe('proposed')
})
it('compares a combined-day week change by its canonical routine-list join', () => {
const wk = (weekday, before) => proposal([change({ type: 'week', target: { weekday }, before, after: 'r1' })])
const S = state({ week: { 1: ['r1', 'r2'] } })
// live matches the list the Coach saw → not stale
expect(markStale(wk(1, ['r1', 'r2']), S).changes[0].status).toBe('proposed')
// a legacy scalar `before` still compares equal to a one-element live list
expect(markStale(wk(1, 'r1'), state({ week: { 1: ['r1'] } })).changes[0].status).toBe('proposed')
// the day gained a routine since → stale
expect(markStale(wk(1, ['r1', 'r2']), state({ week: { 1: ['r1', 'r2', 'r3'] } })).changes[0].status).toBe('stale')
})
it('reads the current value for every scalar change type', () => {
const S = state()
S.routines[0].ex[0].repsMax = 20
@@ -143,7 +173,7 @@ describe('staleness', () => {
expect(currentValue(S, change({ type: 'repsMax' }))).toBe(20)
expect(currentValue(S, change({ type: 'exercise-prog' }))).toBe('linear')
expect(currentValue(S, change({ type: 'routine-prog' }))).toBe('linear')
expect(currentValue(S, change({ type: 'week', target: { weekday: 1 } }))).toBe('r1')
expect(currentValue(S, change({ type: 'week', target: { weekday: 1 } }))).toEqual(['r1']) // a routine-id list; [] = rest
})
})
@@ -269,13 +299,28 @@ describe('applying changes', () => {
expect(removed.week[3]).toBeUndefined() // Wednesday pointed at r2
})
it('moves a day, and clears one', () => {
it('moves a day, and clears one — the slot stays a routine-id list', () => {
const moved = apply(state(), proposal([change({ type: 'week', target: { weekday: 6 }, before: null, after: 'r1' })]), ['c1'])
expect(moved.week[6]).toBe('r1')
expect(moved.week[6]).toEqual(['r1'])
const cleared = apply(state(), proposal([change({ type: 'week', target: { weekday: 1 }, before: 'r1', after: 'rest' })]), ['c1'])
expect(cleared.week[1]).toBeUndefined()
})
it('collapses a combined day to the single routine the Coach named', () => {
const S = state()
S.week = { ...S.week, 3: ['r2', 'r1'] }
const out = apply(S, proposal([change({ type: 'week', target: { weekday: 3 }, before: ['r2', 'r1'], after: 'r1' })]), ['c1'])
expect(out.week[3]).toEqual(['r1'])
})
it('changeValues renders a combined-day before/after as joined routine names, not a count', () => {
const S = state()
const c = { type: 'week', target: { weekday: 3 }, before: ['r1', 'r2'], after: 'r1' }
expect(changeValues(c, S)).toEqual({ before: 'Full body A + Full body B', after: 'Full body A' })
expect(changeValues({ type: 'week', target: { weekday: 3 }, before: ['r1', 'r2'], after: 'rest' }, S).after).toBe('Rest')
expect(changeValues({ type: 'week', target: { weekday: 3 }, before: null, after: 'r2' }, S).before).toBe('Rest')
})
it('never touches history, weigh-ins or settings', () => {
const S = state({
workouts: [{ id: 'w1', d: '2026-07-20', entries: [] }],