Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-4442]): protocol-scoped benchmark trend + structured session conditions
[._.]/ Adam Eivya5422141405f
diff --git a/client/src/components/meatspace/post/PostProgress.jsx b/client/src/components/meatspace/post/PostProgress.jsxindex 1782449749..59e6fa6cae 100644--- a/client/src/components/meatspace/post/PostProgress.jsx+++ b/client/src/components/meatspace/post/PostProgress.jsx@@ -117,6 +117,15 @@ export default function PostProgress({ subtab, onBack }) {() => (progress?.series?.byDay || []).map(p => ({ date: p.date, minutes: p.minutes })),[progress]);+ // Protocol-scoped benchmark trend (issue #4442) — only sessions run under+ // the CURRENT fixed protocol/scorer version, separate from the blended+ // "Score Trend" above which includes every scored session. `excludedCount`+ // is surfaced explicitly rather than silently omitted.+ const benchmark = progress?.series?.benchmark || null;+ const benchmarkScoreData = useMemo(+ () => (benchmark?.byDay || []).filter(p => p.score != null).map(p => ({ date: p.date, score: p.score })),+ [benchmark]+ );// Sub-view: the full session-list table (reuses PostHistory), deep-linked at// /post/progress/sessions.@@ -263,6 +272,33 @@ export default function PostProgress({ subtab, onBack }) {/></div>+ {/* Benchmark trend — a narrower, protocol-scoped comparison than the+ blended "Score Trend" above. Only counts sessions run under the+ CURRENT registered protocol/scorer version (issue #4442); a+ retired protocol/scorer version or an ordinary Quick/Test/Train+ session never contributes here, and the excluded count says so+ instead of quietly under-reporting. */}+ {benchmark && (+ <div className="grid grid-cols-1 gap-4 sm:gap-6">+ <div>+ <TrendChart+ title={`Benchmark Trend — ${benchmark.protocolId} v${benchmark.protocolVersion}`}+ data={benchmarkScoreData}+ dataKey="score"+ domainRange={[0, 100]}+ stroke={chartColors.accent}+ chartColors={chartColors}+ emptyText="No compatible benchmark runs yet — start one from the launcher."+ />+ {benchmark.excludedCount > 0 && (+ <p className="text-xs text-gray-500 mt-2">+ {benchmark.excludedCount} earlier benchmark {benchmark.excludedCount === 1 ? 'run' : 'runs'} excluded — different protocol/scoring version, not comparable to the current battery.+ </p>+ )}+ </div>+ </div>+ )}+{/* Mastery panel */}<div className="grid grid-cols-1 xl:grid-cols-2 gap-4 sm:gap-6">{mastery.multiplication && (diff --git a/client/src/components/meatspace/post/PostProgress.test.jsx b/client/src/components/meatspace/post/PostProgress.test.jsxindex a31cb1086f..664702eec8 100644--- a/client/src/components/meatspace/post/PostProgress.test.jsx+++ b/client/src/components/meatspace/post/PostProgress.test.jsx@@ -114,3 +114,51 @@ describe('PostProgress', () => {expect(getPostProgress).not.toHaveBeenCalled();});});++// Protocol-scoped benchmark trend (issue #4442) — a narrower comparison than+// the blended Score Trend above, visibly separate from legacy/excluded runs.+describe('PostProgress — benchmark trend', () => {+ it('renders the benchmark trend chart with its protocol id/version in the title', async () => {+ getPostProgress.mockResolvedValue({+ ...PROGRESS,+ series: {+ ...PROGRESS.series,+ benchmark: {+ protocolId: 'post-foundation-battery',+ protocolVersion: 1,+ scorerVersion: 'post-deterministic-v1',+ byDay: [{ date: '2026-06-03', score: 88, sessions: 1 }],+ excludedCount: 0,+ },+ },+ });+ renderProgress();+ await waitFor(() => expect(screen.getByText(/Benchmark Trend/)).toBeInTheDocument());+ expect(screen.getByText(/post-foundation-battery v1/)).toBeInTheDocument();+ });++ it('surfaces the excluded-legacy-runs note when excludedCount is set', async () => {+ getPostProgress.mockResolvedValue({+ ...PROGRESS,+ series: {+ ...PROGRESS.series,+ benchmark: {+ protocolId: 'post-foundation-battery',+ protocolVersion: 1,+ scorerVersion: 'post-deterministic-v1',+ byDay: [],+ excludedCount: 2,+ },+ },+ });+ renderProgress();+ await waitFor(() => expect(screen.getByText(/Benchmark Trend/)).toBeInTheDocument());+ expect(screen.getByText(/2 earlier benchmark runs excluded/)).toBeInTheDocument();+ });++ it('omits the benchmark trend section entirely when the server sends no benchmark field', async () => {+ renderProgress();+ await waitFor(() => expect(screen.getByText('Score Trend')).toBeInTheDocument());+ expect(screen.queryByText(/Benchmark Trend/)).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxindex d9ac7e614b..b63480575e 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -70,16 +70,33 @@ export function cognitiveSummary(type, cfg) {return cfg.count ? `${cfg.count} trials` : '';}-// Pure: sanitizes the optional condition-tags map before submit — drops-// empty/whitespace-only values so a session with no conditions filled in-// doesn't persist `{ sleep: '', caffeine: '', stress: '' }` to history.-// `tags` is passed explicitly (lifted from the component's `tags` state).-export function buildCleanTags(tags) {- const cleanTags = {};- for (const [k, v] of Object.entries(tags)) {- if (v.trim()) cleanTags[k] = v.trim();- }- return cleanTags;+// Structured session-condition options (issue #4442) — fixed enums instead+// of free text, so values are filterable/comparable across sessions rather+// than the prior "good/poor", "1 cup" free-text guesswork.+export const SLEEP_QUALITY_OPTIONS = ['poor', 'fair', 'good'];+export const CAFFEINE_OPTIONS = ['none', 'low', 'moderate', 'high'];+export const STRESS_OPTIONS = ['low', 'moderate', 'high'];++// Drives the three condition <select>s below — one entry per enum field, so+// adding/renaming a field is a one-line change instead of a copy-pasted block.+const CONDITION_SELECT_FIELDS = [+ { key: 'sleepQuality', label: 'Sleep', options: SLEEP_QUALITY_OPTIONS },+ { key: 'caffeine', label: 'Caffeine', options: CAFFEINE_OPTIONS },+ { key: 'stress', label: 'Stress', options: STRESS_OPTIONS },+];++// Pure: sanitizes the optional conditions object before submit — drops unset+// enum fields and an empty/whitespace-only note, so a session with nothing+// filled in submits `{}` (server treats an empty object as "no conditions"),+// not a placeholder-filled record. `conditions` is passed explicitly (lifted+// from the component's `conditions` state).+export function buildCleanConditions(conditions) {+ const clean = {};+ if (conditions.sleepQuality) clean.sleepQuality = conditions.sleepQuality;+ if (conditions.caffeine) clean.caffeine = conditions.caffeine;+ if (conditions.stress) clean.stress = conditions.stress;+ if (conditions.note?.trim()) clean.note = conditions.note.trim();+ return clean;}function AutoStartRecommendation({ action, onConsumed, onNavigate }) {@@ -115,10 +132,10 @@ export default function PostSessionLauncher({// windows POST records on the configured local day (issue #2681). Deriving it// from `new Date().toISOString()` (UTC) would disagree near local/UTC midnight.const timezone = useUserTimezone();- const [tags, setTags] = useState({ sleep: '', caffeine: '', stress: '' });+ const [conditions, setConditions] = useState({ sleepQuality: '', caffeine: '', stress: '', note: '' });// Conditions is optional metadata, so it starts collapsed and the start- // buttons stay above the fold (issue #3249). Purely presentational — `tags`- // lives above it, so collapsing never discards typed values.+ // buttons stay above the fold (issue #3249). Purely presentational —+ // `conditions` lives above it, so collapsing never discards typed values.const [showConditions, setShowConditions] = useState(false);const [mode, setMode] = useState('test'); // 'test' | 'train'const [quickDurationMin, setQuickDurationMin] = useState(() => normalizeQuickDurationMinutes(config?.quickDurationMin));@@ -357,7 +374,7 @@ export default function PostSessionLauncher({// for better retention (issue #2100). Full coverage is preserved — every// enabled drill still runs, just reordered.const drillConfigs = interleaveByDomain([...mathConfigs, ...llmConfigs, ...cognitiveConfigs, ...memoryConfigs]);- onStart(drillConfigs, buildCleanTags(tags), mode === 'train');+ onStart(drillConfigs, buildCleanConditions(conditions), mode === 'train');}// Build domain → enabled drills map for quick session@@ -440,7 +457,7 @@ export default function PostSessionLauncher({return drillConfig;});if (!drillConfigs.length) return;- onStart(drillConfigs, buildCleanTags(tags), mode === 'train', {+ onStart(drillConfigs, buildCleanConditions(conditions), mode === 'train', {targetDurationSec: quickPlan.targetDurationSec,estimatedDurationSec: quickPlan.estimatedDurationSec,toleranceSec: quickPlan.toleranceSec,@@ -463,7 +480,7 @@ export default function PostSessionLauncher({config: { ...task.config },timeLimitSec: task.timeLimitSec,}));- onStart(drillConfigs, buildCleanTags(tags), false, null, {+ onStart(drillConfigs, buildCleanConditions(conditions), false, null, {protocolId: protocol.protocolId,protocolVersion: protocol.protocolVersion,scorerVersion: protocol.scorerVersion,@@ -519,7 +536,7 @@ export default function PostSessionLauncher({function handleFocusDomain(domainKey) {const drills = enabledDomains[domainKey];if (!drills || drills.length === 0) return;- onStart(drills.map(d => buildFocusDrillConfig(d, domainKey)), buildCleanTags(tags), mode === 'train');+ onStart(drills.map(d => buildFocusDrillConfig(d, domainKey)), buildCleanConditions(conditions), mode === 'train');}// Start a session with exactly ONE recommended drill (issue #2100): an Up next@@ -528,7 +545,7 @@ export default function PostSessionLauncher({function startDrillByType(type) {const entry = allEnabledDrills.find(d => d.type === type);if (!entry) return;- onStart([buildFocusDrillConfig(entry)], buildCleanTags(tags), mode === 'train');+ onStart([buildFocusDrillConfig(entry)], buildCleanConditions(conditions), mode === 'train');}// Launch a single due maintenance-review rep from an "Up next" skill-review@@ -555,7 +572,7 @@ export default function PostSessionLauncher({reviewLabel: rep.label,...(rep.providerId && { providerId: rep.providerId }),};- onStart([drillConfig], buildCleanTags(tags), mode === 'train');+ onStart([drillConfig], buildCleanConditions(conditions), mode === 'train');}const hasAnyDrills = enabledMathDrills.length > 0 || enabledLlmDrills.length > 0 || enabledCognitiveDrills.length > 0 || enabledMemoryDrills.length > 0;@@ -613,8 +630,10 @@ export default function PostSessionLauncher({: null);// Count of condition fields filled in, surfaced on the collapsed disclosure so- // entered values aren't invisible once it's closed.- const filledTagCount = Object.values(tags).filter(v => v.trim()).length;+ // entered values aren't invisible once it's closed. Reuses the same+ // sanitizer the submit path uses, so "filled in" can't drift from "actually+ // sent".+ const filledConditionCount = Object.keys(buildCleanConditions(conditions)).length;// The CTA renders as a <Link> for a routed rec and a <button> for an in-page// start, but is otherwise identical — so build the shared parts once. A@@ -864,7 +883,9 @@ export default function PostSessionLauncher({{/* Conditions — optional session metadata, collapsed by default so itcan't push the start buttons below the fold. Values are held in- `tags` above, so collapsing never discards what was typed. */}+ `conditions` above, so collapsing never discards what was set.+ Fixed enums (issue #4442) instead of free text so values are+ filterable/comparable across sessions. */}{mode === 'test' && (<div className="border-t border-port-border pt-3"><button@@ -875,23 +896,34 @@ export default function PostSessionLauncher({><ChevronRight size={14} className={`transition-transform ${showConditions ? 'rotate-90' : ''}`} />Conditions (optional)- {!showConditions && filledTagCount > 0 && (- <span className="text-port-accent">· {filledTagCount} set</span>+ {!showConditions && filledConditionCount > 0 && (+ <span className="text-port-accent">· {filledConditionCount} set</span>)}</button>{showConditions && (<div className="grid grid-cols-3 gap-3 mt-3">- {Object.entries(tags).map(([key, value]) => (- <FormField key={key} labelClassName="text-xs text-gray-500 mb-1 block capitalize" label={key}>- <input- type="text"- value={value}- onChange={e => setTags(prev => ({ ...prev, [key]: e.target.value }))}- placeholder={key === 'sleep' ? 'good/poor' : key === 'caffeine' ? '1 cup' : 'low/high'}- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white placeholder-gray-600 focus:border-port-accent focus:outline-none"- />+ {CONDITION_SELECT_FIELDS.map(({ key, label, options }) => (+ <FormField key={key} labelClassName="text-xs text-gray-500 mb-1 block" label={label}>+ <select+ value={conditions[key]}+ onChange={e => setConditions(prev => ({ ...prev, [key]: e.target.value }))}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none capitalize"+ >+ <option value="">—</option>+ {options.map(opt => <option key={opt} value={opt}>{opt}</option>)}+ </select></FormField>))}+ <FormField className="col-span-3" labelClassName="text-xs text-gray-500 mb-1 block" label="Note">+ <input+ type="text"+ value={conditions.note}+ onChange={e => setConditions(prev => ({ ...prev, note: e.target.value }))}+ placeholder="Anything else worth remembering about this session"+ maxLength={500}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white placeholder-gray-600 focus:border-port-accent focus:outline-none"+ />+ </FormField></div>)}</div>diff --git a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx b/client/src/components/meatspace/post/PostSessionLauncher.test.jsxindex e8c48ef8e0..c6a492ff55 100644--- a/client/src/components/meatspace/post/PostSessionLauncher.test.jsx+++ b/client/src/components/meatspace/post/PostSessionLauncher.test.jsx@@ -35,37 +35,39 @@ vi.mock('../../../services/api', () => ({getSettings: vi.fn().mockResolvedValue({ timezone: 'UTC' }),}));-import PostSessionLauncher, { buildCleanTags, cognitiveSummary, interleaveByDomain } from './PostSessionLauncher';+import PostSessionLauncher, { buildCleanConditions, cognitiveSummary, interleaveByDomain } from './PostSessionLauncher';import { getPostRecommendations, getMorseProgress, getPostProgress, getPostReviewReps, getPostBenchmarkProtocol, getMemoryItems, updatePostConfig } from '../../../services/api';// Pure-function tests for PostSessionLauncher's pre-submit helpers (issue-// #2102 gap #10). Both were lifted from component-body closures to module-// scope with explicit parameters (`tags` for buildCleanTags) so they can be-// tested directly without rendering the launcher or its provider fetch.+// #2102 gap #10; structured conditions issue #4442). Both were lifted from+// component-body closures to module scope with explicit parameters+// (`conditions` for buildCleanConditions) so they can be tested directly+// without rendering the launcher or its provider fetch.-describe('buildCleanTags', () => {- it('keeps a filled-in value, trimmed', () => {- expect(buildCleanTags({ sleep: ' good ', caffeine: '', stress: '' })).toEqual({ sleep: 'good' });+describe('buildCleanConditions', () => {+ it('keeps set enum fields and a trimmed note', () => {+ expect(buildCleanConditions({ sleepQuality: 'good', caffeine: '', stress: '', note: ' slept well ' }))+ .toEqual({ sleepQuality: 'good', note: 'slept well' });});- it('drops empty-string values', () => {- expect(buildCleanTags({ sleep: '', caffeine: '', stress: '' })).toEqual({});+ it('drops unset enum fields', () => {+ expect(buildCleanConditions({ sleepQuality: '', caffeine: '', stress: '', note: '' })).toEqual({});});- it('drops whitespace-only values', () => {- expect(buildCleanTags({ sleep: ' ', caffeine: '\t', stress: '' })).toEqual({});+ it('drops a whitespace-only note', () => {+ expect(buildCleanConditions({ sleepQuality: '', caffeine: '', stress: '', note: ' ' })).toEqual({});});- it('keeps multiple filled-in values, each trimmed independently', () => {- expect(buildCleanTags({ sleep: 'poor', caffeine: ' 2 cups ', stress: 'high' })).toEqual({- sleep: 'poor',- caffeine: '2 cups',+ it('keeps multiple set fields', () => {+ expect(buildCleanConditions({ sleepQuality: 'poor', caffeine: 'high', stress: 'high', note: '' })).toEqual({+ sleepQuality: 'poor',+ caffeine: 'high',stress: 'high',});});- it('returns an empty object for an empty tags map', () => {- expect(buildCleanTags({})).toEqual({});+ it('returns an empty object for an empty conditions map', () => {+ expect(buildCleanConditions({})).toEqual({});});});@@ -521,23 +523,23 @@ describe('PostSessionLauncher — Start card (issue #3249)', () => {expect(onStart.mock.calls[0][0].length).toBeGreaterThan(1);});- it('collapses Conditions by default and keeps typed values when re-collapsed', async () => {+ it('collapses Conditions by default and keeps a set value when re-collapsed', async () => {renderLauncher();await waitFor(() => expect(screen.getByText(/Conditions \(optional\)/)).toBeTruthy());- // Collapsed: no inputs rendered.- expect(screen.queryByPlaceholderText('good/poor')).toBeNull();+ // Collapsed: no select rendered.+ expect(screen.queryByLabelText('Sleep')).toBeNull();const toggle = screen.getByText(/Conditions \(optional\)/).closest('button');fireEvent.click(toggle);- const sleep = screen.getByPlaceholderText('good/poor');+ const sleep = screen.getByLabelText('Sleep');fireEvent.change(sleep, { target: { value: 'poor' } });// Re-collapse, then re-expand — the value survives (state lives above it).fireEvent.click(toggle);- expect(screen.queryByPlaceholderText('good/poor')).toBeNull();+ expect(screen.queryByLabelText('Sleep')).toBeNull();expect(screen.getByText('· 1 set')).toBeTruthy();fireEvent.click(toggle);- expect(screen.getByPlaceholderText('good/poor').value).toBe('poor');+ expect(screen.getByLabelText('Sleep').value).toBe('poor');});});diff --git a/client/src/components/meatspace/post/PostSessionResults.jsx b/client/src/components/meatspace/post/PostSessionResults.jsxindex f1259ca03d..be2b3b8943 100644--- a/client/src/components/meatspace/post/PostSessionResults.jsx+++ b/client/src/components/meatspace/post/PostSessionResults.jsx@@ -2,11 +2,11 @@ import { ArrowLeft } from 'lucide-react';import PostSessionSummary from './PostSessionSummary';import PostCompletionActions from './PostCompletionActions';-export default function PostSessionResults({ session, tags = {}, onSaved, onBack }) {+export default function PostSessionResults({ session, conditions = {}, onSaved, onBack }) {const { drillResults, sessionScore, state, saveSession, isTraining, sessionPlan, benchmark, savedSession } = session;async function handleSave(continueDaily) {- const savedSession = await saveSession(tags);+ const savedSession = await saveSession(conditions);if (savedSession) onSaved(savedSession, { continueDaily });}diff --git a/client/src/components/meatspace/post/PostSessionResults.test.jsx b/client/src/components/meatspace/post/PostSessionResults.test.jsxindex b411e412ca..e0f09d997d 100644--- a/client/src/components/meatspace/post/PostSessionResults.test.jsx+++ b/client/src/components/meatspace/post/PostSessionResults.test.jsx@@ -36,7 +36,7 @@ function makeSession(overrides = {}) {function renderResults(overrides = {}) {return render(- <PostSessionResults session={makeSession(overrides)} tags={{}} onSaved={() => {}} onBack={() => {}} />+ <PostSessionResults session={makeSession(overrides)} conditions={{}} onSaved={() => {}} onBack={() => {}} />);}@@ -119,7 +119,7 @@ describe('PostSessionResults daily routine actions', () => {render(<PostSessionResultssession={makeSession({ saveSession })}- tags={{}}+ conditions={{}}onSaved={onSaved}onBack={() => {}}/>diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsxindex 506c9a1e06..34cc0a2a16 100644--- a/client/src/components/meatspace/tabs/PostTab.jsx+++ b/client/src/components/meatspace/tabs/PostTab.jsx@@ -87,8 +87,8 @@ export default function PostTab({ tab = 'launcher', subtab, mode }) {setStatsWeek(stWeek);}- async function handleStart(drillConfigs, tags, training = false, sessionPlan = null, benchmark = null) {- const started = await session.startSession(drillConfigs, training, tags || {}, sessionPlan, benchmark);+ async function handleStart(drillConfigs, conditions, training = false, sessionPlan = null, benchmark = null) {+ const started = await session.startSession(drillConfigs, training, conditions || {}, sessionPlan, benchmark);if (started) navigate('/post/session/run');}@@ -173,7 +173,7 @@ export default function PostTab({ tab = 'launcher', subtab, mode }) {return (<PostSessionResultssession={session}- tags={{}}+ conditions={{}}onSaved={handleSaved}onBack={handleBack}/>diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex 11269a016b..1d48190368 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -172,7 +172,7 @@ export function usePostSession() {// Run id doubles as the client-generated session id (idempotent submit) and// the /post/session/:id results URL — so a saved session's URL === its run id.const [runId, setRunId] = useState(restored?.runId ?? null);- const [tags, setTags] = useState(restored?.tags ?? {}); // session tags captured at launch+ const [conditions, setConditions] = useState(restored?.conditions ?? {}); // session conditions captured at launchconst [sessionPlan, setSessionPlan] = useState(restored?.sessionPlan ?? null);const [benchmark, setBenchmark] = useState(restored?.benchmark ?? null);const [lastAnswer, setLastAnswer] = useState(null); // { correct, expected, answered } for training feedback@@ -204,7 +204,7 @@ export function usePostSession() {if (typeof sessionStorage === 'undefined') return;sessionStorage.setItem(RUN_STORAGE_KEY, JSON.stringify({runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex,- answers, drillResults, sessionScore, isTraining, tags, sessionPlan,+ answers, drillResults, sessionScore, isTraining, conditions, sessionPlan,benchmark,// Persist the timing anchors (mutated synchronously on each question/drill// transition, just before the state change that fires this effect) so a@@ -214,9 +214,9 @@ export function usePostSession() {runStartedAt: runStartedAtRef.current,runCompletedAt: runCompletedAtRef.current,}));- }, [runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex, answers, drillResults, sessionScore, isTraining, tags, sessionPlan, benchmark]);+ }, [runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex, answers, drillResults, sessionScore, isTraining, conditions, sessionPlan, benchmark]);- const startSession = useCallback(async (drillConfigs, training = false, sessionTags = {}, plan = null, benchmarkMetadata = null) => {+ const startSession = useCallback(async (drillConfigs, training = false, sessionConditions = {}, plan = null, benchmarkMetadata = null) => {// drillConfigs: [{ type, config, timeLimitSec }]if (!drillConfigs?.length) {toast.error('No drills configured');@@ -234,9 +234,9 @@ export function usePostSession() {runStartedAtRef.current = new Date().toISOString();runCompletedAtRef.current = null;// New run → new client-side id (also the future /post/session/:id) and the- // tags to submit, so both survive a mid-run refresh via the snapshot.+ // conditions to submit, so both survive a mid-run refresh via the snapshot.setRunId(newRunId());- setTags(sessionTags || {});+ setConditions(sessionConditions || {});const first = drillConfigs[0];const drill = await generatePostDrill(first.type, first.config, first.providerId, first.model, { silent: true }).catch(err => {@@ -484,11 +484,11 @@ export function usePostSession() {}}, [drillResults, currentDrillIndex, drills]);- const saveSession = useCallback(async (overrideTags = {}) => {+ const saveSession = useCallback(async (overrideConditions = {}) => {setState(STATES.SAVING);- // Prefer the tags captured at launch (survive a refresh via the snapshot);- // an explicit arg still wins per-key for a live save.- const finalTags = { ...tags, ...(overrideTags || {}) };+ // Prefer the conditions captured at launch (survive a refresh via the+ // snapshot); an explicit arg still wins per-key for a live save.+ const finalConditions = { ...conditions, ...(overrideConditions || {}) };// Training mode: one validated batch + one transaction for the whole run.// Stable run/attempt ids make a failed-response retry idempotent.@@ -592,7 +592,7 @@ export function usePostSession() {cadence: 'daily',modules,tasks: drillResults,- tags: finalTags,+ conditions: finalConditions,startedAt: new Date(runStartedAtRef.current).toISOString(),...(sessionPlan ? { plan: sessionPlan } : {}),...(benchmark ? { benchmark } : {}),@@ -614,7 +614,7 @@ export function usePostSession() {toast.success(`POST complete — score: ${session.score}`);setState(STATES.SAVED);return session;- }, [drillResults, isTraining, tags, runId, sessionPlan, benchmark]);+ }, [drillResults, isTraining, conditions, runId, sessionPlan, benchmark]);const reset = useCallback(() => {setState(STATES.IDLE);@@ -630,7 +630,7 @@ export function usePostSession() {setRunId(null);runStartedAtRef.current = null;runCompletedAtRef.current = null;- setTags({});+ setConditions({});setSessionPlan(null);setBenchmark(null);setLastAnswer(null);diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.jsindex d6be1729b3..471986cad2 100644--- a/client/src/hooks/usePostSession.test.js+++ b/client/src/hooks/usePostSession.test.js@@ -920,7 +920,7 @@ describe('usePostSession — refresh-safe run + idempotent submit (issue #2098)'drills: [{ type: 'compound-chain' }], currentDrillIndex: 0, currentDrill: null,currentQuestionIndex: 0, answers: [],drillResults: [{ module: 'llm-drills', type: 'compound-chain', score: 90 }],- sessionScore: 90, tags: {},+ sessionScore: 90, conditions: {},}));const { result } = renderHook(() => usePostSession());expect(result.current.state).toBe('complete');diff --git a/docs/features/post.md b/docs/features/post.mdindex 22a677a163..8b0564c6d5 100644--- a/docs/features/post.md+++ b/docs/features/post.md@@ -67,6 +67,18 @@ Configurable memory training for songs, poems, sequences, speeches, or any order- **Wordplay/Verbal/Imagination**: LLM-scored against per-drill rubrics (e.g. wit-comeback: humor 40% / cleverness 30% / relevance 30%), blended as quality 80% + speed bonus 20% (`server/services/meatspacePostLlm.js`).- **Session score**: per-module weighted mean across completed drills (`computeSessionScore`, weights from `config.scoring.weights`, issue #2099). Every module defaults to weight `1.0`, so an unconfigured install still gets the plain arithmetic mean; a module absent from a saved `weights` map also defaults to `1.0` rather than dropping out.+## Benchmark vs. Training (issue #4442)++An ordinary **Test** session (above) scores whatever drills the user's current, possibly adaptive, configuration happens to select — useful for daily practice, but not a stable measurement, since two Test sessions can differ in composition, difficulty rung, or drill order and still get compared as if they were the same instrument. A **Benchmark** run is a separate, fixed-form assessment:++- Composition, drill order, difficulty, and timing come entirely from a registered protocol (`POST_BENCHMARK_PROTOCOL`, `server/services/meatspacePost.js`), never from the user's adaptive/training configuration — no progressive ladder, no random Quick composition, no due maintenance reps, no hints or training feedback.+- Every run stores `protocolId`, `protocolVersion`, `scorerVersion`, and `formId` on its durable session record (`postBenchmarkSchema`, `server/lib/postValidation.js`), and the server rejects a submission whose tasks/config don't match the form it claims (`assertBenchmarkSession`) — a benchmark result can't be silently produced by a mismatched or hand-edited config.+- The protocol offers a small set of alternate **forms** (`GET /api/meatspace/post/benchmark/protocol`), rotated without immediate repetition so back-to-back runs don't reuse the same generated shapes; each form's tasks are deterministic/seeded, so a stored run is reproducible from its identity alone.+- **Trend comparisons stay protocol-scoped.** `getPostProgress`'s `series.benchmark` includes only sessions whose `protocolId`/`protocolVersion`/`scorerVersion` match the *currently registered* protocol; a run under a retired protocol/scorer version, or an ordinary Test/Train/Quick session, is excluded from that series (never silently blended in) and counted in `excludedCount` so the Progress UI can say why a session doesn't appear. The general `series.byDay` "Score Trend" is unchanged and still blends every scored session — it answers "how active/well am I doing generally," not "is this benchmark-comparable."+- This is a training aid, not a clinical, diagnostic, IQ, or generalized-cognitive-transfer instrument — no such claim is made or implied by a benchmark score.++Session **conditions** (optional, set at launch — `PostSessionLauncher.jsx`) are structured rather than free text: `sleepQuality` (poor/fair/good), `caffeine` (none/low/moderate/high), `stress` (low/moderate/high), plus an optional free-text note (`postConditionsSchema`). This makes conditions filterable/comparable across sessions instead of the prior unconstrained strings; historical sessions recorded before this change keep whatever free-text `tags` they were saved with as legacy metadata, which the server still accepts but the launcher no longer writes.+## Adaptive DifficultyOpt-in adaptive tuning for math drills (`server/lib/postAdaptive.js`): recent test and training attempts both inform skill evidence and nudge drill parameters, with a transparent preview of what would change (`GET /api/meatspace/post/adaptive-preview`). Training also feeds domain/drill progress, recommendations, progressive-ladder mastery, and mastered-skill retention scheduling. Benchmark/test history remains isolated: training never increments scored-session counts or changes the benchmark headline/overall score. Multiplication is a special case: whenever the progressive ladder is on (the default), it owns multiplication's difficulty entirely and the preview reflects the ladder rung, not the generic `maxDigits` knob — the two are mutually exclusive per drill type, never blended.@@ -95,6 +107,8 @@ All under `/api/meatspace` (`server/routes/meatspacePostRoutes.js`):- `GET/PUT /post/config` — drill configuration- `GET/POST /post/sessions`, `GET /post/sessions/:id` — scored session history- `GET /post/stats` — rolling averages+- `GET /post/benchmark/protocol` — the next fixed-form benchmark battery and its versioned scoring contract+- `GET /post/progress` — time-series trends, including the protocol-scoped `series.benchmark`- `POST /post/drill` — generate a drill (dispatches math / LLM / memory / cognitive)- `GET /post/adaptive-preview` — adaptive-difficulty preview- `POST /post/score-llm` — score LLM drill responsesdiff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex e610c56ff9..8c0917ad38 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -9,9 +9,24 @@ import { POST_LLM_MAX_SEMANTIC_CANDIDATES, postLlmEvaluationSchema } from './pos// POST (Power On Self Test) VALIDATION SCHEMAS// =============================================================================-// Tags for session conditions (sleep, caffeine, stress, etc.)+// Legacy free-text tags for session conditions (sleep, caffeine, stress, etc.).+// Superseded by `postConditionsSchema` below — kept only so historical session+// records (and any client that still sends it) remain valid; the launcher no+// longer writes free-text values here.export const postTagsSchema = z.record(z.string().max(200));+// Structured session conditions (issue #4442): fixed enums instead of free+// text so values are filterable/comparable across sessions, plus an optional+// note for anything the enums don't capture. Every field is optional — a+// session with no conditions filled in submits `{}`/`undefined`, not a+// placeholder-filled object.+export const postConditionsSchema = z.object({+ sleepQuality: z.enum(['poor', 'fair', 'good']).optional(),+ caffeine: z.enum(['none', 'low', 'moderate', 'high']).optional(),+ stress: z.enum(['low', 'moderate', 'high']).optional(),+ note: z.string().trim().max(500).optional(),+});+// 24h "HH:MM" time-of-day — HHMM_STRICT_RE is timezone.js's single source of// truth for this exact zero-padded pattern (shared with dashboardLayouts.js's// activateWindow validator); don't re-derive a local copy.@@ -306,6 +321,7 @@ export const postSessionSubmitSchema = z.object({modules: z.array(z.enum(POST_MODULES)).min(1),tasks: z.array(taskResultSchema).min(1),tags: postTagsSchema.optional().default({}),+ conditions: postConditionsSchema.optional(),startedAt: z.string().datetime().optional(),plan: postQuickSessionPlanSchema.optional(),benchmark: postBenchmarkSchema.optional(),diff --git a/server/lib/postValidation.test.js b/server/lib/postValidation.test.jsindex 76e61c68d5..e0b06e0ff5 100644--- a/server/lib/postValidation.test.js+++ b/server/lib/postValidation.test.js@@ -15,6 +15,7 @@ import {POST_QUICK_DURATION_MINUTES,postQuickSessionPlanSchema,postBenchmarkSchema,+ postConditionsSchema,} from './postValidation.js';import { getTopic, POST_TOPICS } from './postTopics.js';@@ -46,6 +47,69 @@ describe('postBenchmarkSchema', () => {});});+// Structured session conditions (issue #4442) — fixed enums instead of the+// legacy free-text `tags` map, so values are filterable/comparable.+describe('postConditionsSchema', () => {+ it('accepts every field set', () => {+ expect(postConditionsSchema.parse({+ sleepQuality: 'good',+ caffeine: 'moderate',+ stress: 'low',+ note: 'felt sharp today',+ })).toEqual({+ sleepQuality: 'good',+ caffeine: 'moderate',+ stress: 'low',+ note: 'felt sharp today',+ });+ });++ it('accepts an empty object — every field is optional', () => {+ expect(postConditionsSchema.parse({})).toEqual({});+ });++ it('rejects a value outside the fixed enum', () => {+ expect(() => postConditionsSchema.parse({ sleepQuality: 'terrible' })).toThrow();+ expect(() => postConditionsSchema.parse({ caffeine: '1 cup' })).toThrow();+ expect(() => postConditionsSchema.parse({ stress: 'extreme' })).toThrow();+ });++ it('trims the note and rejects one over 500 chars', () => {+ expect(postConditionsSchema.parse({ note: ' short ' }).note).toBe('short');+ expect(() => postConditionsSchema.parse({ note: 'x'.repeat(501) })).toThrow();+ });++ it('flows through postSessionSubmitSchema as an optional field', () => {+ const parsed = postSessionSubmitSchema.parse({+ modules: ['mental-math'],+ tasks: [{+ module: 'mental-math',+ type: 'doubling-chain',+ questions: [{ prompt: '2 x 2', expected: 4, answered: 4, responseMs: 100 }],+ totalMs: 100,+ }],+ conditions: { sleepQuality: 'poor', stress: 'high' },+ });+ expect(parsed.conditions).toEqual({ sleepQuality: 'poor', stress: 'high' });+ });++ it('legacy tags and structured conditions coexist independently', () => {+ const parsed = postSessionSubmitSchema.parse({+ modules: ['mental-math'],+ tasks: [{+ module: 'mental-math',+ type: 'doubling-chain',+ questions: [{ prompt: '2 x 2', expected: 4, answered: 4, responseMs: 100 }],+ totalMs: 100,+ }],+ tags: { sleep: 'ok-ish, hand-typed' },+ conditions: { sleepQuality: 'fair' },+ });+ expect(parsed.tags).toEqual({ sleep: 'ok-ish, hand-typed' });+ expect(parsed.conditions).toEqual({ sleepQuality: 'fair' });+ });+});+describe('postConfigUpdateSchema llmDrills', () => {// Regression: the config UI (PostDrillConfig.jsx) exposed only 5 of the 14// LLM drill types. All 14 are generatable server-side and must be persistablediff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 268d2f1fca..3ad31e476e 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -125,6 +125,22 @@ export async function getPostBenchmarkProtocol() {return { ...cloneBenchmarkProtocol(POST_BENCHMARK_PROTOCOL), nextFormId: nextForm.formId };}+// A benchmark session is "compatible" only when its stored protocol/version/+// scorer triple exactly matches the CURRENTLY registered protocol — never+// fabricated, never inferred by shape. `null` marks a plain (non-benchmark)+// session so trend code can tell "not a benchmark run" apart from "a+// benchmark run under a retired protocol/scorer version" (issue #4442);+// both are excluded from the compatible series, but for different reasons.+export function benchmarkCompatibility(session) {+ const benchmark = session?.benchmark;+ if (!benchmark) return null;+ return benchmark.protocolId === POST_BENCHMARK_PROTOCOL.protocolId+ && benchmark.protocolVersion === POST_BENCHMARK_PROTOCOL.protocolVersion+ && benchmark.scorerVersion === POST_BENCHMARK_PROTOCOL.scorerVersion+ ? 'compatible'+ : 'legacy';+}+function assertBenchmarkSession(benchmark, tasks, modules) {if (!benchmark) return;const form = benchmark.protocolId === POST_BENCHMARK_PROTOCOL.protocolId@@ -497,6 +513,9 @@ export async function submitPostSession(sessionData) {tasks: rescoredTasks,score: computeSessionScore(rescoredTasks, config.scoring?.weights),tags: sessionData.tags || {},+ ...(sessionData.conditions && Object.keys(sessionData.conditions).length+ ? { conditions: sessionData.conditions }+ : {}),...(sessionData.plan ? { plan: sessionData.plan } : {}),...(sessionData.benchmark ? { benchmark: sessionData.benchmark } : {}),};@@ -1044,7 +1063,10 @@ function pushMetricSeries(map, key, date, score, accuracy, avgResponseMs) {}// Finalize a `key -> (date -> bucket)` map into `key -> [{ date, score,-// accuracy, avgResponseMs }]`, chronologically sorted.+// accuracy, avgResponseMs, count }]`, chronologically sorted. `count` is the+// number of score samples bucketed into that day — for a series pushed once+// per session (e.g. the benchmark trend) that's the session count; for a+// series pushed once per task (byDomain/byDrill) it's the task count.function finalizeMetricSeries(map) {const out = {};for (const [key, byDate] of map) {@@ -1059,6 +1081,7 @@ function finalizeMetricSeries(map) {score: score == null ? null : Math.round(score),accuracy: acc == null ? null : acc,avgResponseMs: resp == null ? null : Math.round(resp),+ count: b.scores.length,};});}@@ -1073,6 +1096,11 @@ function finalizeMetricSeries(map) {* accuracy, avg response time, minutes, and session count.* - `series.byDomain` per-day series keyed by coarse module (`mental-math`, …).* - `series.byDrill` per-day series keyed by drill type (`multiplication`, …).+ * - `series.benchmark` protocol-scoped trend: only sessions run under the+ * CURRENT `POST_BENCHMARK_PROTOCOL` (protocolId+protocolVersion++ * scorerVersion), with `excludedCount` covering benchmark runs under a+ * retired protocol/scorer version (issue #4442). Ordinary Quick/Test/Train+ * sessions never appear here at all.* - `totals` minutes trained (sessions + practice), session count,* practice-entry count over the window.* - `streak` ONE unified streak (sessions OR training-log activity),@@ -1116,6 +1144,17 @@ export async function getPostProgress({ days = 90 } = {}) {const dayMap = new Map(); // date -> { scores, accs, resp, minutes, sessions }const domainMap = new Map(); // module -> Map(date -> metric bucket)const drillMap = new Map(); // type -> Map(date -> metric bucket)+ // Protocol-scoped series (issue #4442): pushed through the SAME date-bucket+ // aggregator as byDomain/byDrill below, under a single constant key, so a+ // benchmark trend is "filter + reuse the existing bucketer" rather than a+ // bespoke Map/ensure/finalize block. Only sessions run under the CURRENT+ // POST_BENCHMARK_PROTOCOL contribute, so the trend never blends across a+ // protocol/scorer version change or with ordinary Quick/Test/Train+ // sessions. `excludedCount` surfaces what was left out (benchmark runs+ // under a retired version) so the UI can say so rather than silently+ // under-counting.+ const benchmarkMap = new Map();+ let benchmarkExcludedCount = 0;const ensureDay = (date) => {let d = dayMap.get(date);@@ -1131,6 +1170,13 @@ export async function getPostProgress({ days = 90 } = {}) {day.minutes += (s.durationMs || 0) / 60000;if (typeof s.score === 'number' && !Number.isNaN(s.score)) day.scores.push(s.score);+ const compat = benchmarkCompatibility(s);+ if (compat === 'compatible') {+ pushMetricSeries(benchmarkMap, 'benchmark', date, s.score, null, null);+ } else if (compat === 'legacy') {+ benchmarkExcludedCount += 1;+ }+const sessionAccs = [];const sessionResp = [];for (const task of s.tasks || []) {@@ -1178,6 +1224,9 @@ export async function getPostProgress({ days = 90 } = {}) {};});+ const benchmarkByDay = (finalizeMetricSeries(benchmarkMap).benchmark || [])+ .map(({ date, score, count }) => ({ date, score, sessions: count }));+const sessionMs = sessions.reduce((sum, s) => sum + (s.durationMs || 0), 0);const trainingMs = training.reduce((sum, e) => sum + (e.totalMs || 0), 0);@@ -1201,6 +1250,19 @@ export async function getPostProgress({ days = 90 } = {}) {byDay,byDomain: finalizeMetricSeries(domainMap),byDrill: finalizeMetricSeries(drillMap),+ // Protocol-scoped benchmark trend (issue #4442) — additive, does not+ // change `byDay`'s existing blended-score semantics. `byDay` above+ // stays the general activity headline; this is the narrower "only+ // compatible, versioned benchmark runs" comparison the issue's+ // acceptance criteria require, with legacy/incompatible sessions+ // visibly excluded via `excludedCount` rather than silently dropped.+ benchmark: {+ protocolId: POST_BENCHMARK_PROTOCOL.protocolId,+ protocolVersion: POST_BENCHMARK_PROTOCOL.protocolVersion,+ scorerVersion: POST_BENCHMARK_PROTOCOL.scorerVersion,+ byDay: benchmarkByDay,+ excludedCount: benchmarkExcludedCount,+ },},totals: {minutesTrained: Math.round((sessionMs + trainingMs) / 60000),diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex d4aadf5f32..f4b3319548 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -104,6 +104,53 @@ describe('Fixed POST benchmark protocol', () => {});});+// Structured session conditions (issue #4442) — sleepQuality/caffeine/stress+// enums plus an optional note, persisted independently of the legacy+// free-text `tags` map.+describe('submitPostSession — structured conditions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ readJSONFile.mockImplementation((path, defaultValue) => Promise.resolve(defaultValue));+ });++ const baseSession = (overrides = {}) => ({+ modules: ['mental-math'],+ tasks: [{+ module: 'mental-math',+ type: 'doubling-chain',+ questions: [{ prompt: '2 x 2', expected: 4, answered: 4, responseMs: 100 }],+ totalMs: 100,+ }],+ ...overrides,+ });++ it('persists a filled-in conditions object', async () => {+ const session = await submitPostSession(baseSession({+ conditions: { sleepQuality: 'good', caffeine: 'low', stress: 'moderate', note: 'felt sharp' },+ }));+ expect(session.conditions).toEqual({ sleepQuality: 'good', caffeine: 'low', stress: 'moderate', note: 'felt sharp' });+ });++ it('omits the conditions field entirely when nothing was set', async () => {+ const session = await submitPostSession(baseSession({ conditions: {} }));+ expect(session.conditions).toBeUndefined();+ });++ it('omits conditions when the field is absent altogether', async () => {+ const session = await submitPostSession(baseSession());+ expect(session.conditions).toBeUndefined();+ });++ it('keeps legacy tags and structured conditions independent when both are present', async () => {+ const session = await submitPostSession(baseSession({+ tags: { sleep: 'hand-typed legacy value' },+ conditions: { sleepQuality: 'fair' },+ }));+ expect(session.tags).toEqual({ sleep: 'hand-typed legacy value' });+ expect(session.conditions).toEqual({ sleepQuality: 'fair' });+ });+});+function llmTaskResult(score, overrides = {}) {const responses = overrides.responses || [{ response: 'example', responseMs: 1000, llmScore: score }];return {diff --git a/server/services/meatspacePostProgress.test.js b/server/services/meatspacePostProgress.test.jsindex 52cb34b51f..4fe79ee303 100644--- a/server/services/meatspacePostProgress.test.js+++ b/server/services/meatspacePostProgress.test.js@@ -26,7 +26,7 @@ vi.mock('../services/settings.js', () => ({getSettings: () => Promise.resolve(settingsState),}));-import { getPostProgress, getPostStats } from './meatspacePost.js';+import { getPostProgress, getPostStats, benchmarkCompatibility, POST_BENCHMARK_PROTOCOL } from './meatspacePost.js';import { getTrainingStats, getAllTrainingEntries } from './meatspacePostTraining.js';import { getUnifiedActivityStreak } from './postActivityStreak.js';import { postProgressQuerySchema } from '../lib/postValidation.js';@@ -207,6 +207,103 @@ describe('getPostProgress bucketing', () => {});});+// Protocol-scoped benchmark trend (issue #4442): getPostProgress's `benchmark`+// series only counts sessions run under the CURRENTLY registered protocol —+// separate from `byDay`'s blended score, which every session above already+// exercises.+describe('benchmarkCompatibility', () => {+ const currentBenchmark = () => ({+ protocolId: POST_BENCHMARK_PROTOCOL.protocolId,+ protocolVersion: POST_BENCHMARK_PROTOCOL.protocolVersion,+ scorerVersion: POST_BENCHMARK_PROTOCOL.scorerVersion,+ formId: 'a',+ });++ it('returns null for a session with no benchmark field', () => {+ expect(benchmarkCompatibility({ score: 80 })).toBeNull();+ });++ it('returns "compatible" when protocol/version/scorer match the current registration', () => {+ expect(benchmarkCompatibility({ benchmark: currentBenchmark() })).toBe('compatible');+ });++ it('returns "legacy" when the protocol version has moved on', () => {+ expect(benchmarkCompatibility({ benchmark: { ...currentBenchmark(), protocolVersion: 0 } })).toBe('legacy');+ });++ it('returns "legacy" when the scorer version has moved on', () => {+ expect(benchmarkCompatibility({ benchmark: { ...currentBenchmark(), scorerVersion: 'retired-scorer' } })).toBe('legacy');+ });++ it('returns "legacy" for an unrecognized protocolId', () => {+ expect(benchmarkCompatibility({ benchmark: { ...currentBenchmark(), protocolId: 'some-other-battery' } })).toBe('legacy');+ });+});++describe('getPostProgress — protocol-scoped benchmark series', () => {+ const currentBenchmark = () => ({+ protocolId: POST_BENCHMARK_PROTOCOL.protocolId,+ protocolVersion: POST_BENCHMARK_PROTOCOL.protocolVersion,+ scorerVersion: POST_BENCHMARK_PROTOCOL.scorerVersion,+ formId: 'a',+ });++ it('names the current protocol and returns an empty byDay/excludedCount with no sessions', async () => {+ const p = await getPostProgress({ days: 90 });+ expect(p.series.benchmark).toMatchObject({+ protocolId: POST_BENCHMARK_PROTOCOL.protocolId,+ protocolVersion: POST_BENCHMARK_PROTOCOL.protocolVersion,+ scorerVersion: POST_BENCHMARK_PROTOCOL.scorerVersion,+ byDay: [],+ excludedCount: 0,+ });+ });++ it('includes a session run under the current protocol in byDay', async () => {+ const d = todayStr();+ state.sessions = [+ { date: d, durationMs: 60000, score: 85, tasks: [mathTask(85, [q(true)])], benchmark: currentBenchmark() },+ ];+ const p = await getPostProgress({ days: 90 });+ expect(p.series.benchmark.byDay).toEqual([{ date: d, score: 85, sessions: 1 }]);+ expect(p.series.benchmark.excludedCount).toBe(0);+ });++ it('excludes a benchmark session run under a retired protocol version and counts it', async () => {+ const d = todayStr();+ state.sessions = [+ {+ date: d, durationMs: 60000, score: 40, tasks: [mathTask(40, [q(false)])],+ benchmark: { ...currentBenchmark(), protocolVersion: 0 },+ },+ ];+ const p = await getPostProgress({ days: 90 });+ expect(p.series.benchmark.byDay).toEqual([]);+ expect(p.series.benchmark.excludedCount).toBe(1);+ });++ it('excludes an ordinary (non-benchmark) session without counting it as excluded', async () => {+ const d = todayStr();+ state.sessions = [+ { date: d, durationMs: 60000, score: 70, tasks: [mathTask(70, [q(true)])] },+ ];+ const p = await getPostProgress({ days: 90 });+ expect(p.series.benchmark.byDay).toEqual([]);+ // Not a benchmark run at all — nothing to exclude, unlike a stale-version one.+ expect(p.series.benchmark.excludedCount).toBe(0);+ });++ it('averages multiple same-day compatible benchmark sessions, mirroring byDay', async () => {+ const d = todayStr();+ state.sessions = [+ { date: d, durationMs: 60000, score: 80, tasks: [mathTask(80, [q(true)])], benchmark: currentBenchmark() },+ { date: d, durationMs: 60000, score: 60, tasks: [mathTask(60, [q(false)])], benchmark: currentBenchmark() },+ ];+ const p = await getPostProgress({ days: 90 });+ expect(p.series.benchmark.byDay).toEqual([{ date: d, score: 70, sessions: 2 }]);+ });+});+describe('unified streak agrees across every POST surface', () => {it('getPostStats, getTrainingStats, and getPostProgress report the SAME streak', async () => {// Interleave scored sessions and practice on distinct days: neither source